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
Go
Go
check the output, not the errcode
bcb9adf49e6726eccc1ee1ed41fbe21789c2367f
<ide><path>integration-cli/docker_cli_daemon_test.go <ide> func (s *DockerDaemonSuite) TestDaemonNoSpaceleftOnDeviceError(c *check.C) { <ide> <ide> // pull a repository large enough to fill the mount point <ide> out, err := s.d.Cmd("pull", "registry:2") <del> c.Assert(out, check.Not(check.Equals), 1, check.Commentf("no space left on device")) <add> <add> c.Assert(strings.Contains(out, "no space left on device"), check.Equals, true) <ide> } <ide> <ide> // Test daemon restart with container links + auto restart
1
Ruby
Ruby
load an application before use
1555fcf32cb13e65ae9d4f1cd776b8becaed1906
<ide><path>railties/test/application/configuration_test.rb <ide> class MyLogger < ::Logger <ide> config.rake_eager_load = true <ide> RUBY <ide> <add> app "development" <add> <ide> assert_equal true, Rails.application.config.rake_eager_load <ide> end <ide>
1
Python
Python
add initialization for everybody
5705333441f44858d9e656a8370b6c4c2921455b
<ide><path>examples/run_tf_glue.py <ide> import tensorflow as tf <ide> import tensorflow_datasets <del>from transformers import * <add>from pytorch_transformers import * <ide> <ide> # Load dataset, tokenizer, model from pretrained model/vocabulary <ide> tokenizer = BertTokenizer.from_pretrained('bert-base-cased') <del>dataset = tensorflow_datasets.load('glue/mrpc') <ide> model = TFBertForSequenceClassification.from_pretrained('bert-base-cased') <add>data = tensorflow_datasets.load('glue/mrpc') <ide> <ide> # Prepare dataset for GLUE as a tf.data.Dataset instance <del>train_dataset = glue_convert_examples_to_features(dataset['train'], tokenizer, task='mrpc') <del>valid_dataset = glue_convert_examples_to_features(dataset['validation'], tokenizer, task='mrpc') <del>train_dataset = train_dataset.shuffle(100).batch(32).repeat(3) <add>train_dataset = glue_convert_examples_to_features(data['train'], tokenizer, 128, 'mrpc') <add>valid_dataset = glue_convert_examples_to_features(data['validation'], tokenizer, 128, 'mrpc') <add>train_dataset = train_dataset.shuffle(100).batch(32).repeat(2) <ide> valid_dataset = valid_dataset.batch(64) <ide> <ide> # Prepare training: Compile tf.keras model with optimizer, loss and learning rate schedule <del>learning_rate = tf.keras.optimizers.schedules.PolynomialDecay(2e-5, 345, end_learning_rate=0) <del>optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate, epsilon=1e-08, clipnorm=1.0) <add>optimizer = tf.keras.optimizers.Adam(learning_rate=3e-5, epsilon=1e-08, clipnorm=1.0) <ide> loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) <del> <del>model.compile(optimizer=optimizer, loss=loss, metrics=['sparse_categorical_accuracy']) <add>metric = tf.keras.metrics.SparseCategoricalAccuracy('accuracy') <add>model.compile(optimizer=optimizer, loss=loss, metrics=[metric]) <ide> <ide> # Train and evaluate using tf.keras.Model.fit() <del>model.fit(train_dataset, epochs=3, steps_per_epoch=115, <del> validation_data=valid_dataset, validation_steps=7) <add>history = model.fit(train_dataset, epochs=2, steps_per_epoch=115, <add> validation_data=valid_dataset, validation_steps=7) <add> <add>>>> Train for 115 steps, validate for 7 steps <add>>>> Epoch 1/2 <add>>>> 115/115 [==============================] - 53s 459ms/step - loss: 0.6033 - accuracy: 0.6712 - val_loss: 0.4964 - val_accuracy: 0.7647 <add>>>> Epoch 2/2 <add>>>> 115/115 [==============================] - 33s 289ms/step - loss: 0.4141 - accuracy: 0.8160 - val_loss: 0.3914 - val_accuracy: 0.8382 <ide> <del># Save the TensorFlow model and load it in PyTorch <add># Load the TensorFlow model in PyTorch for inspection <ide> model.save_pretrained('./save/') <ide> pytorch_model = BertForSequenceClassification.from_pretrained('./save/', from_tf=True) <ide> <del># Quickly inspect a few predictions - MRPC is a paraphrasing task <del>inputs = tokenizer.encode_plus("The company is doing great", <del> "The company has good results", <del> add_special_tokens=True, <del> return_tensors='pt') <del>pred = pytorch_model(**inputs) <del>print("Paraphrase" if pred.argmax().item() == 0 else "Not paraphrase") <add># Quickly test a few predictions - MRPC is a paraphrasing task, let's see if our model learned the task <add>sentence_0 = "This research was consistent with his findings." <add>sentence_1 = "His findings were compatible with this research." <add>sentence_2 = "His findings were not compatible with this research." <add>inputs_1 = tokenizer.encode_plus(sentence_0, sentence_1, add_special_tokens=True, return_tensors='pt') <add>inputs_2 = tokenizer.encode_plus(sentence_0, sentence_2, add_special_tokens=True, return_tensors='pt') <add> <add>pred_1 = pytorch_model(**inputs_1)[0].argmax().item() <add>pred_2 = pytorch_model(**inputs_2)[0].argmax().item() <add>print("sentence_1 is", "a paraphrase" if pred_1 else "not a paraphrase", "of sentence_0") <add>print("sentence_2 is", "a paraphrase" if pred_2 else "not a paraphrase", "of sentence_0") <add>>>> sentence_1 is a paraphrase of sentence_0 <add>>>> sentence_2 is not a paraphrase of sentence_0 <ide>\ No newline at end of file <ide><path>pytorch_transformers/modeling_tf_distilbert.py <ide> import tensorflow as tf <ide> <ide> from .configuration_distilbert import DistilBertConfig <del>from .modeling_tf_utils import TFPreTrainedModel, TFSharedEmbeddings, shape_list <add>from .modeling_tf_utils import TFPreTrainedModel, TFSharedEmbeddings, shape_list, get_initializer <ide> from .file_utils import add_start_docstrings <ide> from .modeling_tf_pytorch_utils import load_pytorch_checkpoint_in_tf2_model <ide> <ide> def __init__(self, config, **kwargs): <ide> super(TFEmbeddings, self).__init__(**kwargs) <ide> self.vocab_size = config.vocab_size <ide> self.dim = config.dim <del> self.word_embeddings = TFSharedEmbeddings(config.vocab_size, config.dim, name='word_embeddings') # padding_idx=0) <del> self.position_embeddings = tf.keras.layers.Embedding(config.max_position_embeddings, config.dim, name='position_embeddings') <add> self.initializer_range = config.initializer_range <add> self.word_embeddings = TFSharedEmbeddings(config.vocab_size, <add> config.dim, <add> initializer_range=config.initializer_range, <add> name='word_embeddings') # padding_idx=0) <add> self.position_embeddings = tf.keras.layers.Embedding(config.max_position_embeddings, <add> config.dim, <add> embeddings_initializer=get_initializer(config.initializer_range), <add> name='position_embeddings') <ide> if config.sinusoidal_pos_embds: <ide> raise NotImplementedError <ide> <ide> def build(self, input_shape): <ide> self.word_embeddings = self.add_weight( <ide> "weight", <ide> shape=[self.vocab_size, self.dim], <del> initializer=tf.random_normal_initializer( <del> mean=0., stddev=self.dim**-0.5)) <add> initializer=get_initializer(self.initializer_range)) <ide> super(TFEmbeddings, self).build(input_shape) <ide> <ide> def call(self, inputs, mode="embedding", training=False): <ide> def __init__(self, config, **kwargs): <ide> <ide> assert self.dim % self.n_heads == 0 <ide> <del> self.q_lin = tf.keras.layers.Dense(config.dim, name="q_lin") <del> self.k_lin = tf.keras.layers.Dense(config.dim, name="k_lin") <del> self.v_lin = tf.keras.layers.Dense(config.dim, name="v_lin") <del> self.out_lin = tf.keras.layers.Dense(config.dim, name="out_lin") <add> self.q_lin = tf.keras.layers.Dense(config.dim, <add> kernel_initializer=get_initializer(config.initializer_range), <add> name="q_lin") <add> self.k_lin = tf.keras.layers.Dense(config.dim, <add> kernel_initializer=get_initializer(config.initializer_range), <add> name="k_lin") <add> self.v_lin = tf.keras.layers.Dense(config.dim, <add> kernel_initializer=get_initializer(config.initializer_range), <add> name="v_lin") <add> self.out_lin = tf.keras.layers.Dense(config.dim, <add> kernel_initializer=get_initializer(config.initializer_range), <add> name="out_lin") <ide> <ide> self.pruned_heads = set() <ide> <ide> class TFFFN(tf.keras.layers.Layer): <ide> def __init__(self, config, **kwargs): <ide> super(TFFFN, self).__init__(**kwargs) <ide> self.dropout = tf.keras.layers.Dropout(config.dropout) <del> self.lin1 = tf.keras.layers.Dense(config.hidden_dim, name="lin1") <del> self.lin2 = tf.keras.layers.Dense(config.dim, name="lin2") <add> self.lin1 = tf.keras.layers.Dense(config.hidden_dim, <add> kernel_initializer=get_initializer(config.initializer_range), <add> name="lin1") <add> self.lin2 = tf.keras.layers.Dense(config.dim, <add> kernel_initializer=get_initializer(config.initializer_range), <add> name="lin2") <ide> assert config.activation in ['relu', 'gelu'], "activation ({}) must be in ['relu', 'gelu']".format(config.activation) <ide> self.activation = tf.keras.layers.Activation(gelu) if config.activation=='gelu' else tf.keras.activations.relu <ide> <ide> def __init__(self, config, *inputs, **kwargs): <ide> self.vocab_size = config.vocab_size <ide> <ide> self.distilbert = TFDistilBertMainLayer(config, name="distilbert") <del> self.vocab_transform = tf.keras.layers.Dense(config.dim, name="vocab_transform") <add> self.vocab_transform = tf.keras.layers.Dense(config.dim, <add> kernel_initializer=get_initializer(config.initializer_range), <add> name="vocab_transform") <ide> self.act = tf.keras.layers.Activation(gelu) <ide> self.vocab_layer_norm = tf.keras.layers.LayerNormalization(epsilon=1e-12, name="vocab_layer_norm") <ide> self.vocab_projector = TFDistilBertLMHead(config, self.distilbert.embeddings, name="vocab_projector") <ide> def __init__(self, config, *inputs, **kwargs): <ide> self.num_labels = config.num_labels <ide> <ide> self.distilbert = TFDistilBertMainLayer(config, name="distilbert") <del> self.pre_classifier = tf.keras.layers.Dense(config.dim, activation='relu', name="pre_classifier") <del> self.classifier = tf.keras.layers.Dense(config.num_labels, name="classifier") <add> self.pre_classifier = tf.keras.layers.Dense(config.dim, <add> kernel_initializer=get_initializer(config.initializer_range), <add> activation='relu', <add> name="pre_classifier") <add> self.classifier = tf.keras.layers.Dense(config.num_labels, <add> kernel_initializer=get_initializer(config.initializer_range), <add> name="classifier") <ide> self.dropout = tf.keras.layers.Dropout(config.seq_classif_dropout) <ide> <ide> def call(self, inputs, **kwargs): <ide> def __init__(self, config, *inputs, **kwargs): <ide> super(TFDistilBertForQuestionAnswering, self).__init__(config, *inputs, **kwargs) <ide> <ide> self.distilbert = TFDistilBertMainLayer(config, name="distilbert") <del> self.qa_outputs = tf.keras.layers.Dense(config.num_labels, name='qa_outputs') <add> self.qa_outputs = tf.keras.layers.Dense(config.num_labels, <add> kernel_initializer=get_initializer(config.initializer_range), <add> name='qa_outputs') <ide> assert config.num_labels == 2 <ide> self.dropout = tf.keras.layers.Dropout(config.qa_dropout) <ide> <ide><path>pytorch_transformers/modeling_tf_gpt2.py <ide> import tensorflow as tf <ide> <ide> from .modeling_tf_utils import (TFPreTrainedModel, TFConv1D, TFSharedEmbeddings, <del> TFSequenceSummary, shape_list) <add> TFSequenceSummary, shape_list, get_initializer) <ide> from .configuration_gpt2 import GPT2Config <ide> from .file_utils import add_start_docstrings <ide> from .modeling_tf_pytorch_utils import load_pytorch_checkpoint_in_tf2_model <ide> def __init__(self, nx, n_ctx, config, scale=False, **kwargs): <ide> self.split_size = n_state <ide> self.scale = scale <ide> <del> self.c_attn = TFConv1D(n_state * 3, nx, name='c_attn') <del> self.c_proj = TFConv1D(n_state, nx, name='c_proj') <add> self.c_attn = TFConv1D(n_state * 3, nx, initializer_range=config.initializer_range, name='c_attn') <add> self.c_proj = TFConv1D(n_state, nx, initializer_range=config.initializer_range, name='c_proj') <ide> self.attn_dropout = tf.keras.layers.Dropout(config.attn_pdrop) <ide> self.resid_dropout = tf.keras.layers.Dropout(config.resid_pdrop) <ide> self.pruned_heads = set() <ide> class TFMLP(tf.keras.layers.Layer): <ide> def __init__(self, n_state, config, **kwargs): <ide> super(TFMLP, self).__init__(**kwargs) <ide> nx = config.n_embd <del> self.c_fc = TFConv1D(n_state, nx, name='c_fc') <del> self.c_proj = TFConv1D(nx, n_state, name='c_proj') <add> self.c_fc = TFConv1D(n_state, nx, initializer_range=config.initializer_range, name='c_fc') <add> self.c_proj = TFConv1D(nx, n_state, initializer_range=config.initializer_range, name='c_proj') <ide> self.act = gelu <ide> self.dropout = tf.keras.layers.Dropout(config.resid_pdrop) <ide> <ide> def __init__(self, config, *inputs, **kwargs): <ide> self.vocab_size = config.vocab_size <ide> self.n_embd = config.n_embd <ide> <del> self.wte = TFSharedEmbeddings(config.vocab_size, config.hidden_size, name='wte') <del> self.wpe = tf.keras.layers.Embedding(config.n_positions, config.n_embd, name='wpe') <add> self.wte = TFSharedEmbeddings(config.vocab_size, <add> config.hidden_size, <add> initializer_range=config.initializer_range, <add> name='wte') <add> self.wpe = tf.keras.layers.Embedding(config.n_positions, <add> config.n_embd, <add> embeddings_initializer=get_initializer(config.initializer_range), <add> name='wpe') <ide> self.drop = tf.keras.layers.Dropout(config.embd_pdrop) <ide> self.h = [TFBlock(config.n_ctx, <ide> config, <ide> class TFGPT2DoubleHeadsModel(TFGPT2PreTrainedModel): <ide> def __init__(self, config, *inputs, **kwargs): <ide> super(TFGPT2DoubleHeadsModel, self).__init__(config, *inputs, **kwargs) <ide> self.transformer = TFGPT2MainLayer(config, name='transformer') <del> self.multiple_choice_head = TFSequenceSummary(config, name='multiple_choice_head') <add> self.multiple_choice_head = TFSequenceSummary(config, initializer_range=config.initializer_range, name='multiple_choice_head') <ide> <ide> def call(self, inputs, past=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, mc_token_ids=None, training=False): <ide> if isinstance(inputs, (tuple, list)): <ide><path>pytorch_transformers/modeling_tf_openai.py <ide> import tensorflow as tf <ide> <ide> from .modeling_tf_utils import (TFPreTrainedModel, TFConv1D, TFSharedEmbeddings, <del> TFSequenceSummary, shape_list) <add> TFSequenceSummary, shape_list, get_initializer) <ide> from .configuration_openai import OpenAIGPTConfig <ide> from .file_utils import add_start_docstrings <ide> from .modeling_tf_pytorch_utils import load_pytorch_checkpoint_in_tf2_model <ide> def __init__(self, nx, n_ctx, config, scale=False, **kwargs): <ide> self.split_size = n_state <ide> self.scale = scale <ide> <del> self.c_attn = TFConv1D(n_state * 3, nx, name='c_attn') <del> self.c_proj = TFConv1D(n_state, nx, name='c_proj') <add> self.c_attn = TFConv1D(n_state * 3, nx, initializer_range=config.initializer_range, name='c_attn') <add> self.c_proj = TFConv1D(n_state, nx, initializer_range=config.initializer_range, name='c_proj') <ide> self.attn_dropout = tf.keras.layers.Dropout(config.attn_pdrop) <ide> self.resid_dropout = tf.keras.layers.Dropout(config.resid_pdrop) <ide> self.pruned_heads = set() <ide> class TFMLP(tf.keras.layers.Layer): <ide> def __init__(self, n_state, config, **kwargs): <ide> super(TFMLP, self).__init__(**kwargs) <ide> nx = config.n_embd <del> self.c_fc = TFConv1D(n_state, nx, name='c_fc') <del> self.c_proj = TFConv1D(nx, n_state, name='c_proj') <add> self.c_fc = TFConv1D(n_state, nx, initializer_range=config.initializer_range, name='c_fc') <add> self.c_proj = TFConv1D(nx, n_state, initializer_range=config.initializer_range, name='c_proj') <ide> self.act = gelu <ide> self.dropout = tf.keras.layers.Dropout(config.resid_pdrop) <ide> <ide> def __init__(self, config, *inputs, **kwargs): <ide> self.vocab_size = config.vocab_size <ide> self.n_embd = config.n_embd <ide> <del> self.tokens_embed = TFSharedEmbeddings(config.vocab_size, config.n_embd, name='tokens_embed') <del> self.positions_embed = tf.keras.layers.Embedding(config.n_positions, config.n_embd, name='positions_embed') <add> self.tokens_embed = TFSharedEmbeddings(config.vocab_size, <add> config.n_embd, <add> initializer_range=config.initializer_range, <add> name='tokens_embed') <add> self.positions_embed = tf.keras.layers.Embedding(config.n_positions, <add> config.n_embd, <add> embeddings_initializer=get_initializer(config.initializer_range), <add> name='positions_embed') <ide> self.drop = tf.keras.layers.Dropout(config.embd_pdrop) <ide> self.h = [TFBlock(config.n_ctx, <ide> config, <ide> class TFOpenAIGPTDoubleHeadsModel(TFOpenAIGPTPreTrainedModel): <ide> def __init__(self, config, *inputs, **kwargs): <ide> super(TFOpenAIGPTDoubleHeadsModel, self).__init__(config, *inputs, **kwargs) <ide> self.transformer = TFOpenAIGPTMainLayer(config, name='transformer') <del> self.multiple_choice_head = TFSequenceSummary(config, name='multiple_choice_head') <add> self.multiple_choice_head = TFSequenceSummary(config, initializer_range=config.initializer_range, name='multiple_choice_head') <ide> <ide> def call(self, inputs, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, mc_token_ids=None, training=False): <ide> if isinstance(inputs, (tuple, list)): <ide><path>pytorch_transformers/modeling_tf_roberta.py <ide> import tensorflow as tf <ide> <ide> from .configuration_roberta import RobertaConfig <del>from .modeling_tf_utils import TFPreTrainedModel <add>from .modeling_tf_utils import TFPreTrainedModel, get_initializer <ide> from .file_utils import add_start_docstrings <ide> from .modeling_tf_pytorch_utils import load_pytorch_checkpoint_in_tf2_model <ide> <ide> class TFRobertaLMHead(tf.keras.layers.Layer): <ide> def __init__(self, config, input_embeddings, **kwargs): <ide> super(TFRobertaLMHead, self).__init__(**kwargs) <ide> self.vocab_size = config.vocab_size <del> self.dense = tf.keras.layers.Dense(config.hidden_size, name='dense') <add> self.dense = tf.keras.layers.Dense(config.hidden_size, <add> kernel_initializer=get_initializer(config.initializer_range), <add> name='dense') <ide> self.layer_norm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name='layer_norm') <ide> self.act = tf.keras.layers.Activation(gelu) <ide> <ide> class TFRobertaClassificationHead(tf.keras.layers.Layer): <ide> <ide> def __init__(self, config, **kwargs): <ide> super(TFRobertaClassificationHead, self).__init__(config, **kwargs) <del> self.dense = tf.keras.layers.Dense(config.hidden_size, activation='tanh', name="dense") <add> self.dense = tf.keras.layers.Dense(config.hidden_size, <add> kernel_initializer=get_initializer(config.initializer_range), <add> activation='tanh', <add> name="dense") <ide> self.dropout = tf.keras.layers.Dropout(config.hidden_dropout_prob) <del> self.out_proj = tf.keras.layers.Dense(config.num_labels, name="out_proj") <add> self.out_proj = tf.keras.layers.Dense(config.num_labels, <add> kernel_initializer=get_initializer(config.initializer_range), <add> name="out_proj") <ide> <ide> def call(self, features, training=False): <ide> x = features[:, 0, :] # take <s> token (equiv. to [CLS]) <ide><path>pytorch_transformers/modeling_tf_transfo_xl.py <ide> import tensorflow as tf <ide> <ide> from .configuration_transfo_xl import TransfoXLConfig <del>from .modeling_tf_utils import TFPreTrainedModel, TFConv1D, TFSequenceSummary, shape_list <add>from .modeling_tf_utils import TFPreTrainedModel, TFConv1D, TFSequenceSummary, shape_list, get_initializer <ide> from .modeling_tf_transfo_xl_utilities import TFAdaptiveSoftmaxMask <ide> from .file_utils import add_start_docstrings <ide> from .modeling_tf_pytorch_utils import load_pytorch_checkpoint_in_tf2_model <ide> def call(self, pos_seq, bsz=None): <ide> <ide> <ide> class TFPositionwiseFF(tf.keras.layers.Layer): <del> def __init__(self, d_model, d_inner, dropout, pre_lnorm=False, layer_norm_epsilon=1e-5, **kwargs): <add> def __init__(self, d_model, d_inner, dropout, pre_lnorm=False, layer_norm_epsilon=1e-5, init_std=0.02, **kwargs): <ide> super(TFPositionwiseFF, self).__init__(**kwargs) <ide> <ide> self.d_model = d_model <ide> self.d_inner = d_inner <ide> self.dropout = dropout <ide> <del> self.layer_1 = tf.keras.layers.Dense(d_inner, activation=tf.nn.relu, name='CoreNet_._0') <add> self.layer_1 = tf.keras.layers.Dense(d_inner, <add> kernel_initializer=get_initializer(init_std), <add> activation=tf.nn.relu, <add> name='CoreNet_._0') <ide> self.drop_1 = tf.keras.layers.Dropout(dropout) <del> self.layer_2 = tf.keras.layers.Dense(d_model, name='CoreNet_._3') <add> self.layer_2 = tf.keras.layers.Dense(d_model, <add> kernel_initializer=get_initializer(init_std), <add> name='CoreNet_._3') <ide> self.drop_2 = tf.keras.layers.Dropout(dropout) <ide> <ide> self.layer_norm = tf.keras.layers.LayerNormalization(epsilon=layer_norm_epsilon, name='layer_norm') <ide> class TFRelPartialLearnableMultiHeadAttn(tf.keras.layers.Layer): <ide> def __init__(self, n_head, d_model, d_head, dropout, dropatt=0, <ide> tgt_len=None, ext_len=None, mem_len=None, pre_lnorm=False, <ide> r_r_bias=None, r_w_bias=None, output_attentions=False, <del> layer_norm_epsilon=1e-5, **kwargs): <add> layer_norm_epsilon=1e-5, init_std=0.02, **kwargs): <ide> super(TFRelPartialLearnableMultiHeadAttn, self).__init__(**kwargs) <ide> <ide> self.output_attentions = output_attentions <ide> def __init__(self, n_head, d_model, d_head, dropout, dropatt=0, <ide> self.d_head = d_head <ide> self.dropout = dropout <ide> <del> self.qkv_net = tf.keras.layers.Dense(3 * n_head * d_head, use_bias=False, name='qkv_net') <add> self.qkv_net = tf.keras.layers.Dense(3 * n_head * d_head, <add> kernel_initializer=get_initializer(init_std), <add> use_bias=False, <add> name='qkv_net') <ide> <ide> self.drop = tf.keras.layers.Dropout(dropout) <ide> self.dropatt = tf.keras.layers.Dropout(dropatt) <del> self.o_net = tf.keras.layers.Dense(d_model, use_bias=False, name='o_net') <add> self.o_net = tf.keras.layers.Dense(d_model, <add> kernel_initializer=get_initializer(init_std), <add> use_bias=False, <add> name='o_net') <ide> <ide> self.layer_norm = tf.keras.layers.LayerNormalization(epsilon=layer_norm_epsilon, name='layer_norm') <ide> <ide> def __init__(self, n_head, d_model, d_head, dropout, dropatt=0, <ide> self.r_r_bias = None <ide> self.r_w_bias = None <ide> <del> self.r_net = tf.keras.layers.Dense(self.n_head * self.d_head, use_bias=False, name='r_net') <add> self.r_net = tf.keras.layers.Dense(self.n_head * self.d_head, <add> kernel_initializer=get_initializer(init_std), <add> use_bias=False, <add> name='r_net') <ide> <ide> def build(self, input_shape): <ide> if self.r_r_bias is None or self.r_w_bias is None: # Biases are not shared <ide> self.r_r_bias = self.add_weight(shape=(self.n_head, self.d_head), <add> initializer='zeros', <ide> trainable=True, <ide> name='r_r_bias') <ide> self.r_w_bias = self.add_weight(shape=(self.n_head, self.d_head), <add> initializer='zeros', <ide> trainable=True, <ide> name='r_w_bias') <ide> super(TFRelPartialLearnableMultiHeadAttn, self).build(input_shape) <ide> def __init__(self, n_head, d_model, d_head, d_inner, dropout, <ide> r_r_bias=None, <ide> output_attentions=False, <ide> layer_norm_epsilon=1e-5, <add> init_std=0.02, <ide> **kwargs): <ide> super(TFRelPartialLearnableDecoderLayer, self).__init__(**kwargs) <ide> <ide> self.dec_attn = TFRelPartialLearnableMultiHeadAttn(n_head, d_model, <ide> d_head, dropout, tgt_len=tgt_len, ext_len=ext_len, <ide> mem_len=mem_len, dropatt=dropatt, pre_lnorm=pre_lnorm, <del> r_w_bias=r_w_bias, r_r_bias=r_r_bias, <add> r_w_bias=r_w_bias, r_r_bias=r_r_bias, init_std=init_std, <ide> output_attentions=output_attentions, <ide> layer_norm_epsilon=layer_norm_epsilon, name='dec_attn') <ide> self.pos_ff = TFPositionwiseFF(d_model, d_inner, dropout, <del> pre_lnorm=pre_lnorm, <add> pre_lnorm=pre_lnorm, init_std=init_std, <ide> layer_norm_epsilon=layer_norm_epsilon, <ide> name='pos_ff') <ide> <ide> def call(self, inputs, training=False): <ide> <ide> <ide> class TFAdaptiveEmbedding(tf.keras.layers.Layer): <del> def __init__(self, n_token, d_embed, d_proj, cutoffs, div_val=1, <add> def __init__(self, n_token, d_embed, d_proj, cutoffs, div_val=1, init_std=0.02, <ide> sample_softmax=False, **kwargs): <ide> super(TFAdaptiveEmbedding, self).__init__(**kwargs) <ide> <ide> self.n_token = n_token <ide> self.d_embed = d_embed <add> self.init_std = init_std <ide> <ide> self.cutoffs = cutoffs + [n_token] <ide> self.div_val = div_val <ide> def __init__(self, n_token, d_embed, d_proj, cutoffs, div_val=1, <ide> for i in range(len(self.cutoffs)): <ide> l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i+1] <ide> d_emb_i = d_embed // (div_val ** i) <del> self.emb_layers.append(tf.keras.layers.Embedding(r_idx-l_idx, d_emb_i, name='emb_layers_._{}'.format(i))) <add> self.emb_layers.append(tf.keras.layers.Embedding(r_idx-l_idx, <add> d_emb_i, <add> embeddings_initializer=get_initializer(init_std), <add> name='emb_layers_._{}'.format(i))) <ide> <ide> def build(self, input_shape): <ide> for i in range(len(self.cutoffs)): <ide> d_emb_i = self.d_embed // (self.div_val ** i) <ide> self.emb_projs.append(self.add_weight(shape=(d_emb_i, self.d_proj), <add> initializer=get_initializer(self.init_std), <ide> trainable=True, <ide> name='emb_projs_._{}'.format(i))) <ide> super(TFAdaptiveEmbedding, self).build(input_shape) <ide> def __init__(self, config, **kwargs): <ide> self.untie_r = config.untie_r <ide> <ide> self.word_emb = TFAdaptiveEmbedding(config.n_token, config.d_embed, config.d_model, config.cutoffs, <del> div_val=config.div_val, name='word_emb') <add> div_val=config.div_val, init_std=config.init_std, name='word_emb') <ide> <ide> self.drop = tf.keras.layers.Dropout(config.dropout) <ide> <ide> def __init__(self, config, **kwargs): <ide> r_r_bias=None if self.untie_r else self.r_r_bias, <ide> output_attentions=self.output_attentions, <ide> layer_norm_epsilon=config.layer_norm_epsilon, <add> init_std=config.init_std, <ide> name='layers_._{}'.format(i)) <ide> ) <ide> else: # learnable embeddings and absolute embeddings <ide><path>pytorch_transformers/modeling_tf_utils.py <ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): <ide> return model <ide> <ide> class TFConv1D(tf.keras.layers.Layer): <del> def __init__(self, nf, nx, *inputs, **kwargs): <add> def __init__(self, nf, nx, *inputs, initializer_range=0.02, **kwargs): <ide> """ TFConv1D layer as defined by Radford et al. for OpenAI GPT (and also used in GPT-2) <ide> Basically works like a Linear layer but the weights are transposed <ide> """ <ide> super(TFConv1D, self).__init__(*inputs, **kwargs) <ide> self.nf = nf <ide> self.nx = nx <add> self.initializer_range = initializer_range <ide> <ide> def build(self, input_shape): <ide> self.weight = self.add_weight( <ide> "weight", <ide> shape=[self.nx, self.nf], <del> initializer=tf.random_normal_initializer( <del> mean=0., stddev=0.02)) <add> initializer=get_initializer(self.initializer_range)) <ide> self.bias = self.add_weight( <ide> "bias", <ide> shape=[1, self.nf], <ide> def __init__(self, vocab_size, hidden_size, initializer_range=None, **kwargs): <ide> super(TFSharedEmbeddings, self).__init__(**kwargs) <ide> self.vocab_size = vocab_size <ide> self.hidden_size = hidden_size <del> self.initializer_range = initializer_range <add> self.initializer_range = hidden_size**-0.5 if initializer_range is None else initializer_range <ide> <ide> def build(self, input_shape): <ide> """Build shared word embedding layer <ide> Shared weights logic adapted from <ide> https://github.com/tensorflow/models/blob/a009f4fb9d2fc4949e32192a944688925ef78659/official/transformer/v2/embedding_layer.py#L24 <ide> """ <del> initializer_range = self.hidden_size**-0.5 if self.initializer_range is None else self.initializer_range <ide> self.weight = self.add_weight( <ide> "weight", <ide> shape=[self.vocab_size, self.hidden_size], <del> initializer=tf.random_normal_initializer( <del> mean=0., stddev=initializer_range)) <add> initializer=get_initializer(self.initializer_range)) <ide> super(TFSharedEmbeddings, self).build(input_shape) <ide> <ide> def call(self, inputs, mode="embedding"): <ide> class TFSequenceSummary(tf.keras.layers.Layer): <ide> summary_first_dropout: Add a dropout before the projection and activation <ide> summary_last_dropout: Add a dropout after the projection and activation <ide> """ <del> def __init__(self, config, **kwargs): <add> def __init__(self, config, initializer_range=0.02, **kwargs): <ide> super(TFSequenceSummary, self).__init__(**kwargs) <ide> <ide> self.summary_type = config.summary_type if hasattr(config, 'summary_use_proj') else 'last' <ide> def __init__(self, config, **kwargs): <ide> num_classes = config.num_labels <ide> else: <ide> num_classes = config.hidden_size <del> self.summary = tf.keras.layers.Dense(num_classes, name='summary') <add> self.summary = tf.keras.layers.Dense(num_classes, <add> kernel_initializer=get_initializer(initializer_range), <add> name='summary') <ide> <ide> self.activation = None <ide> if hasattr(config, 'summary_activation') and config.summary_activation == 'tanh': <ide><path>pytorch_transformers/modeling_tf_xlm.py <ide> import tensorflow as tf <ide> <ide> from .configuration_xlm import XLMConfig <del>from .modeling_tf_utils import TFPreTrainedModel, TFSharedEmbeddings, TFSequenceSummary, shape_list <add>from .modeling_tf_utils import TFPreTrainedModel, TFSharedEmbeddings, TFSequenceSummary, shape_list, get_initializer <ide> from .file_utils import add_start_docstrings <ide> from .modeling_tf_pytorch_utils import load_pytorch_checkpoint_in_tf2_model <ide> <ide> def __init__(self, n_heads, dim, config, **kwargs): <ide> self.n_heads = n_heads <ide> assert self.dim % self.n_heads == 0 <ide> <del> self.q_lin = tf.keras.layers.Dense(dim, name='q_lin') <del> self.k_lin = tf.keras.layers.Dense(dim, name='k_lin') <del> self.v_lin = tf.keras.layers.Dense(dim, name='v_lin') <del> self.out_lin = tf.keras.layers.Dense(dim, name='out_lin') <add> self.q_lin = tf.keras.layers.Dense(dim, kernel_initializer=get_initializer(config.init_std), name='q_lin') <add> self.k_lin = tf.keras.layers.Dense(dim, kernel_initializer=get_initializer(config.init_std), name='k_lin') <add> self.v_lin = tf.keras.layers.Dense(dim, kernel_initializer=get_initializer(config.init_std), name='v_lin') <add> self.out_lin = tf.keras.layers.Dense(dim, kernel_initializer=get_initializer(config.init_std), name='out_lin') <ide> self.dropout = tf.keras.layers.Dropout(config.attention_dropout) <ide> self.pruned_heads = set() <ide> <ide> class TFTransformerFFN(tf.keras.layers.Layer): <ide> <ide> def __init__(self, in_dim, dim_hidden, out_dim, config, **kwargs): <ide> super(TFTransformerFFN, self).__init__(**kwargs) <del> self.lin1 = tf.keras.layers.Dense(dim_hidden, name='lin1') <del> self.lin2 = tf.keras.layers.Dense(out_dim, name='lin2') <add> self.lin1 = tf.keras.layers.Dense(dim_hidden, kernel_initializer=get_initializer(config.init_std), name='lin1') <add> self.lin2 = tf.keras.layers.Dense(out_dim, kernel_initializer=get_initializer(config.init_std), name='lin2') <ide> self.act = tf.keras.layers.Activation(gelu) if config.gelu_activation else tf.keras.activations.relu <ide> self.dropout = tf.keras.layers.Dropout(config.dropout) <ide> <ide> def __init__(self, config, **kwargs): <ide> self.dropout = tf.keras.layers.Dropout(config.dropout) <ide> self.attention_dropout = tf.keras.layers.Dropout(config.attention_dropout) <ide> <del> self.position_embeddings = tf.keras.layers.Embedding(config.max_position_embeddings, self.dim, name='position_embeddings') <add> self.position_embeddings = tf.keras.layers.Embedding(config.max_position_embeddings, <add> self.dim, <add> embeddings_initializer=get_initializer(config.embed_init_std), <add> name='position_embeddings') <ide> if config.sinusoidal_embeddings: <ide> raise NotImplementedError <ide> # create_sinusoidal_embeddings(config.max_position_embeddings, self.dim, out=self.position_embeddings.weight) <ide> if config.n_langs > 1 and config.use_lang_emb: <del> self.lang_embeddings = tf.keras.layers.Embedding(self.n_langs, self.dim, name='lang_embeddings') <del> self.embeddings = TFSharedEmbeddings(self.n_words, self.dim, name='embeddings') # padding_idx=self.pad_index) <add> self.lang_embeddings = tf.keras.layers.Embedding(self.n_langs, <add> self.dim, <add> embeddings_initializer=get_initializer(config.embed_init_std), <add> name='lang_embeddings') <add> self.embeddings = TFSharedEmbeddings(self.n_words, self.dim, initializer_range=config.embed_init_std, name='embeddings') # padding_idx=self.pad_index) <ide> self.layer_norm_emb = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name='layer_norm_emb') <ide> <ide> # transformer layers <ide> def __init__(self, config, *inputs, **kwargs): <ide> self.num_labels = config.num_labels <ide> <ide> self.transformer = TFXLMMainLayer(config, name='transformer') <del> self.sequence_summary = TFSequenceSummary(config, name='sequence_summary') <add> self.sequence_summary = TFSequenceSummary(config, initializer_range=config.init_std, name='sequence_summary') <ide> <ide> def call(self, inputs, **kwargs): <ide> transformer_outputs = self.transformer(inputs, **kwargs) <ide> class TFXLMForQuestionAnsweringSimple(TFXLMPreTrainedModel): <ide> def __init__(self, config, *inputs, **kwargs): <ide> super(TFXLMForQuestionAnsweringSimple, self).__init__(config, *inputs, **kwargs) <ide> self.transformer = TFXLMMainLayer(config, name='transformer') <del> self.qa_outputs = tf.keras.layers.Dense(config.num_labels, name='qa_outputs') <add> self.qa_outputs = tf.keras.layers.Dense(config.num_labels, <add> kernel_initializer=get_initializer(config.init_std), <add> name='qa_outputs') <ide> <ide> def call(self, inputs, **kwargs): <ide> transformer_outputs = self.transformer(inputs, **kwargs) <ide><path>pytorch_transformers/modeling_tf_xlnet.py <ide> import tensorflow as tf <ide> <ide> from .configuration_xlnet import XLNetConfig <del>from .modeling_tf_utils import TFPreTrainedModel, TFSharedEmbeddings, TFSequenceSummary, shape_list <add>from .modeling_tf_utils import TFPreTrainedModel, TFSharedEmbeddings, TFSequenceSummary, shape_list, get_initializer <ide> from .file_utils import add_start_docstrings <ide> from .modeling_tf_pytorch_utils import load_pytorch_checkpoint_in_tf2_model <ide> <ide> def __init__(self, config, **kwargs): <ide> self.dropout = tf.keras.layers.Dropout(config.dropout) <ide> <ide> def build(self, input_shape): <del> initializer = tf.random_normal_initializer(mean=0., stddev=self.initializer_range) <add> initializer = get_initializer(self.initializer_range) <ide> self.q = self.add_weight(shape=(self.d_model, self.n_head, self.d_head), <ide> initializer=initializer, <ide> trainable=True, name='q') <ide> def build(self, input_shape): <ide> initializer=initializer, <ide> trainable=True, name='r') <ide> self.r_r_bias = self.add_weight(shape=(self.n_head, self.d_head), <del> initializer=initializer, <add> initializer='zeros', <ide> trainable=True, name='r_r_bias') <ide> self.r_s_bias = self.add_weight(shape=(self.n_head, self.d_head), <del> initializer=initializer, <add> initializer='zeros', <ide> trainable=True, name='r_s_bias') <ide> self.r_w_bias = self.add_weight(shape=(self.n_head, self.d_head), <del> initializer=initializer, <add> initializer='zeros', <ide> trainable=True, name='r_w_bias') <ide> self.seg_embed = self.add_weight(shape=(2, self.n_head, self.d_head), <ide> initializer=initializer, <ide> class TFXLNetFeedForward(tf.keras.layers.Layer): <ide> def __init__(self, config, **kwargs): <ide> super(TFXLNetFeedForward, self).__init__(**kwargs) <ide> self.layer_norm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name='layer_norm') <del> self.layer_1 = tf.keras.layers.Dense(config.d_inner, name='layer_1') <del> self.layer_2 = tf.keras.layers.Dense(config.d_model, name='layer_2') <add> self.layer_1 = tf.keras.layers.Dense(config.d_inner, <add> kernel_initializer=get_initializer(config.initializer_range), <add> name='layer_1') <add> self.layer_2 = tf.keras.layers.Dense(config.d_model, <add> kernel_initializer=get_initializer(config.initializer_range), <add> name='layer_2') <ide> self.dropout = tf.keras.layers.Dropout(config.dropout) <ide> if isinstance(config.ff_activation, str) or \ <ide> (sys.version_info[0] == 2 and isinstance(config.ff_activation, unicode)): <ide> def __init__(self, config, **kwargs): <ide> self.dropout = tf.keras.layers.Dropout(config.dropout) <ide> <ide> def build(self, input_shape): <del> initializer = tf.random_normal_initializer(mean=0., stddev=self.initializer_range) <add> initializer = get_initializer(self.initializer_range) <ide> self.mask_emb = self.add_weight(shape=(1, 1, self.d_model), <ide> initializer=initializer, <ide> trainable=True, name='mask_emb') <ide> def __init__(self, config, *inputs, **kwargs): <ide> self.num_labels = config.num_labels <ide> <ide> self.transformer = TFXLNetMainLayer(config, name='transformer') <del> self.sequence_summary = TFSequenceSummary(config, name='sequence_summary') <del> self.logits_proj = tf.keras.layers.Dense(config.num_labels, name='logits_proj') <add> self.sequence_summary = TFSequenceSummary(config, initializer_range=config.initializer_range, name='sequence_summary') <add> self.logits_proj = tf.keras.layers.Dense(config.num_labels, <add> kernel_initializer=get_initializer(config.initializer_range), <add> name='logits_proj') <ide> <ide> def call(self, inputs, **kwargs): <ide> transformer_outputs = self.transformer(inputs, **kwargs) <ide> class TFXLNetForQuestionAnsweringSimple(TFXLNetPreTrainedModel): <ide> def __init__(self, config, *inputs, **kwargs): <ide> super(TFXLNetForQuestionAnsweringSimple, self).__init__(config, *inputs, **kwargs) <ide> self.transformer = TFXLNetMainLayer(config, name='transformer') <del> self.qa_outputs = tf.keras.layers.Dense(config.num_labels, name='qa_outputs') <add> self.qa_outputs = tf.keras.layers.Dense(config.num_labels, <add> kernel_initializer=get_initializer(config.initializer_range), <add> name='qa_outputs') <ide> <ide> def call(self, inputs, **kwargs): <ide> transformer_outputs = self.transformer(inputs, **kwargs)
9
Javascript
Javascript
remove duplication of $browser to docs
842741ee9958ce3895f709c3faf47bfac762ef64
<ide><path>src/AngularPublic.js <ide> 'use strict'; <ide> <ide> var browserSingleton; <del>/** <del> * @workInProgress <del> * @ngdoc service <del> * @name angular.service.$browser <del> * @requires $log <del> * <del> * @description <del> * Represents the browser. <del> */ <add> <ide> angularService('$browser', function($log){ <ide> if (!browserSingleton) { <ide> browserSingleton = new Browser(window, jqLite(window.document), jqLite(window.document.body),
1
PHP
PHP
fix missing inflection on prefix value
a3298a439a7a5c8223c9e032d86411b42a4147c2
<ide><path>src/Routing/Router.php <ide> public static function prefix($name, $params = [], $callback = null) <ide> $callback = $params; <ide> $params = []; <ide> } <add> $name = Inflector::underscore($name); <ide> <ide> if (empty($params['path'])) { <del> $path = '/' . Inflector::underscore($name); <add> $path = '/' . $name; <ide> } else { <ide> $path = $params['path']; <ide> unset($params['path']); <ide><path>tests/TestCase/Routing/RouterTest.php <ide> public function testPrefixOptions() <ide> Router::prefix('CustomPath', ['path' => '/custom-path'], function ($routes) { <ide> $this->assertInstanceOf('Cake\Routing\RouteBuilder', $routes); <ide> $this->assertEquals('/custom-path', $routes->path()); <del> $this->assertEquals(['prefix' => 'CustomPath'], $routes->params()); <add> $this->assertEquals(['prefix' => 'custom_path'], $routes->params()); <ide> }); <ide> } <ide>
2
Ruby
Ruby
fix a failing test
4e3c215dcbeb122c59fe7158715c07bd4b1f41fd
<ide><path>actionpack/test/template/template_test.rb <ide> def disable_cache <ide> <ide> def find_template(*args) <ide> end <add> <add> attr_writer :formats <ide> end <ide> <ide> class Context
1
Javascript
Javascript
check noop invocation with mustnotcall()
d64d36126604f012461181d7f53c05233056394e
<ide><path>test/parallel/test-child-process-spawnsync-validation-errors.js <ide> function fail(option, value, message) { <ide> fail('cwd', false, err); <ide> fail('cwd', [], err); <ide> fail('cwd', {}, err); <del> fail('cwd', common.noop, err); <add> fail('cwd', common.mustNotCall(), err); <ide> } <ide> <ide> { <ide> function fail(option, value, message) { <ide> fail('detached', __dirname, err); <ide> fail('detached', [], err); <ide> fail('detached', {}, err); <del> fail('detached', common.noop, err); <add> fail('detached', common.mustNotCall(), err); <ide> } <ide> <ide> if (!common.isWindows) { <ide> if (!common.isWindows) { <ide> fail('uid', false, err); <ide> fail('uid', [], err); <ide> fail('uid', {}, err); <del> fail('uid', common.noop, err); <add> fail('uid', common.mustNotCall(), err); <ide> fail('uid', NaN, err); <ide> fail('uid', Infinity, err); <ide> fail('uid', 3.1, err); <ide> if (!common.isWindows) { <ide> fail('gid', false, err); <ide> fail('gid', [], err); <ide> fail('gid', {}, err); <del> fail('gid', common.noop, err); <add> fail('gid', common.mustNotCall(), err); <ide> fail('gid', NaN, err); <ide> fail('gid', Infinity, err); <ide> fail('gid', 3.1, err); <ide> if (!common.isWindows) { <ide> fail('shell', 1, err); <ide> fail('shell', [], err); <ide> fail('shell', {}, err); <del> fail('shell', common.noop, err); <add> fail('shell', common.mustNotCall(), err); <ide> } <ide> <ide> { <ide> if (!common.isWindows) { <ide> fail('argv0', false, err); <ide> fail('argv0', [], err); <ide> fail('argv0', {}, err); <del> fail('argv0', common.noop, err); <add> fail('argv0', common.mustNotCall(), err); <ide> } <ide> <ide> { <ide> if (!common.isWindows) { <ide> fail('windowsVerbatimArguments', __dirname, err); <ide> fail('windowsVerbatimArguments', [], err); <ide> fail('windowsVerbatimArguments', {}, err); <del> fail('windowsVerbatimArguments', common.noop, err); <add> fail('windowsVerbatimArguments', common.mustNotCall(), err); <ide> } <ide> <ide> { <ide> if (!common.isWindows) { <ide> fail('timeout', __dirname, err); <ide> fail('timeout', [], err); <ide> fail('timeout', {}, err); <del> fail('timeout', common.noop, err); <add> fail('timeout', common.mustNotCall(), err); <ide> fail('timeout', NaN, err); <ide> fail('timeout', Infinity, err); <ide> fail('timeout', 3.1, err); <ide> if (!common.isWindows) { <ide> fail('maxBuffer', __dirname, err); <ide> fail('maxBuffer', [], err); <ide> fail('maxBuffer', {}, err); <del> fail('maxBuffer', common.noop, err); <add> fail('maxBuffer', common.mustNotCall(), err); <ide> } <ide> <ide> { <ide> if (!common.isWindows) { <ide> fail('killSignal', false, typeErr); <ide> fail('killSignal', [], typeErr); <ide> fail('killSignal', {}, typeErr); <del> fail('killSignal', common.noop, typeErr); <add> fail('killSignal', common.mustNotCall(), typeErr); <ide> <ide> // Invalid signal names and numbers should fail <ide> fail('killSignal', 500, unknownSignalErr);
1
Go
Go
remove transportport.fromstring() as it's unused
073f8df0fef934a72f5d74adb6e9f8d2fe09a06f
<ide><path>libnetwork/types/types.go <ide> import ( <ide> "bytes" <ide> "fmt" <ide> "net" <del> "strconv" <ide> "strings" <ide> <ide> "github.com/ishidawataru/sctp" <ide> func (t *TransportPort) String() string { <ide> return fmt.Sprintf("%s/%d", t.Proto.String(), t.Port) <ide> } <ide> <del>// FromString reads the TransportPort structure from string <del>func (t *TransportPort) FromString(s string) error { <del> ps := strings.Split(s, "/") <del> if len(ps) == 2 { <del> t.Proto = ParseProtocol(ps[0]) <del> if p, err := strconv.ParseUint(ps[1], 10, 16); err == nil { <del> t.Port = uint16(p) <del> return nil <del> } <del> } <del> return BadRequestErrorf("invalid format for transport port: %s", s) <del>} <del> <ide> // PortBinding represents a port binding between the container and the host <ide> type PortBinding struct { <ide> Proto Protocol <ide><path>libnetwork/types/types_test.go <ide> import ( <ide> "testing" <ide> ) <ide> <del>func TestTransportPortConv(t *testing.T) { <del> sform := "tcp/23" <del> tp := &TransportPort{Proto: TCP, Port: uint16(23)} <del> <del> if sform != tp.String() { <del> t.Fatalf("String() method failed") <del> } <del> <del> rc := new(TransportPort) <del> if err := rc.FromString(sform); err != nil { <del> t.Fatal(err) <del> } <del> if !tp.Equal(rc) { <del> t.Fatalf("FromString() method failed") <del> } <del>} <del> <ide> func TestErrorConstructors(t *testing.T) { <ide> var err error <ide>
2
Python
Python
fix broken kubeexecutor tests
78503e0cd562be422a142d49461cbc27b2982ad2
<ide><path>kubernetes_tests/test_kubernetes_executor.py <ide> @pytest.mark.skipif(EXECUTOR != 'KubernetesExecutor', reason="Only runs on KubernetesExecutor") <ide> class TestKubernetesExecutor(TestBase): <ide> def test_integration_run_dag(self): <del> dag_id = 'example_kubernetes_executor_config' <add> dag_id = 'example_kubernetes_executor' <ide> dag_run_id, execution_date = self.start_job_in_kubernetes(dag_id, self.host) <ide> print(f"Found the job with execution_date {execution_date}") <ide> <ide> def test_integration_run_dag(self): <ide> ) <ide> <ide> def test_integration_run_dag_with_scheduler_failure(self): <del> dag_id = 'example_kubernetes_executor_config' <add> dag_id = 'example_kubernetes_executor' <ide> <ide> dag_run_id, execution_date = self.start_job_in_kubernetes(dag_id, self.host) <ide>
1
Javascript
Javascript
fix integration test with js-colors
17363bbc6fa46f04bf308a23443b931c85856ff2
<ide><path>test/integration/scripting_spec.js <ide> describe("Interaction", () => { <ide> pages = await loadAndWait("js-colors.pdf", "#\\33 4R"); <ide> }); <ide> <del> it("must changes colors", async () => { <add> it("must change colors", async () => { <ide> await Promise.all( <ide> pages.map(async ([browserName, page]) => { <ide> for (const [name, ref] of [ <ide> describe("Interaction", () => { <ide> await page.type("#\\33 4R", `${name}`, { <ide> delay: 10, <ide> }); <del> await page.click("[data-annotation-id='41R']"); <del> let color = await page.$eval( <del> ref, <del> el => getComputedStyle(el).backgroundColor <del> ); <del> expect(color) <del> .withContext(`In ${browserName}`) <del> .toEqual("rgb(255, 0, 0)"); <ide> <del> await page.click("[data-annotation-id='43R']"); <del> color = await page.$eval(ref, el => getComputedStyle(el).color); <del> expect(color) <del> .withContext(`In ${browserName}`) <del> .toEqual("rgb(0, 255, 0)"); <add> for (const [id, propName, expected] of [ <add> [41, "backgroundColor", "rgb(255, 0, 0)"], <add> [43, "color", "rgb(0, 255, 0)"], <add> [44, "border-top-color", "rgb(0, 0, 255)"], <add> ]) { <add> const current = await page.$eval( <add> ref, <add> (el, _propName) => getComputedStyle(el)[_propName], <add> propName <add> ); <ide> <del> await page.click("[data-annotation-id='44R']"); <del> color = await page.$eval( <del> ref, <del> el => getComputedStyle(el)["border-top-color"] <del> ); <del> expect(color) <del> .withContext(`In ${browserName}`) <del> .toEqual("rgb(0, 0, 255)"); <add> await page.click(`[data-annotation-id='${id}R']`); <add> await page.waitForFunction( <add> (_ref, _current, _propName) => <add> getComputedStyle(document.querySelector(_ref))[_propName] !== <add> _current, <add> {}, <add> ref, <add> current, <add> propName <add> ); <add> <add> const color = await page.$eval( <add> ref, <add> (el, _propName) => getComputedStyle(el)[_propName], <add> propName <add> ); <add> expect(color).withContext(`In ${browserName}`).toEqual(expected); <add> } <ide> } <ide> }) <ide> );
1
Python
Python
modify transfer operators to handle more data
99b0211d5087cf486415b5fc8399d3f15d84ed69
<ide><path>airflow/providers/google/cloud/transfers/cassandra_to_gcs.py <ide> def execute(self, context: 'Context'): <ide> <ide> cursor = hook.get_conn().execute(self.cql, **query_extra) <ide> <del> files_to_upload = self._write_local_data_files(cursor) <del> <ide> # If a schema is set, create a BQ schema JSON file. <ide> if self.schema_filename: <del> files_to_upload.update(self._write_local_schema_file(cursor)) <add> self.log.info('Writing local schema file') <add> schema_file = self._write_local_schema_file(cursor) <add> <add> # Flush file before uploading <add> schema_file['file_handle'].flush() <add> <add> self.log.info('Uploading schema file to GCS.') <add> self._upload_to_gcs(schema_file) <add> schema_file['file_handle'].close() <ide> <del> # Flush all files before uploading <del> for file_handle in files_to_upload.values(): <del> file_handle.flush() <add> counter = 0 <add> self.log.info('Writing local data files') <add> for file_to_upload in self._write_local_data_files(cursor): <add> # Flush file before uploading <add> file_to_upload['file_handle'].flush() <ide> <del> self._upload_to_gcs(files_to_upload) <add> self.log.info('Uploading chunk file #%d to GCS.', counter) <add> self._upload_to_gcs(file_to_upload) <ide> <del> # Close all temp file handles. <del> for file_handle in files_to_upload.values(): <del> file_handle.close() <add> self.log.info('Removing local file') <add> file_to_upload['file_handle'].close() <add> counter += 1 <ide> <ide> # Close all sessions and connection associated with this Cassandra cluster <ide> hook.shutdown_cluster() <ide> def _write_local_data_files(self, cursor): <ide> contain the data for the GCS objects. <ide> """ <ide> file_no = 0 <add> <ide> tmp_file_handle = NamedTemporaryFile(delete=True) <del> tmp_file_handles = {self.filename.format(file_no): tmp_file_handle} <add> file_to_upload = { <add> 'file_name': self.filename.format(file_no), <add> 'file_handle': tmp_file_handle, <add> } <ide> for row in cursor: <ide> row_dict = self.generate_data_dict(row._fields, row) <ide> content = json.dumps(row_dict).encode('utf-8') <ide> def _write_local_data_files(self, cursor): <ide> <ide> if tmp_file_handle.tell() >= self.approx_max_file_size_bytes: <ide> file_no += 1 <del> tmp_file_handle = NamedTemporaryFile(delete=True) <del> tmp_file_handles[self.filename.format(file_no)] = tmp_file_handle <ide> <del> return tmp_file_handles <add> yield file_to_upload <add> tmp_file_handle = NamedTemporaryFile(delete=True) <add> file_to_upload = { <add> 'file_name': self.filename.format(file_no), <add> 'file_handle': tmp_file_handle, <add> } <add> yield file_to_upload <ide> <ide> def _write_local_schema_file(self, cursor): <ide> """ <ide> def _write_local_schema_file(self, cursor): <ide> json_serialized_schema = json.dumps(schema).encode('utf-8') <ide> <ide> tmp_schema_file_handle.write(json_serialized_schema) <del> return {self.schema_filename: tmp_schema_file_handle} <del> <del> def _upload_to_gcs(self, files_to_upload: Dict[str, Any]): <add> schema_file_to_upload = { <add> 'file_name': self.schema_filename, <add> 'file_handle': tmp_schema_file_handle, <add> } <add> return schema_file_to_upload <add> <add> def _upload_to_gcs(self, file_to_upload): <add> """Upload a file (data split or schema .json file) to Google Cloud Storage.""" <ide> hook = GCSHook( <ide> gcp_conn_id=self.gcp_conn_id, <ide> delegate_to=self.delegate_to, <ide> impersonation_chain=self.impersonation_chain, <ide> ) <del> for obj, tmp_file_handle in files_to_upload.items(): <del> hook.upload( <del> bucket_name=self.bucket, <del> object_name=obj, <del> filename=tmp_file_handle.name, <del> mime_type='application/json', <del> gzip=self.gzip, <del> ) <add> hook.upload( <add> bucket_name=self.bucket, <add> object_name=file_to_upload.get('file_name'), <add> filename=file_to_upload.get('file_handle').name, <add> mime_type='application/json', <add> gzip=self.gzip, <add> ) <ide> <ide> @classmethod <ide> def generate_data_dict(cls, names: Iterable[str], values: Any) -> Dict[str, Any]: <ide><path>airflow/providers/google/cloud/transfers/sql_to_gcs.py <ide> def execute(self, context: 'Context'): <ide> self.log.info("Executing query") <ide> cursor = self.query() <ide> <del> self.log.info("Writing local data files") <del> files_to_upload = self._write_local_data_files(cursor) <ide> # If a schema is set, create a BQ schema JSON file. <ide> if self.schema_filename: <del> self.log.info("Writing local schema file") <del> files_to_upload.append(self._write_local_schema_file(cursor)) <add> self.log.info('Writing local schema file') <add> schema_file = self._write_local_schema_file(cursor) <ide> <del> # Flush all files before uploading <del> for tmp_file in files_to_upload: <del> tmp_file['file_handle'].flush() <add> # Flush file before uploading <add> schema_file['file_handle'].flush() <ide> <del> self.log.info("Uploading %d files to GCS.", len(files_to_upload)) <del> self._upload_to_gcs(files_to_upload) <add> self.log.info('Uploading schema file to GCS.') <add> self._upload_to_gcs(schema_file) <add> schema_file['file_handle'].close() <ide> <del> self.log.info("Removing local files") <del> # Close all temp file handles. <del> for tmp_file in files_to_upload: <del> tmp_file['file_handle'].close() <add> counter = 0 <add> self.log.info('Writing local data files') <add> for file_to_upload in self._write_local_data_files(cursor): <add> # Flush file before uploading <add> file_to_upload['file_handle'].flush() <add> <add> self.log.info('Uploading chunk file #%d to GCS.', counter) <add> self._upload_to_gcs(file_to_upload) <add> <add> self.log.info('Removing local file') <add> file_to_upload['file_handle'].close() <add> counter += 1 <ide> <ide> def convert_types(self, schema, col_type_dict, row) -> list: <ide> """Convert values from DBAPI to output-friendly formats.""" <ide> def _write_local_data_files(self, cursor): <ide> file_mime_type = 'application/octet-stream' <ide> else: <ide> file_mime_type = 'application/json' <del> files_to_upload = [ <del> { <del> 'file_name': self.filename.format(file_no), <del> 'file_handle': tmp_file_handle, <del> 'file_mime_type': file_mime_type, <del> } <del> ] <del> self.log.info("Current file count: %d", len(files_to_upload)) <add> file_to_upload = { <add> 'file_name': self.filename.format(file_no), <add> 'file_handle': tmp_file_handle, <add> 'file_mime_type': file_mime_type, <add> } <ide> <ide> if self.export_format == 'csv': <ide> csv_writer = self._configure_csv_file(tmp_file_handle, schema) <ide> def _write_local_data_files(self, cursor): <ide> if tmp_file_handle.tell() >= self.approx_max_file_size_bytes: <ide> file_no += 1 <ide> <add> if self.export_format == 'parquet': <add> parquet_writer.close() <add> yield file_to_upload <ide> tmp_file_handle = NamedTemporaryFile(delete=True) <del> files_to_upload.append( <del> { <del> 'file_name': self.filename.format(file_no), <del> 'file_handle': tmp_file_handle, <del> 'file_mime_type': file_mime_type, <del> } <del> ) <del> self.log.info("Current file count: %d", len(files_to_upload)) <add> file_to_upload = { <add> 'file_name': self.filename.format(file_no), <add> 'file_handle': tmp_file_handle, <add> 'file_mime_type': file_mime_type, <add> } <ide> if self.export_format == 'csv': <ide> csv_writer = self._configure_csv_file(tmp_file_handle, schema) <ide> if self.export_format == 'parquet': <ide> parquet_writer = self._configure_parquet_file(tmp_file_handle, parquet_schema) <del> return files_to_upload <add> if self.export_format == 'parquet': <add> parquet_writer.close() <add> yield file_to_upload <ide> <ide> def _configure_csv_file(self, file_handle, schema): <ide> """Configure a csv writer with the file_handle and write schema <ide> def _write_local_schema_file(self, cursor): <ide> } <ide> return schema_file_to_upload <ide> <del> def _upload_to_gcs(self, files_to_upload): <del> """ <del> Upload all of the file splits (and optionally the schema .json file) to <del> Google Cloud Storage. <del> """ <add> def _upload_to_gcs(self, file_to_upload): <add> """Upload a file (data split or schema .json file) to Google Cloud Storage.""" <ide> hook = GCSHook( <ide> gcp_conn_id=self.gcp_conn_id, <ide> delegate_to=self.delegate_to, <ide> impersonation_chain=self.impersonation_chain, <ide> ) <del> for tmp_file in files_to_upload: <del> hook.upload( <del> self.bucket, <del> tmp_file.get('file_name'), <del> tmp_file.get('file_handle').name, <del> mime_type=tmp_file.get('file_mime_type'), <del> gzip=self.gzip if tmp_file.get('file_name') != self.schema_filename else False, <del> ) <add> hook.upload( <add> self.bucket, <add> file_to_upload.get('file_name'), <add> file_to_upload.get('file_handle').name, <add> mime_type=file_to_upload.get('file_mime_type'), <add> gzip=self.gzip if file_to_upload.get('file_name') != self.schema_filename else False, <add> ) <ide><path>tests/providers/google/cloud/transfers/test_sql_to_gcs.py <ide> <ide> SQL = "SELECT * FROM test_table" <ide> BUCKET = "TEST-BUCKET-1" <del>FILENAME = "test_results.csv" <add>FILENAME = "test_results_{}.csv" <ide> TASK_ID = "TEST_TASK_ID" <ide> SCHEMA = [ <ide> {"name": "column_a", "type": "3"}, <ide> def test_exec(self, mock_convert_type, mock_query, mock_upload, mock_writerow, m <ide> ] <ide> ) <ide> mock_flush.assert_has_calls([mock.call(), mock.call(), mock.call(), mock.call(), mock.call()]) <del> csv_call = mock.call(BUCKET, FILENAME, TMP_FILE_NAME, mime_type='text/csv', gzip=True) <add> csv_calls = [] <add> for i in range(0, 3): <add> csv_calls.append( <add> mock.call(BUCKET, FILENAME.format(i), TMP_FILE_NAME, mime_type='text/csv', gzip=True) <add> ) <ide> json_call = mock.call(BUCKET, SCHEMA_FILE, TMP_FILE_NAME, mime_type=APP_JSON, gzip=False) <del> upload_calls = [csv_call, csv_call, csv_call, json_call] <add> upload_calls = [json_call, csv_calls[0], csv_calls[1], csv_calls[2]] <ide> mock_upload.assert_has_calls(upload_calls) <ide> mock_close.assert_has_calls([mock.call(), mock.call(), mock.call(), mock.call(), mock.call()]) <ide> <ide> def test_exec(self, mock_convert_type, mock_query, mock_upload, mock_writerow, m <ide> ] <ide> ) <ide> mock_flush.assert_called_once() <del> mock_upload.assert_called_once_with(BUCKET, FILENAME, TMP_FILE_NAME, mime_type=APP_JSON, gzip=False) <add> mock_upload.assert_called_once_with( <add> BUCKET, FILENAME.format(0), TMP_FILE_NAME, mime_type=APP_JSON, gzip=False <add> ) <ide> mock_close.assert_called_once() <ide> <ide> mock_query.reset_mock() <ide> def test_exec(self, mock_convert_type, mock_query, mock_upload, mock_writerow, m <ide> mock_query.assert_called_once() <ide> mock_flush.assert_called_once() <ide> mock_upload.assert_called_once_with( <del> BUCKET, FILENAME, TMP_FILE_NAME, mime_type='application/octet-stream', gzip=False <add> BUCKET, FILENAME.format(0), TMP_FILE_NAME, mime_type='application/octet-stream', gzip=False <ide> ) <ide> mock_close.assert_called_once() <ide> <ide> def test__write_local_data_files_csv(self): <ide> cursor.description = CURSOR_DESCRIPTION <ide> <ide> files = op._write_local_data_files(cursor) <del> file = files[0]['file_handle'] <add> file = next(files)['file_handle'] <ide> file.flush() <ide> df = pd.read_csv(file.name) <ide> assert df.equals(OUTPUT_DF) <ide> def test__write_local_data_files_json(self): <ide> cursor.description = CURSOR_DESCRIPTION <ide> <ide> files = op._write_local_data_files(cursor) <del> file = files[0]['file_handle'] <add> file = next(files)['file_handle'] <ide> file.flush() <ide> df = pd.read_json(file.name, orient='records', lines=True) <ide> assert df.equals(OUTPUT_DF) <ide> def test__write_local_data_files_parquet(self): <ide> cursor.description = CURSOR_DESCRIPTION <ide> <ide> files = op._write_local_data_files(cursor) <del> file = files[0]['file_handle'] <add> file = next(files)['file_handle'] <ide> file.flush() <ide> df = pd.read_parquet(file.name) <ide> assert df.equals(OUTPUT_DF)
3
Go
Go
add a test case for expose ports order
1e7ba09b60aa0bc527dc7e0159071a6d47796de4
<ide><path>integration-cli/docker_cli_build_test.go <ide> func TestBuildExpose(t *testing.T) { <ide> logDone("build - expose") <ide> } <ide> <add>func TestBuildExposeOrder(t *testing.T) { <add> buildID := func(name, exposed string) string { <add> _, err := buildImage(name, fmt.Sprintf(`FROM scratch <add> EXPOSE %s`, exposed), true) <add> if err != nil { <add> t.Fatal(err) <add> } <add> id, err := inspectField(name, "Id") <add> if err != nil { <add> t.Fatal(err) <add> } <add> return id <add> } <add> <add> id1 := buildID("testbuildexpose1", "80 2375") <add> id2 := buildID("testbuildexpose2", "2375 80") <add> defer deleteImages("testbuildexpose1", "testbuildexpose2") <add> if id1 != id2 { <add> t.Errorf("EXPOSE should invalidate the cache only when ports actually changed") <add> } <add> logDone("build - expose order") <add>} <add> <ide> func TestBuildEmptyEntrypointInheritance(t *testing.T) { <ide> name := "testbuildentrypointinheritance" <ide> name2 := "testbuildentrypointinheritance2"
1
PHP
PHP
remove unnecessary code
73695d9766ff341906664c0f101e85189915a516
<ide><path>tests/Database/DatabaseEloquentMorphToTest.php <ide> protected function getRelationAssociate($parent) <ide> public function getRelation($parent = null, $builder = null) <ide> { <ide> $builder = $builder ?: m::mock('Illuminate\Database\Eloquent\Builder'); <del> $builder->shouldReceive('toBase')->andReturn($builder); <del> $builder->shouldReceive('removedScopes')->andReturn([]); <del> $builder->shouldReceive('withoutGlobalScopes')->with([])->andReturn($builder); <del> $builder->shouldReceive('getRawBindings')->andReturn([ <del> 'select' => [], <del> 'join' => [], <del> 'where' => [], <del> 'having' => [], <del> 'order' => [], <del> 'union' => [], <del> ]); <ide> $builder->shouldReceive('where')->with('relation.id', '=', 'foreign.value'); <ide> $related = m::mock('Illuminate\Database\Eloquent\Model'); <ide> $related->shouldReceive('getKeyName')->andReturn('id'); <ide><path>tests/Database/DatabaseEloquentSoftDeletesIntegrationTest.php <ide> <ide> use Carbon\Carbon; <ide> use Illuminate\Database\Connection; <del>use Illuminate\Database\Eloquent\SoftDeletingScope; <ide> use Illuminate\Pagination\Paginator; <ide> use Illuminate\Database\Query\Builder; <ide> use Illuminate\Database\Eloquent\SoftDeletes; <ide> use Illuminate\Database\Capsule\Manager as DB; <add>use Illuminate\Database\Eloquent\SoftDeletingScope; <ide> use Illuminate\Database\Eloquent\Model as Eloquent; <ide> <ide> class DatabaseEloquentSoftDeletesIntegrationTest extends PHPUnit_Framework_TestCase
2
Javascript
Javascript
replace opacity console error with warning
64d5da775408194f7b0bad551f5b6292136ad081
<ide><path>Libraries/Animated/src/AnimatedImplementation.js <ide> function createAnimatedComponent(Component: any): any { <ide> <ide> for (var key in ViewStylePropTypes) { <ide> if (!Component.propTypes[key] && props[key] !== undefined) { <del> console.error( <add> console.warn( <ide> 'You are setting the style `{ ' + key + ': ... }` as a prop. You ' + <ide> 'should nest it in a style object. ' + <ide> 'E.g. `{ style: { ' + key + ': ... } }`'
1
Ruby
Ruby
remove unused debug_routes
18bf7b421d55c60029289edef1df409a58d021e4
<ide><path>actionpack/lib/action_controller/base.rb <ide> class Base <ide> @@consider_all_requests_local = true <ide> cattr_accessor :consider_all_requests_local <ide> <del> # Enable or disable the collection of failure information for RoutingErrors. <del> # This information can be extremely useful when tweaking custom routes, but is <del> # pointless once routes have been tested and verified. <del> @@debug_routes = true <del> cattr_accessor :debug_routes <del> <ide> # Indicates whether to allow concurrent action processing. Your <ide> # controller actions and any other code they call must also behave well <ide> # when called from concurrent threads. Turned off by default.
1
Ruby
Ruby
define default prefix constants
8ff7601a92b9200c660706d60e04aa63200baa73
<ide><path>Library/Homebrew/dev-cmd/bottle.rb <ide> <% if !root_url.start_with?(HOMEBREW_BOTTLE_DEFAULT_DOMAIN) %> <ide> root_url "<%= root_url %>" <ide> <% end %> <del> <% if ![Homebrew::DEFAULT_PREFIX, "/usr/local"].include?(prefix) %> <add> <% if ![HOMEBREW_DEFAULT_PREFIX, LINUXBREW_DEFAULT_PREFIX].include?(prefix) %> <ide> prefix "<%= prefix %>" <ide> <% end %> <ide> <% if cellar.is_a? Symbol %> <ide><path>Library/Homebrew/global.rb <ide> HOMEBREW_BOTTLE_DEFAULT_DOMAIN = ENV["HOMEBREW_BOTTLE_DEFAULT_DOMAIN"] <ide> HOMEBREW_BOTTLE_DOMAIN = ENV["HOMEBREW_BOTTLE_DOMAIN"] <ide> <add>HOMEBREW_DEFAULT_PREFIX = "/usr/local" <add>LINUXBREW_DEFAULT_PREFIX = "/home/linuxbrew/.linuxbrew" <add> <ide> require "fileutils" <ide> require "os" <ide> require "os/global" <ide> <ide> module Homebrew <ide> extend FileUtils <ide> <del> DEFAULT_PREFIX ||= "/usr/local" <add> DEFAULT_PREFIX ||= HOMEBREW_DEFAULT_PREFIX <ide> DEFAULT_CELLAR = "#{DEFAULT_PREFIX}/Cellar" <ide> DEFAULT_REPOSITORY = "#{DEFAULT_PREFIX}/Homebrew" <ide> <ide><path>Library/Homebrew/os/linux/global.rb <ide> <ide> module Homebrew <ide> DEFAULT_PREFIX ||= if ENV["HOMEBREW_FORCE_HOMEBREW_ON_LINUX"] <del> "/usr/local" <add> HOMEBREW_DEFAULT_PREFIX <ide> else <del> "/home/linuxbrew/.linuxbrew" <add> LINUXBREW_DEFAULT_PREFIX <ide> end.freeze <ide> end
3
PHP
PHP
fix negative validation for pagination
2c76a733715b8754d8752658f743032947cf746c
<ide><path>src/Illuminate/Database/Eloquent/Builder.php <ide> namespace Illuminate\Database\Eloquent; <ide> <ide> use Closure; <add>use InvalidArgumentException; <ide> use Illuminate\Support\Arr; <ide> use Illuminate\Support\Str; <ide> use Illuminate\Pagination\Paginator; <ide> public function lists($column, $key = null) <ide> * @param string $pageName <ide> * @param int|null $page <ide> * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator <add> * <add> * @throws InvalidArgumentException <ide> */ <ide> public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null) <ide> { <add> if( $perPage <= 0) { <add> throw new InvalidArgumentException("Negative values can't be used to query results"); <add> } <add> <ide> $total = $this->query->getCountForPagination(); <ide> <ide> $this->query->forPage( <ide> public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', <ide> */ <ide> public function simplePaginate($perPage = null, $columns = ['*'], $pageName = 'page') <ide> { <add> <add> <ide> $page = Paginator::resolveCurrentPage($pageName); <ide> <ide> $perPage = $perPage ?: $this->model->getPerPage();
1
Java
Java
standardize error objects for promises
a10b4d8c479b2c21dffb0a2bbc76435b7ebfa009
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/Promise.java <ide> public interface Promise { <ide> void resolve(Object value); <ide> void reject(Throwable reason); <add> @Deprecated <ide> void reject(String reason); <add> void reject(String code, Throwable extra); <add> void reject(String code, String reason, Throwable extra); <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/PromiseImpl.java <ide> import javax.annotation.Nullable; <ide> <ide> public class PromiseImpl implements Promise { <add> <add> private static final String DEFAULT_ERROR = "EUNSPECIFIED"; <add> <ide> private @Nullable Callback mResolve; <ide> private @Nullable Callback mReject; <ide> <ide> public void resolve(Object value) { <ide> <ide> @Override <ide> public void reject(Throwable reason) { <del> reject(reason.getMessage()); <add> reject(DEFAULT_ERROR, reason.getMessage(), reason); <ide> } <ide> <ide> @Override <add> @Deprecated <ide> public void reject(String reason) { <add> reject(DEFAULT_ERROR, reason, null); <add> } <add> <add> @Override <add> public void reject(String code, Throwable extra) { <add> reject(code, extra.getMessage(), extra); <add> } <add> <add> @Override <add> public void reject(String code, String reason, Throwable extra) { <ide> if (mReject != null) { <add> if (code == null) { <add> code = DEFAULT_ERROR; <add> } <ide> // The JavaScript side expects a map with at least the error message. <ide> // It is possible to expose all kind of information. It will be available on the JS <ide> // error instance. <del> // TODO(8850038): add more useful information, e.g. the native stack trace. <ide> WritableNativeMap errorInfo = new WritableNativeMap(); <add> errorInfo.putString("code", code); <ide> errorInfo.putString("message", reason); <add> // TODO(8850038): add the stack trace info in, need to figure out way to serialize that <ide> mReject.invoke(errorInfo); <ide> } <ide> }
2
Ruby
Ruby
shorten jenkins env sha-1s
1856f8eadf68cb69195dac95ac79857485789b74
<ide><path>Library/Contributions/cmd/brew-test-bot.rb <ide> def git arguments <ide> end <ide> <ide> def download <add> def shorten_revision revision <add> git("rev-parse --short #{revision}").strip <add> end <add> <ide> def current_sha1 <del> git('rev-parse --short HEAD').strip <add> shorten_revision 'HEAD' <ide> end <ide> <ide> def current_branch <ide> def current_branch <ide> <ide> # Use Jenkins environment variables if present. <ide> if ENV['GIT_PREVIOUS_COMMIT'] and ENV['GIT_COMMIT'] <del> diff_start_sha1 = ENV['GIT_PREVIOUS_COMMIT'] <del> diff_end_sha1 = ENV['GIT_COMMIT'] <add> diff_start_sha1 = shorten_revision ENV['GIT_PREVIOUS_COMMIT'] <add> diff_end_sha1 = shorten_revision ENV['GIT_COMMIT'] <ide> test "brew update" if current_branch == "master" <ide> elsif @hash or @url <ide> diff_start_sha1 = current_sha1
1
PHP
PHP
remove alias loading that isn't necessary
cb913ead92d57fa5bdf09acf89f1d985466fe624
<ide><path>src/Http/ActionDispatcher.php <ide> public function __construct($factory = null, $eventManager = null, array $filter <ide> $this->addFilter($filter); <ide> } <ide> $this->factory = $factory ?: new ControllerFactory(); <del> <del> // Force aliases to be autoloaded. <del> class_exists('Cake\Network\Request'); <ide> } <ide> <ide> /**
1
Ruby
Ruby
use full name in verbose
d3788c58efbae7c841faeb89a3eea539862245f7
<ide><path>Library/Homebrew/cmd/outdated.rb <ide> def print_outdated(formulae) <ide> end <ide> <ide> outdated_versions = outdated_kegs. <del> group_by(&:name). <del> sort_by(&:first). <del> map { |name, kegs| "#{name} (#{kegs.map(&:version) * ", "})" } * ", " <add> group_by { |keg| Formulary.from_keg(keg) }. <add> sort_by { |formula, kegs| formula.full_name }. <add> map do |formula, kegs| <add> "#{formula.full_name} (#{kegs.map(&:version) * ", "})" <add> end * ", " <ide> <ide> puts "#{outdated_versions} < #{current_version}" <ide> else
1
Python
Python
handle more expr warnings
04585856537ccf802d881943235205d95b59527e
<ide><path>numpy/f2py/symbolic.py <ide> def _pairs_add(d, k, v): <ide> del d[k] <ide> <ide> <add>class ExprWarning(warnings.UserWarning): <add> pass <add> <add> <add>def warn(message): <add> warnings.warn(message, ExprWarning, stacklevel=2) <add> <add> <ide> class Expr: <ide> """Represents a Fortran expression as a op-data pair. <ide> <ide> def __getitem__(self, index): <ide> if not isinstance(index, tuple): <ide> index = index, <ide> if len(index) > 1: <del> warnings.warn( <del> f'C-index should be a single expression but got `{index}`', <del> category=warnings.SyntaxWarning, <del> stacklevel=1) <add> warn(f'C-index should be a single expression but got `{index}`') <ide> return Expr(Op.INDEXING, (self,) + index) <ide> <ide> def substitute(self, symbols_map): <ide> def substitute(self, symbols_map): <ide> else: <ide> r += term.substitute(symbols_map) * coeff <ide> if r is None: <del> warnings.warn('substitute: empty TERMS expression interpreted' <del> ' as int-literal 0') <add> warn('substitute: empty TERMS expression interpreted as' <add> ' int-literal 0') <ide> return as_number(0) <ide> return r <ide> if self.op is Op.FACTORS: <ide> def substitute(self, symbols_map): <ide> else: <ide> r *= base.substitute(symbols_map) ** exponent <ide> if r is None: <del> warnings.warn( <del> 'substitute: empty FACTORS expression interpreted' <del> ' as int-literal 1') <add> warn('substitute: empty FACTORS expression interpreted' <add> ' as int-literal 1') <ide> return as_number(1) <ide> return r <ide> if self.op is Op.APPLY: <ide> def _fromstring_worker(s, dummy=None): <ide> # f2py special dummy name <ide> return as_symbol(r) <ide> <del> warnings.warn(f'fromstring: treating {r!r} as symbol') <add> warn(f'fromstring: treating {r!r} as symbol') <ide> return as_symbol(r)
1
Javascript
Javascript
send os version to the autoupdate endpoint
3a4fed4201247fb85ea30bad9d89394a8206df78
<ide><path>src/main-process/auto-update-manager.js <ide> const { EventEmitter } = require('events'); <add>const os = require('os'); <ide> const path = require('path'); <ide> <ide> const IdleState = 'idle'; <ide> module.exports = class AutoUpdateManager extends EventEmitter { <ide> initialize() { <ide> if (process.platform === 'win32') { <ide> const archSuffix = process.arch === 'ia32' ? '' : `-${process.arch}`; <del> this.feedUrl = `${ <del> this.updateUrlPrefix <del> }/api/updates${archSuffix}?version=${this.version}`; <add> this.feedUrl = <add> this.updateUrlPrefix + <add> `/api/updates${archSuffix}?version=${this.version}&os_version=${ <add> os.release <add> }`; <ide> autoUpdater = require('./auto-updater-win32'); <ide> } else { <del> this.feedUrl = `${this.updateUrlPrefix}/api/updates?version=${ <del> this.version <del> }`; <add> this.feedUrl = <add> this.updateUrlPrefix + <add> `/api/updates?version=${this.version}&os_version=${os.release}`; <ide> ({ autoUpdater } = require('electron')); <ide> } <ide>
1
Javascript
Javascript
remove newline in tictactoe example
8f50ace8b3a6439fec63ea5ed8642d290c843cfd
<ide><path>Examples/TicTacToe/TicTacToeApp.js <ide> class Board { <ide> } <ide> } <ide> } <del> <ide> return this.winner() === null; <ide> } <ide> }
1
Text
Text
fix a typo in the documentation
7af469a605a90260951817bc1e8e370fb28b897e
<ide><path>doc/api/deprecations.md <ide> to the `constants` property exposed by the relevant module. For instance, <ide> Type: End-of-life <ide> <ide> Use of the [`crypto.pbkdf2()`][] API without specifying a digest was deprecated <del>in Node.js 6.0 because the method defaulted to using the non-recommendend <add>in Node.js 6.0 because the method defaulted to using the non-recommended <ide> `'SHA1'` digest. Previously, a deprecation warning was printed. Starting in <ide> Node.js 8.0.0, calling `crypto.pbkdf2()` or `crypto.pbkdf2Sync()` with an <ide> undefined `digest` will throw a `TypeError`.
1
Javascript
Javascript
fix random broken test (because its sunday?)
2d8704b3c39f29d82df4a73b4f14d36b775d27d9
<ide><path>src/test/locale/zh-cn.js <ide> test("calendar last week", function (assert) { <ide> } <ide> assert.equal(m.calendar(), m.format('[上]ddd凌晨12点整'), 'Monday - ' + i + ' days next week'); <ide> } <add> // ensure at least one assertion is run <add> assert.equal(42, 42); <ide> }); <ide> <ide> test("calendar all else", function (assert) { <ide> test("strict ordinal parsing", function (assert) { <ide> testMoment = moment(ordinalStr, 'YYYY MM Do', true); <ide> assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); <ide> } <del>}); <ide>\ No newline at end of file <add>});
1
Ruby
Ruby
remove deprecated local_constants
c32ccd837ee37272b5b7abee6afec40cb45491ed
<ide><path>activesupport/lib/active_support/core_ext/module/introspection.rb <ide> def parents <ide> parents << Object unless parents.include? Object <ide> parents <ide> end <del> <del> def local_constants #:nodoc: <del> ActiveSupport::Deprecation.warn(<<-MSG.squish) <del> Module#local_constants is deprecated and will be removed in Rails 5.1. <del> Use Module#constants(false) instead. <del> MSG <del> constants(false) <del> end <ide> end <ide><path>activesupport/test/core_ext/module_test.rb <ide> def test_parents <ide> assert_equal [Yz::Zy, Yz, Object], Yz::Zy::Cd.parents <ide> assert_equal [Yz, Object], Yz::Zy.parents <ide> end <del> <del> def test_local_constants <del> ActiveSupport::Deprecation.silence do <del> assert_equal %w(Constant1 Constant3), Ab.local_constants.sort.map(&:to_s) <del> end <del> end <del> <del> def test_local_constants_is_deprecated <del> assert_deprecated { Ab.local_constants.sort.map(&:to_s) } <del> end <ide> end <ide> <ide> module BarMethodAliaser
2
Mixed
Ruby
parallelize tests only when overhead is justified
ecc5afed30b83650c7b4ccc004143a12a0ef0f88
<ide><path>activesupport/CHANGELOG.md <add>* Parallelize tests only when overhead is justified by the number of them <add> <add> Running tests in parallel adds overhead in terms of database <add> setup and fixture loading. Now, Rails will only parallelize test executions when <add> there are enough tests to make it worth it. <add> <add> This threshold is 50 by default, and is configurable via: <add> <add> ```ruby <add> config.active_support.test_parallelization_minimum_number_of_tests = 100 <add> ``` <add> <add> *Jorge Manrubia* <add> <ide> * OpenSSL constants are now used for Digest computations. <ide> <ide> *Dirkjan Bussink* <ide><path>activesupport/lib/active_support.rb <ide> def self.eager_load! <ide> <ide> cattr_accessor :test_order # :nodoc: <ide> cattr_accessor :test_parallelization_disabled, default: false # :nodoc: <add> cattr_accessor :test_parallelization_minimum_number_of_tests, default: 50 # :nodoc: <ide> <ide> def self.disable_test_parallelization! <ide> self.test_parallelization_disabled = true unless ENV["PARALLEL_WORKERS"] <ide><path>activesupport/lib/active_support/test_case.rb <ide> require "active_support/testing/time_helpers" <ide> require "active_support/testing/file_fixtures" <ide> require "active_support/testing/parallelization" <add>require "active_support/testing/parallelize_executor" <ide> require "concurrent/utility/processor_counter" <ide> <ide> module ActiveSupport <ide> def parallelize(workers: :number_of_processors, with: :processes) <ide> <ide> return if workers <= 1 || ActiveSupport.test_parallelization_disabled <ide> <del> executor = case with <del> when :processes <del> Testing::Parallelization.new(workers) <del> when :threads <del> Minitest::Parallel::Executor.new(workers) <del> else <del> raise ArgumentError, "#{with} is not a supported parallelization executor." <del> end <del> <del> self.lock_threads = false if defined?(self.lock_threads) && with == :threads <del> <del> Minitest.parallel_executor = executor <del> <del> parallelize_me! <add> Minitest.parallel_executor = ActiveSupport::Testing::ParallelizeExecutor.new(size: workers, with: with) <ide> end <ide> <ide> # Set up hook for parallel testing. This can be used if you have multiple <ide><path>activesupport/lib/active_support/testing/parallelization.rb <ide> def <<(work) <ide> @queue_server << work <ide> end <ide> <add> def size <add> @worker_count <add> end <add> <ide> def shutdown <ide> @queue_server.shutdown <ide> @worker_pool.each { |pid| Process.waitpid pid } <ide><path>activesupport/lib/active_support/testing/parallelize_executor.rb <add># frozen_string_literal: true <add> <add>module ActiveSupport <add> module Testing <add> class ParallelizeExecutor # :nodoc: <add> attr_reader :size, :parallelize_with, :parallel_executor <add> <add> def initialize(size:, with:) <add> @size = size <add> @parallelize_with = with <add> @parallel_executor = build_parallel_executor <add> end <add> <add> def start <add> parallelize if should_parallelize? <add> show_execution_info <add> <add> parallel_executor.start if parallelized? <add> end <add> <add> def <<(work) <add> parallel_executor << work if parallelized? <add> end <add> <add> def shutdown <add> parallel_executor.shutdown if parallelized? <add> end <add> <add> private <add> def build_parallel_executor <add> case parallelize_with <add> when :processes <add> Testing::Parallelization.new(size) <add> when :threads <add> ActiveSupport::TestCase.lock_threads = false if defined?(ActiveSupport::TestCase.lock_threads) <add> Minitest::Parallel::Executor.new(size) <add> else <add> raise ArgumentError, "#{parallelize_with} is not a supported parallelization executor." <add> end <add> end <add> <add> def parallelize <add> @parallelized = true <add> Minitest::Test.parallelize_me! <add> end <add> <add> def parallelized? <add> @parallelized <add> end <add> <add> def should_parallelize? <add> ENV["PARALLEL_WORKERS"] || tests_count > ActiveSupport.test_parallelization_minimum_number_of_tests <add> end <add> <add> def tests_count <add> @tests_count ||= Minitest::Runnable.runnables.sum { |runnable| runnable.runnable_methods.size } <add> end <add> <add> def show_execution_info <add> puts execution_info <add> end <add> <add> def execution_info <add> if should_parallelize? <add> "Running #{tests_count} tests in parallel using #{parallel_executor.size} #{parallelize_with}" <add> else <add> "Running #{tests_count} tests in a single process (parallelization threshold is #{ActiveSupport.test_parallelization_minimum_number_of_tests})" <add> end <add> end <add> end <add> end <add>end <ide><path>guides/source/testing.md <ide> end <ide> NOTE: With disabled transactional tests, you have to clean up any data tests <ide> create as changes are not automatically rolled back after the test completes. <ide> <add>### Threshold to parallelize tests <add> <add>Running tests in parallel adds an overhead in terms of database setup and <add>fixture loading. Because of this, Rails won't parallelize executions that involve <add>fewer than 50 tests. You can configure this threshold in your `test.rb`: <add> <add>```ruby <add>config.active_support.test_parallelization_minimum_number_of_tests = 100 <add>``` <add> <ide> The Test Database <ide> ----------------- <ide> <ide><path>railties/test/application/configuration_test.rb <ide> class D < C <ide> assert_equal OpenSSL::Digest::SHA256, ActiveSupport::KeyGenerator.hash_digest_class <ide> end <ide> <add> test "ActiveSupport.test_parallelization_minimum_number_of_tests can be configured via config.active_support.test_parallelization_minimum_number_of_tests" do <add> remove_from_config '.*config\.load_defaults.*\n' <add> <add> app_file "config/environments/test.rb", <<-RUBY <add> Rails.application.configure do <add> config.active_support.test_parallelization_minimum_number_of_tests = 1234 <add> end <add> RUBY <add> <add> app "test" <add> <add> assert_equal 1234, ActiveSupport.test_parallelization_minimum_number_of_tests <add> end <add> <ide> test "custom serializers should be able to set via config.active_job.custom_serializers in an initializer" do <ide> class ::DummySerializer < ActiveJob::Serializers::ObjectSerializer; end <ide> <ide><path>railties/test/application/test_runner_test.rb <ide> def test_run_in_parallel_with_processes <ide> output = run_test_command(file_name) <ide> <ide> assert_match %r{Finished in.*\n2 runs, 2 assertions}, output <add> assert_match %r{Running \d+ tests in parallel using \d+ processes}, output <ide> assert_no_match "create_table(:users)", output <ide> end <ide> <add> def test_avoid_paralleling_when_number_of_tests_if_below_threshold <add> exercise_parallelization_regardless_of_machine_core_count(with: :processes, threshold: 100) <add> <add> file_name = create_parallel_processes_test_file <add> <add> app_file "db/schema.rb", <<-RUBY <add> ActiveRecord::Schema.define(version: 1) do <add> create_table :users do |t| <add> t.string :name <add> end <add> end <add> RUBY <add> <add> output = run_test_command(file_name) <add> <add> assert_match %r{Running \d+ tests in a single process}, output <add> assert_no_match %r{Running \d+ tests in parallel using \d+ processes}, output <add> end <add> <ide> def test_parallel_is_disabled_when_single_file_is_run <ide> exercise_parallelization_regardless_of_machine_core_count(with: :processes, force: false) <ide> <ide> class ParallelTest < ActiveSupport::TestCase <ide> RUBY <ide> end <ide> <del> def exercise_parallelization_regardless_of_machine_core_count(with:, force: true) <add> def exercise_parallelization_regardless_of_machine_core_count(with:, force: true, threshold: 0) <ide> file_content = ERB.new(<<-ERB, trim_mode: "-").result_with_hash(with: with.to_s, force: force) <ide> ENV["RAILS_ENV"] ||= "test" <ide> require_relative "../config/environment" <ide> require "rails/test_help" <ide> <add> ActiveSupport.test_parallelization_minimum_number_of_tests = #{threshold} <add> <ide> class ActiveSupport::TestCase <ide> <%- if force -%> <ide> # Force parallelization, even with single files
8
Text
Text
fix url for group_names action example
8f55cd8db5480ad811cdf431c4ba89f7f8a04a9d
<ide><path>docs/api-guide/routers.md <ide> The following mappings would be generated... <ide> <tr><th>URL</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr> <ide> <tr><td>/users</td><td>GET</td><td>list</td><td>user-list</td></tr> <ide> <tr><td>/users/{username}</td><td>GET</td><td>retrieve</td><td>user-detail</td></tr> <del> <tr><td>/users/{username}/group-names</td><td>GET</td><td>group_names</td><td>user-group-names</td></tr> <add> <tr><td>/users/{username}/group_names</td><td>GET</td><td>group_names</td><td>user-group-names</td></tr> <ide> </table> <ide> <ide> For another example of setting the `.routes` attribute, see the source code for the `SimpleRouter` class.
1
Java
Java
avoid use of `var` declarations
54c7f53eff4b4abf5e288d2e8d3bfc4ff6eecf17
<ide><path>spring-context/src/test/java/org/springframework/context/groovy/GroovyApplicationContextDynamicBeanPropertyTests.java <ide> class GroovyApplicationContextDynamicBeanPropertyTests { <ide> <ide> @Test <ide> void accessDynamicBeanProperties() { <del> var ctx = new GenericGroovyApplicationContext(); <del> ctx.getReader().loadBeanDefinitions("org/springframework/context/groovy/applicationContext.groovy"); <del> ctx.refresh(); <add> GenericGroovyApplicationContext ctx = new GenericGroovyApplicationContext("org/springframework/context/groovy/applicationContext.groovy"); <ide> <del> var framework = ctx.getProperty("framework"); <add> Object framework = ctx.getBean("framework"); <ide> assertThat(framework).as("could not find framework bean").isNotNull(); <ide> assertThat(framework).isEqualTo("Grails"); <ide> <ide> ctx.close(); <ide> } <ide> <ide> @Test <del> void accessingNonExistentBeanViaDynamicProperty() { <del> var ctx = new GenericGroovyApplicationContext(); <del> ctx.getReader().loadBeanDefinitions("org/springframework/context/groovy/applicationContext.groovy"); <del> ctx.refresh(); <add> void accessNonExistentBeanViaDynamicProperty() { <add> GenericGroovyApplicationContext ctx = new GenericGroovyApplicationContext("org/springframework/context/groovy/applicationContext.groovy"); <ide> <ide> assertThatExceptionOfType(NoSuchBeanDefinitionException.class) <del> .isThrownBy(() -> ctx.getProperty("someNonExistentBean")) <add> .isThrownBy(() -> ctx.getBean("someNonExistentBean")) <ide> .withMessage("No bean named 'someNonExistentBean' available"); <ide> <ide> ctx.close(); <ide><path>spring-context/src/test/java/org/springframework/context/groovy/GroovyBeanDefinitionReaderTests.java <ide> class GroovyBeanDefinitionReaderTests { <ide> <ide> @Test <ide> void importSpringXml() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> beans { <ide> void importSpringXml() { <ide> <ide> @Test <ide> void importBeansFromGroovy() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> beans { <ide> void importBeansFromGroovy() { <ide> <ide> @Test <ide> void singletonPropertyOnBeanDefinition() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy; <ide> void singletonPropertyOnBeanDefinition() { <ide> <ide> @Test <ide> void inheritPropertiesFromAbstractBean() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy; <ide> void inheritPropertiesFromAbstractBean() { <ide> <ide> @Test <ide> void contextComponentScanSpringTag() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> beans { <ide> void contextComponentScanSpringTag() { <ide> <ide> @Test <ide> void useSpringNamespaceAsMethod() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy; <ide> void useSpringNamespaceAsMethod() { <ide> @Test <ide> @SuppressWarnings("unchecked") <ide> void useTwoSpringNamespaces() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> TestScope scope = new TestScope(); <ide> appCtx.getBeanFactory().registerScope("test", scope); <ide> <ide> void useTwoSpringNamespaces() { <ide> <ide> @Test <ide> void springAopSupport() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy <ide> void springAopSupport() { <ide> <ide> @Test <ide> void springScopedProxyBean() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> TestScope scope = new TestScope(); <ide> appCtx.getBeanFactory().registerScope("test", scope); <ide> void springScopedProxyBean() { <ide> @Test <ide> @SuppressWarnings("unchecked") <ide> void springNamespaceBean() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy <ide> void springNamespaceBean() { <ide> <ide> @Test <ide> void namedArgumentConstructor() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy <ide> void namedArgumentConstructor() { <ide> <ide> @Test <ide> void abstractBeanDefinition() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy <ide> beans { <ide> void abstractBeanDefinition() { <ide> <ide> @Test <ide> void abstractBeanDefinitionWithClass() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy <ide> beans { <ide> void abstractBeanDefinitionWithClass() { <ide> <ide> @Test <ide> void scopes() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy <ide> beans { <ide> void scopes() { <ide> } <ide> """); <ide> <del> var b1 = appCtx.getBean("myBean"); <del> var b2 = appCtx.getBean("myBean"); <add> Object b1 = appCtx.getBean("myBean"); <add> Object b2 = appCtx.getBean("myBean"); <ide> <ide> assertThat(b1).isNotSameAs(b2); <ide> <ide> void scopes() { <ide> <ide> @Test <ide> void simpleBean() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy <ide> void simpleBean() { <ide> <ide> @Test <ide> void beanWithParentRef() { <del> var parentAppCtx = new GenericApplicationContext(); <add> GenericApplicationContext parentAppCtx = new GenericApplicationContext(); <ide> loadGroovyDsl(parentAppCtx, """ <ide> package org.springframework.context.groovy <ide> beans { <ide> void beanWithParentRef() { <ide> } <ide> """); <ide> <del> var appCtx = new GenericApplicationContext(parentAppCtx); <add> GenericApplicationContext appCtx = new GenericApplicationContext(parentAppCtx); <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy <ide> beans { <ide> void beanWithParentRef() { <ide> <ide> @Test <ide> void withAnonymousInnerBean() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy <ide> void withAnonymousInnerBean() { <ide> <ide> @Test <ide> void withUntypedAnonymousInnerBean() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy <ide> void withUntypedAnonymousInnerBean() { <ide> <ide> @Test <ide> void beanReferences() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy <ide> void beanReferences() { <ide> } <ide> """); <ide> <del> var homer = appCtx.getBean("homer"); <add> Object homer = appCtx.getBean("homer"); <ide> Bean2 marge = (Bean2) appCtx.getBean("marge"); <ide> Bean1 bart = (Bean1) appCtx.getBean("bart"); <ide> Bean1 lisa = (Bean1) appCtx.getBean("lisa"); <ide> void beanReferences() { <ide> <ide> @Test <ide> void beanWithConstructor() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy <ide> void beanWithConstructor() { <ide> <ide> @Test <ide> void beanWithFactoryMethod() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy <ide> void beanWithFactoryMethod() { <ide> <ide> @Test <ide> void beanWithFactoryMethodUsingClosureArgs() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy <ide> void beanWithFactoryMethodUsingClosureArgs() { <ide> <ide> @Test <ide> void beanWithFactoryMethodWithConstructorArgs() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy <ide> void beanWithFactoryMethodWithConstructorArgs() { <ide> <ide> @Test <ide> void getBeanDefinitions() { <del> var appCtx = new GenericApplicationContext(); <del> var reader = new GroovyBeanDefinitionReader(appCtx); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <add> GroovyBeanDefinitionReader reader = new GroovyBeanDefinitionReader(appCtx); <ide> <ide> reader.loadBeanDefinitions(new ByteArrayResource((""" <ide> package org.springframework.context.groovy <ide> void getBeanDefinitions() { <ide> <ide> @Test <ide> void beanWithFactoryBean() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy <ide> void beanWithFactoryBean() { <ide> <ide> @Test <ide> void beanWithFactoryBeanAndMethod() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy <ide> void beanWithFactoryBeanAndMethod() { <ide> <ide> @Test <ide> void loadExternalBeans() { <del> var appCtx = new GenericGroovyApplicationContext("org/springframework/context/groovy/applicationContext.groovy"); <add> GenericApplicationContext appCtx = new GenericGroovyApplicationContext("org/springframework/context/groovy/applicationContext.groovy"); <ide> <ide> assertThat(appCtx.containsBean("foo")).isTrue(); <ide> assertThat(appCtx.getBean("foo")).isEqualTo("hello"); <ide> void loadExternalBeans() { <ide> <ide> @Test <ide> void loadExternalBeansWithExplicitRefresh() { <del> var appCtx = new GenericGroovyApplicationContext(); <del> appCtx.load("org/springframework/context/groovy/applicationContext.groovy"); <del> appCtx.refresh(); <add> GenericGroovyApplicationContext appCtx = new GenericGroovyApplicationContext("org/springframework/context/groovy/applicationContext.groovy"); <ide> <ide> assertThat(appCtx.containsBean("foo")).isTrue(); <ide> assertThat(appCtx.getBean("foo")).isEqualTo("hello"); <ide> void loadExternalBeansWithExplicitRefresh() { <ide> <ide> @Test <ide> void holyGrailWiring() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy <ide> void holyGrailWiring() { <ide> <ide> @Test <ide> void abstractBeanSpecifyingClass() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy <ide> void abstractBeanSpecifyingClass() { <ide> <ide> @Test <ide> void groovyBeanDefinitionReaderWithScript() throws Exception { <del> var script = """ <add> String script = """ <ide> def appCtx = new org.springframework.context.support.GenericGroovyApplicationContext() <ide> appCtx.reader.beans { <ide> quest(org.springframework.context.groovy.HolyGrailQuest) <ide> void groovyBeanDefinitionReaderWithScript() throws Exception { <ide> // test for GRAILS-5057 <ide> @Test <ide> void registerBeans() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy <ide> void registerBeans() { <ide> <ide> @Test <ide> void listOfBeansAsConstructorArg() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy <ide> void listOfBeansAsConstructorArg() { <ide> <ide> @Test <ide> void beanWithListAndMapConstructor() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy <ide> void beanWithListAndMapConstructor() { <ide> <ide> @Test <ide> void anonymousInnerBeanViaBeanMethod() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy <ide> void anonymousInnerBeanViaBeanMethod() { <ide> <ide> @Test <ide> void anonymousInnerBeanViaBeanMethodWithConstructorArgs() { <del> var appCtx = new GenericApplicationContext(); <add> GenericApplicationContext appCtx = new GenericApplicationContext(); <ide> <ide> loadGroovyDsl(appCtx, """ <ide> package org.springframework.context.groovy
2
PHP
PHP
update doc blocks to fqcn
b6e8a99db6dbc60428ca94385bdac1c494592d3e
<ide><path>tests/TestCase/Controller/Component/SecurityComponentTest.php <ide> public function testValidatePostDebugFormat() <ide> /** <ide> * test blackhole will now throw passed exception if debug enabled <ide> * <del> * @expectedException Cake\Controller\Exception\SecurityException <add> * @expectedException \Cake\Controller\Exception\SecurityException <ide> * @expectedExceptionMessage error description <ide> * @return void <ide> */ <ide> public function testValidatePostUnexpectedDebugToken() <ide> * Auth required throws exception token not found <ide> * <ide> * @return void <del> * @expectedException Cake\Controller\Exception\AuthSecurityException <add> * @expectedException \Cake\Controller\Exception\AuthSecurityException <ide> * @expectedExceptionMessage '_Token' was not found in request data. <ide> * @triggers Controller.startup $this->Controller <ide> */ <ide> public function testAuthRequiredThrowsExceptionTokenNotFoundPost() <ide> * Auth required throws exception token not found in Session <ide> * <ide> * @return void <del> * @expectedException Cake\Controller\Exception\AuthSecurityException <add> * @expectedException \Cake\Controller\Exception\AuthSecurityException <ide> * @expectedExceptionMessage '_Token' was not found in session. <ide> * @triggers Controller.startup $this->Controller <ide> */ <ide> public function testAuthRequiredThrowsExceptionTokenNotFoundSession() <ide> * Auth required throws exception controller not allowed <ide> * <ide> * @return void <del> * @expectedException Cake\Controller\Exception\AuthSecurityException <add> * @expectedException \Cake\Controller\Exception\AuthSecurityException <ide> * @expectedExceptionMessage Controller 'NotAllowed' was not found in allowed controllers: 'Allowed, AnotherAllowed'. <ide> * @triggers Controller.startup $this->Controller <ide> */ <ide> public function testAuthRequiredThrowsExceptionControllerNotAllowed() <ide> * Auth required throws exception controller not allowed <ide> * <ide> * @return void <del> * @expectedException Cake\Controller\Exception\AuthSecurityException <add> * @expectedException \Cake\Controller\Exception\AuthSecurityException <ide> * @expectedExceptionMessage Action 'NotAllowed::protected' was not found in allowed actions: 'index, view'. <ide> * @triggers Controller.startup $this->Controller <ide> */ <ide><path>tests/TestCase/Core/ConfigureTest.php <ide> public function testReadOrFail() <ide> /** <ide> * testReadOrFail method <ide> * <del> * @expectedException RuntimeException <add> * @expectedException \RuntimeException <ide> * @expectedExceptionMessage Expected configuration key "This.Key.Does.Not.exist" not found <ide> * @return void <ide> */ <ide><path>tests/TestCase/Database/QueryTest.php <ide> public function testSelectWhereArrayType() <ide> * Tests that passing an empty array type to any where condition will not <ide> * result in a SQL error, but an internal exception <ide> * <del> * @expectedException Cake\Database\Exception <add> * @expectedException \Cake\Database\Exception <ide> * @expectedExceptionMessage Impossible to generate condition with empty list of values for field <ide> * @return void <ide> */ <ide> public function testSelectWhereArrayTypeEmpty() <ide> <ide> /** <ide> * Tests exception message for impossible condition when using an expression <del> * @expectedException Cake\Database\Exception <add> * @expectedException \Cake\Database\Exception <ide> * @expectedExceptionMessage with empty list of values for field (SELECT 1) <ide> * @return void <ide> */ <ide><path>tests/TestCase/Database/Type/BoolTypeTest.php <ide> public function testToDatabase() <ide> /** <ide> * Test converting an array to boolean results in an exception <ide> * <del> * @expectedException InvalidArgumentException <add> * @expectedException \InvalidArgumentException <ide> * @return void <ide> */ <ide> public function testToDatabaseInvalid() <ide> public function testToDatabaseInvalid() <ide> /** <ide> * Tests that passing an invalid value will throw an exception <ide> * <del> * @expectedException InvalidArgumentException <add> * @expectedException \InvalidArgumentException <ide> * @return void <ide> */ <ide> public function testToDatabaseInvalidArray() <ide><path>tests/TestCase/Database/Type/DecimalTypeTest.php <ide> public function testToDatabase() <ide> /** <ide> * Arrays are invalid. <ide> * <del> * @expectedException InvalidArgumentException <add> * @expectedException \InvalidArgumentException <ide> * @return void <ide> */ <ide> public function testToDatabaseInvalid() <ide> public function testMarshalWithLocaleParsing() <ide> /** <ide> * Test that exceptions are raised on invalid parsers. <ide> * <del> * @expectedException RuntimeException <add> * @expectedException \RuntimeException <ide> * @return void <ide> */ <ide> public function testUseLocaleParsingInvalid() <ide><path>tests/TestCase/Database/Type/FloatTypeTest.php <ide> public function testMarshalWithLocaleParsing() <ide> /** <ide> * Test that exceptions are raised on invalid parsers. <ide> * <del> * @expectedException RuntimeException <add> * @expectedException \RuntimeException <ide> * @return void <ide> */ <ide> public function testUseLocaleParsingInvalid() <ide><path>tests/TestCase/Database/Type/IntegerTypeTest.php <ide> public function testToDatabase() <ide> /** <ide> * Tests that passing an invalid value will throw an exception <ide> * <del> * @expectedException InvalidArgumentException <add> * @expectedException \InvalidArgumentException <ide> * @return void <ide> */ <ide> public function testToDatabseInvalid() <ide><path>tests/TestCase/Database/Type/JsonTypeTest.php <ide> public function testToDatabase() <ide> /** <ide> * Tests that passing an invalid value will throw an exception <ide> * <del> * @expectedException InvalidArgumentException <add> * @expectedException \InvalidArgumentException <ide> * @return void <ide> */ <ide> public function testToDatabaseInvalid() <ide><path>tests/TestCase/Database/Type/StringTypeTest.php <ide> public function testToDatabase() <ide> /** <ide> * Tests that passing an invalid value will throw an exception <ide> * <del> * @expectedException InvalidArgumentException <add> * @expectedException \InvalidArgumentException <ide> * @return void <ide> */ <ide> public function testToDatabaseInvalidArray() <ide><path>tests/TestCase/Error/Middleware/ErrorHandlerMiddlewareTest.php <ide> public function testNoErrorResponse() <ide> /** <ide> * Test an invalid rendering class. <ide> * <del> * @expectedException Exception <add> * @expectedException \Exception <ide> * @expectedExceptionMessage The 'TotallyInvalid' renderer class could not be found <ide> */ <ide> public function testInvalidRenderer() <ide><path>tests/TestCase/Http/MiddlewareQueueTest.php <ide> public function testInsertBefore() <ide> /** <ide> * Test insertBefore an invalid classname <ide> * <del> * @expectedException LogicException <add> * @expectedException \LogicException <ide> * @expectedExceptionMessage No middleware matching 'InvalidClassName' could be found. <ide> * @return void <ide> */ <ide><path>tests/TestCase/Http/RunnerTest.php <ide> public function testRunSequencing() <ide> /** <ide> * Test that exceptions bubble up. <ide> * <del> * @expectedException RuntimeException <add> * @expectedException \RuntimeException <ide> * @expectedExceptionMessage A bad thing <ide> */ <ide> public function testRunExceptionInMiddleware() <ide><path>tests/TestCase/Http/ServerTest.php <ide> public function testRunInvalidProtocol() <ide> /** <ide> * Test an application failing to build middleware properly <ide> * <del> * @expectedException RuntimeException <add> * @expectedException \RuntimeException <ide> * @expectedExceptionMessage The application `middleware` method <ide> */ <ide> public function testRunWithApplicationNotMakingMiddleware() <ide> public function testRunMultipleMiddlewareSuccess() <ide> /** <ide> * Test middleware not creating a response. <ide> * <del> * @expectedException RuntimeException <add> * @expectedException \RuntimeException <ide> * @expectedExceptionMessage Application did not create a response. Got "Not a response" instead. <ide> */ <ide> public function testRunMiddlewareNoResponse() <ide><path>tests/TestCase/Mailer/MailerAwareTraitTest.php <ide> public function testGetMailer() <ide> /** <ide> * Test exception thrown by getMailer. <ide> * <del> * @expectedException Cake\Mailer\Exception\MissingMailerException <add> * @expectedException \Cake\Mailer\Exception\MissingMailerException <ide> * @expectedExceptionMessage Mailer class "Test" could not be found. <ide> */ <ide> public function testGetMailerThrowsException() <ide><path>tests/TestCase/Mailer/MailerTest.php <ide> public function testDefaultProfileRestoration() <ide> } <ide> <ide> /** <del> * @expectedException Cake\Mailer\Exception\MissingActionException <add> * @expectedException \Cake\Mailer\Exception\MissingActionException <ide> * @expectedExceptionMessage Mail TestMailer::test() could not be found, or is not accessible. <ide> */ <ide> public function testMissingActionThrowsException() <ide><path>tests/TestCase/ORM/Association/BelongsToManyTest.php <ide> public function emptyProvider() <ide> /** <ide> * Test that saveAssociated() fails on non-empty, non-iterable value <ide> * <del> * @expectedException InvalidArgumentException <add> * @expectedException \InvalidArgumentException <ide> * @expectedExceptionMessage Could not save tags, it cannot be traversed <ide> * @return void <ide> */ <ide><path>tests/TestCase/ORM/AssociationTest.php <ide> public function findPublished($query) <ide> class AssociationTest extends TestCase <ide> { <ide> <add> /** <add> * @var \Cake\ORM\Association|\PHPUnit_Framework_MockObject_MockObject <add> */ <add> public $association; <add> <ide> /** <ide> * Set up <ide> * <ide> public function testProperty() <ide> * Test that warning is shown if property name clashes with table field. <ide> * <ide> * @return void <del> * @expectedException PHPUnit_Framework_Error_Warning <add> * @expectedException \PHPUnit_Framework_Error_Warning <ide> * @expectedExceptionMessageRegExp /^Association property name "foo" clashes with field of same name of table "test"/ <ide> */ <ide> public function testPropertyNameClash() <ide><path>tests/TestCase/ORM/Behavior/TreeBehaviorTest.php <ide> public function testAddRoot() <ide> /** <ide> * Tests making a node its own parent as an existing entity <ide> * <del> * @expectedException RuntimeException <add> * @expectedException \RuntimeException <ide> * @expectedExceptionMessage Cannot set a node's parent as itself <ide> * @return void <ide> */ <ide> public function testReParentSelf() <ide> /** <ide> * Tests making a node its own parent as a new entity. <ide> * <del> * @expectedException RuntimeException <add> * @expectedException \RuntimeException <ide> * @expectedExceptionMessage Cannot set a node's parent as itself <ide> * @return void <ide> */ <ide><path>tests/TestCase/ORM/MarshallerTest.php <ide> public function testOneAccessibleFieldsOption() <ide> /** <ide> * Test one() with an invalid association <ide> * <del> * @expectedException InvalidArgumentException <add> * @expectedException \InvalidArgumentException <ide> * @expectedExceptionMessage Cannot marshal data for "Derp" association. It is not associated with "Articles". <ide> * @return void <ide> */ <ide> public function testMergeWhitelist() <ide> /** <ide> * Test merge() with an invalid association <ide> * <del> * @expectedException InvalidArgumentException <add> * @expectedException \InvalidArgumentException <ide> * @expectedExceptionMessage Cannot marshal data for "Derp" association. It is not associated with "Articles". <ide> * @return void <ide> */ <ide><path>tests/TestCase/ORM/QueryRegressionTest.php <ide> public function testFindMatchingOverwrite2() <ide> * Tests that trying to contain an inexistent association <ide> * throws an exception and not a fatal error. <ide> * <del> * @expectedException InvalidArgumentException <add> * @expectedException \InvalidArgumentException <ide> * @return void <ide> */ <ide> public function testQueryNotFatalError() <ide><path>tests/TestCase/ORM/RulesCheckerIntegrationTest.php <ide> public function testExistsInWithBindingKey() <ide> * Tests existsIn with invalid associations <ide> * <ide> * @group save <del> * @expectedException RuntimeException <add> * @expectedException \RuntimeException <ide> * @expectedExceptionMessage ExistsIn rule for 'author_id' is invalid. 'NotValid' is not associated with 'Cake\ORM\Table'. <ide> * @return void <ide> */ <ide><path>tests/TestCase/ORM/TableRegressionTest.php <ide> public function tearDown() <ide> * in the afterSave callback <ide> * <ide> * @see https://github.com/cakephp/cakephp/issues/9079 <del> * @expectedException Cake\ORM\Exception\RolledbackTransactionException <add> * @expectedException \Cake\ORM\Exception\RolledbackTransactionException <ide> * @return void <ide> */ <ide> public function testAfterSaveRollbackTransaction() <ide><path>tests/TestCase/Routing/Route/RedirectRouteTest.php <ide> public function testParseMiss() <ide> /** <ide> * test the parsing of routes. <ide> * <del> * @expectedException Cake\Routing\Exception\RedirectException <add> * @expectedException \Cake\Routing\Exception\RedirectException <ide> * @expectedExceptionMessage http://localhost/posts <ide> * @expectedExceptionCode 301 <ide> * @return void <ide> public function testParseSimple() <ide> /** <ide> * test the parsing of routes. <ide> * <del> * @expectedException Cake\Routing\Exception\RedirectException <add> * @expectedException \Cake\Routing\Exception\RedirectException <ide> * @expectedExceptionMessage http://localhost/posts <ide> * @expectedExceptionCode 301 <ide> * @return void <ide> public function testParseRedirectOption() <ide> /** <ide> * test the parsing of routes. <ide> * <del> * @expectedException Cake\Routing\Exception\RedirectException <add> * @expectedException \Cake\Routing\Exception\RedirectException <ide> * @expectedExceptionMessage http://localhost/posts <ide> * @expectedExceptionCode 301 <ide> * @return void <ide> public function testParseArray() <ide> /** <ide> * test redirecting to an external url <ide> * <del> * @expectedException Cake\Routing\Exception\RedirectException <add> * @expectedException \Cake\Routing\Exception\RedirectException <ide> * @expectedExceptionMessage http://google.com <ide> * @expectedExceptionCode 301 <ide> * @return void <ide> public function testParseAbsolute() <ide> /** <ide> * test redirecting with a status code <ide> * <del> * @expectedException Cake\Routing\Exception\RedirectException <add> * @expectedException \Cake\Routing\Exception\RedirectException <ide> * @expectedExceptionMessage http://localhost/posts/view <ide> * @expectedExceptionCode 302 <ide> * @return void <ide> public function testParseStatusCode() <ide> /** <ide> * test redirecting with the persist option <ide> * <del> * @expectedException Cake\Routing\Exception\RedirectException <add> * @expectedException \Cake\Routing\Exception\RedirectException <ide> * @expectedExceptionMessage http://localhost/posts/view/2 <ide> * @expectedExceptionCode 301 <ide> * @return void <ide> public function testParsePersist() <ide> /** <ide> * test redirecting with persist and string target URLs <ide> * <del> * @expectedException Cake\Routing\Exception\RedirectException <add> * @expectedException \Cake\Routing\Exception\RedirectException <ide> * @expectedExceptionMessage http://localhost/test <ide> * @expectedExceptionCode 301 <ide> * @return void <ide> public function testParsePersistStringUrl() <ide> /** <ide> * test redirecting with persist and passed args <ide> * <del> * @expectedException Cake\Routing\Exception\RedirectException <add> * @expectedException \Cake\Routing\Exception\RedirectException <ide> * @expectedExceptionMessage http://localhost/tags/add/passme <ide> * @expectedExceptionCode 301 <ide> * @return void <ide> public function testParsePersistPassedArgs() <ide> /** <ide> * test redirecting without persist and passed args <ide> * <del> * @expectedException Cake\Routing\Exception\RedirectException <add> * @expectedException \Cake\Routing\Exception\RedirectException <ide> * @expectedExceptionMessage http://localhost/tags/add <ide> * @expectedExceptionCode 301 <ide> * @return void <ide> public function testParseNoPersistPassedArgs() <ide> /** <ide> * test redirecting with patterns <ide> * <del> * @expectedException Cake\Routing\Exception\RedirectException <add> * @expectedException \Cake\Routing\Exception\RedirectException <ide> * @expectedExceptionMessage http://localhost/tags/add?lang=nl <ide> * @expectedExceptionCode 301 <ide> * @return void <ide> public function testParsePersistPatterns() <ide> /** <ide> * test redirecting with patterns and a routed target <ide> * <del> * @expectedException Cake\Routing\Exception\RedirectException <add> * @expectedException \Cake\Routing\Exception\RedirectException <ide> * @expectedExceptionMessage http://localhost/nl/preferred_controllers <ide> * @expectedExceptionCode 301 <ide> * @return void <ide><path>tests/TestCase/Routing/RouterTest.php <ide> public function setUp() <ide> { <ide> parent::setUp(); <ide> Configure::write('Routing', ['admin' => null, 'prefixes' => []]); <del> Router::fullbaseUrl(''); <add> Router::fullBaseUrl(''); <ide> Configure::write('App.fullBaseUrl', 'http://localhost'); <ide> } <ide> <ide> public function testbaseUrl() <ide> */ <ide> public function testfullBaseURL() <ide> { <del> Router::fullbaseUrl('http://example.com'); <add> Router::fullBaseUrl('http://example.com'); <ide> $this->assertEquals('http://example.com/', Router::url('/', true)); <ide> $this->assertEquals('http://example.com', Configure::read('App.fullBaseUrl')); <ide> Router::fullBaseUrl('https://example.com'); <ide> public function testSetRequestContextPsr() <ide> /** <ide> * Test setting the request context. <ide> * <del> * @expectedException InvalidArgumentException <add> * @expectedException \InvalidArgumentException <ide> * @return void <ide> */ <ide> public function testSetRequestContextInvalid() <ide><path>tests/TestCase/TestSuite/IntegrationTestCaseTest.php <ide> public function testGet() <ide> /** <ide> * Test customizing the app class. <ide> * <del> * @expectedException LogicException <add> * @expectedException \LogicException <ide> * @expectedExceptionMessage Cannot load "TestApp\MissingApp" for use in integration <ide> * @return void <ide> */ <ide> public function testFlashSessionAndCookieAssertsHttpServer() <ide> /** <ide> * Tests the failure message for assertCookieNotSet <ide> * <del> * @expectedException PHPUnit_Framework_AssertionFailedError <add> * @expectedException \PHPUnit_Framework_AssertionFailedError <ide> * @expectedExceptionMessage Cookie 'remember_me' has been set <ide> * @return void <ide> */ <ide> public function testCookieNotSetFailure() <ide> * Tests the failure message for assertCookieNotSet when no <ide> * response whas generated <ide> * <del> * @expectedException PHPUnit_Framework_AssertionFailedError <add> * @expectedException \PHPUnit_Framework_AssertionFailedError <ide> * @expectedExceptionMessage No response set, cannot assert cookies. <ide> * @return void <ide> */ <ide> public function testWithExpectedExceptionHttpServer() <ide> /** <ide> * Test that exceptions being thrown are handled correctly. <ide> * <del> * @expectedException PHPUnit_Framework_AssertionFailedError <add> * @expectedException \PHPUnit_Framework_AssertionFailedError <ide> * @return void <ide> */ <ide> public function testWithUnexpectedException() <ide> public function testSendFileHttpServer() <ide> /** <ide> * Test that assertFile requires a response <ide> * <del> * @expectedException PHPUnit_Framework_AssertionFailedError <add> * @expectedException \PHPUnit_Framework_AssertionFailedError <ide> * @expectedExceptionMessage No response set, cannot assert file <ide> * @return void <ide> */ <ide> public function testAssertFileNoReponse() <ide> /** <ide> * Test that assertFile requires a file <ide> * <del> * @expectedException PHPUnit_Framework_AssertionFailedError <add> * @expectedException \PHPUnit_Framework_AssertionFailedError <ide> * @expectedExceptionMessage No file was sent in this response <ide> * @return void <ide> */ <ide><path>tests/TestCase/Utility/HashTest.php <ide> public function testNumeric() <ide> /** <ide> * Test passing invalid argument type <ide> * <del> * @expectedException InvalidArgumentException <add> * @expectedException \InvalidArgumentException <ide> * @expectedExceptionMessage Invalid data type, must be an array or \ArrayAccess instance. <ide> * @return void <ide> */ <ide><path>tests/TestCase/Validation/ValidatorTest.php <ide> public function testRequirePresenceAsArray() <ide> /** <ide> * Tests the requirePresence failure case <ide> * <del> * @expectedException InvalidArgumentException <add> * @expectedException \InvalidArgumentException <ide> * @return void <ide> */ <ide> public function testRequirePresenceAsArrayFailure() <ide> public function testAllowEmptyAsArray() <ide> /** <ide> * Tests the allowEmpty failure case <ide> * <del> * @expectedException InvalidArgumentException <add> * @expectedException \InvalidArgumentException <ide> * @return void <ide> */ <ide> public function testAllowEmptyAsArrayFailure() <ide> public function testNotEmptyAsArray() <ide> /** <ide> * Tests the notEmpty failure case <ide> * <del> * @expectedException InvalidArgumentException <add> * @expectedException \InvalidArgumentException <ide> * @return void <ide> */ <ide> public function testNotEmptyAsArrayFailure() <ide> public function testLengthBetween() <ide> /** <ide> * Tests the lengthBetween proxy method <ide> * <del> * @expectedException InvalidArgumentException <add> * @expectedException \InvalidArgumentException <ide> * @return void <ide> */ <ide> public function testLengthBetweenFailure() <ide> public function testRange() <ide> /** <ide> * Tests the range failure case <ide> * <del> * @expectedException InvalidArgumentException <add> * @expectedException \InvalidArgumentException <ide> * @return void <ide> */ <ide> public function testRangeFailure() <ide><path>tests/TestCase/View/HelperRegistryTest.php <ide> public function afterRender($viewFile) <ide> class HelperRegistryTest extends TestCase <ide> { <ide> <add> /** <add> * @var \Cake\View\HelperRegistry <add> */ <add> public $Helpers; <add> <ide> /** <ide> * setUp <ide> * <ide> public function testLoadMultipleTimesDefaultConfigValuesWorks() <ide> /** <ide> * Loading a helper with different config, should throw an exception <ide> * <del> * @expectedException RuntimeException <add> * @expectedException \RuntimeException <ide> * @expectedExceptionMessage The "Html" alias has already been loaded with the following <ide> * @return void <ide> */ <ide> public function testLoadMultipleTimesDifferentConfigured() <ide> /** <ide> * Loading a helper with different config, should throw an exception <ide> * <del> * @expectedException RuntimeException <add> * @expectedException \RuntimeException <ide> * @expectedExceptionMessage The "Html" alias has already been loaded with the following <ide> * @return void <ide> */ <ide><path>tests/TestCase/View/StringTemplateTest.php <ide> public function testFormatArrayData() <ide> /** <ide> * Test formatting a missing template. <ide> * <del> * @expectedException RuntimeException <add> * @expectedException \RuntimeException <ide> * @expectedExceptionMessage Cannot find template named 'missing' <ide> * @return void <ide> */ <ide><path>tests/TestCase/View/ViewTest.php <ide> public function testPluginGetTemplate() <ide> * Test that plugin files with absolute file paths are scoped <ide> * to the plugin and do now allow any file path. <ide> * <del> * @expectedException Cake\View\Exception\MissingTemplateException <add> * @expectedException \Cake\View\Exception\MissingTemplateException <ide> * @return void <ide> */ <ide> public function testPluginGetTemplateAbsoluteFail()
30
Javascript
Javascript
fix bug that was crashing heroku
1e427d723c93a3d483627618d95369bedb1489cd
<ide><path>controllers/bonfire.js <ide> var _ = require('lodash'), <del> debug = require('debug')('freecc:cntr:bonfires'), <del> bonfire = require('./../models/bonfire'); <add> debug = require('debug')('freecc:cntr:bonfires'); <add>// bonfire = require('./../models/Bonfire'); <ide> <ide> /** <ide> * Bonfire controller
1
Python
Python
fix identation problems in docs
dbb20ce653c2f70b5a9c5f1f39a2de5eaa9e0257
<ide><path>libcloud/compute/drivers/gce.py <ide> def ex_create_multiple_nodes( <ide> :type description: ``str`` or ``None`` <ide> <ide> :keyword ex_can_ip_forward: Set to ``True`` to allow this node to <del> send/receive non-matching src/dst packets. <add> send/receive non-matching src/dst packets. <ide> :type ex_can_ip_forward: ``bool`` or ``None`` <ide> <ide> :keyword ex_preemptible: Defines whether the instance is preemptible. <del> (If not supplied, the instance will <del> not be preemptible) <add> (If not supplied, the instance will <add> not be preemptible) <ide> :type ex_preemptible: ``bool`` or ``None`` <ide> <ide> :keyword ex_disks_gce_struct: Support for passing in the GCE-specific
1
PHP
PHP
fix another inconsistent type
c4560bfdceda208ed7b5af2e1092345d64e78e57
<ide><path>src/Database/Schema/TableSchema.php <ide> public function getOptions(): array <ide> /** <ide> * {@inheritDoc} <ide> */ <del> public function setTemporary($temporary): TableSchemaInterface <add> public function setTemporary(bool $temporary): TableSchemaInterface <ide> { <ide> $this->_temporary = (bool)$temporary; <ide> <ide><path>src/Database/Schema/TableSchemaInterface.php <ide> public function hasAutoincrement(): bool; <ide> * @param bool $temporary Whether or not the table is to be temporary. <ide> * @return $this <ide> */ <del> public function setTemporary(bool $temporary); <add> public function setTemporary(bool $temporary): self; <ide> <ide> /** <ide> * Gets whether the table is temporary in the database.
2
Python
Python
add traceback in logrecord in ``jsonformatter``
99ec208024933d790272a09a6f20b241410a7df7
<ide><path>airflow/utils/log/json_formatter.py <ide> def usesTime(self): <ide> def format(self, record): <ide> super().format(record) <ide> record_dict = {label: getattr(record, label, None) for label in self.json_fields} <add> if "message" in self.json_fields: <add> msg = record_dict["message"] <add> if record.exc_text: <add> if msg[-1:] != "\n": <add> msg = msg + "\n" <add> msg = msg + record.exc_text <add> if record.stack_info: <add> if msg[-1:] != "\n": <add> msg = msg + "\n" <add> msg = msg + self.formatStack(record.stack_info) <add> record_dict["message"] = msg <ide> merged_record = merge_dicts(record_dict, self.extras) <ide> return json.dumps(merged_record) <ide><path>tests/utils/log/test_json_formatter.py <ide> Module for all tests airflow.utils.log.json_formatter.JSONFormatter <ide> """ <ide> import json <add>import sys <ide> import unittest <ide> from logging import makeLogRecord <ide> <ide> def test_format_with_extras(self): <ide> json_fmt = JSONFormatter(json_fields=["label"], extras={'pod_extra': 'useful_message'}) <ide> # compare as a dicts to not fail on sorting errors <ide> assert json.loads(json_fmt.format(log_record)) == {"label": "value", "pod_extra": "useful_message"} <add> <add> def test_format_with_exception(self): <add> """ <add> Test exception is included in the message when using JSONFormatter <add> """ <add> try: <add> raise RuntimeError("message") <add> except RuntimeError: <add> exc_info = sys.exc_info() <add> <add> log_record = makeLogRecord({"exc_info": exc_info, "message": "Some msg"}) <add> json_fmt = JSONFormatter(json_fields=["message"]) <add> <add> log_fmt = json.loads(json_fmt.format(log_record)) <add> assert "message" in log_fmt <add> assert "Traceback (most recent call last)" in log_fmt["message"] <add> assert 'raise RuntimeError("message")' in log_fmt["message"]
2
Javascript
Javascript
normalize error message indenation and readibility
4d89326368758d8a97a1b97ea4b9fa796325b734
<ide><path>lib/performance/AssetsOverSizeLimitWarning.js <ide> function AssetsOverSizeLimitWarning(assetsOverSizeLimit, compilation) { <ide> return "\n -" + asset.name; <ide> }).join(""); <ide> <del> this.message = "The following assets exceed the recommended size limit.\n" + <add> this.message = "asset size limit: The following assets exceed the recommended size limit.\n" + <ide> "This can impact web performance.\n" + <ide> "Assets: " + assetLists; <ide> } <ide><path>lib/performance/EmittedAssetSizeLimitPlugin.js <ide> EmittedAssetSizeLimitPlugin.prototype.apply = function(compiler) { <ide> } <ide> <ide> if(!hasAsyncChunks) { <del> warnings.push(new Error("EmittedAssetSizeWarning: NoAsyncChunks: " + <add> warnings.push(new Error("webpack performance recommendations: \n" + <ide> "You can limit the size of your bundles by using System.import() or require.ensure to lazy load some parts of your application.\n" + <ide> "For more info visit https://webpack.github.io/docs/code-splitting.html" <ide> )); <ide><path>lib/performance/EntrypointsOverSizeLimitWarning.js <ide> function EntrypointsOverSizeLimitWarning(entrypoints, compilation, formatSizeFn) <ide> }).join(""); <ide> }).join(""); <ide> <del> this.message = "The following Entrypoints combined asset size exceeds the recommended limit. " + <add> this.message = "entrypoint size limit: The following Entrypoints combined asset size exceeds the recommended limit. " + <ide> "This can impact web performance.\n" + <ide> "Entrypoints: \n" + <ide> entrypointList;
3
Java
Java
use set.of() in stringtobooleanconverter
d533eb4a55baa9e03850801c30071af33bb9cbc8
<ide><path>spring-core/src/main/java/org/springframework/core/convert/support/StringToBooleanConverter.java <ide> /* <del> * Copyright 2002-2020 the original author or authors. <add> * Copyright 2002-2022 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> package org.springframework.core.convert.support; <ide> <del>import java.util.HashSet; <ide> import java.util.Set; <ide> <ide> import org.springframework.core.convert.converter.Converter; <ide> import org.springframework.lang.Nullable; <ide> <ide> /** <del> * Converts String to a Boolean. <add> * Converts a String to a Boolean. <ide> * <ide> * @author Keith Donald <ide> * @author Juergen Hoeller <add> * @author Sam Brannen <ide> * @since 3.0 <ide> */ <ide> final class StringToBooleanConverter implements Converter<String, Boolean> { <ide> <del> private static final Set<String> trueValues = new HashSet<>(8); <add> private static final Set<String> trueValues = Set.of("true", "on", "yes", "1"); <ide> <del> private static final Set<String> falseValues = new HashSet<>(8); <del> <del> static { <del> trueValues.add("true"); <del> trueValues.add("on"); <del> trueValues.add("yes"); <del> trueValues.add("1"); <del> <del> falseValues.add("false"); <del> falseValues.add("off"); <del> falseValues.add("no"); <del> falseValues.add("0"); <del> } <add> private static final Set<String> falseValues = Set.of("false", "off", "no", "0"); <ide> <ide> <ide> @Override
1
Python
Python
use assertequal instead
ac8872daa28037759e2e34311c4848a42b270b25
<ide><path>libcloud/test/compute/test_azure.py <ide> def test_locations_returned_successfully(self): <ide> def test_images_returned_successfully(self): <ide> images = self.driver.list_images() <ide> # There should be 215 standard OSImages and one VMImage returned <del> self.assertEquals(len(images), 216) <add> self.assertEqual(len(images), 216) <ide> <ide> def test_images_returned_successfully_filter_by_location(self): <ide> images = self.driver.list_images(location="West US") <del> self.assertEquals(len(images), 207) <add> self.assertEqual(len(images), 207) <ide> <ide> def test_list_nodes_returned_successfully(self): <ide> vmimages = self.driver.list_nodes( <ide> def test_list_nodes_returned_successfully(self): <ide> self.assertEqual(len(vmimages), 2) <ide> <ide> img0 = vmimages[0] <del> self.assertEquals(img0.id, "dc03") <del> self.assertEquals(img0.name, u"dc03") <add> self.assertEqual(img0.id, "dc03") <add> self.assertEqual(img0.name, u"dc03") <ide> self.assertListEqual(img0.public_ips, ["191.235.135.62"]) <ide> self.assertListEqual(img0.private_ips, ["100.92.66.69"]) <del> self.assertEquals(img0.size, None) <del> self.assertEquals(img0.state, 0) <add> self.assertEqual(img0.size, None) <add> self.assertEqual(img0.state, 0) <ide> self.assertTrue(isinstance(img0.extra, dict)) <ide> extra = img0.extra <del> self.assertEquals(extra["instance_size"], u'Small') <del> self.assertEquals(extra["power_state"], u'Started') <del> self.assertEquals(extra["ssh_port"], u'22') <add> self.assertEqual(extra["instance_size"], u'Small') <add> self.assertEqual(extra["power_state"], u'Started') <add> self.assertEqual(extra["ssh_port"], u'22') <ide> <ide> def test_list_nodes_returned_no_deployments(self): <ide> nodes = self.driver.list_nodes(
1
Text
Text
add a section with es5 examples
eee449c5ffa4a0a9c6f918a052257e2d1366d5dc
<ide><path>README.md <ide> Atomic Flux with hot reloading. <ide> - [Demo](#demo) <ide> - [Examples](#examples) <ide> - [Simple Examples](#simple-examples) <add> - [ES5 Examples](#es5-examples) <ide> - [Async and Universal Examples with Routing](#async-and-universal-examples-with-routing) <ide> - [What does it look like?](#what-does-it-look-like) <ide> - [Actions](#actions) <ide> npm install <ide> npm start <ide> ``` <ide> <add>### ES5 Examples <add> <add>If you have not used ES6 before, check out one of these ES5 examples: <add> <add>* [redux-todomvc-es5](https://github.com/insin/redux-todomvc-es5) <add> <ide> ### Async and Universal Examples with Routing <ide> <ide> These async and [universal (aka “isomorphic”)](https://medium.com/@mjackson/universal-javascript-4761051b7ae9) examples using React Router should help you get started:
1
PHP
PHP
add flashnow functionality
2aecef2e625be2e93bc05874feaf24041a8eafab
<ide><path>src/Illuminate/Session/Store.php <ide> public function start() <ide> $this->regenerateToken(); <ide> } <ide> <add> $this->removeFlashNowData(); <add> <ide> return $this->started = true; <ide> } <ide> <ide> public function ageFlashData() <ide> $this->put('flash.new', []); <ide> } <ide> <add> /** <add> * Remove data that was flashed on last request <add> * <add> * @return void <add> */ <add> public function removeFlashNowData() <add> { <add> foreach ($this->get('flash.now', []) as $old) { <add> $this->forget($old); <add> } <add> <add> $this->remove('flash.now'); <add> } <add> <ide> /** <ide> * {@inheritdoc} <ide> */ <ide> public function flash($key, $value) <ide> $this->removeFromOldFlashData([$key]); <ide> } <ide> <add> /** <add> * Flash a key / value pair to the session <add> * for immediate use <add> * <add> * @param string $key <add> * @param mixed $value <add> * @return void <add> */ <add> public function flashNow($key, $value) <add> { <add> $this->put($key, $value); <add> <add> $this->push('flash.now', $key); <add> } <add> <ide> /** <ide> * Flash an input array to the session. <ide> * <ide><path>tests/Session/SessionStoreTest.php <ide> public function testDataFlashing() <ide> $this->assertNull($session->get('foo')); <ide> } <ide> <add> public function testDataFlashingNow() <add> { <add> $session = $this->getSession(); <add> $session->flashNow('foo', 'bar'); <add> $session->flashNow('bar', 0); <add> <add> $this->assertTrue($session->has('foo')); <add> $this->assertEquals('bar', $session->get('foo')); <add> $this->assertEquals(0, $session->get('bar')); <add> <add> $session->removeFlashNowData(); <add> <add> $this->assertFalse($session->has('foo')); <add> $this->assertNull($session->get('foo')); <add> } <add> <ide> public function testDataMergeNewFlashes() <ide> { <ide> $session = $this->getSession();
2
Javascript
Javascript
add callback to watching.prototype.invalidate
af3422c5d6e8d69e34679f99ceb92c56219ed985
<ide><path>lib/Compiler.js <ide> function Watching(compiler, watchOptions, handler) { <ide> this.error = null; <ide> this.stats = null; <ide> this.handler = handler; <add> this.callbacks = []; <ide> if(typeof watchOptions === "number") { <ide> this.watchOptions = { <ide> aggregateTimeout: watchOptions <ide> Watching.prototype._done = function(err, compilation) { <ide> this.handler(this.error, this.stats); <ide> if(!this.error) <ide> this.watch(compilation.fileDependencies, compilation.contextDependencies, compilation.missingDependencies); <add> this.callbacks.forEach(function(cb) { <add> cb(); <add> }); <add> this.callbacks.length = 0; <ide> }; <ide> <ide> Watching.prototype.watch = function(files, dirs, missing) { <ide> Watching.prototype.watch = function(files, dirs, missing) { <ide> }.bind(this)); <ide> }; <ide> <del>Watching.prototype.invalidate = function() { <add>Watching.prototype.invalidate = function(callback) { <add> if(callback) { <add> this.callbacks.push(callback); <add> } <ide> if(this.watcher) { <ide> this.watcher.pause(); <ide> this.watcher = null;
1
Python
Python
fix datacollatorforwholewordmask again
4a53e8e9e405779cc9f01c11c4d866b3fb6738e2
<ide><path>src/transformers/data/data_collator.py <ide> def _collate_batch(examples, tokenizer): <ide> return result <ide> <ide> <add>def tolist(x: Union[List[Any], torch.Tensor]): <add> return x.tolist() if isinstance(x, torch.Tensor) else x <add> <add> <ide> @dataclass <ide> class DataCollatorForLanguageModeling: <ide> """ <ide> def __call__( <ide> mask_labels = [] <ide> for e in examples: <ide> ref_tokens = [] <del> for id in e["input_ids"].tolist(): <add> for id in tolist(e["input_ids"]): <ide> token = self.tokenizer._convert_id_to_token(id) <ide> ref_tokens.append(token) <ide> <ide> # For Chinese tokens, we need extra inf to mark sub-word, e.g [喜,欢]-> [喜,##欢] <ide> if "chinese_ref" in e: <del> ref_pos = e["chinese_ref"].tolist() <add> ref_pos = tolist(e["chinese_ref"]) <ide> len_seq = e["input_ids"].size(0) <ide> for i in range(len_seq): <ide> if i in ref_pos:
1
Javascript
Javascript
use asyncit here too
8f59693d839f11f8f792c4271648d9e83d4541ba
<ide><path>spec/git-repository-async-spec.js <ide> fdescribe('GitRepositoryAsync-js', () => { <ide> }) <ide> <ide> describe('@open(path)', () => { <del> it('repo is null when no repository is found', () => { <del> waitsForPromise(async () => { <del> repo = GitRepositoryAsync.open(path.join(temp.dir, 'nogit.txt')) <del> <del> let threw = false <del> try { <del> await repo.repoPromise <del> } catch(e) { <del> threw = true <del> } <del> <del> expect(threw).toBeTruthy() <del> expect(repo.repo).toBe(null) <del> }) <add> asyncIt('repo is null when no repository is found', async () => { <add> repo = GitRepositoryAsync.open(path.join(temp.dir, 'nogit.txt')) <add> <add> let threw = false <add> try { <add> await repo.repoPromise <add> } catch(e) { <add> threw = true <add> } <add> <add> expect(threw).toBeTruthy() <add> expect(repo.repo).toBe(null) <ide> }) <ide> }) <ide>
1
Ruby
Ruby
fix set_pk_sequence and add a test for it
3dae34e217320324dd0db9953b9ba77c2419ab34
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb <ide> def set_pk_sequence!(table, value, pk = nil, sequence = nil) #:nodoc: <ide> <ide> if pk <ide> if sequence <del> quoted_sequence = quote_column_name(sequence) <add> quoted_sequence = quote_table_name(sequence) <ide> <ide> select_value <<-end_sql, 'SCHEMA' <ide> SELECT setval('#{quoted_sequence}', #{value}) <ide><path>activerecord/test/cases/adapters/postgresql/schema_test.rb <ide> def test_reset_pk_sequence <ide> assert_equal "1", @connection.select_value("SELECT nextval('#{sequence_name}')") <ide> end <ide> <add> def test_set_pk_sequence <add> table_name = "#{SCHEMA_NAME}.#{PK_TABLE_NAME}" <add> _, sequence_name = @connection.pk_and_sequence_for table_name <add> @connection.set_pk_sequence! table_name, 123 <add> assert_equal "124", @connection.select_value("SELECT nextval('#{sequence_name}')") <add> @connection.reset_pk_sequence! table_name <add> end <add> <ide> private <ide> def columns(table_name) <ide> @connection.send(:column_definitions, table_name).map do |name, type, default|
2
Python
Python
fix wildcard imports
3ca611fe48f79518004ab98f2f82713469abc687
<ide><path>spacy/language_data/__init__.py <del>from .abbreviations import * <del>from .emoticons import * <ide> from .punctuation import * <del>from .tag_map import * <del>from .entity_rules import * <del>from .tokenizer_exceptions import * <add>from .tag_map import TAG_MAP <add>from .entity_rules import ENTITY_RULES <add>from .tokenizer_exceptions import BASE_EXCEPTIONS
1
Ruby
Ruby
use stderr for header output
888c38480188ac8b1772e85e636ee33c8c9ed252
<ide><path>Library/Homebrew/dev-cmd/release-notes.rb <ide> def release_notes <ide> end <ide> end <ide> <del> puts "Release notes between #{previous_tag} and #{end_ref}:" <add> $stderr.puts "Release notes between #{previous_tag} and #{end_ref}:" <ide> puts output <ide> end <ide> end
1
Ruby
Ruby
introduce view renderer
b73576138529b1344a38f4e4b16c642f3510d514
<ide><path>actionpack/lib/abstract_controller/rendering.rb <ide> def initialize(*) <ide> # <ide> # Override this method in a module to change the default behavior. <ide> def view_context <del> view_context_class.new(lookup_context, view_assigns, self) <add> view_context_class.new(view_renderer, view_assigns, self) <add> end <add> <add> # Returns an object that is able to render templates. <add> def view_renderer <add> @view_renderer ||= ActionView::Renderer.new(lookup_context, self) <ide> end <ide> <ide> # Normalize arguments, options and then delegates render_to_body and <ide> def render_to_body(options = {}) <ide> # Find and renders a template based on the options given. <ide> # :api: private <ide> def _render_template(options) #:nodoc: <del> view_context.render(options) <add> if options.key?(:partial) <add> view_renderer.render_partial(view_context, options) <add> else <add> view_renderer.render_template(view_context, options) <add> end <ide> end <ide> <ide> # The prefixes used in render "foo" shortcuts. <ide><path>actionpack/lib/action_controller/metal/streaming.rb <ide> def _process_options(options) #:nodoc: <ide> # Call render_to_body if we are streaming instead of usual +render+. <ide> def _render_template(options) #:nodoc: <ide> if options.delete(:stream) <del> Rack::Chunked::Body.new view_context.render_body(options) <add> Rack::Chunked::Body.new view_renderer.render_body(view_context, options) <ide> else <ide> super <ide> end <ide><path>actionpack/lib/action_view/context.rb <ide> module CompiledTemplates #:nodoc: <ide> # The default Action View context is ActionView::Base. <ide> # <ide> # In order to work with ActionController, a Context must just include this module. <add> # The initialization of the variables used by the context (@output_buffer, @view_flow, <add> # and @virtual_path) is responsibility of the object that includes this module. <ide> module Context <ide> include CompiledTemplates <ide> attr_accessor :output_buffer, :view_flow <ide><path>actionpack/lib/action_view/renderer/renderer.rb <ide> def initialize(lookup_context, controller) <ide> @controller = controller <ide> end <ide> <del> def render(context, options = {}, locals = {}, &block) <del> case options <del> when Hash <del> if block_given? <del> _render_partial(context, options.merge(:partial => options[:layout]), &block) <del> elsif options.key?(:partial) <del> _render_partial(context, options) <del> else <del> _render_template(context, options) <del> end <del> else <del> _render_partial(context, :partial => options, :locals => locals) <del> end <del> end <del> <ide> # Render but returns a valid Rack body. If fibers are defined, we return <ide> # a streaming body that renders the template piece by piece. <ide> # <ide> # Note that partials are not supported to be rendered with streaming, <ide> # so in such cases, we just wrap them in an array. <ide> def render_body(context, options) <ide> if options.key?(:partial) <del> [_render_partial(context, options)] <add> [render_partial(context, options)] <ide> else <ide> StreamingTemplateRenderer.new(@lookup_context, @controller).render(context, options) <ide> end <ide> end <ide> <del> private <del> <del> def _render_template(context, options) #:nodoc: <add> # Direct accessor to template rendering. <add> def render_template(context, options) #:nodoc: <ide> _template_renderer.render(context, options) <ide> end <ide> <del> def _template_renderer #:nodoc: <del> @_template_renderer ||= TemplateRenderer.new(@lookup_context, @controller) <add> # Direct access to partial rendering. <add> def render_partial(context, options, &block) #:nodoc: <add> _partial_renderer.render(context, options, block) <ide> end <ide> <del> def _render_partial(context, options, &block) #:nodoc: <del> _partial_renderer.render(context, options, block) <add> private <add> <add> def _template_renderer #:nodoc: <add> @_template_renderer ||= TemplateRenderer.new(@lookup_context, @controller) <ide> end <ide> <ide> def _partial_renderer #:nodoc: <ide><path>actionpack/lib/action_view/rendering.rb <ide> module Rendering <ide> # If no options hash is passed or :update specified, the default is to render a partial and use the second parameter <ide> # as the locals hash. <ide> # def render(options = {}, locals = {}, &block) <del> def render(*args, &block) <del> view_renderer.render(self, *args, &block) <del> end <del> <del> # TODO: This is temporary, but the previous render is sticking. <del> def render_body(*args, &block) <del> view_renderer.render_body(self, *args, &block) <add> def render(options = {}, locals = {}, &block) <add> case options <add> when Hash <add> if block_given? <add> view_renderer.render_partial(self, options.merge(:partial => options[:layout]), &block) <add> elsif options.key?(:partial) <add> view_renderer.render_partial(self, options) <add> else <add> view_renderer.render_template(self, options) <add> end <add> else <add> view_renderer.render_partial(self, :partial => options, :locals => locals) <add> end <ide> end <ide> end <ide> end <ide>\ No newline at end of file
5
Javascript
Javascript
remove debugging output
86523359e466eec6cfefa7549a9843c691927c21
<ide><path>src/animation/AnimationClip.js <ide> THREE.AnimationClip = function ( name, duration, tracks ) { <ide> this.tracks = tracks; <ide> this.duration = duration || 1; <ide> <del> // TODO: maybe only do these on demand, as doing them here could potentially slow down loading <add> // maybe only do these on demand, as doing them here could potentially slow down loading <ide> // but leaving these here during development as this ensures a lot of testing of these functions <ide> this.trim(); <ide> this.optimize(); <ide> THREE.AnimationClip.prototype = { <ide> for( var i = 0; i < this.tracks.length; i ++ ) { <ide> <ide> var track = this.tracks[ i ]; <del> //console.log( 'track', track ); <ide> <ide> this.results[ track.name ] = track.getAt( clipTime ); <ide> <ide> THREE.AnimationClip.prototype = { <ide> }; <ide> <ide> <del>/* <del> "animation" : { <del> "name" : "Action", <del> "fps" : 25, <del> "length" : 2.0, <del> "hierarchy" : [ <del> { <del> "parent" : -1, <del> "keys" : [ <del> { <del> "time":0, <del> "pos" :[0.532239,5.88733,-0.119685], <del> "rot" :[-0.451519,0.544179,0.544179,0.451519], <del> "scl" :[1,1,1] <del> }, <del>*/ <del> <ide> THREE.AnimationClip.CreateMorphAnimationFromNames = function( morphTargetNames, duration ) { <del> //console.log( morphTargetNames, duration ); <ide> <ide> var tracks = []; <ide> var frameStep = duration / morphTargetNames.length; <del> //console.log( 'frameStep', frameStep ); <ide> <ide> for( var i = 0; i < morphTargetNames.length; i ++ ) { <ide> <ide> THREE.AnimationClip.CreateMorphAnimationFromNames = function( morphTargetNames, <ide> <ide> } <ide> <del> //console.log( 'keys', keys ); <del> <ide> var morphName = morphTargetNames[i]; <ide> var trackName = '.morphTargetInfluences[' + morphName + ']'; <ide> var track = new THREE.KeyframeTrack( trackName, keys ); <ide> THREE.AnimationClip.CreateMorphAnimationFromNames = function( morphTargetNames, <ide> } <ide> <ide> var clip = new THREE.AnimationClip( 'morphAnimation', duration, tracks ); <del> //console.log( 'morphAnimationClip', clip ); <ide> <ide> return clip; <ide> }; <ide> THREE.AnimationClip.FromImplicitMorphTargetAnimations = function( morphTargets, <ide> <ide> } <ide> <del> //console.log( animations ); <del> <ide> var clips = []; <ide> <ide> for( var i = 0; i < animationsArray.length; i ++ ) { <ide> THREE.AnimationClip.FromImplicitMorphTargetAnimations = function( morphTargets, <ide> <ide> THREE.AnimationClip.FromJSONLoaderAnimation = function( animation, bones, nodeName ) { <ide> <del> //var animation = jsonLoader.animation; <ide> if( ! animation ) { <ide> console.error( " no animation in JSONLoader data" ); <ide> return null; <ide> THREE.AnimationClip.FromJSONLoaderAnimation = function( animation, bones, nodeNa <ide> <ide> var tracks = []; <ide> <del> //var boneList = jsonLoader.bones; <ide> var animationTracks = animation.hierarchy; <ide> <ide> for ( var h = 0; h < animationTracks.length; h ++ ) { <ide> THREE.AnimationClip.FromJSONLoaderAnimation = function( animation, bones, nodeNa <ide> else { <ide> <ide> var boneName = nodeName + '.bones[' + bones[ h ].name + ']'; <del> //console.log( 'boneName', boneName ); <ide> <ide> // track contains positions... <ide> var positionTrack = convertTrack( boneName + '.position', animationKeys, 'pos', function( animationKey ) { <ide> THREE.AnimationClip.FromJSONLoaderAnimation = function( animation, bones, nodeNa <ide> } <ide> <ide> var clip = new THREE.AnimationClip( clipName, duration, tracks ); <del> //console.log( 'clipFromJSONLoaderAnimation', clip ); <ide> <ide> return clip; <ide> <ide><path>src/animation/AnimationMixer.js <ide> * <ide> * Mixes together the AnimationClips scheduled by AnimationActions and applies them to the root and subtree <ide> * <del> * TODO: MUST add support for blending between AnimationActions based on their weights, right now only the last AnimationAction is applied at full weight. <ide> * <ide> * @author Ben Houston / http://clara.io/ <ide> * @author David Sarno / http://lighthaus.us/ <ide> THREE.AnimationMixer.prototype = { <ide> constructor: THREE.AnimationMixer, <ide> <ide> addAction: function( action ) { <del> //console.log( this.root.name + ".AnimationMixer.addAnimationAction( " + action.name + " )" ); <ide> <ide> this.actions.push( action ); <ide> <ide> THREE.AnimationMixer.prototype = { <ide> }, <ide> <ide> removeAction: function( action ) { <del> //console.log( this.root.name + ".AnimationMixer.addRemove( " + action.name + " )" ); <ide> <ide> var index = this.actions.indexOf( action ); <ide> <ide> THREE.AnimationMixer.prototype = { <ide> var mixerDeltaTime = deltaTime * this.timeScale; <ide> this.time += mixerDeltaTime; <ide> <del> //console.log( this.root.name + ".AnimationMixer.update( " + time + " )" ); <del> <ide> for( var i = 0; i < this.actions.length; i ++ ) { <ide> <ide> var action = this.actions[i]; <ide> <ide> var weight = action.getWeightAt( this.time ); <del> //console.log( action.clip.name, weight, this.time ); <ide> <ide> var actionTimeScale = action.getTimeScaleAt( this.time ); <ide> var actionDeltaTime = mixerDeltaTime * actionTimeScale; <ide><path>src/animation/AnimationUtils.js <ide> if( exemplarValue.lerp ) { <ide> <ide> return function( a, b, alpha ) { <del> //console.log( a, b ); <ide> return a.lerp( b, alpha ); <ide> } <ide> <ide> } <ide> if( exemplarValue.slerp ) { <ide> <ide> return function( a, b, alpha ) { <del> //console.log( a, b ); <ide> return a.slerp( b, alpha ); <ide> } <ide> <ide><path>src/animation/KeyframeTrack.js <ide> /** <ide> * <del> * A Track that returns a keyframe interpolated value. <del> * <del> * TODO: Add cubic in addition to linear interpolation. <add> * A Track that returns a keyframe interpolated value, currently linearly interpolated <ide> * <ide> * @author Ben Houston / http://clara.io/ <ide> * @author David Sarno / http://lighthaus.us/ <ide> THREE.KeyframeTrack = function ( name, keys ) { <ide> <ide> // local cache of value type to avoid allocations during runtime. <ide> this.result = THREE.AnimationUtils.clone( this.keys[0].value ); <del> //console.log( 'constructor result', this.result ) <ide> <ide> // the index of the last result, used as a starting point for local search. <del> // TODO: this is okay in the keyframetrack, but it would be better stored in AnimationAction eventually. <ide> this.lastIndex = 0; <ide> <ide> this.sort(); <ide> THREE.KeyframeTrack.prototype = { <ide> constructor: THREE.KeyframeTrack, <ide> <ide> getAt: function( time ) { <del> //if( /morph/i.test( this.name ) ) { <del> // console.log( 'KeyframeTrack[' + this.name + '].getAt( ' + time + ' )' ); <del> //} <ide> <ide> // this can not go higher than this.keys.length. <ide> while( ( this.lastIndex < this.keys.length ) && ( time >= this.keys[this.lastIndex].time ) ) { <ide> THREE.KeyframeTrack.prototype = { <ide> this.lastIndex --; <ide> } <ide> <del> //if( /morph/i.test( this.name ) ) { <del> // console.log( "lastIndex: ", this.lastIndex ); <del> //} <del> <ide> if( this.lastIndex >= this.keys.length ) { <ide> <ide> this.setResult( this.keys[ this.keys.length - 1 ].value ); <ide> THREE.KeyframeTrack.prototype = { <ide> var alpha = ( time - prevKey.time ) / ( currentKey.time - prevKey.time ); <ide> this.result = this.lerp( this.result, currentKey.value, alpha ); <ide> <del> //console.log( 'lerp result', this.result ) <del> /*if( /morph/i.test( this.name ) ) { <del> console.log( ' interpolated: ', { <del> index: this.lastIndex, <del> value: this.result, <del> alpha: alpha, <del> time0: this.keys[ this.lastIndex - 1 ].time, <del> time1: this.keys[ this.lastIndex ].time, <del> value0: this.keys[ this.lastIndex - 1 ].value, <del> value1: this.keys[ this.lastIndex ].value <del> } ); <del> }*/ <del> <ide> return this.result; <ide> <ide> }, <ide> THREE.KeyframeTrack.prototype = { <ide> }(), <ide> <ide> // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable <del> // TODO: ensure that all key.values in a track are all of the same type (otherwise interpolation makes no sense.) <add> // One could eventually ensure that all key.values in a track are all of the same type (otherwise interpolation makes no sense.) <ide> validate: function() { <ide> <ide> var prevKey = null; <ide> THREE.KeyframeTrack.prototype = { <ide> }, <ide> <ide> // currently only removes equivalent sequential keys (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0), which are common in morph target animations <del> // TODO: linear based interpolation optimization with an error threshold. <ide> optimize: function() { <ide> <ide> var newKeys = []; <ide> THREE.KeyframeTrack.prototype = { <ide> for( var i = 1; i < this.keys.length - 1; i ++ ) { <ide> var currKey = this.keys[i]; <ide> var nextKey = this.keys[i+1]; <del> //console.log( prevKey, currKey, nextKey ); <ide> <ide> // if prevKey & currKey are the same time, remove currKey. If you want immediate adjacent keys, use an epsilon offset <ide> // it is not possible to have two keys at the same time as we sort them. The sort is not stable on keys with the same time. <ide> if( ( prevKey.time === currKey.time ) ) { <del> //console.log( 'removing key at the same time', currKey ); <add> <ide> continue; <add> <ide> } <ide> <ide> // remove completely unnecessary keyframes that are the same as their prev and next keys <ide> if( equalsFunc( prevKey.value, currKey.value ) && equalsFunc( currKey.value, nextKey.value ) ) { <del> //console.log( 'removing key identical to prev and next', currKey ); <add> <ide> continue; <del> } <ide> <del> // TODO:add here a check for linear interpolation optimization. <add> } <ide> <ide> // determine if interpolation is required <ide> prevKey.constantToNext = equalsFunc( prevKey.value, currKey.value ); <ide> THREE.KeyframeTrack.prototype = { <ide> } <ide> newKeys.push( this.keys[ this.keys.length - 1 ] ); <ide> <del> //if( ( this.keys.length - newKeys.length ) > 0 ) { <del> //console.log( ' optimizing removed keys:', ( this.keys.length - newKeys.length ), this.name ); <del> //} <ide> this.keys = newKeys; <ide> <ide> }, <ide> THREE.KeyframeTrack.prototype = { <ide> <ide> // remove last keys first because it doesn't affect the position of the first keys (the otherway around doesn't work as easily) <ide> if( ( firstKeysToRemove + lastKeysToRemove ) > 0 ) { <del> //console.log( ' triming removed keys: first and last', firstKeysToRemove, lastKeysToRemove, this.keys ); <ide> this.keys = this.keys.splice( firstKeysToRemove, this.keys.length - lastKeysToRemove - firstKeysToRemove );; <del> //console.log( ' result', this.keys ); <ide> } <ide> <ide> } <ide><path>src/animation/PropertyBinding.js <ide> THREE.PropertyBinding = function ( rootNode, trackName ) { <ide> <ide> var parseResults = THREE.PropertyBinding.parseTrackName( trackName ); <ide> <del> //console.log( parseResults ); <ide> this.directoryName = parseResults.directoryName; <ide> this.nodeName = parseResults.nodeName; <ide> this.objectName = parseResults.objectName; <ide> THREE.PropertyBinding.prototype = { <ide> this.cumulativeWeight = weight; <ide> <ide> } <del> //console.log( this ); <ide> <ide> } <ide> else { <ide> <ide> var lerpAlpha = weight / ( this.cumulativeWeight + weight ); <ide> this.cumulativeValue = this.lerpValue( this.cumulativeValue, value, lerpAlpha ); <ide> this.cumulativeWeight += weight; <del> //console.log( this ); <ide> <ide> } <ide> <ide> THREE.PropertyBinding.prototype = { <ide> <ide> }, <ide> <del> // creates the member functions: <del> // - setValue( value ) <del> // - getValue() <del> // - triggerDirty() <del> <add> // bind to the real property in the scene graph, remember original value, memorize various accessors for speed/inefficiency <ide> bind: function() { <ide> <ide> if( this.isBound ) return; <del> <del> //console.log( "PropertyBinding", this ); <ide> <ide> var targetObject = this.node; <ide> <ide> THREE.PropertyBinding.prototype = { <ide> console.error( ' can not bind to bones as node does not have a skeleton', this ); <ide> return; <ide> } <del> // TODO/OPTIMIZE, skip this if propertyIndex is already an integer, and convert the integer string to a true integer. <add> // potential future optimization: skip this if propertyIndex is already an integer, and convert the integer string to a true integer. <ide> <ide> targetObject = targetObject.skeleton.bones; <ide> <ide> // support resolving morphTarget names into indices. <del> //console.log( " resolving bone name: ", this.objectIndex ); <ide> for( var i = 0; i < targetObject.length; i ++ ) { <ide> if( targetObject[i].name === this.objectIndex ) { <del> //console.log( " resolved to index: ", i ); <ide> this.objectIndex = i; <ide> break; <ide> } <ide> THREE.PropertyBinding.prototype = { <ide> if( this.propertyIndex !== undefined ) { <ide> <ide> if( this.propertyName === "morphTargetInfluences" ) { <del> // TODO/OPTIMIZE, skip this if propertyIndex is already an integer, and convert the integer string to a true integer. <add> // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer. <ide> <ide> // support resolving morphTarget names into indices. <del> //console.log( " resolving morphTargetInfluence name: ", this.propertyIndex ); <ide> if( ! targetObject.geometry ) { <ide> console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this ); <ide> } <ide> THREE.PropertyBinding.prototype = { <ide> <ide> for( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) { <ide> if( targetObject.geometry.morphTargets[i].name === this.propertyIndex ) { <del> //console.log( " resolved to index: ", i ); <ide> this.propertyIndex = i; <ide> break; <ide> } <ide> } <ide> } <ide> <del> //console.log( ' update property array ' + this.propertyName + '[' + this.propertyIndex + '] via assignment.' ); <ide> this.setValue = function( value ) { <ide> if( ! this.equalsValue( nodeProperty[ this.propertyIndex ], value ) ) { <ide> nodeProperty[ this.propertyIndex ] = value; <ide> THREE.PropertyBinding.prototype = { <ide> // must use copy for Object3D.Euler/Quaternion <ide> else if( nodeProperty.copy ) { <ide> <del> //console.log( ' update property ' + this.name + '.' + this.propertyName + ' via a set() function.' ); <ide> this.setValue = function( value ) { <ide> if( ! this.equalsValue( nodeProperty, value ) ) { <ide> nodeProperty.copy( value ); <ide> THREE.PropertyBinding.prototype = { <ide> // otherwise just set the property directly on the node (do not use nodeProperty as it may not be a reference object) <ide> else { <ide> <del> //console.log( ' update property ' + this.name + '.' + this.propertyName + ' via assignment.' ); <ide> this.setValue = function( value ) { <ide> if( ! this.equalsValue( targetObject[ this.propertyName ], value ) ) { <ide> targetObject[ this.propertyName ] = value; <ide> THREE.PropertyBinding.prototype = { <ide> // trigger node dirty <ide> if( targetObject.needsUpdate !== undefined ) { // material <ide> <del> //console.log( ' triggering material as dirty' ); <ide> this.triggerDirty = function() { <ide> this.node.needsUpdate = true; <ide> } <ide> <ide> } <ide> else if( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform <ide> <del> //console.log( ' triggering node as dirty' ); <ide> this.triggerDirty = function() { <ide> targetObject.matrixWorldNeedsUpdate = true; <ide> } <ide> THREE.PropertyBinding.parseTrackName = function( trackName ) { <ide> propertyIndex: matches[11] // allowed to be null, specifies that the whole property is set. <ide> }; <ide> <del> //console.log( "PropertyBinding.parseTrackName", trackName, results, matches ); <del> <ide> if( results.propertyName === null || results.propertyName.length === 0 ) { <ide> throw new Error( "can not parse propertyName from trackName: " + trackName ); <ide> } <ide> THREE.PropertyBinding.parseTrackName = function( trackName ) { <ide> // TODO: Cache this at some point <ide> THREE.PropertyBinding.findNode = function( root, nodeName ) { <ide> <del> //console.log( 'AnimationUtils.findNode( ' + root.name + ', nodeName: ' + nodeName + ')', root ); <del> <ide> if( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) { <ide> <del> //console.log( ' root.' ); <ide> return root; <ide> <ide> } <ide> THREE.PropertyBinding.findNode = function( root, nodeName ) { <ide> <ide> if( bone ) { <ide> <del> //console.log( ' bone: ' + bone.name + '.' ); <ide> return bone; <ide> <ide> } <ide> THREE.PropertyBinding.findNode = function( root, nodeName ) { <ide> <ide> if( subTreeNode ) { <ide> <del> //console.log( ' node: ' + subTreeNode.name + '.' ); <ide> return subTreeNode; <ide> <ide> } <ide> <ide> } <ide> <del> //console.log( " <null>. No node found for name: " + nodeName ); <del> <ide> return null; <ide> }
5
PHP
PHP
convert password reminders to notifications
e23e05e9f949e0d21ad7d39f4e028e826e0328ef
<ide><path>src/Illuminate/Auth/Notifications/ResetPassword.php <add><?php <add> <add>namespace Illuminate\Auth\Notifications; <add> <add>use Illuminate\Notifications\Notification; <add> <add>class ResetPassword extends Notification <add>{ <add> /** <add> * The password reset token. <add> * <add> * @var string <add> */ <add> public $token; <add> <add> /** <add> * Create a notification instance. <add> * <add> * @param string $token <add> * @return void <add> */ <add> public function __construct($token) <add> { <add> $this->token = $token; <add> } <add> <add> /** <add> * Get the notification's channels. <add> * <add> * @param mixed $notifiable <add> * @return array|string <add> */ <add> public function via($notifiable) <add> { <add> return ['mail']; <add> } <add> <add> /** <add> * Get the notification message. <add> * <add> * @param mixed $notifiable <add> * @return array <add> */ <add> public function message($notifiable) <add> { <add> return $this->line("You are receiving this email because we received a password reset request for your account. Click the button below to reset your password:") <add> ->action('Reset Password', url('password/reset', $this->token).'?email='.urlencode($notifiable->email)) <add> ->line("If you did not request a password reset, no further action is required."); <add> } <add>} <ide><path>src/Illuminate/Auth/Passwords/PasswordBroker.php <ide> use Illuminate\Support\Arr; <ide> use UnexpectedValueException; <ide> use Illuminate\Contracts\Auth\UserProvider; <del>use Illuminate\Contracts\Mail\Mailer as MailerContract; <ide> use Illuminate\Contracts\Auth\PasswordBroker as PasswordBrokerContract; <ide> use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; <add>use Illuminate\Auth\Notifications\ResetPassword as ResetPasswordNotification; <ide> <ide> class PasswordBroker implements PasswordBrokerContract <ide> { <ide> class PasswordBroker implements PasswordBrokerContract <ide> */ <ide> protected $users; <ide> <del> /** <del> * The mailer instance. <del> * <del> * @var \Illuminate\Contracts\Mail\Mailer <del> */ <del> protected $mailer; <del> <del> /** <del> * The view of the password reset link e-mail. <del> * <del> * @var string <del> */ <del> protected $emailView; <del> <ide> /** <ide> * The custom password validator callback. <ide> * <ide> class PasswordBroker implements PasswordBrokerContract <ide> * <ide> * @param \Illuminate\Auth\Passwords\TokenRepositoryInterface $tokens <ide> * @param \Illuminate\Contracts\Auth\UserProvider $users <del> * @param \Illuminate\Contracts\Mail\Mailer $mailer <del> * @param string $emailView <ide> * @return void <ide> */ <ide> public function __construct(TokenRepositoryInterface $tokens, <del> UserProvider $users, <del> MailerContract $mailer, <del> $emailView) <add> UserProvider $users) <ide> { <ide> $this->users = $users; <del> $this->mailer = $mailer; <ide> $this->tokens = $tokens; <del> $this->emailView = $emailView; <ide> } <ide> <ide> /** <ide> public function sendResetLink(array $credentials, Closure $callback = null) <ide> // Once we have the reset token, we are ready to send the message out to this <ide> // user with a link to reset their password. We will then redirect back to <ide> // the current URI having nothing set in the session to indicate errors. <del> $token = $this->tokens->create($user); <del> <del> $this->emailResetLink($user, $token, $callback); <add> if ($callback) { <add> call_user_func($callback, $user, $this->tokens->create($user)); <add> } else { <add> $user->notify(new ResetPasswordNotification( <add> $this->tokens->create($user) <add> )); <add> } <ide> <ide> return static::RESET_LINK_SENT; <ide> } <ide> <del> /** <del> * Send the password reset link via e-mail. <del> * <del> * @param \Illuminate\Contracts\Auth\CanResetPassword $user <del> * @param string $token <del> * @param \Closure|null $callback <del> * @return int <del> */ <del> public function emailResetLink(CanResetPasswordContract $user, $token, Closure $callback = null) <del> { <del> // We will use the reminder view that was given to the broker to display the <del> // password reminder e-mail. We'll pass a "token" variable into the views <del> // so that it may be displayed for an user to click for password reset. <del> $view = $this->emailView; <del> <del> return $this->mailer->send($view, compact('token', 'user'), function ($m) use ($user, $token, $callback) { <del> $m->to($user->getEmailForPasswordReset()); <del> <del> if (! is_null($callback)) { <del> call_user_func($callback, $m, $user, $token); <del> } <del> }); <del> } <del> <ide> /** <ide> * Reset the password for the given token. <ide> * <ide><path>src/Illuminate/Auth/Passwords/PasswordBrokerManager.php <ide> protected function resolve($name) <ide> // aggregate service of sorts providing a convenient interface for resets. <ide> return new PasswordBroker( <ide> $this->createTokenRepository($config), <del> $this->app['auth']->createUserProvider($config['provider']), <del> $this->app['mailer'], <del> $config['email'] <add> $this->app['auth']->createUserProvider($config['provider']) <ide> ); <ide> } <ide> <ide><path>src/Illuminate/Contracts/Notifications/Factory.php <add><?php <add> <add>namespace Illuminate\Contracts\Notifications; <add> <add>interface Factory <add>{ <add> /** <add> * Create a new notification for the given notifiable entities. <add> * <add> * @param array $notifiables <add> * @return \Illuminate\Notifications\Notification <add> */ <add> public function to($notifiables); <add>} <ide><path>src/Illuminate/Foundation/Auth/ResetsPasswords.php <ide> public function sendResetLinkEmail(Request $request) <ide> <ide> $response = Password::broker($broker)->sendResetLink( <ide> $this->getSendResetLinkEmailCredentials($request), <del> $this->resetEmailBuilder() <add> $this->resetNotifier() <ide> ); <ide> <ide> switch ($response) { <ide> protected function getSendResetLinkEmailCredentials(Request $request) <ide> } <ide> <ide> /** <del> * Get the Closure which is used to build the password reset email message. <add> * Get the Closure which is used to build the password reset notification. <ide> * <ide> * @return \Closure <ide> */ <del> protected function resetEmailBuilder() <add> protected function resetNotifier() <ide> { <del> return function (Message $message) { <del> $message->subject($this->getEmailSubject()); <del> }; <add> // <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Notifications/ChannelManager.php <ide> use Illuminate\Support\Manager; <ide> use Nexmo\Client as NexmoClient; <ide> use Nexmo\Client\Credentials\Basic as NexmoCredentials; <add>use Illuminate\Contracts\Notifications\Factory as FactoryContract; <ide> <del>class ChannelManager extends Manager <add>class ChannelManager extends Manager implements FactoryContract <ide> { <ide> /** <ide> * The default channels used to deliver messages. <ide><path>src/Illuminate/Notifications/Channels/Notification.php <ide> public static function notificationsFromInstance($notifiable, $instance, $channe <ide> <ide> $method = static::messageMethod($instance, $channel); <ide> <del> foreach ($instance->{$method}()->elements as $element) { <add> foreach ($instance->{$method}($notifiable)->elements as $element) { <ide> $notification->with($element); <ide> } <ide> } <ide><path>src/Illuminate/Notifications/NotificationServiceProvider.php <ide> namespace Illuminate\Notifications; <ide> <ide> use Illuminate\Support\ServiceProvider; <add>use Illuminate\Contracts\Notifications\Factory as FactoryContract; <ide> <ide> class NotificationServiceProvider extends ServiceProvider <ide> { <ide> public function register() <ide> $this->app->singleton(ChannelManager::class, function ($app) { <ide> return new ChannelManager($app); <ide> }); <add> <add> $this->app->alias( <add> ChannelManager::class, FactoryContract::class <add> ); <ide> } <ide> <ide> /** <ide> public function register() <ide> public function provides() <ide> { <ide> return [ <del> ChannelManager::class, <add> ChannelManager::class, FactoryContract::class, <ide> ]; <ide> } <ide> }
8
Javascript
Javascript
fix comment about dns lookup test
1204400d6411694d08bde0c3c197c9a72b72f570
<ide><path>test/parallel/test-c-ares.js <ide> const dnsPromises = dns.promises; <ide> assert.strictEqual(res.family, 6); <ide> })().then(common.mustCall()); <ide> <del>// Try resolution without callback <del> <add>// Try resolution without hostname. <ide> dns.lookup(null, common.mustCall((error, result, addressType) => { <ide> assert.ifError(error); <ide> assert.strictEqual(result, null);
1
Ruby
Ruby
pass stdinput to super
a56081d99ab056859679a92fb8f4a95e02bb6b5c
<ide><path>actionpack/lib/action_controller/integration.rb <ide> def url_for(options) <ide> <ide> private <ide> class MockCGI < CGI #:nodoc: <del> attr_accessor :stdinput, :stdoutput, :env_table <add> attr_accessor :stdoutput, :env_table <ide> <del> def initialize(env, input=nil) <add> def initialize(env, input = nil) <ide> self.env_table = env <del> self.stdinput = StringIO.new(input || "") <ide> self.stdoutput = StringIO.new <ide> <del> super() <add> super('query', StringIO.new(input || '')) <ide> end <ide> end <ide>
1
Python
Python
update data processors __init__
99a90e43d421369357815b21771f5211c2528667
<ide><path>pytorch_transformers/__init__.py <ide> <ide> from .data import (is_sklearn_available, <ide> InputExample, InputFeatures, DataProcessor, <del> glue_output_modes, glue_convert_examples_to_features, glue_processors) <add> glue_output_modes, glue_convert_examples_to_features, glue_processors, glue_tasks_num_labels) <ide> <ide> if is_sklearn_available(): <ide> from .data import glue_compute_metrics <ide><path>pytorch_transformers/data/__init__.py <del>from .processors import (InputExample, InputFeatures, DataProcessor, <del> glue_output_modes, glue_convert_examples_to_features, glue_processors) <del>from .metrics import is_sklearn_available <add>from .processors import InputExample, InputFeatures, DataProcessor <add>from .processors import glue_output_modes, glue_processors, glue_tasks_num_labels, glue_convert_examples_to_features <ide> <add>from .metrics import is_sklearn_available <ide> if is_sklearn_available(): <ide> from .metrics import glue_compute_metrics <ide><path>pytorch_transformers/data/processors/__init__.py <ide> from .utils import InputExample, InputFeatures, DataProcessor <del>from .glue import output_modes, processors, convert_examples_to_glue_features <add>from .glue import glue_output_modes, glue_processors, glue_tasks_num_labels, glue_convert_examples_to_features <add> <ide><path>pytorch_transformers/data/processors/glue.py <ide> <ide> logger = logging.getLogger(__name__) <ide> <del>GLUE_TASKS_NUM_LABELS = { <del> "cola": 2, <del> "mnli": 3, <del> "mrpc": 2, <del> "sst-2": 2, <del> "sts-b": 1, <del> "qqp": 2, <del> "qnli": 2, <del> "rte": 2, <del> "wnli": 2, <del>} <del> <del>processors = { <del> "cola": ColaProcessor, <del> "mnli": MnliProcessor, <del> "mnli-mm": MnliMismatchedProcessor, <del> "mrpc": MrpcProcessor, <del> "sst-2": Sst2Processor, <del> "sts-b": StsbProcessor, <del> "qqp": QqpProcessor, <del> "qnli": QnliProcessor, <del> "rte": RteProcessor, <del> "wnli": WnliProcessor, <del>} <del> <del>output_modes = { <del> "cola": "classification", <del> "mnli": "classification", <del> "mnli-mm": "classification", <del> "mrpc": "classification", <del> "sst-2": "classification", <del> "sts-b": "regression", <del> "qqp": "classification", <del> "qnli": "classification", <del> "rte": "classification", <del> "wnli": "classification", <del>} <del> <del>def convert_examples_to_glue_features(examples, label_list, max_seq_length, <add>def glue_convert_examples_to_features(examples, label_list, max_seq_length, <ide> tokenizer, output_mode, <ide> pad_on_left=False, <ide> pad_token=0, <ide> def _create_examples(self, lines, set_type): <ide> examples.append( <ide> InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) <ide> return examples <add> <add>glue_tasks_num_labels = { <add> "cola": 2, <add> "mnli": 3, <add> "mrpc": 2, <add> "sst-2": 2, <add> "sts-b": 1, <add> "qqp": 2, <add> "qnli": 2, <add> "rte": 2, <add> "wnli": 2, <add>} <add> <add>glue_processors = { <add> "cola": ColaProcessor, <add> "mnli": MnliProcessor, <add> "mnli-mm": MnliMismatchedProcessor, <add> "mrpc": MrpcProcessor, <add> "sst-2": Sst2Processor, <add> "sts-b": StsbProcessor, <add> "qqp": QqpProcessor, <add> "qnli": QnliProcessor, <add> "rte": RteProcessor, <add> "wnli": WnliProcessor, <add>} <add> <add>glue_output_modes = { <add> "cola": "classification", <add> "mnli": "classification", <add> "mnli-mm": "classification", <add> "mrpc": "classification", <add> "sst-2": "classification", <add> "sts-b": "regression", <add> "qqp": "classification", <add> "qnli": "classification", <add> "rte": "classification", <add> "wnli": "classification", <add>}
4
Python
Python
add subdir parameter to dags reserialize command
4be5616a5b3ccc146316c651c4279e914c93740b
<ide><path>airflow/cli/cli_parser.py <ide> class GroupCommand(NamedTuple): <ide> "version of Airflow that you are running." <ide> ), <ide> func=lazy_load_command('airflow.cli.commands.dag_command.dag_reserialize'), <del> args=(ARG_CLEAR_ONLY,), <add> args=( <add> ARG_CLEAR_ONLY, <add> ARG_SUBDIR, <add> ), <ide> ), <ide> ) <ide> TASKS_COMMANDS = ( <ide><path>airflow/cli/commands/dag_command.py <ide> def dag_reserialize(args, session: Session = NEW_SESSION): <ide> session.query(SerializedDagModel).delete(synchronize_session=False) <ide> <ide> if not args.clear_only: <del> dagbag = DagBag() <del> dagbag.collect_dags(only_if_updated=False, safe_mode=False) <add> dagbag = DagBag(process_subdir(args.subdir)) <ide> dagbag.sync_to_db(session=session) <ide><path>tests/cli/commands/test_dag_command.py <ide> def test_reserialize(self): <ide> serialized_dags_after_reserialize = session.query(SerializedDagModel).all() <ide> assert len(serialized_dags_after_reserialize) >= 40 # Serialized DAGs back <ide> <add> def test_reserialize_should_support_subdir_argument(self): <add> # Run clear of serialized dags <add> dag_command.dag_reserialize(self.parser.parse_args(['dags', 'reserialize', "--clear-only"])) <add> <add> # Assert no serialized Dags <add> with create_session() as session: <add> serialized_dags_after_clear = session.query(SerializedDagModel).all() <add> assert len(serialized_dags_after_clear) == 0 <add> <add> # Serialize manually <add> dag_path = self.dagbag.dags['example_bash_operator'].fileloc <add> # Set default value of include_examples parameter to false <add> dagbag_default = list(DagBag.__init__.__defaults__) <add> dagbag_default[1] = False <add> with mock.patch( <add> 'airflow.cli.commands.dag_command.DagBag.__init__.__defaults__', tuple(dagbag_default) <add> ): <add> dag_command.dag_reserialize(self.parser.parse_args(['dags', 'reserialize', '--subdir', dag_path])) <add> <add> # Check serialized DAG are back <add> with create_session() as session: <add> serialized_dags_after_reserialize = session.query(SerializedDagModel).all() <add> assert len(serialized_dags_after_reserialize) == 1 # Serialized DAG back <add> <ide> @mock.patch("airflow.cli.commands.dag_command.DAG.run") <ide> def test_backfill(self, mock_run): <ide> dag_command.dag_backfill( <ide><path>tests/cli/commands/test_task_command.py <ide> def setup_class(cls): <ide> clear_db_runs() <ide> <ide> cls.dag = cls.dagbag.get_dag(cls.dag_id) <add> cls.dagbag.sync_to_db() <ide> cls.dag_run = cls.dag.create_dagrun( <ide> state=State.NONE, run_id=cls.run_id, run_type=DagRunType.MANUAL, execution_date=DEFAULT_DATE <ide> )
4
Ruby
Ruby
use stty instead of tput to get terminal width
a9c83f14a749f6295daafc31440d0f74d1aa27e0
<ide><path>Library/Homebrew/utils/tty.rb <ide> def strip_ansi(string) <ide> end <ide> <ide> def width <del> `/usr/bin/tput cols`.strip.to_i <add> (`/bin/stty size`.split[1] || 80).to_i <ide> end <ide> <ide> def truncate(string)
1
Javascript
Javascript
add children.toarray to reactnative
7cbad9f53048ab5d19a8004df30ae621f1bfbd09
<ide><path>Libraries/ReactNative/ReactNative.js <ide> var ReactNative = { <ide> map: ReactChildren.map, <ide> forEach: ReactChildren.forEach, <ide> count: ReactChildren.count, <add> toArray: ReactChildren.toArray, <ide> only: onlyChild <ide> }, <ide> Component: ReactComponent,
1
Ruby
Ruby
require helpers so autoload is properly setup
d6f1291f48d2c7c1719fbeabbafbfa7c6e2f1dc6
<ide><path>actionpack/lib/sprockets/helpers/rails_helper.rb <del>require "action_view/helpers/asset_tag_helper" <add>require "action_view/helpers" <ide> <ide> module Sprockets <ide> module Helpers
1
Ruby
Ruby
allow more ttys
1cd75e4298be0b11185506cb16d67497d335f91c
<ide><path>Library/Homebrew/sandbox.rb <ide> class SandboxProfile <ide> (literal "/dev/random") <ide> (literal "/dev/zero") <ide> (regex #"^/dev/fd/[0-9]+$") <del> (regex #"^/dev/ttys?[0-9]*$") <add> (regex #"^/dev/tty[a-z0-9]*$") <ide> ) <ide> (deny file-write*) ; deny non-whitelist file write operations <ide> (allow process-exec
1
Ruby
Ruby
fix pry deprecation warning on tab-completion
8fe649a4dce7ca14be48fbb066d9a47d848e31ea
<ide><path>activesupport/lib/active_support/deprecation/proxy_wrappers.rb <ide> def inspect <ide> <ide> # Don't give a deprecation warning on methods that IRB may invoke <ide> # during tab-completion. <del> delegate :hash, :instance_methods, :name, to: :target <add> delegate :hash, :instance_methods, :name, :respond_to?, to: :target <ide> <ide> # Returns the class of the new constant. <ide> #
1
Ruby
Ruby
add bottle filenames method
82eee276e3cbd5ace72606273484022e69390334
<ide><path>Library/Homebrew/cmd/versions.rb <ide> def versions <ide> return versions <ide> end <ide> <add> def bottle_filenames branch='HEAD' <add> filenames = [] <add> rev_list(branch).each do |sha| <add> filename = formula_for_sha(sha) {|f| bottle_filename f } <add> unless filenames.include? filename or filename.nil? <add> filenames << filename <add> end <add> end <add> return filenames <add> end <add> <ide> def pretty_relative_path <ide> if Pathname.pwd == repository <ide> entry_name
1
Python
Python
update heap.py (#726)
6f6510623c7250ebea78afbd3d6eab1bfe467ada
<ide><path>data_structures/heap/heap.py <ide> except NameError: <ide> raw_input = input # Python 3 <ide> <add>#This heap class start from here. <ide> class Heap: <del> def __init__(self): <add> def __init__(self): #Default constructor of heap class. <ide> self.h = [] <ide> self.currsize = 0 <ide> <ide> def maxHeapify(self,node): <ide> self.h[m] = temp <ide> self.maxHeapify(m) <ide> <del> def buildHeap(self,a): <add> def buildHeap(self,a): #This function is used to build the heap from the data container 'a'. <ide> self.currsize = len(a) <ide> self.h = list(a) <ide> for i in range(self.currsize//2,-1,-1): <ide> self.maxHeapify(i) <ide> <del> def getMax(self): <add> def getMax(self): #This function is used to get maximum value from the heap. <ide> if self.currsize >= 1: <ide> me = self.h[0] <ide> temp = self.h[0] <ide> def getMax(self): <ide> return me <ide> return None <ide> <del> def heapSort(self): <add> def heapSort(self): #This function is used to sort the heap. <ide> size = self.currsize <ide> while self.currsize-1 >= 0: <ide> temp = self.h[0] <ide> def heapSort(self): <ide> self.maxHeapify(0) <ide> self.currsize = size <ide> <del> def insert(self,data): <add> def insert(self,data): #This function is used to insert data in the heap. <ide> self.h.append(data) <ide> curr = self.currsize <ide> self.currsize+=1 <ide> def insert(self,data): <ide> self.h[curr] = temp <ide> curr = curr/2 <ide> <del> def display(self): <add> def display(self): #This function is used to print the heap. <ide> print(self.h) <ide> <ide> def main():
1
Python
Python
add test case for integer division
26a9e8134689af1b37b815f969283b42942ec194
<ide><path>numpy/core/tests/test_umath.py <ide> from numpy import zeros, ndarray, array, choose <ide> restore_path() <ide> <add>class test_division(NumpyTestCase): <add> def check_division_int(self): <add> # int division should return the floor of the result, a la Python <add> x = array([5, 10, 90, 100, -5, -10, -90, -100, -120]) <add> assert_equal(x / 100, [0, 0, 0, 1, -1, -1, -1, -1, -2]) <add> assert_equal(x // 100, [0, 0, 0, 1, -1, -1, -1, -1, -2]) <add> assert_equal(x % 100, [5, 10, 90, 0, 95, 90, 10, 0, 80]) <add> <ide> class test_power(NumpyTestCase): <ide> def check_power_float(self): <ide> x = array([1., 2., 3.])
1
Javascript
Javascript
add standard define
aaaa526bc49351794e20da2940f48825d2f0c053
<ide><path>examples/js/nodes/materials/StandardNode.js <ide> THREE.StandardNode.prototype.build = function( builder ) { <ide> var material = builder.material; <ide> var code; <ide> <add> material.define( 'STANDARD' ); <ide> material.define( 'PHYSICAL' ); <ide> material.define( 'ALPHATEST', '0.0' ); <ide>
1
Ruby
Ruby
say it briefly
73213f4ca7e0db8d617abfdbbc79e6d31ccb5cc7
<ide><path>railties/helpers/application_controller.rb <ide> <ide> class ApplicationController < ActionController::Base <ide> helper :all # include all helpers, all the time <add> protect_from_forgery # See ActionController::RequestForgeryProtection for details <ide> <del> # See ActionController::RequestForgeryProtection for details <del> protect_from_forgery <del> <del> # See ActionController::Base for details <del> # Uncomment this to filter the contents of submitted sensitive data parameters <del> # from your application log (in this case, all fields with names like "password"). <add> # Scrub sensitive parameters from your log <ide> # filter_parameter_logging :password <ide> end
1
Python
Python
fix typo in pop documentation
553b26f8579a21a2d3644cb3bc5cb2ed8cedabc5
<ide><path>src/flask/ctx.py <ide> def pop(self, name, default=_sentinel): <ide> <ide> :param name: Name of attribute to pop. <ide> :param default: Value to return if the attribute is not present, <del> instead of raise a ``KeyError``. <add> instead of raising a ``KeyError``. <ide> <ide> .. versionadded:: 0.11 <ide> """
1
Javascript
Javascript
improve performance caused by primordials
e1a63a9785ae1d74ae362dea1479d6f890e1d187
<ide><path>lib/_http_agent.js <ide> <ide> 'use strict'; <ide> <del>const { Object } = primordials; <add>const { <add> Object: { <add> setPrototypeOf: ObjectSetPrototypeOf, <add> keys: ObjectKeys, <add> values: ObjectValues <add> } <add>} = primordials; <ide> <ide> const net = require('net'); <ide> const EventEmitter = require('events'); <ide> function Agent(options) { <ide> // Don't emit keylog events unless there is a listener for them. <ide> this.on('newListener', maybeEnableKeylog); <ide> } <del>Object.setPrototypeOf(Agent.prototype, EventEmitter.prototype); <del>Object.setPrototypeOf(Agent, EventEmitter); <add>ObjectSetPrototypeOf(Agent.prototype, EventEmitter.prototype); <add>ObjectSetPrototypeOf(Agent, EventEmitter); <ide> <ide> function maybeEnableKeylog(eventName) { <ide> if (eventName === 'keylog') { <ide> function maybeEnableKeylog(eventName) { <ide> agent.emit('keylog', keylog, this); <ide> }; <ide> // Existing sockets will start listening on keylog now. <del> const sockets = Object.values(this.sockets); <add> const sockets = ObjectValues(this.sockets); <ide> for (let i = 0; i < sockets.length; i++) { <ide> sockets[i].on('keylog', this[kOnKeylog]); <ide> } <ide> Agent.prototype.destroy = function destroy() { <ide> const sets = [this.freeSockets, this.sockets]; <ide> for (let s = 0; s < sets.length; s++) { <ide> const set = sets[s]; <del> const keys = Object.keys(set); <add> const keys = ObjectKeys(set); <ide> for (let v = 0; v < keys.length; v++) { <ide> const setName = set[keys[v]]; <ide> for (let n = 0; n < setName.length; n++) {
1
Python
Python
add bulk_insert_rows() for more performant inserts
bece6af289109de8be4c5aa97780806ae1db8275
<ide><path>airflow/hooks/oracle_hook.py <ide> def insert_rows(self, table, rows, target_fields = None, commit_every = 1000): <ide> cur.close() <ide> conn.close() <ide> logging.info('Done loading. Loaded a total of {i} rows'.format(**locals())) <add> <add> def bulk_insert_rows(self, table, rows, target_fields=None, commit_every=5000): <add> """A performant bulk insert for cx_Oracle that uses prepared statements via `executemany()`. <add> For best performance, pass in `rows` as an iterator. <add> """ <add> conn = self.get_conn() <add> cursor = conn.cursor() <add> values = ', '.join(':%s' % i for i in range(1, len(target_fields) + 1)) <add> prepared_stm = 'insert into {tablename} ({columns}) values ({values})'.format( <add> tablename=table, <add> columns=', '.join(target_fields), <add> values=values <add> ) <add> row_count = 0 <add> # Chunk the rows <add> row_chunk = [] <add> for row in rows: <add> row_chunk.append(row) <add> row_count += 1 <add> if row_count % commit_every == 0: <add> cursor.prepare(prepared_stm) <add> cursor.executemany(None, row_chunk) <add> conn.commit() <add> logging.info('[%s] inserted %s rows', table, row_count) <add> # Empty chunk <add> row_chunk = [] <add> # Commit the leftover chunk <add> cursor.prepare(prepared_stm) <add> cursor.executemany(None, row_chunk) <add> conn.commit() <add> logging.info('[%s] inserted %s rows', table, row_count) <add> cursor.close() <add> conn.close()
1
Text
Text
fix total downloads url
9f9a692f724c538e30701877f9073297856c5763
<ide><path>readme.md <ide> ## Laravel Framework (Kernel) <ide> <ide> [![Build Status](https://travis-ci.org/laravel/framework.svg)](https://travis-ci.org/laravel/framework) <del>[![Total Downloads](https://poser.pugx.org/laravel/framework/downloads.svg)](https://packagist.org/packages/laravel/framework) <add>[![Total Downloads](https://poser.pugx.org/laravel/framework/d/total.svg)](https://packagist.org/packages/laravel/framework) <ide> [![Latest Stable Version](https://poser.pugx.org/laravel/framework/v/stable.svg)](https://packagist.org/packages/laravel/framework) <ide> [![Latest Unstable Version](https://poser.pugx.org/laravel/framework/v/unstable.svg)](https://packagist.org/packages/laravel/framework) <ide> [![License](https://poser.pugx.org/laravel/framework/license.svg)](https://packagist.org/packages/laravel/framework)
1
Go
Go
remove layerstore.setos(), layerstore.getos()
c28a8e9cf7ffc9e0ac56987620d160326902ba11
<ide><path>layer/filestore_unix.go <del>//go:build !windows <del>// +build !windows <del> <del>package layer // import "github.com/docker/docker/layer" <del> <del>import "runtime" <del> <del>// setOS writes the "os" file to the layer filestore <del>func (fm *fileMetadataTransaction) setOS(os string) error { <del> return nil <del>} <del> <del>// getOS reads the "os" file from the layer filestore <del>func (fms *fileMetadataStore) getOS(layer ChainID) (string, error) { <del> return runtime.GOOS, nil <del>} <ide><path>layer/filestore_windows.go <del>package layer // import "github.com/docker/docker/layer" <del> <del>import ( <del> "fmt" <del> "os" <del> "strings" <del>) <del> <del>// setOS writes the "os" file to the layer filestore <del>func (fm *fileMetadataTransaction) setOS(os string) error { <del> if os == "" { <del> return nil <del> } <del> return fm.ws.WriteFile("os", []byte(os), 0644) <del>} <del> <del>// getOS reads the "os" file from the layer filestore <del>func (fms *fileMetadataStore) getOS(layer ChainID) (string, error) { <del> contentBytes, err := os.ReadFile(fms.getLayerFilename(layer, "os")) <del> if err != nil { <del> // For backwards compatibility, the os file may not exist. Default to "windows" if missing. <del> if os.IsNotExist(err) { <del> return "windows", nil <del> } <del> return "", err <del> } <del> content := strings.TrimSpace(string(contentBytes)) <del> <del> if content != "windows" && content != "linux" { <del> return "", fmt.Errorf("invalid operating system value: %s", content) <del> } <del> <del> return content, nil <del>} <ide><path>layer/layer_store.go <ide> import ( <ide> "github.com/docker/docker/pkg/idtools" <ide> "github.com/docker/docker/pkg/plugingetter" <ide> "github.com/docker/docker/pkg/stringid" <del> "github.com/docker/docker/pkg/system" <ide> "github.com/moby/locker" <ide> "github.com/opencontainers/go-digest" <ide> "github.com/sirupsen/logrus" <ide> func (ls *layerStore) loadLayer(layer ChainID) (*roLayer, error) { <ide> return nil, fmt.Errorf("failed to get descriptor for %s: %s", layer, err) <ide> } <ide> <del> os, err := ls.store.getOS(layer) <del> if err != nil { <del> return nil, fmt.Errorf("failed to get operating system for %s: %s", layer, err) <del> } <del> <del> if !system.IsOSSupported(os) { <del> return nil, fmt.Errorf("failed to load layer with os %s into layerstore: %w", os, system.ErrNotSupportedOperatingSystem) <del> } <del> <ide> cl = &roLayer{ <ide> chainID: layer, <ide> diffID: diff, <ide><path>layer/ro_layer.go <ide> package layer // import "github.com/docker/docker/layer" <ide> import ( <ide> "fmt" <ide> "io" <del> "runtime" <ide> <ide> "github.com/docker/distribution" <ide> "github.com/opencontainers/go-digest" <ide> func storeLayer(tx *fileMetadataTransaction, layer *roLayer) error { <ide> return err <ide> } <ide> } <del> return tx.setOS(runtime.GOOS) <add> return nil <ide> } <ide> <ide> func newVerifiedReadCloser(rc io.ReadCloser, dgst digest.Digest) (io.ReadCloser, error) {
4
Mixed
Javascript
resolve merge conflict in test_slave.html
f4b169ddba10e8bf59552a9813aef5a3fa58f7e8
<ide><path>fonts.js <ide> var Font = (function () { <ide> return array; <ide> }; <ide> <add> function int16(bytes) { <add> return (bytes[0] << 8) + (bytes[1] & 0xff); <add> }; <add> <add> function int32(bytes) { <add> return (bytes[0] << 24) + (bytes[1] << 16) + <add> (bytes[2] << 8) + (bytes[3] & 0xff); <add> }; <add> <add> function getMaxPower2(number) { <add> var maxPower = 0; <add> var value = number; <add> while (value >= 2) { <add> value /= 2; <add> maxPower++; <add> } <add> <add> value = 2; <add> for (var i = 1; i < maxPower; i++) <add> value *= 2; <add> return value; <add> }; <add> <ide> function string16(value) { <ide> return String.fromCharCode((value >> 8) & 0xff) + <ide> String.fromCharCode(value & 0xff); <ide> var Font = (function () { <ide> header += string16(numTables); <ide> <ide> // searchRange (2 bytes) <del> var tablesMaxPower2 = FontsUtils.getMaxPower2(numTables); <add> var tablesMaxPower2 = getMaxPower2(numTables); <ide> var searchRange = tablesMaxPower2 * 16; <ide> header += string16(searchRange); <ide> <ide> var Font = (function () { <ide> <ide> // length <ide> var length = data.length; <del> <add> <ide> // Per spec tables must be 4-bytes align so add padding as needed <ide> while (data.length & 3) <ide> data.push(0x00); <ide> var Font = (function () { <ide> // checksum <ide> var checksum = 0; <ide> for (var i = 0; i < length; i+=4) <del> checksum += FontsUtils.bytesToInteger([data[i], data[i+1], data[i+2], data[i+3]]); <add> checksum += int16([data[i], data[i+1], data[i+2], data[i+3]]); <ide> <ide> var tableEntry = tag + string32(checksum) + string32(offset) + string32(length); <ide> tableEntry = stringToArray(tableEntry); <ide> var Font = (function () { <ide> var headerSize = (12 * 2 + (ranges.length * 5 * 2)); <ide> var segCount = ranges.length + 1; <ide> var segCount2 = segCount * 2; <del> var searchRange = FontsUtils.getMaxPower2(segCount) * 2; <add> var searchRange = getMaxPower2(segCount) * 2; <ide> var searchEntry = Math.log(segCount) / Math.log(2); <ide> var rangeShift = 2 * segCount - searchRange; <ide> <ide> var Font = (function () { <ide> String.fromCharCode(tag[2]) + <ide> String.fromCharCode(tag[3]); <ide> <del> var checksum = FontsUtils.bytesToInteger(file.getBytes(4)); <del> var offset = FontsUtils.bytesToInteger(file.getBytes(4)); <del> var length = FontsUtils.bytesToInteger(file.getBytes(4)); <add> var checksum = int32(file.getBytes(4)); <add> var offset = int32(file.getBytes(4)); <add> var length = int32(file.getBytes(4)); <ide> <ide> // Read the table associated data <ide> var previousPosition = file.pos; <ide> var Font = (function () { <ide> function readOpenTypeHeader(ttf) { <ide> return { <ide> version: ttf.getBytes(4), <del> numTables: FontsUtils.bytesToInteger(ttf.getBytes(2)), <del> searchRange: FontsUtils.bytesToInteger(ttf.getBytes(2)), <del> entrySelector: FontsUtils.bytesToInteger(ttf.getBytes(2)), <del> rangeShift: FontsUtils.bytesToInteger(ttf.getBytes(2)) <add> numTables: int16(ttf.getBytes(2)), <add> searchRange: int16(ttf.getBytes(2)), <add> entrySelector: int16(ttf.getBytes(2)), <add> rangeShift: int16(ttf.getBytes(2)) <ide> } <ide> }; <ide> <ide> function replaceCMapTable(cmap, font, properties) { <ide> font.pos = (font.start ? font.start : 0) + cmap.length; <ide> <del> var version = FontsUtils.bytesToInteger(font.getBytes(2)); <del> var numTables = FontsUtils.bytesToInteger(font.getBytes(2)); <add> var version = int16(font.getBytes(2)); <add> var numTables = int16(font.getBytes(2)); <ide> <ide> for (var i = 0; i < numTables; i++) { <del> var platformID = FontsUtils.bytesToInteger(font.getBytes(2)); <del> var encodingID = FontsUtils.bytesToInteger(font.getBytes(2)); <del> var offset = FontsUtils.bytesToInteger(font.getBytes(4)); <del> var format = FontsUtils.bytesToInteger(font.getBytes(2)); <del> var length = FontsUtils.bytesToInteger(font.getBytes(2)); <del> var language = FontsUtils.bytesToInteger(font.getBytes(2)); <add> var platformID = int16(font.getBytes(2)); <add> var encodingID = int16(font.getBytes(2)); <add> var offset = int32(font.getBytes(4)); <add> var format = int16(font.getBytes(2)); <add> var length = int16(font.getBytes(2)); <add> var language = int16(font.getBytes(2)); <ide> <ide> if ((format == 0 && numTables == 1) || <ide> (format == 6 && numTables == 1 && !properties.encoding.empty)) { <ide> var Font = (function () { <ide> // table. (This looks weird, so I can have missed something), this <ide> // works on Linux but seems to fails on Mac so let's rewrite the <ide> // cmap table to a 3-1-4 style <del> var firstCode = FontsUtils.bytesToInteger(font.getBytes(2)); <del> var entryCount = FontsUtils.bytesToInteger(font.getBytes(2)); <add> var firstCode = int16(font.getBytes(2)); <add> var entryCount = int16(font.getBytes(2)); <ide> <ide> var glyphs = []; <ide> var min = 0xffff, max = 0; <ide> for (var j = 0; j < entryCount; j++) { <del> var charcode = FontsUtils.bytesToInteger(font.getBytes(2)); <add> var charcode = int16(font.getBytes(2)); <ide> glyphs.push(charcode); <ide> <ide> if (charcode < min) <ide> var Font = (function () { <ide> <ide> // Tables needs to be written by ascendant alphabetic order <ide> tables.sort(function tables_sort(a, b) { <del> return a.tag > b.tag; <add> return (a.tag > b.tag) - (a.tag < b.tag); <ide> }); <ide> <ide> // rewrite the tables but tweak offsets <ide> var Font = (function () { <ide> }, <ide> <ide> convert: function font_convert(fontName, font, properties) { <del> var otf = new Uint8Array(kMaxFontFileSize); <del> <ide> function createNameTable(name) { <ide> // All the strings of the name table should be an odd number of bytes <ide> if (name.length % 2) <ide> var Font = (function () { <ide> nameTable += strings.join("") + stringsUnicode.join(""); <ide> return nameTable; <ide> } <del> <add> <ide> function isFixedPitch(glyphs) { <ide> for (var i = 0; i < glyphs.length - 1; i++) { <ide> if (glyphs[i] != glyphs[i+1]) <ide> var Font = (function () { <ide> return true; <ide> }; <ide> <del> // Required Tables <del> var CFF = <del> font.data, // PostScript Font Program <del> OS2, // OS/2 and Windows Specific metrics <del> cmap, // Character to glyphs mapping <del> head, // Font header <del> hhea, // Horizontal header <del> hmtx, // Horizontal metrics <del> maxp, // Maximum profile <del> name, // Naming tables <del> post; // PostScript informations <del> var tables = [CFF, OS2, cmap, head, hhea, hmtx, maxp, name, post]; <del> <ide> // The offsets object holds at the same time a representation of where <ide> // to write the table entry information about a table and another offset <ide> // representing the offset where to draw the actual data of a particular <ide> // table <add> var kRequiredTablesCount = 9; <ide> var offsets = { <ide> currentOffset: 0, <del> virtualOffset: tables.length * (4 * 4) <add> virtualOffset: 9 * (4 * 4) <ide> }; <ide> <del> // It there is only one font, offset table is the first bytes of the file <del> createOpenTypeHeader("\x4F\x54\x54\x4F", otf, offsets, tables.length); <del> <del> /** CFF */ <del> createTableEntry(otf, offsets, "CFF ", CFF); <add> var otf = new Uint8Array(kMaxFontFileSize); <add> createOpenTypeHeader("\x4F\x54\x54\x4F", otf, offsets, 9); <ide> <del> /** OS/2 */ <ide> var charstrings = font.charstrings; <ide> properties.fixedPitch = isFixedPitch(charstrings); <del> OS2 = stringToArray(createOS2Table(properties)); <del> createTableEntry(otf, offsets, "OS/2", OS2); <add> var fields = { <add> // PostScript Font Program <add> "CFF ": font.data, <ide> <del> /** CMAP */ <del> cmap = createCMapTable(charstrings.slice()); <del> createTableEntry(otf, offsets, "cmap", cmap); <add> // OS/2 and Windows Specific metrics <add> "OS/2": stringToArray(createOS2Table(properties)), <ide> <del> /** HEAD */ <del> head = stringToArray( <add> // Character to glyphs mapping <add> "cmap": createCMapTable(charstrings.slice()), <add> <add> // Font header <add> "head": (function() { <add> return stringToArray( <ide> "\x00\x01\x00\x00" + // Version number <ide> "\x00\x00\x10\x00" + // fontRevision <ide> "\x00\x00\x00\x00" + // checksumAdjustement <ide> var Font = (function () { <ide> "\x00\x11" + // lowestRecPPEM <ide> "\x00\x00" + // fontDirectionHint <ide> "\x00\x00" + // indexToLocFormat <del> "\x00\x00" // glyphDataFormat <del> ); <del> createTableEntry(otf, offsets, "head", head); <del> <del> /** HHEA */ <del> hhea = stringToArray( <del> "\x00\x01\x00\x00" + // Version number <del> string16(properties.ascent) + // Typographic Ascent <del> string16(properties.descent) + // Typographic Descent <del> "\x00\x00" + // Line Gap <del> "\xFF\xFF" + // advanceWidthMax <del> "\x00\x00" + // minLeftSidebearing <del> "\x00\x00" + // minRightSidebearing <del> "\x00\x00" + // xMaxExtent <del> string16(properties.capHeight) + // caretSlopeRise <del> string16(Math.tan(properties.italicAngle) * properties.xHeight) + // caretSlopeRun <del> "\x00\x00" + // caretOffset <del> "\x00\x00" + // -reserved- <del> "\x00\x00" + // -reserved- <del> "\x00\x00" + // -reserved- <del> "\x00\x00" + // -reserved- <del> "\x00\x00" + // metricDataFormat <del> string16(charstrings.length + 1) // Number of HMetrics <del> ); <del> createTableEntry(otf, offsets, "hhea", hhea); <del> <del> /** HMTX */ <del> /* For some reasons, probably related to how the backend handle fonts, <del> * Linux seems to ignore this file and prefer the data from the CFF itself <del> * while Windows use this data. So be careful if you hack on Linux and <del> * have to touch the 'hmtx' table <del> */ <del> hmtx = "\x00\x00\x00\x00"; // Fake .notdef <del> for (var i = 0; i < charstrings.length; i++) { <del> hmtx += string16(charstrings[i].width) + string16(0); <del> } <del> hmtx = stringToArray(hmtx); <del> createTableEntry(otf, offsets, "hmtx", hmtx); <del> <del> /** MAXP */ <del> maxp = "\x00\x00\x50\x00" + // Version number <del> string16(charstrings.length + 1); // Num of glyphs <del> maxp = stringToArray(maxp); <del> createTableEntry(otf, offsets, "maxp", maxp); <del> <del> /** NAME */ <del> name = stringToArray(createNameTable(fontName)); <del> createTableEntry(otf, offsets, "name", name); <del> <del> /** POST */ <del> post = stringToArray(createPostTable(properties)); <del> createTableEntry(otf, offsets, "post", post); <del> <del> // Once all the table entries header are written, dump the data! <del> var tables = [CFF, OS2, cmap, head, hhea, hmtx, maxp, name, post]; <del> for (var i = 0; i < tables.length; i++) { <del> var table = tables[i]; <add> "\x00\x00"); // glyphDataFormat <add> })(), <add> <add> // Horizontal header <add> "hhea": (function() { <add> return stringToArray( <add> "\x00\x01\x00\x00" + // Version number <add> string16(properties.ascent) + // Typographic Ascent <add> string16(properties.descent) + // Typographic Descent <add> "\x00\x00" + // Line Gap <add> "\xFF\xFF" + // advanceWidthMax <add> "\x00\x00" + // minLeftSidebearing <add> "\x00\x00" + // minRightSidebearing <add> "\x00\x00" + // xMaxExtent <add> string16(properties.capHeight) + // caretSlopeRise <add> string16(Math.tan(properties.italicAngle) * properties.xHeight) + // caretSlopeRun <add> "\x00\x00" + // caretOffset <add> "\x00\x00" + // -reserved- <add> "\x00\x00" + // -reserved- <add> "\x00\x00" + // -reserved- <add> "\x00\x00" + // -reserved- <add> "\x00\x00" + // metricDataFormat <add> string16(charstrings.length + 1)); // Number of HMetrics <add> })(), <add> <add> // Horizontal metrics <add> "hmtx": (function() { <add> var hmtx = "\x00\x00\x00\x00"; // Fake .notdef <add> for (var i = 0; i < charstrings.length; i++) { <add> hmtx += string16(charstrings[i].width) + string16(0); <add> } <add> return stringToArray(hmtx); <add> })(), <add> <add> // Maximum profile <add> "maxp": (function() { <add> return stringToArray( <add> "\x00\x00\x50\x00" + // Version number <add> string16(charstrings.length + 1)); // Num of glyphs <add> })(), <add> <add> // Naming tables <add> "name": stringToArray(createNameTable(fontName)), <add> <add> // PostScript informations <add> "post": stringToArray(createPostTable(properties)) <add> }; <add> <add> for (var field in fields) <add> createTableEntry(otf, offsets, field, fields[field]); <add> <add> for (var field in fields) { <add> var table = fields[field]; <ide> otf.set(table, offsets.currentOffset); <ide> offsets.currentOffset += table.length; <ide> } <ide> var Font = (function () { <ide> return constructor; <ide> })(); <ide> <del> <del>/** <del> * FontsUtils is a static class dedicated to hold codes that are not related <del> * to fonts in particular and needs to be share between them. <del> */ <del>var FontsUtils = { <del> _bytesArray: new Uint8Array(4), <del> integerToBytes: function fu_integerToBytes(value, bytesCount) { <del> var bytes = this._bytesArray; <del> <del> if (bytesCount == 1) { <del> bytes.set([value]); <del> return bytes[0]; <del> } else if (bytesCount == 2) { <del> bytes.set([value >> 8, value & 0xff]); <del> return [bytes[0], bytes[1]]; <del> } else if (bytesCount == 4) { <del> bytes.set([value >> 24, value >> 16, value >> 8, value]); <del> return [bytes[0], bytes[1], bytes[2], bytes[3]]; <del> } <del> <del> error("This number of bytes " + bytesCount + " is not supported"); <del> return null; <del> }, <del> <del> bytesToInteger: function fu_bytesToInteger(bytesArray) { <del> var value = 0; <del> for (var i = 0; i < bytesArray.length; i++) <del> value = (value << 8) + bytesArray[i]; <del> return value; <del> }, <del> <del> getMaxPower2: function fu_getMaxPower2(number) { <del> var maxPower = 0; <del> var value = number; <del> while (value >= 2) { <del> value /= 2; <del> maxPower++; <del> } <del> <del> value = 2; <del> for (var i = 1; i < maxPower; i++) <del> value *= 2; <del> return value; <del> } <del>}; <del> <del> <ide> /** <ide> * Type1Parser encapsulate the needed code for parsing a Type1 font <ide> * program. <ide> CFF.prototype = { <ide> if (count == 0) <ide> return "\x00\x00\x00"; <ide> <del> var data = ""; <del> var bytes = FontsUtils.integerToBytes(count, 2); <del> for (var i = 0; i < bytes.length; i++) <del> data += String.fromCharCode(bytes[i]); <add> var data = String.fromCharCode(count >> 8, count & 0xff); <ide> <ide> // Next byte contains the offset size use to reference object in the file <ide> // Actually we're using 0x04 to be sure to be able to store everything <ide> CFF.prototype = { <ide> // Add another offset after this one because we need a new offset <ide> var relativeOffset = 1; <ide> for (var i = 0; i < count + 1; i++) { <del> var bytes = FontsUtils.integerToBytes(relativeOffset, 4); <del> for (var j = 0; j < bytes.length; j++) <del> data += String.fromCharCode(bytes[j]); <add> data += String.fromCharCode(relativeOffset >> 24, relativeOffset >> 16, <add> relativeOffset >> 8, relativeOffset & 0xff); <ide> <ide> if (objects[i]) <ide> relativeOffset += objects[i].length; <ide> CFF.prototype = { <ide> }; <ide> <ide> charstrings.sort(function charstrings_sort(a, b) { <del> return a.unicode > b.unicode; <add> return a.unicode - b.unicode; <ide> }); <ide> return charstrings; <ide> }, <ide> CFF.prototype = { <ide> if (index == -1) <ide> index = 0; <ide> <del> var bytes = FontsUtils.integerToBytes(index, 2); <del> charset += String.fromCharCode(bytes[0]) + String.fromCharCode(bytes[1]); <add> charset += String.fromCharCode(index >> 8, index & 0xff); <ide> } <ide> return charset; <ide> })(this), <ide><path>pdf.js <ide> var Catalog = (function() { <ide> <ide> var PDFDoc = (function() { <ide> function constructor(stream) { <add> assertWellFormed(stream.length > 0, "stream must have data"); <ide> this.stream = stream; <ide> this.setup(); <ide> } <ide> var CanvasGraphics = (function() { <ide> this.setFillRGBColor.apply(this, color); <ide> }, <ide> setFillColorN: function(/*...*/) { <del> var cs = this.getStrokeColorSpace(); <add> var cs = this.getFillColorSpace(); <ide> <ide> if (cs.name == "Pattern") { <ide> var patternName = arguments[0]; <ide> var ColorSpace = (function() { <ide> constructor.parse = function colorspace_parse(cs, xref, res) { <ide> if (IsName(cs)) { <ide> var colorSpaces = res.get("ColorSpace"); <del> var refcs = colorSpaces.get(cs.name); <del> if (refcs) <del> cs = refcs; <add> if (colorSpaces) { <add> var refcs = colorSpaces.get(cs.name); <add> if (refcs) <add> cs = refcs; <add> } <ide> } <ide> <ide> cs = xref.fetchIfRef(cs); <ide><path>test/test.py <ide> def sendFile(self, path, ext): <ide> self.send_header("Content-Type", MIMEs[ext]) <ide> self.send_header("Content-Length", os.path.getsize(path)) <ide> self.end_headers() <del> with open(path) as f: <add> with open(path, "rb") as f: <ide> self.wfile.write(f.read()) <ide> <ide> def do_GET(self): <ide> def downloadLinkedPDFs(manifestList): <ide> sys.stdout.flush() <ide> response = urllib2.urlopen(link) <ide> <del> with open(f, 'w') as out: <add> with open(f, 'wb') as out: <ide> out.write(response.read()) <ide> <ide> print 'done'
3
Javascript
Javascript
use internal/validators in event_target.js
5e6ae9aa5d228eb9b54f3ebde6a3d791dff3d0ed
<ide><path>lib/internal/event_target.js <ide> const { <ide> Object, <ide> Set, <ide> Symbol, <del> NumberIsNaN, <ide> SymbolToStringTag, <ide> } = primordials; <ide> <ide> const { <ide> codes: { <ide> ERR_INVALID_ARG_TYPE, <ide> ERR_EVENT_RECURSION, <del> ERR_OUT_OF_RANGE, <ide> ERR_MISSING_ARGS <ide> } <ide> } = require('internal/errors'); <add>const { validateInteger, validateObject } = require('internal/validators'); <ide> <ide> const { customInspectSymbol } = require('internal/util'); <ide> const { inspect } = require('util'); <ide> class Event { <ide> <ide> <ide> constructor(type, options) { <del> if (arguments.length === 0) { <add> if (arguments.length === 0) <ide> throw new ERR_MISSING_ARGS('type'); <del> } <del> if (options != null && typeof options !== 'object') <del> throw new ERR_INVALID_ARG_TYPE('options', 'object', options); <add> if (options != null) <add> validateObject(options, 'options'); <ide> const { cancelable, bubbles, composed } = { ...options }; <ide> this.#cancelable = !!cancelable; <ide> this.#bubbles = !!bubbles; <ide> class NodeEventTarget extends EventTarget { <ide> } <ide> <ide> setMaxListeners(n) { <del> if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { <del> throw new ERR_OUT_OF_RANGE('n', 'a non-negative number', n); <del> } <add> validateInteger(n, 'n', 0); <ide> this.#maxListeners = n; <ide> return this; <ide> } <ide> function validateListener(listener) { <ide> } <ide> <ide> function validateEventListenerOptions(options) { <del> if (typeof options === 'boolean') { <del> options = { capture: options }; <del> } <del> if (options == null || typeof options !== 'object') <del> throw new ERR_INVALID_ARG_TYPE('options', 'object', options); <add> if (typeof options === 'boolean') <add> return { capture: options }; <add> validateObject(options, 'options'); <ide> const { <ide> once = false, <ide> capture = false,
1
Javascript
Javascript
fix proptypes test in ie10
7cd5e9b399b32daf3f4b1c494cfb4587067360eb
<ide><path>src/core/__tests__/ReactPropTypes-test.js <ide> describe('Component Type', function() { <ide> describe('Instance Types', function() { <ide> it("should warn for invalid instances", function() { <ide> function Person() {} <add> var personName = Person.name || '<<anonymous>>'; <add> var dateName = Date.name || '<<anonymous>>'; <add> var regExpName = RegExp.name || '<<anonymous>>'; <ide> <ide> typeCheckFail( <ide> PropTypes.instanceOf(Person), <ide> false, <ide> 'Invalid prop `testProp` supplied to `testComponent`, expected ' + <del> 'instance of `Person`.' <add> 'instance of `' + personName + '`.' <ide> ); <ide> typeCheckFail( <ide> PropTypes.instanceOf(Person), <ide> {}, <ide> 'Invalid prop `testProp` supplied to `testComponent`, expected ' + <del> 'instance of `Person`.' <add> 'instance of `' + personName + '`.' <ide> ); <ide> typeCheckFail( <ide> PropTypes.instanceOf(Person), <ide> '', <ide> 'Invalid prop `testProp` supplied to `testComponent`, expected ' + <del> 'instance of `Person`.' <add> 'instance of `' + personName + '`.' <ide> ); <ide> typeCheckFail( <ide> PropTypes.instanceOf(Date), <ide> {}, <ide> 'Invalid prop `testProp` supplied to `testComponent`, expected ' + <del> 'instance of `Date`.' <add> 'instance of `' + dateName + '`.' <ide> ); <ide> typeCheckFail( <ide> PropTypes.instanceOf(RegExp), <ide> {}, <ide> 'Invalid prop `testProp` supplied to `testComponent`, expected ' + <del> 'instance of `RegExp`.' <add> 'instance of `' + regExpName + '`.' <ide> ); <ide> }); <ide>
1
Ruby
Ruby
add serializers for time, date and datetime
d9a5c7011f62dd771a2fa430090e068b1f9785f3
<ide><path>activejob/lib/active_job/serializers.rb <ide> module Serializers <ide> autoload :StandardTypeSerializer <ide> autoload :SymbolSerializer <ide> autoload :DurationSerializer <add> autoload :DateSerializer <add> autoload :TimeSerializer <add> autoload :DateTimeSerializer <ide> <ide> mattr_accessor :_additional_serializers <ide> self._additional_serializers = Set.new <ide> def reserved_serializers_keys <ide> HashSerializer, <ide> ArraySerializer, <ide> SymbolSerializer, <del> DurationSerializer <add> DurationSerializer, <add> DateTimeSerializer, <add> DateSerializer, <add> TimeSerializer <ide> end <ide> end <ide><path>activejob/lib/active_job/serializers/date_serializer.rb <add># frozen_string_literal: true <add> <add>module ActiveJob <add> module Serializers <add> class DateSerializer < ObjectSerializer # :nodoc: <add> def serialize(date) <add> super("value" => date.iso8601) <add> end <add> <add> def deserialize(hash) <add> Date.iso8601(hash["value"]) <add> end <add> <add> private <add> <add> def klass <add> Date <add> end <add> end <add> end <add>end <ide><path>activejob/lib/active_job/serializers/date_time_serializer.rb <add># frozen_string_literal: true <add> <add>module ActiveJob <add> module Serializers <add> class DateTimeSerializer < ObjectSerializer # :nodoc: <add> def serialize(time) <add> super("value" => time.iso8601) <add> end <add> <add> def deserialize(hash) <add> DateTime.iso8601(hash["value"]) <add> end <add> <add> private <add> <add> def klass <add> DateTime <add> end <add> end <add> end <add>end <ide><path>activejob/lib/active_job/serializers/duration_serializer.rb <add># frozen_string_literal: true <add> <ide> module ActiveJob <ide> module Serializers <ide> class DurationSerializer < ObjectSerializer # :nodoc: <ide><path>activejob/lib/active_job/serializers/symbol_serializer.rb <add># frozen_string_literal: true <add> <ide> module ActiveJob <ide> module Serializers <ide> class SymbolSerializer < ObjectSerializer # :nodoc: <ide><path>activejob/lib/active_job/serializers/time_serializer.rb <add># frozen_string_literal: true <add> <add>module ActiveJob <add> module Serializers <add> class TimeSerializer < ObjectSerializer # :nodoc: <add> def serialize(time) <add> super("value" => time.iso8601) <add> end <add> <add> def deserialize(hash) <add> Time.iso8601(hash["value"]) <add> end <add> <add> private <add> <add> def klass <add> Time <add> end <add> end <add> end <add>end <ide><path>activejob/test/cases/argument_serialization_test.rb <ide> class ArgumentSerializationTest < ActiveSupport::TestCase <ide> <ide> [ nil, 1, 1.0, 1_000_000_000_000_000_000_000, <ide> "a", true, false, BigDecimal.new(5), <del> :a, 1.day, <add> :a, 1.day, Date.new(2001, 2, 3), Time.new(2002, 10, 31, 2, 2, 2, "+02:00"), <add> DateTime.new(2001, 2, 3, 4, 5, 6, '+03:00'), <add> ActiveSupport::TimeWithZone.new(Time.utc(1999, 12, 31, 23, 59, 59), ActiveSupport::TimeZone["UTC"]), <ide> [ 1, "a" ], <ide> { "a" => 1 } <ide> ].each do |arg|
7
Python
Python
clarify dtype default for logspace and geomspace
e84f49e62d9d951af13a08fc103ef90bae368f6f
<ide><path>numpy/core/function_base.py <ide> def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, <ide> between samples. <ide> dtype : dtype, optional <ide> The type of the output array. If `dtype` is not given, the data type <del> is inferred from `start` and `stop`. The inferred dtype will <del> never be an integer; `float` is chosen even if the arguments would <del> produce an array of integers. <add> is inferred from `start` and `stop`. The inferred dtype will never be <add> an integer; `float` is chosen even if the arguments would produce an <add> array of integers. <ide> <ide> .. versionadded:: 1.9.0 <ide> <ide> def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, <ide> ``ln(samples) / ln(base)`` (or ``log_base(samples)``) is uniform. <ide> Default is 10.0. <ide> dtype : dtype <del> The type of the output array. If `dtype` is not given, infer the data <del> type from the other input arguments. <add> The type of the output array. If `dtype` is not given, the data type <add> is inferred from `start` and `stop`. The inferred type will never be <add> an integer; `float` is chosen even if the arguments would produce an <add> array of integers. <ide> axis : int, optional <ide> The axis in the result to store the samples. Relevant only if start <ide> or stop are array-like. By default (0), the samples will be along a <ide> def geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0): <ide> If true, `stop` is the last sample. Otherwise, it is not included. <ide> Default is True. <ide> dtype : dtype <del> The type of the output array. If `dtype` is not given, infer the data <del> type from the other input arguments. <add> The type of the output array. If `dtype` is not given, the data type <add> is inferred from `start` and `stop`. The inferred dtype will never be <add> an integer; `float` is chosen even if the arguments would produce an <add> array of integers. <ide> axis : int, optional <ide> The axis in the result to store the samples. Relevant only if start <ide> or stop are array-like. By default (0), the samples will be along a
1
Javascript
Javascript
convert vars to let/const
ea9714807b0d694e6f67d52ccf7aac93439b16f7
<ide><path>packages/react-native-renderer/index.js <ide> <ide> 'use strict'; <ide> <del>var ReactNativeRenderer = require('./src/ReactNativeRenderer'); <add>const ReactNativeRenderer = require('./src/ReactNativeRenderer'); <ide> <ide> // TODO: decide on the top-level export form. <ide> // This is hacky but makes it work with both Rollup and Jest. <ide><path>packages/react-native-renderer/src/NativeMethodsMixinUtils.js <ide> export function mountSafeCallback(context: any, callback: ?Function): any { <ide> <ide> export function throwOnStylesProp(component: any, props: any) { <ide> if (props.styles !== undefined) { <del> var owner = component._owner || null; <del> var name = component.constructor.displayName; <del> var msg = <add> const owner = component._owner || null; <add> const name = component.constructor.displayName; <add> let msg = <ide> '`styles` is not a supported property of `' + <ide> name + <ide> '`, did ' + <ide> export function throwOnStylesProp(component: any, props: any) { <ide> } <ide> <ide> export function warnForStyleProps(props: any, validAttributes: any) { <del> for (var key in validAttributes.style) { <add> for (const key in validAttributes.style) { <ide> if (!(validAttributes[key] || props[key] === undefined)) { <ide> console.error( <ide> 'You are setting the style `{ ' + <ide><path>packages/react-native-renderer/src/ReactNativeAttributePayload.js <ide> import flattenStyle from 'flattenStyle'; <ide> <ide> import ReactNativePropRegistry from './ReactNativePropRegistry'; <ide> <del>var emptyObject = {}; <add>const emptyObject = {}; <ide> <ide> /** <ide> * Create a payload that contains all the updates between two sets of props. <ide> type AttributeConfiguration = { <ide> type NestedNode = Array<NestedNode> | Object | number; <ide> <ide> // Tracks removed keys <del>var removedKeys = null; <del>var removedKeyCount = 0; <add>let removedKeys = null; <add>let removedKeyCount = 0; <ide> <ide> function defaultDiffer(prevProp: mixed, nextProp: mixed): boolean { <ide> if (typeof nextProp !== 'object' || nextProp === null) { <ide> function restoreDeletedValuesInNestedArray( <ide> validAttributes: AttributeConfiguration, <ide> ) { <ide> if (Array.isArray(node)) { <del> var i = node.length; <add> let i = node.length; <ide> while (i-- && removedKeyCount > 0) { <ide> restoreDeletedValuesInNestedArray( <ide> updatePayload, <ide> function restoreDeletedValuesInNestedArray( <ide> ); <ide> } <ide> } else if (node && removedKeyCount > 0) { <del> var obj = resolveObject(node); <del> for (var propKey in removedKeys) { <add> const obj = resolveObject(node); <add> for (const propKey in removedKeys) { <ide> if (!removedKeys[propKey]) { <ide> continue; <ide> } <del> var nextProp = obj[propKey]; <add> let nextProp = obj[propKey]; <ide> if (nextProp === undefined) { <ide> continue; <ide> } <ide> <del> var attributeConfig = validAttributes[propKey]; <add> const attributeConfig = validAttributes[propKey]; <ide> if (!attributeConfig) { <ide> continue; // not a valid native prop <ide> } <ide> function restoreDeletedValuesInNestedArray( <ide> typeof attributeConfig.process === 'function' <ide> ) { <ide> // case: CustomAttributeConfiguration <del> var nextValue = <add> const nextValue = <ide> typeof attributeConfig.process === 'function' <ide> ? attributeConfig.process(nextProp) <ide> : nextProp; <ide> function diffNestedArrayProperty( <ide> nextArray: Array<NestedNode>, <ide> validAttributes: AttributeConfiguration, <ide> ): ?Object { <del> var minLength = <add> const minLength = <ide> prevArray.length < nextArray.length ? prevArray.length : nextArray.length; <del> var i; <add> let i; <ide> for (i = 0; i < minLength; i++) { <ide> // Diff any items in the array in the forward direction. Repeated keys <ide> // will be overwritten by later values. <ide> function addNestedProperty( <ide> ); <ide> } <ide> <del> for (var i = 0; i < nextProp.length; i++) { <add> for (let i = 0; i < nextProp.length; i++) { <ide> // Add all the properties of the array. <ide> updatePayload = addNestedProperty( <ide> updatePayload, <ide> function clearNestedProperty( <ide> ); <ide> } <ide> <del> for (var i = 0; i < prevProp.length; i++) { <add> for (let i = 0; i < prevProp.length; i++) { <ide> // Add all the properties of the array. <ide> updatePayload = clearNestedProperty( <ide> updatePayload, <ide> function diffProperties( <ide> nextProps: Object, <ide> validAttributes: AttributeConfiguration, <ide> ): ?Object { <del> var attributeConfig: ?(CustomAttributeConfiguration | AttributeConfiguration); <del> var nextProp; <del> var prevProp; <add> let attributeConfig: ?(CustomAttributeConfiguration | AttributeConfiguration); <add> let nextProp; <add> let prevProp; <ide> <del> for (var propKey in nextProps) { <add> for (const propKey in nextProps) { <ide> attributeConfig = validAttributes[propKey]; <ide> if (!attributeConfig) { <ide> continue; // not a valid native prop <ide> function diffProperties( <ide> typeof attributeConfig.process === 'function' <ide> ) { <ide> // case: CustomAttributeConfiguration <del> var nextValue = <add> const nextValue = <ide> typeof attributeConfig.process === 'function' <ide> ? attributeConfig.process(nextProp) <ide> : nextProp; <ide> function diffProperties( <ide> typeof attributeConfig.process === 'function' <ide> ) { <ide> // case: CustomAttributeConfiguration <del> var shouldUpdate = <add> const shouldUpdate = <ide> prevProp === undefined || <ide> (typeof attributeConfig.diff === 'function' <ide> ? attributeConfig.diff(prevProp, nextProp) <ide> : defaultDiffer(prevProp, nextProp)); <ide> if (shouldUpdate) { <del> nextValue = <add> const nextValue = <ide> typeof attributeConfig.process === 'function' <ide> ? attributeConfig.process(nextProp) <ide> : nextProp; <ide> function diffProperties( <ide> // Also iterate through all the previous props to catch any that have been <ide> // removed and make sure native gets the signal so it can reset them to the <ide> // default. <del> for (propKey in prevProps) { <add> for (const propKey in prevProps) { <ide> if (nextProps[propKey] !== undefined) { <ide> continue; // we've already covered this key in the previous pass <ide> } <ide><path>packages/react-native-renderer/src/ReactNativeComponent.js <ide> class ReactNativeComponent<DefaultProps, Props, State> extends React.Component< <ide> const viewConfig: ReactNativeBaseComponentViewConfig = <ide> maybeInstance.viewConfig; <ide> <del> var updatePayload = ReactNativeAttributePayload.create( <add> const updatePayload = ReactNativeAttributePayload.create( <ide> nativeProps, <ide> viewConfig.validAttributes, <ide> ); <ide><path>packages/react-native-renderer/src/ReactNativeComponentTree.js <ide> <ide> import invariant from 'fbjs/lib/invariant'; <ide> <del>var instanceCache = {}; <del>var instanceProps = {}; <add>const instanceCache = {}; <add>const instanceProps = {}; <ide> <ide> export function precacheFiberNode(hostInst, tag) { <ide> instanceCache[tag] = hostInst; <ide> function getInstanceFromTag(tag) { <ide> } <ide> <ide> function getTagFromInstance(inst) { <del> var tag = inst.stateNode._nativeTag; <add> const tag = inst.stateNode._nativeTag; <ide> invariant(tag, 'All native instances should have a tag.'); <ide> return tag; <ide> } <ide><path>packages/react-native-renderer/src/ReactNativeEventEmitter.js <ide> export {getListener, registrationNameModules as registrationNames}; <ide> */ <ide> <ide> // Shared default empty native event - conserve memory. <del>var EMPTY_NATIVE_EVENT = {}; <add>const EMPTY_NATIVE_EVENT = {}; <ide> <ide> /** <ide> * Selects a subsequence of `Touch`es, without destroying `touches`. <ide> var EMPTY_NATIVE_EVENT = {}; <ide> * @param {Array<number>} indices Indices by which to pull subsequence. <ide> * @return {Array<Touch>} Subsequence of touch objects. <ide> */ <del>var touchSubsequence = function(touches, indices) { <del> var ret = []; <del> for (var i = 0; i < indices.length; i++) { <add>const touchSubsequence = function(touches, indices) { <add> const ret = []; <add> for (let i = 0; i < indices.length; i++) { <ide> ret.push(touches[indices[i]]); <ide> } <ide> return ret; <ide> var touchSubsequence = function(touches, indices) { <ide> * @param {Array<number>} indices Indices to remove from `touches`. <ide> * @return {Array<Touch>} Subsequence of removed touch objects. <ide> */ <del>var removeTouchesAtIndices = function( <add>const removeTouchesAtIndices = function( <ide> touches: Array<Object>, <ide> indices: Array<number>, <ide> ): Array<Object> { <del> var rippedOut = []; <add> const rippedOut = []; <ide> // use an unsafe downcast to alias to nullable elements, <ide> // so we can delete and then compact. <del> var temp: Array<?Object> = (touches: Array<any>); <del> for (var i = 0; i < indices.length; i++) { <del> var index = indices[i]; <add> const temp: Array<?Object> = (touches: Array<any>); <add> for (let i = 0; i < indices.length; i++) { <add> const index = indices[i]; <ide> rippedOut.push(touches[index]); <ide> temp[index] = null; <ide> } <del> var fillAt = 0; <del> for (var j = 0; j < temp.length; j++) { <del> var cur = temp[j]; <add> let fillAt = 0; <add> for (let j = 0; j < temp.length; j++) { <add> const cur = temp[j]; <ide> if (cur !== null) { <ide> temp[fillAt++] = cur; <ide> } <ide> export function _receiveRootNodeIDEvent( <ide> topLevelType: string, <ide> nativeEventParam: ?Object, <ide> ) { <del> var nativeEvent = nativeEventParam || EMPTY_NATIVE_EVENT; <del> var inst = getInstanceFromNode(rootNodeID); <add> const nativeEvent = nativeEventParam || EMPTY_NATIVE_EVENT; <add> const inst = getInstanceFromNode(rootNodeID); <ide> batchedUpdates(function() { <ide> handleTopLevel(topLevelType, inst, nativeEvent, nativeEvent.target); <ide> }); <ide> export function receiveTouches( <ide> touches: Array<Object>, <ide> changedIndices: Array<number>, <ide> ) { <del> var changedTouches = <add> const changedTouches = <ide> eventTopLevelType === 'topTouchEnd' || <ide> eventTopLevelType === 'topTouchCancel' <ide> ? removeTouchesAtIndices(touches, changedIndices) <ide> : touchSubsequence(touches, changedIndices); <ide> <del> for (var jj = 0; jj < changedTouches.length; jj++) { <del> var touch = changedTouches[jj]; <add> for (let jj = 0; jj < changedTouches.length; jj++) { <add> const touch = changedTouches[jj]; <ide> // Touch objects can fulfill the role of `DOM` `Event` objects if we set <ide> // the `changedTouches`/`touches`. This saves allocations. <ide> touch.changedTouches = changedTouches; <ide> touch.touches = touches; <del> var nativeEvent = touch; <del> var rootNodeID = null; <del> var target = nativeEvent.target; <add> const nativeEvent = touch; <add> let rootNodeID = null; <add> const target = nativeEvent.target; <ide> if (target !== null && target !== undefined) { <ide> if (target < ReactNativeTagHandles.tagsStartAt) { <ide> if (__DEV__) { <ide><path>packages/react-native-renderer/src/ReactNativeEventPluginOrder.js <ide> * @flow <ide> */ <ide> <del>var ReactNativeEventPluginOrder = [ <add>const ReactNativeEventPluginOrder = [ <ide> 'ResponderEventPlugin', <ide> 'ReactNativeBridgeEventPlugin', <ide> ]; <ide><path>packages/react-native-renderer/src/ReactNativeFiberHostComponent.js <ide> class ReactNativeFiberHostComponent { <ide> warnForStyleProps(nativeProps, this.viewConfig.validAttributes); <ide> } <ide> <del> var updatePayload = ReactNativeAttributePayload.create( <add> const updatePayload = ReactNativeAttributePayload.create( <ide> nativeProps, <ide> this.viewConfig.validAttributes, <ide> ); <ide><path>packages/react-native-renderer/src/ReactNativeFiberInspector.js <ide> import {getClosestInstanceFromNode} from './ReactNativeComponentTree'; <ide> let getInspectorDataForViewTag; <ide> <ide> if (__DEV__) { <del> var traverseOwnerTreeUp = function(hierarchy, instance: any) { <add> const traverseOwnerTreeUp = function(hierarchy, instance: any) { <ide> if (instance) { <ide> hierarchy.unshift(instance); <ide> traverseOwnerTreeUp(hierarchy, instance._debugOwner); <ide> } <ide> }; <ide> <del> var getOwnerHierarchy = function(instance: any) { <del> var hierarchy = []; <add> const getOwnerHierarchy = function(instance: any) { <add> const hierarchy = []; <ide> traverseOwnerTreeUp(hierarchy, instance); <ide> return hierarchy; <ide> }; <ide> <del> var lastNonHostInstance = function(hierarchy) { <add> const lastNonHostInstance = function(hierarchy) { <ide> for (let i = hierarchy.length - 1; i > 1; i--) { <ide> const instance = hierarchy[i]; <ide> <ide> if (__DEV__) { <ide> return hierarchy[0]; <ide> }; <ide> <del> var getHostProps = function(fiber) { <add> const getHostProps = function(fiber) { <ide> const host = findCurrentHostFiber(fiber); <ide> if (host) { <ide> return host.memoizedProps || emptyObject; <ide> } <ide> return emptyObject; <ide> }; <ide> <del> var getHostNode = function(fiber: Fiber | null, findNodeHandle) { <add> const getHostNode = function(fiber: Fiber | null, findNodeHandle) { <ide> let hostNode; <ide> // look for children first for the hostNode <ide> // as composite fibers do not have a hostNode <ide> if (__DEV__) { <ide> return null; <ide> }; <ide> <del> var createHierarchy = function(fiberHierarchy) { <add> const createHierarchy = function(fiberHierarchy) { <ide> return fiberHierarchy.map(fiber => ({ <ide> name: getComponentName(fiber), <ide> getInspectorData: findNodeHandle => ({ <ide><path>packages/react-native-renderer/src/ReactNativeGlobalResponderHandler.js <ide> // Module provided by RN: <ide> import UIManager from 'UIManager'; <ide> <del>var ReactNativeGlobalResponderHandler = { <add>const ReactNativeGlobalResponderHandler = { <ide> onChange: function(from, to, blockNativeResponder) { <ide> if (to !== null) { <del> var tag = to.stateNode._nativeTag; <add> const tag = to.stateNode._nativeTag; <ide> UIManager.setJSResponder(tag, blockNativeResponder); <ide> } else { <ide> UIManager.clearJSResponder(); <ide><path>packages/react-native-renderer/src/ReactNativePropRegistry.js <ide> * @flow <ide> */ <ide> <del>var objects = {}; <del>var uniqueID = 1; <del>var emptyObject = {}; <add>const objects = {}; <add>let uniqueID = 1; <add>const emptyObject = {}; <ide> <ide> class ReactNativePropRegistry { <ide> static register(object: Object): number { <del> var id = ++uniqueID; <add> const id = ++uniqueID; <ide> if (__DEV__) { <ide> Object.freeze(object); <ide> } <ide> class ReactNativePropRegistry { <ide> return emptyObject; <ide> } <ide> <del> var object = objects[id]; <add> const object = objects[id]; <ide> if (!object) { <ide> console.warn('Invalid style with id `' + id + '`. Skipping ...'); <ide> return emptyObject; <ide><path>packages/react-native-renderer/src/ReactNativeTagHandles.js <ide> import invariant from 'fbjs/lib/invariant'; <ide> * Why: Because `dangerouslyReplaceNodeWithMarkupByID` relies on being able to <ide> * unmount a component with a `rootNodeID`, then mount a new one in its place, <ide> */ <del>var INITIAL_TAG_COUNT = 1; <del>var ReactNativeTagHandles = { <add>const INITIAL_TAG_COUNT = 1; <add>const ReactNativeTagHandles = { <ide> tagsStartAt: INITIAL_TAG_COUNT, <ide> tagCount: INITIAL_TAG_COUNT, <ide> <ide> var ReactNativeTagHandles = { <ide> while (this.reactTagIsNativeTopRootID(ReactNativeTagHandles.tagCount)) { <ide> ReactNativeTagHandles.tagCount++; <ide> } <del> var tag = ReactNativeTagHandles.tagCount; <add> const tag = ReactNativeTagHandles.tagCount; <ide> ReactNativeTagHandles.tagCount++; <ide> return tag; <ide> }, <ide><path>packages/react-native-renderer/src/__mocks__/BatchedBridge.js <ide> <ide> 'use strict'; <ide> <del>var BatchedBridge = { <add>const BatchedBridge = { <ide> registerCallableModule: jest.fn(), <ide> }; <ide> <ide><path>packages/react-native-renderer/src/__mocks__/RCTEventEmitter.js <ide> <ide> 'use strict'; <ide> <del>var RCTEventEmitter = { <add>const RCTEventEmitter = { <ide> register: jest.fn(), <ide> }; <ide> <ide><path>packages/react-native-renderer/src/__mocks__/RTManager.js <ide> <ide> // Mock of the Native Hooks <ide> <del>var RCTRTManager = { <add>const RCTRTManager = { <ide> createNode: jest.fn(function createView(tag, classType, props) {}), <ide> beginUpdates: jest.fn(function beginUpdates() {}), <ide> appendChildToContext: jest.fn(function appendChildToContext( <ide><path>packages/react-native-renderer/src/__mocks__/TextInputState.js <ide> // Mock of the Native Hooks <ide> // TODO: Should this move into the components themselves? E.g. focusable <ide> <del>var TextInputState = {}; <add>const TextInputState = {}; <ide> <ide> module.exports = TextInputState; <ide><path>packages/react-native-renderer/src/__mocks__/UIManager.js <ide> function removeChild(parent, child) { <ide> childInfo.parent = null; <ide> } <ide> <del>var RCTUIManager = { <add>const RCTUIManager = { <ide> __dumpHierarchyForJestTestsOnly: function() { <ide> return roots.map(tag => dumpSubtree(tag, 0)).join('\n'); <ide> <ide><path>packages/react-native-renderer/src/__mocks__/View.js <ide> <ide> 'use strict'; <ide> <del>var createReactNativeComponentClass = require('../createReactNativeComponentClass') <add>const createReactNativeComponentClass = require('../createReactNativeComponentClass') <ide> .default; <ide> <del>var View = createReactNativeComponentClass({ <add>const View = createReactNativeComponentClass({ <ide> validAttributes: {}, <ide> uiViewClassName: 'View', <ide> }); <ide><path>packages/react-native-renderer/src/__mocks__/deepDiffer.js <ide> <ide> // TODO: Move deepDiffer into react <ide> <del>var deepDiffer = function(one: any, two: any): boolean { <add>const deepDiffer = function(one: any, two: any): boolean { <ide> if (one === two) { <ide> // Short circuit on identical object references instead of traversing them. <ide> return false; <ide> var deepDiffer = function(one: any, two: any): boolean { <ide> } <ide> if (Array.isArray(one)) { <ide> // We know two is also an array because the constructors are equal <del> var len = one.length; <add> const len = one.length; <ide> if (two.length !== len) { <ide> return true; <ide> } <del> for (var ii = 0; ii < len; ii++) { <add> for (let ii = 0; ii < len; ii++) { <ide> if (deepDiffer(one[ii], two[ii])) { <ide> return true; <ide> } <ide> } <ide> } else { <del> for (var key in one) { <add> for (const key in one) { <ide> if (deepDiffer(one[key], two[key])) { <ide> return true; <ide> } <ide> } <del> for (var twoKey in two) { <add> for (const twoKey in two) { <ide> // The only case we haven't checked yet is keys that are in two but aren't <ide> // in one, which means they are different. <ide> if (one[twoKey] === undefined && two[twoKey] !== undefined) { <ide><path>packages/react-native-renderer/src/__mocks__/deepFreezeAndThrowOnMutationInDev.js <ide> <ide> // TODO: move into react or fbjs <ide> <del>var deepFreezeAndThrowOnMutationInDev = function() {}; <add>const deepFreezeAndThrowOnMutationInDev = function() {}; <ide> <ide> module.exports = deepFreezeAndThrowOnMutationInDev; <ide><path>packages/react-native-renderer/src/__mocks__/flattenStyle.js <ide> <ide> // TODO: Move flattenStyle into react <ide> <del>var flattenStyle = function() {}; <add>const flattenStyle = function() {}; <ide> <ide> module.exports = flattenStyle; <ide><path>packages/react-native-renderer/src/__tests__/ReactNativeAttributePayload-test.js <ide> */ <ide> 'use strict'; <ide> <del>var ReactNativeAttributePayload = require('../ReactNativeAttributePayload'); <del>var ReactNativePropRegistry = require('../ReactNativePropRegistry').default; <add>const ReactNativeAttributePayload = require('../ReactNativeAttributePayload'); <add>const ReactNativePropRegistry = require('../ReactNativePropRegistry').default; <ide> <del>var diff = ReactNativeAttributePayload.diff; <add>const diff = ReactNativeAttributePayload.diff; <ide> <ide> describe('ReactNativeAttributePayload', () => { <ide> it('should work with simple example', () => { <ide> describe('ReactNativeAttributePayload', () => { <ide> }); <ide> <ide> it('should use the diff attribute', () => { <del> var diffA = jest.fn((a, b) => true); <del> var diffB = jest.fn((a, b) => false); <add> const diffA = jest.fn((a, b) => true); <add> const diffB = jest.fn((a, b) => false); <ide> expect( <ide> diff( <ide> {a: [1], b: [3]}, <ide> describe('ReactNativeAttributePayload', () => { <ide> }); <ide> <ide> it('should not use the diff attribute on addition/removal', () => { <del> var diffA = jest.fn(); <del> var diffB = jest.fn(); <add> const diffA = jest.fn(); <add> const diffB = jest.fn(); <ide> expect( <ide> diff({a: [1]}, {b: [2]}, {a: {diff: diffA}, b: {diff: diffB}}), <ide> ).toEqual({a: null, b: [2]}); <ide> describe('ReactNativeAttributePayload', () => { <ide> }); <ide> <ide> it('should flatten nested styles and predefined styles', () => { <del> var validStyleAttribute = {someStyle: {foo: true, bar: true}}; <add> const validStyleAttribute = {someStyle: {foo: true, bar: true}}; <ide> <ide> expect( <ide> diff({}, {someStyle: [{foo: 1}, {bar: 2}]}, validStyleAttribute), <ide> describe('ReactNativeAttributePayload', () => { <ide> diff({someStyle: [{foo: 1}, {bar: 2}]}, {}, validStyleAttribute), <ide> ).toEqual({foo: null, bar: null}); <ide> <del> var barStyle = ReactNativePropRegistry.register({ <add> const barStyle = ReactNativePropRegistry.register({ <ide> bar: 3, <ide> }); <ide> <ide> describe('ReactNativeAttributePayload', () => { <ide> }); <ide> <ide> it('should reset a value to a previous if it is removed', () => { <del> var validStyleAttribute = {someStyle: {foo: true, bar: true}}; <add> const validStyleAttribute = {someStyle: {foo: true, bar: true}}; <ide> <ide> expect( <ide> diff( <ide> describe('ReactNativeAttributePayload', () => { <ide> }); <ide> <ide> it('should not clear removed props if they are still in another slot', () => { <del> var validStyleAttribute = {someStyle: {foo: true, bar: true}}; <add> const validStyleAttribute = {someStyle: {foo: true, bar: true}}; <ide> <ide> expect( <ide> diff( <ide> describe('ReactNativeAttributePayload', () => { <ide> }); <ide> <ide> it('should clear a prop if a later style is explicit null/undefined', () => { <del> var validStyleAttribute = {someStyle: {foo: true, bar: true}}; <add> const validStyleAttribute = {someStyle: {foo: true, bar: true}}; <ide> expect( <ide> diff( <ide> {someStyle: [{}, {foo: 3, bar: 2}]}, <ide> describe('ReactNativeAttributePayload', () => { <ide> <ide> // Test the same case with object equality because an early bailout doesn't <ide> // work in this case. <del> var fooObj = {foo: 3}; <add> const fooObj = {foo: 3}; <ide> expect( <ide> diff( <ide> {someStyle: [{foo: 1}, fooObj]}, <ide><path>packages/react-native-renderer/src/__tests__/ReactNativeEvents-test.internal.js <ide> <ide> 'use strict'; <ide> <del>var PropTypes; <del>var RCTEventEmitter; <del>var React; <del>var ReactNative; <del>var ReactNativeBridgeEventPlugin; <del>var ResponderEventPlugin; <del>var UIManager; <del>var createReactNativeComponentClass; <add>let PropTypes; <add>let RCTEventEmitter; <add>let React; <add>let ReactNative; <add>let ReactNativeBridgeEventPlugin; <add>let ResponderEventPlugin; <add>let UIManager; <add>let createReactNativeComponentClass; <ide> <ide> // Parallels requireNativeComponent() in that it lazily constructs a view config, <ide> // And registers view manager event types with ReactNativeBridgeEventPlugin. <ide> beforeEach(() => { <ide> <ide> it('fails if unknown/unsupported event types are dispatched', () => { <ide> expect(RCTEventEmitter.register.mock.calls.length).toBe(1); <del> var EventEmitter = RCTEventEmitter.register.mock.calls[0][0]; <del> var View = fakeRequireNativeComponent('View', {}); <add> const EventEmitter = RCTEventEmitter.register.mock.calls[0][0]; <add> const View = fakeRequireNativeComponent('View', {}); <ide> <ide> ReactNative.render(<View onUnspecifiedEvent={() => {}} />, 1); <ide> <ide> it('fails if unknown/unsupported event types are dispatched', () => { <ide> <ide> it('handles events', () => { <ide> expect(RCTEventEmitter.register.mock.calls.length).toBe(1); <del> var EventEmitter = RCTEventEmitter.register.mock.calls[0][0]; <del> var View = fakeRequireNativeComponent('View', {foo: true}); <add> const EventEmitter = RCTEventEmitter.register.mock.calls[0][0]; <add> const View = fakeRequireNativeComponent('View', {foo: true}); <ide> <del> var log = []; <add> const log = []; <ide> ReactNative.render( <ide> <View <ide> foo="outer" <ide> it('handles events', () => { <ide> <ide> // Don't depend on the order of createView() calls. <ide> // Stack creates views outside-in; fiber creates them inside-out. <del> var innerTag = UIManager.createView.mock.calls.find( <add> const innerTag = UIManager.createView.mock.calls.find( <ide> args => args[3].foo === 'inner', <ide> )[0]; <ide> <ide> it('handles events', () => { <ide> <ide> it('handles events on text nodes', () => { <ide> expect(RCTEventEmitter.register.mock.calls.length).toBe(1); <del> var EventEmitter = RCTEventEmitter.register.mock.calls[0][0]; <del> var Text = fakeRequireNativeComponent('Text', {}); <add> const EventEmitter = RCTEventEmitter.register.mock.calls[0][0]; <add> const Text = fakeRequireNativeComponent('Text', {}); <ide> <ide> class ContextHack extends React.Component { <ide> static childContextTypes = {isInAParentText: PropTypes.bool}; <ide> it('handles events on text nodes', () => { <ide> } <ide> } <ide> <del> var log = []; <add> const log = []; <ide> ReactNative.render( <ide> <ContextHack> <ide> <Text> <ide> it('handles events on text nodes', () => { <ide> <ide> // Don't depend on the order of createView() calls. <ide> // Stack creates views outside-in; fiber creates them inside-out. <del> var innerTagString = UIManager.createView.mock.calls.find( <add> const innerTagString = UIManager.createView.mock.calls.find( <ide> args => args[3] && args[3].text === 'Text Content', <ide> )[0]; <del> var innerTagNumber = UIManager.createView.mock.calls.find( <add> const innerTagNumber = UIManager.createView.mock.calls.find( <ide> args => args[3] && args[3].text === '123', <ide> )[0]; <ide> <ide> it('handles events on text nodes', () => { <ide> }); <ide> <ide> it('handles when a responder is unmounted while a touch sequence is in progress', () => { <del> var EventEmitter = RCTEventEmitter.register.mock.calls[0][0]; <del> var View = fakeRequireNativeComponent('View', {id: true}); <add> const EventEmitter = RCTEventEmitter.register.mock.calls[0][0]; <add> const View = fakeRequireNativeComponent('View', {id: true}); <ide> <ide> function getViewById(id) { <ide> return UIManager.createView.mock.calls.find( <ide> it('handles when a responder is unmounted while a touch sequence is in progress' <ide> return props ? props.id : null; <ide> } <ide> <del> var log = []; <add> const log = []; <ide> ReactNative.render( <ide> <View id="parent"> <ide> <View key={1}> <ide> it('handles when a responder is unmounted while a touch sequence is in progress' <ide> }); <ide> <ide> it('handles events without target', () => { <del> var EventEmitter = RCTEventEmitter.register.mock.calls[0][0]; <add> const EventEmitter = RCTEventEmitter.register.mock.calls[0][0]; <ide> <del> var View = fakeRequireNativeComponent('View', {id: true}); <add> const View = fakeRequireNativeComponent('View', {id: true}); <ide> <ide> function getViewById(id) { <ide> return UIManager.createView.mock.calls.find( <ide> it('handles events without target', () => { <ide> return props ? props.id : null; <ide> } <ide> <del> var log = []; <add> const log = []; <ide> <ide> function render(renderFirstComponent) { <ide> ReactNative.render( <ide><path>packages/react-native-renderer/src/__tests__/ReactNativeMount-test.internal.js <ide> <ide> 'use strict'; <ide> <del>var React; <del>var ReactNative; <del>var createReactNativeComponentClass; <del>var UIManager; <add>let React; <add>let ReactNative; <add>let createReactNativeComponentClass; <add>let UIManager; <ide> <ide> describe('ReactNative', () => { <ide> beforeEach(() => { <ide> describe('ReactNative', () => { <ide> }); <ide> <ide> it('should be able to create and render a native component', () => { <del> var View = createReactNativeComponentClass('View', () => ({ <add> const View = createReactNativeComponentClass('View', () => ({ <ide> validAttributes: {foo: true}, <ide> uiViewClassName: 'View', <ide> })); <ide> describe('ReactNative', () => { <ide> }); <ide> <ide> it('should be able to create and update a native component', () => { <del> var View = createReactNativeComponentClass('View', () => ({ <add> const View = createReactNativeComponentClass('View', () => ({ <ide> validAttributes: {foo: true}, <ide> uiViewClassName: 'View', <ide> })); <ide> describe('ReactNative', () => { <ide> }); <ide> <ide> it('returns the correct instance and calls it in the callback', () => { <del> var View = createReactNativeComponentClass('View', () => ({ <add> const View = createReactNativeComponentClass('View', () => ({ <ide> validAttributes: {foo: true}, <ide> uiViewClassName: 'View', <ide> })); <ide> <del> var a; <del> var b; <del> var c = ReactNative.render( <add> let a; <add> let b; <add> const c = ReactNative.render( <ide> <View foo="foo" ref={v => (a = v)} />, <ide> 11, <ide> function() { <ide> describe('ReactNative', () => { <ide> }); <ide> <ide> it('renders and reorders children', () => { <del> var View = createReactNativeComponentClass('View', () => ({ <add> const View = createReactNativeComponentClass('View', () => ({ <ide> validAttributes: {title: true}, <ide> uiViewClassName: 'View', <ide> })); <ide> <ide> class Component extends React.Component { <ide> render() { <del> var chars = this.props.chars.split(''); <add> const chars = this.props.chars.split(''); <ide> return ( <ide> <View>{chars.map(text => <View key={text} title={text} />)}</View> <ide> ); <ide> } <ide> } <ide> <ide> // Mini multi-child stress test: lots of reorders, some adds, some removes. <del> var before = 'abcdefghijklmnopqrst'; <del> var after = 'mxhpgwfralkeoivcstzy'; <add> const before = 'abcdefghijklmnopqrst'; <add> const after = 'mxhpgwfralkeoivcstzy'; <ide> <ide> ReactNative.render(<Component chars={before} />, 11); <ide> expect(UIManager.__dumpHierarchyForJestTestsOnly()).toMatchSnapshot(); <ide> describe('ReactNative', () => { <ide> }); <ide> <ide> it('calls setState with no arguments', () => { <del> var mockArgs; <add> let mockArgs; <ide> class Component extends React.Component { <ide> componentDidMount() { <ide> this.setState({}, (...args) => (mockArgs = args)); <ide><path>packages/react-native-renderer/src/findNodeHandle.js <ide> import ReactNativeFiberRenderer from './ReactNativeFiberRenderer'; <ide> // accidentally deep-requiring this version. <ide> function findNodeHandle(componentOrHandle: any): any { <ide> if (__DEV__) { <del> var owner = ReactCurrentOwner.current; <add> const owner = ReactCurrentOwner.current; <ide> if (owner !== null && owner.stateNode !== null) { <ide> warning( <ide> owner.stateNode._warnedAboutRefsInRender, <ide> function findNodeHandle(componentOrHandle: any): any { <ide> return componentOrHandle; <ide> } <ide> <del> var component = componentOrHandle; <add> const component = componentOrHandle; <ide> <ide> // TODO (balpert): Wrap iOS native components in a composite wrapper, then <ide> // ReactInstanceMap.get here will always succeed for mounted components <del> var internalInstance: Fiber = ReactInstanceMap.get(component); <add> const internalInstance: Fiber = ReactInstanceMap.get(component); <ide> if (internalInstance) { <ide> return ReactNativeFiberRenderer.findHostInstance(internalInstance); <ide> } else {
25
Javascript
Javascript
repair the fs/readfile benchmark
d9b0e4c729fedfe5369ada4229fd170bd6dc7e2f
<ide><path>benchmark/fs/readfile.js <ide> function main(conf) { <ide> data = null; <ide> <ide> var reads = 0; <add> var bench_ended = false; <ide> bench.start(); <ide> setTimeout(function() { <add> bench_ended = true; <ide> bench.end(reads); <ide> try { fs.unlinkSync(filename); } catch (e) {} <ide> process.exit(0); <ide> function main(conf) { <ide> throw new Error('wrong number of bytes returned'); <ide> <ide> reads++; <del> read(); <add> if (!bench_ended) <add> read(); <ide> } <ide> <ide> var cur = +conf.concurrent;
1
Text
Text
apply a recommendation (fixes )
71ede8d52c4663520d9b8bbb43ce0852b2fe54ad
<ide><path>docs/03-Line-Chart.md <ide> var myLineChart = Chart.Line(ctx, { <ide> }); <ide> ``` <ide> <del>### Data Structure <add>### Dataset Structure <ide> <ide> The following options can be included in a line chart dataset to configure options for that specific dataset. <ide> <ide><path>docs/04-Bar-Chart.md <ide> var myBarChart = new Chart(ctx, { <ide> }); <ide> ``` <ide> <del>### Data Structure <add>### Dataset Structure <ide> The following options can be included in a bar chart dataset to configure options for that specific dataset. <ide> <ide> Some properties can be specified as an array. If these are set to an array value, the first value applies to the first bar, the second value to the second bar, and so on. <ide><path>docs/05-Radar-Chart.md <ide> var myRadarChart = new Chart(ctx, { <ide> }); <ide> ``` <ide> <del>### Data Structure <add>### Dataset Structure <ide> <ide> The following options can be included in a radar chart dataset to configure options for that specific dataset. <ide> <ide><path>docs/06-Polar-Area-Chart.md <ide> new Chart(ctx, { <ide> }); <ide> ``` <ide> <del>### Data Structure <add>### Dataset Structure <ide> <ide> The following options can be included in a polar area chart dataset to configure options for that specific dataset. <ide> <ide><path>docs/07-Pie-Doughnut-Chart.md <ide> var myDoughnutChart = new Chart(ctx, { <ide> }); <ide> ``` <ide> <del>### Data Structure <add>### Dataset Structure <ide> <ide> Property | Type | Usage <ide> --- | --- | --- <ide><path>docs/08-Bubble-Chart.md <ide> var myBubbleChart = new Chart(ctx,{ <ide> }); <ide> ``` <ide> <del>### Data Structure <add>### Dataset Structure <ide> <ide> Property | Type | Usage <ide> --- | --- | ---
6
Go
Go
remove unneeded import aliases
9060126639e9141082ab0edbdce921895058af88
<ide><path>client/interface.go <ide> import ( <ide> "time" <ide> <ide> "github.com/docker/docker/api/types" <del> containertypes "github.com/docker/docker/api/types/container" <add> "github.com/docker/docker/api/types/container" <ide> "github.com/docker/docker/api/types/events" <ide> "github.com/docker/docker/api/types/filters" <ide> "github.com/docker/docker/api/types/image" <del> networktypes "github.com/docker/docker/api/types/network" <add> "github.com/docker/docker/api/types/network" <ide> "github.com/docker/docker/api/types/registry" <ide> "github.com/docker/docker/api/types/swarm" <del> volumetypes "github.com/docker/docker/api/types/volume" <add> "github.com/docker/docker/api/types/volume" <ide> specs "github.com/opencontainers/image-spec/specs-go/v1" <ide> ) <ide> <ide> type CommonAPIClient interface { <ide> type ContainerAPIClient interface { <ide> ContainerAttach(ctx context.Context, container string, options types.ContainerAttachOptions) (types.HijackedResponse, error) <ide> ContainerCommit(ctx context.Context, container string, options types.ContainerCommitOptions) (types.IDResponse, error) <del> ContainerCreate(ctx context.Context, config *containertypes.Config, hostConfig *containertypes.HostConfig, networkingConfig *networktypes.NetworkingConfig, platform *specs.Platform, containerName string) (containertypes.ContainerCreateCreatedBody, error) <del> ContainerDiff(ctx context.Context, container string) ([]containertypes.ContainerChangeResponseItem, error) <add> ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, platform *specs.Platform, containerName string) (container.ContainerCreateCreatedBody, error) <add> ContainerDiff(ctx context.Context, container string) ([]container.ContainerChangeResponseItem, error) <ide> ContainerExecAttach(ctx context.Context, execID string, config types.ExecStartCheck) (types.HijackedResponse, error) <ide> ContainerExecCreate(ctx context.Context, container string, config types.ExecConfig) (types.IDResponse, error) <ide> ContainerExecInspect(ctx context.Context, execID string) (types.ContainerExecInspect, error) <ide> type ContainerAPIClient interface { <ide> ContainerStatsOneShot(ctx context.Context, container string) (types.ContainerStats, error) <ide> ContainerStart(ctx context.Context, container string, options types.ContainerStartOptions) error <ide> ContainerStop(ctx context.Context, container string, timeout *time.Duration) error <del> ContainerTop(ctx context.Context, container string, arguments []string) (containertypes.ContainerTopOKBody, error) <add> ContainerTop(ctx context.Context, container string, arguments []string) (container.ContainerTopOKBody, error) <ide> ContainerUnpause(ctx context.Context, container string) error <del> ContainerUpdate(ctx context.Context, container string, updateConfig containertypes.UpdateConfig) (containertypes.ContainerUpdateOKBody, error) <del> ContainerWait(ctx context.Context, container string, condition containertypes.WaitCondition) (<-chan containertypes.ContainerWaitOKBody, <-chan error) <add> ContainerUpdate(ctx context.Context, container string, updateConfig container.UpdateConfig) (container.ContainerUpdateOKBody, error) <add> ContainerWait(ctx context.Context, container string, condition container.WaitCondition) (<-chan container.ContainerWaitOKBody, <-chan error) <ide> CopyFromContainer(ctx context.Context, container, srcPath string) (io.ReadCloser, types.ContainerPathStat, error) <ide> CopyToContainer(ctx context.Context, container, path string, content io.Reader, options types.CopyToContainerOptions) error <ide> ContainersPrune(ctx context.Context, pruneFilters filters.Args) (types.ContainersPruneReport, error) <ide> type ImageAPIClient interface { <ide> <ide> // NetworkAPIClient defines API client methods for the networks <ide> type NetworkAPIClient interface { <del> NetworkConnect(ctx context.Context, network, container string, config *networktypes.EndpointSettings) error <add> NetworkConnect(ctx context.Context, network, container string, config *network.EndpointSettings) error <ide> NetworkCreate(ctx context.Context, name string, options types.NetworkCreate) (types.NetworkCreateResponse, error) <ide> NetworkDisconnect(ctx context.Context, network, container string, force bool) error <ide> NetworkInspect(ctx context.Context, network string, options types.NetworkInspectOptions) (types.NetworkResource, error) <ide> type SystemAPIClient interface { <ide> <ide> // VolumeAPIClient defines API client methods for the volumes <ide> type VolumeAPIClient interface { <del> VolumeCreate(ctx context.Context, options volumetypes.VolumeCreateBody) (types.Volume, error) <add> VolumeCreate(ctx context.Context, options volume.VolumeCreateBody) (types.Volume, error) <ide> VolumeInspect(ctx context.Context, volumeID string) (types.Volume, error) <ide> VolumeInspectWithRaw(ctx context.Context, volumeID string) (types.Volume, []byte, error) <del> VolumeList(ctx context.Context, filter filters.Args) (volumetypes.VolumeListOKBody, error) <add> VolumeList(ctx context.Context, filter filters.Args) (volume.VolumeListOKBody, error) <ide> VolumeRemove(ctx context.Context, volumeID string, force bool) error <ide> VolumesPrune(ctx context.Context, pruneFilter filters.Args) (types.VolumesPruneReport, error) <ide> } <ide><path>integration-cli/docker_api_containers_test.go <ide> import ( <ide> "time" <ide> <ide> "github.com/docker/docker/api/types" <del> containertypes "github.com/docker/docker/api/types/container" <del> mounttypes "github.com/docker/docker/api/types/mount" <del> networktypes "github.com/docker/docker/api/types/network" <add> "github.com/docker/docker/api/types/container" <add> "github.com/docker/docker/api/types/mount" <add> "github.com/docker/docker/api/types/network" <ide> "github.com/docker/docker/api/types/versions" <ide> "github.com/docker/docker/client" <ide> dconfig "github.com/docker/docker/daemon/config" <ide> func (s *DockerSuite) TestContainerAPICommitWithLabelInConfig(c *testing.T) { <ide> assert.NilError(c, err) <ide> defer cli.Close() <ide> <del> config := containertypes.Config{ <add> config := container.Config{ <ide> Labels: map[string]string{"key1": "value1", "key2": "value2"}} <ide> <ide> options := types.ContainerCommitOptions{ <ide> func (s *DockerSuite) TestContainerAPIBadPort(c *testing.T) { <ide> // TODO Windows to Windows CI - Port this test <ide> testRequires(c, DaemonIsLinux) <ide> <del> config := containertypes.Config{ <add> config := container.Config{ <ide> Image: "busybox", <ide> Cmd: []string{"/bin/sh", "-c", "echo test"}, <ide> } <ide> <del> hostConfig := containertypes.HostConfig{ <add> hostConfig := container.HostConfig{ <ide> PortBindings: nat.PortMap{ <ide> "8080/tcp": []nat.PortBinding{ <ide> { <ide> func (s *DockerSuite) TestContainerAPIBadPort(c *testing.T) { <ide> assert.NilError(c, err) <ide> defer cli.Close() <ide> <del> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, nil, "") <add> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &network.NetworkingConfig{}, nil, "") <ide> assert.ErrorContains(c, err, `invalid port specification: "aa80"`) <ide> } <ide> <ide> func (s *DockerSuite) TestContainerAPICreate(c *testing.T) { <del> config := containertypes.Config{ <add> config := container.Config{ <ide> Image: "busybox", <ide> Cmd: []string{"/bin/sh", "-c", "touch /test && ls /test"}, <ide> } <ide> func (s *DockerSuite) TestContainerAPICreate(c *testing.T) { <ide> assert.NilError(c, err) <ide> defer cli.Close() <ide> <del> container, err := cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, nil, "") <add> container, err := cli.ContainerCreate(context.Background(), &config, &container.HostConfig{}, &network.NetworkingConfig{}, nil, "") <ide> assert.NilError(c, err) <ide> <ide> out, _ := dockerCmd(c, "start", "-a", container.ID) <ide> func (s *DockerSuite) TestContainerAPICreateEmptyConfig(c *testing.T) { <ide> assert.NilError(c, err) <ide> defer cli.Close() <ide> <del> _, err = cli.ContainerCreate(context.Background(), &containertypes.Config{}, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, nil, "") <add> _, err = cli.ContainerCreate(context.Background(), &container.Config{}, &container.HostConfig{}, &network.NetworkingConfig{}, nil, "") <ide> <ide> expected := "No command specified" <ide> assert.ErrorContains(c, err, expected) <ide> } <ide> <ide> func (s *DockerSuite) TestContainerAPICreateMultipleNetworksConfig(c *testing.T) { <ide> // Container creation must fail if client specified configurations for more than one network <del> config := containertypes.Config{ <add> config := container.Config{ <ide> Image: "busybox", <ide> } <ide> <del> networkingConfig := networktypes.NetworkingConfig{ <del> EndpointsConfig: map[string]*networktypes.EndpointSettings{ <add> networkingConfig := network.NetworkingConfig{ <add> EndpointsConfig: map[string]*network.EndpointSettings{ <ide> "net1": {}, <ide> "net2": {}, <ide> "net3": {}, <ide> func (s *DockerSuite) TestContainerAPICreateMultipleNetworksConfig(c *testing.T) <ide> assert.NilError(c, err) <ide> defer cli.Close() <ide> <del> _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networkingConfig, nil, "") <add> _, err = cli.ContainerCreate(context.Background(), &config, &container.HostConfig{}, &networkingConfig, nil, "") <ide> msg := err.Error() <ide> // network name order in error message is not deterministic <ide> assert.Assert(c, strings.Contains(msg, "Container cannot be connected to network endpoints")) <ide> func (s *DockerSuite) TestContainerAPICreateOtherNetworkModes(c *testing.T) { <ide> UtilCreateNetworkMode(c, "container:web1") <ide> } <ide> <del>func UtilCreateNetworkMode(c *testing.T, networkMode containertypes.NetworkMode) { <del> config := containertypes.Config{ <add>func UtilCreateNetworkMode(c *testing.T, networkMode container.NetworkMode) { <add> config := container.Config{ <ide> Image: "busybox", <ide> } <ide> <del> hostConfig := containertypes.HostConfig{ <add> hostConfig := container.HostConfig{ <ide> NetworkMode: networkMode, <ide> } <ide> <ide> cli, err := client.NewClientWithOpts(client.FromEnv) <ide> assert.NilError(c, err) <ide> defer cli.Close() <ide> <del> container, err := cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, nil, "") <add> container, err := cli.ContainerCreate(context.Background(), &config, &hostConfig, &network.NetworkingConfig{}, nil, "") <ide> assert.NilError(c, err) <ide> <ide> containerJSON, err := cli.ContainerInspect(context.Background(), container.ID) <ide> func UtilCreateNetworkMode(c *testing.T, networkMode containertypes.NetworkMode) <ide> func (s *DockerSuite) TestContainerAPICreateWithCpuSharesCpuset(c *testing.T) { <ide> // TODO Windows to Windows CI. The CpuShares part could be ported. <ide> testRequires(c, DaemonIsLinux) <del> config := containertypes.Config{ <add> config := container.Config{ <ide> Image: "busybox", <ide> } <ide> <del> hostConfig := containertypes.HostConfig{ <del> Resources: containertypes.Resources{ <add> hostConfig := container.HostConfig{ <add> Resources: container.Resources{ <ide> CPUShares: 512, <ide> CpusetCpus: "0", <ide> }, <ide> func (s *DockerSuite) TestContainerAPICreateWithCpuSharesCpuset(c *testing.T) { <ide> assert.NilError(c, err) <ide> defer cli.Close() <ide> <del> container, err := cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, nil, "") <add> container, err := cli.ContainerCreate(context.Background(), &config, &hostConfig, &network.NetworkingConfig{}, nil, "") <ide> assert.NilError(c, err) <ide> <ide> containerJSON, err := cli.ContainerInspect(context.Background(), container.ID) <ide> func (s *DockerSuite) TestContainerAPIRestartNotimeoutParam(c *testing.T) { <ide> <ide> func (s *DockerSuite) TestContainerAPIStart(c *testing.T) { <ide> name := "testing-start" <del> config := containertypes.Config{ <add> config := container.Config{ <ide> Image: "busybox", <ide> Cmd: append([]string{"/bin/sh", "-c"}, sleepCommandForDaemonPlatform()...), <ide> OpenStdin: true, <ide> func (s *DockerSuite) TestContainerAPIStart(c *testing.T) { <ide> assert.NilError(c, err) <ide> defer cli.Close() <ide> <del> _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, nil, name) <add> _, err = cli.ContainerCreate(context.Background(), &config, &container.HostConfig{}, &network.NetworkingConfig{}, nil, name) <ide> assert.NilError(c, err) <ide> <ide> err = cli.ContainerStart(context.Background(), name, types.ContainerStartOptions{}) <ide> func (s *DockerSuite) TestContainerAPIPostContainerStop(c *testing.T) { <ide> <ide> // #14170 <ide> func (s *DockerSuite) TestPostContainerAPICreateWithStringOrSliceEntrypoint(c *testing.T) { <del> config := containertypes.Config{ <add> config := container.Config{ <ide> Image: "busybox", <ide> Entrypoint: []string{"echo"}, <ide> Cmd: []string{"hello", "world"}, <ide> func (s *DockerSuite) TestPostContainerAPICreateWithStringOrSliceEntrypoint(c *t <ide> assert.NilError(c, err) <ide> defer cli.Close() <ide> <del> _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, nil, "echotest") <add> _, err = cli.ContainerCreate(context.Background(), &config, &container.HostConfig{}, &network.NetworkingConfig{}, nil, "echotest") <ide> assert.NilError(c, err) <ide> out, _ := dockerCmd(c, "start", "-a", "echotest") <ide> assert.Equal(c, strings.TrimSpace(out), "hello world") <ide> func (s *DockerSuite) TestPostContainerAPICreateWithStringOrSliceEntrypoint(c *t <ide> <ide> // #14170 <ide> func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCmd(c *testing.T) { <del> config := containertypes.Config{ <add> config := container.Config{ <ide> Image: "busybox", <ide> Cmd: []string{"echo", "hello", "world"}, <ide> } <ide> func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCmd(c *testing.T) <ide> assert.NilError(c, err) <ide> defer cli.Close() <ide> <del> _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, nil, "echotest") <add> _, err = cli.ContainerCreate(context.Background(), &config, &container.HostConfig{}, &network.NetworkingConfig{}, nil, "echotest") <ide> assert.NilError(c, err) <ide> out, _ := dockerCmd(c, "start", "-a", "echotest") <ide> assert.Equal(c, strings.TrimSpace(out), "hello world") <ide> func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCapAddDrop(c *tes <ide> assert.NilError(c, err) <ide> assert.Equal(c, res.StatusCode, http.StatusCreated) <ide> <del> config2 := containertypes.Config{ <add> config2 := container.Config{ <ide> Image: "busybox", <ide> } <del> hostConfig := containertypes.HostConfig{ <add> hostConfig := container.HostConfig{ <ide> CapAdd: []string{"net_admin", "SYS_ADMIN"}, <ide> CapDrop: []string{"SETGID", "CAP_SETPCAP"}, <ide> } <ide> func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCapAddDrop(c *tes <ide> assert.NilError(c, err) <ide> defer cli.Close() <ide> <del> _, err = cli.ContainerCreate(context.Background(), &config2, &hostConfig, &networktypes.NetworkingConfig{}, nil, "capaddtest1") <add> _, err = cli.ContainerCreate(context.Background(), &config2, &hostConfig, &network.NetworkingConfig{}, nil, "capaddtest1") <ide> assert.NilError(c, err) <ide> } <ide> <ide> // #14915 <ide> func (s *DockerSuite) TestContainerAPICreateNoHostConfig118(c *testing.T) { <ide> testRequires(c, DaemonIsLinux) // Windows only support 1.25 or later <del> config := containertypes.Config{ <add> config := container.Config{ <ide> Image: "busybox", <ide> } <ide> <ide> cli, err := client.NewClientWithOpts(client.FromEnv, client.WithVersion("v1.18")) <ide> assert.NilError(c, err) <ide> <del> _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, nil, "") <add> _, err = cli.ContainerCreate(context.Background(), &config, &container.HostConfig{}, &network.NetworkingConfig{}, nil, "") <ide> assert.NilError(c, err) <ide> } <ide> <ide> func (s *DockerSuite) TestPostContainersCreateWithWrongCpusetValues(c *testing.T <ide> assert.NilError(c, err) <ide> defer cli.Close() <ide> <del> config := containertypes.Config{ <add> config := container.Config{ <ide> Image: "busybox", <ide> } <del> hostConfig1 := containertypes.HostConfig{ <del> Resources: containertypes.Resources{ <add> hostConfig1 := container.HostConfig{ <add> Resources: container.Resources{ <ide> CpusetCpus: "1-42,,", <ide> }, <ide> } <ide> name := "wrong-cpuset-cpus" <ide> <del> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig1, &networktypes.NetworkingConfig{}, nil, name) <add> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig1, &network.NetworkingConfig{}, nil, name) <ide> expected := "Invalid value 1-42,, for cpuset cpus" <ide> assert.ErrorContains(c, err, expected) <ide> <del> hostConfig2 := containertypes.HostConfig{ <del> Resources: containertypes.Resources{ <add> hostConfig2 := container.HostConfig{ <add> Resources: container.Resources{ <ide> CpusetMems: "42-3,1--", <ide> }, <ide> } <ide> name = "wrong-cpuset-mems" <del> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig2, &networktypes.NetworkingConfig{}, nil, name) <add> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig2, &network.NetworkingConfig{}, nil, name) <ide> expected = "Invalid value 42-3,1-- for cpuset mems" <ide> assert.ErrorContains(c, err, expected) <ide> } <ide> <ide> func (s *DockerSuite) TestPostContainersCreateShmSizeNegative(c *testing.T) { <ide> // ShmSize is not supported on Windows <ide> testRequires(c, DaemonIsLinux) <del> config := containertypes.Config{ <add> config := container.Config{ <ide> Image: "busybox", <ide> } <del> hostConfig := containertypes.HostConfig{ <add> hostConfig := container.HostConfig{ <ide> ShmSize: -1, <ide> } <ide> <ide> cli, err := client.NewClientWithOpts(client.FromEnv) <ide> assert.NilError(c, err) <ide> defer cli.Close() <ide> <del> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, nil, "") <add> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &network.NetworkingConfig{}, nil, "") <ide> assert.ErrorContains(c, err, "SHM size can not be less than 0") <ide> } <ide> <ide> func (s *DockerSuite) TestPostContainersCreateShmSizeHostConfigOmitted(c *testing.T) { <ide> // ShmSize is not supported on Windows <ide> testRequires(c, DaemonIsLinux) <ide> <del> config := containertypes.Config{ <add> config := container.Config{ <ide> Image: "busybox", <ide> Cmd: []string{"mount"}, <ide> } <ide> func (s *DockerSuite) TestPostContainersCreateShmSizeHostConfigOmitted(c *testin <ide> assert.NilError(c, err) <ide> defer cli.Close() <ide> <del> container, err := cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, nil, "") <add> container, err := cli.ContainerCreate(context.Background(), &config, &container.HostConfig{}, &network.NetworkingConfig{}, nil, "") <ide> assert.NilError(c, err) <ide> <ide> containerJSON, err := cli.ContainerInspect(context.Background(), container.ID) <ide> func (s *DockerSuite) TestPostContainersCreateShmSizeHostConfigOmitted(c *testin <ide> func (s *DockerSuite) TestPostContainersCreateShmSizeOmitted(c *testing.T) { <ide> // ShmSize is not supported on Windows <ide> testRequires(c, DaemonIsLinux) <del> config := containertypes.Config{ <add> config := container.Config{ <ide> Image: "busybox", <ide> Cmd: []string{"mount"}, <ide> } <ide> func (s *DockerSuite) TestPostContainersCreateShmSizeOmitted(c *testing.T) { <ide> assert.NilError(c, err) <ide> defer cli.Close() <ide> <del> container, err := cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, nil, "") <add> container, err := cli.ContainerCreate(context.Background(), &config, &container.HostConfig{}, &network.NetworkingConfig{}, nil, "") <ide> assert.NilError(c, err) <ide> <ide> containerJSON, err := cli.ContainerInspect(context.Background(), container.ID) <ide> func (s *DockerSuite) TestPostContainersCreateShmSizeOmitted(c *testing.T) { <ide> func (s *DockerSuite) TestPostContainersCreateWithShmSize(c *testing.T) { <ide> // ShmSize is not supported on Windows <ide> testRequires(c, DaemonIsLinux) <del> config := containertypes.Config{ <add> config := container.Config{ <ide> Image: "busybox", <ide> Cmd: []string{"mount"}, <ide> } <ide> <del> hostConfig := containertypes.HostConfig{ <add> hostConfig := container.HostConfig{ <ide> ShmSize: 1073741824, <ide> } <ide> <ide> cli, err := client.NewClientWithOpts(client.FromEnv) <ide> assert.NilError(c, err) <ide> defer cli.Close() <ide> <del> container, err := cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, nil, "") <add> container, err := cli.ContainerCreate(context.Background(), &config, &hostConfig, &network.NetworkingConfig{}, nil, "") <ide> assert.NilError(c, err) <ide> <ide> containerJSON, err := cli.ContainerInspect(context.Background(), container.ID) <ide> func (s *DockerSuite) TestPostContainersCreateWithShmSize(c *testing.T) { <ide> func (s *DockerSuite) TestPostContainersCreateMemorySwappinessHostConfigOmitted(c *testing.T) { <ide> // Swappiness is not supported on Windows <ide> testRequires(c, DaemonIsLinux) <del> config := containertypes.Config{ <add> config := container.Config{ <ide> Image: "busybox", <ide> } <ide> <ide> cli, err := client.NewClientWithOpts(client.FromEnv) <ide> assert.NilError(c, err) <ide> defer cli.Close() <ide> <del> container, err := cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, nil, "") <add> container, err := cli.ContainerCreate(context.Background(), &config, &container.HostConfig{}, &network.NetworkingConfig{}, nil, "") <ide> assert.NilError(c, err) <ide> <ide> containerJSON, err := cli.ContainerInspect(context.Background(), container.ID) <ide> func (s *DockerSuite) TestPostContainersCreateWithOomScoreAdjInvalidRange(c *tes <ide> // OomScoreAdj is not supported on Windows <ide> testRequires(c, DaemonIsLinux) <ide> <del> config := containertypes.Config{ <add> config := container.Config{ <ide> Image: "busybox", <ide> } <ide> <del> hostConfig := containertypes.HostConfig{ <add> hostConfig := container.HostConfig{ <ide> OomScoreAdj: 1001, <ide> } <ide> <ide> func (s *DockerSuite) TestPostContainersCreateWithOomScoreAdjInvalidRange(c *tes <ide> defer cli.Close() <ide> <ide> name := "oomscoreadj-over" <del> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, nil, name) <add> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &network.NetworkingConfig{}, nil, name) <ide> <ide> expected := "Invalid value 1001, range for oom score adj is [-1000, 1000]" <ide> assert.ErrorContains(c, err, expected) <ide> <del> hostConfig = containertypes.HostConfig{ <add> hostConfig = container.HostConfig{ <ide> OomScoreAdj: -1001, <ide> } <ide> <ide> name = "oomscoreadj-low" <del> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, nil, name) <add> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &network.NetworkingConfig{}, nil, name) <ide> <ide> expected = "Invalid value -1001, range for oom score adj is [-1000, 1000]" <ide> assert.ErrorContains(c, err, expected) <ide> func (s *DockerSuite) TestContainerAPIStatsWithNetworkDisabled(c *testing.T) { <ide> <ide> name := "testing-network-disabled" <ide> <del> config := containertypes.Config{ <add> config := container.Config{ <ide> Image: "busybox", <ide> Cmd: []string{"top"}, <ide> NetworkDisabled: true, <ide> func (s *DockerSuite) TestContainerAPIStatsWithNetworkDisabled(c *testing.T) { <ide> assert.NilError(c, err) <ide> defer cli.Close() <ide> <del> _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, nil, name) <add> _, err = cli.ContainerCreate(context.Background(), &config, &container.HostConfig{}, &network.NetworkingConfig{}, nil, name) <ide> assert.NilError(c, err) <ide> <ide> err = cli.ContainerStart(context.Background(), name, types.ContainerStartOptions{}) <ide> func (s *DockerSuite) TestContainerAPIStatsWithNetworkDisabled(c *testing.T) { <ide> <ide> func (s *DockerSuite) TestContainersAPICreateMountsValidation(c *testing.T) { <ide> type testCase struct { <del> config containertypes.Config <del> hostConfig containertypes.HostConfig <add> config container.Config <add> hostConfig container.HostConfig <ide> msg string <ide> } <ide> <ide> func (s *DockerSuite) TestContainersAPICreateMountsValidation(c *testing.T) { <ide> <ide> cases := []testCase{ <ide> { <del> config: containertypes.Config{ <add> config: container.Config{ <ide> Image: "busybox", <ide> }, <del> hostConfig: containertypes.HostConfig{ <del> Mounts: []mounttypes.Mount{{ <add> hostConfig: container.HostConfig{ <add> Mounts: []mount.Mount{{ <ide> Type: "notreal", <ide> Target: destPath, <ide> }, <ide> func (s *DockerSuite) TestContainersAPICreateMountsValidation(c *testing.T) { <ide> msg: "mount type unknown", <ide> }, <ide> { <del> config: containertypes.Config{ <add> config: container.Config{ <ide> Image: "busybox", <ide> }, <del> hostConfig: containertypes.HostConfig{ <del> Mounts: []mounttypes.Mount{{ <add> hostConfig: container.HostConfig{ <add> Mounts: []mount.Mount{{ <ide> Type: "bind"}}}, <ide> msg: "Target must not be empty", <ide> }, <ide> { <del> config: containertypes.Config{ <add> config: container.Config{ <ide> Image: "busybox", <ide> }, <del> hostConfig: containertypes.HostConfig{ <del> Mounts: []mounttypes.Mount{{ <add> hostConfig: container.HostConfig{ <add> Mounts: []mount.Mount{{ <ide> Type: "bind", <ide> Target: destPath}}}, <ide> msg: "Source must not be empty", <ide> }, <ide> { <del> config: containertypes.Config{ <add> config: container.Config{ <ide> Image: "busybox", <ide> }, <del> hostConfig: containertypes.HostConfig{ <del> Mounts: []mounttypes.Mount{{ <add> hostConfig: container.HostConfig{ <add> Mounts: []mount.Mount{{ <ide> Type: "bind", <ide> Source: notExistPath, <ide> Target: destPath}}}, <ide> func (s *DockerSuite) TestContainersAPICreateMountsValidation(c *testing.T) { <ide> // msg: "source path does not exist: " + notExistPath, <ide> }, <ide> { <del> config: containertypes.Config{ <add> config: container.Config{ <ide> Image: "busybox", <ide> }, <del> hostConfig: containertypes.HostConfig{ <del> Mounts: []mounttypes.Mount{{ <add> hostConfig: container.HostConfig{ <add> Mounts: []mount.Mount{{ <ide> Type: "volume"}}}, <ide> msg: "Target must not be empty", <ide> }, <ide> { <del> config: containertypes.Config{ <add> config: container.Config{ <ide> Image: "busybox", <ide> }, <del> hostConfig: containertypes.HostConfig{ <del> Mounts: []mounttypes.Mount{{ <add> hostConfig: container.HostConfig{ <add> Mounts: []mount.Mount{{ <ide> Type: "volume", <ide> Source: "hello", <ide> Target: destPath}}}, <ide> msg: "", <ide> }, <ide> { <del> config: containertypes.Config{ <add> config: container.Config{ <ide> Image: "busybox", <ide> }, <del> hostConfig: containertypes.HostConfig{ <del> Mounts: []mounttypes.Mount{{ <add> hostConfig: container.HostConfig{ <add> Mounts: []mount.Mount{{ <ide> Type: "volume", <ide> Source: "hello2", <ide> Target: destPath, <del> VolumeOptions: &mounttypes.VolumeOptions{ <del> DriverConfig: &mounttypes.Driver{ <add> VolumeOptions: &mount.VolumeOptions{ <add> DriverConfig: &mount.Driver{ <ide> Name: "local"}}}}}, <ide> msg: "", <ide> }, <ide> func (s *DockerSuite) TestContainersAPICreateMountsValidation(c *testing.T) { <ide> defer os.RemoveAll(tmpDir) <ide> cases = append(cases, []testCase{ <ide> { <del> config: containertypes.Config{ <add> config: container.Config{ <ide> Image: "busybox", <ide> }, <del> hostConfig: containertypes.HostConfig{ <del> Mounts: []mounttypes.Mount{{ <add> hostConfig: container.HostConfig{ <add> Mounts: []mount.Mount{{ <ide> Type: "bind", <ide> Source: tmpDir, <ide> Target: destPath}}}, <ide> msg: "", <ide> }, <ide> { <del> config: containertypes.Config{ <add> config: container.Config{ <ide> Image: "busybox", <ide> }, <del> hostConfig: containertypes.HostConfig{ <del> Mounts: []mounttypes.Mount{{ <add> hostConfig: container.HostConfig{ <add> Mounts: []mount.Mount{{ <ide> Type: "bind", <ide> Source: tmpDir, <ide> Target: destPath, <del> VolumeOptions: &mounttypes.VolumeOptions{}}}}, <add> VolumeOptions: &mount.VolumeOptions{}}}}, <ide> msg: "VolumeOptions must not be specified", <ide> }, <ide> }...) <ide> func (s *DockerSuite) TestContainersAPICreateMountsValidation(c *testing.T) { <ide> if DaemonIsWindows() { <ide> cases = append(cases, []testCase{ <ide> { <del> config: containertypes.Config{ <add> config: container.Config{ <ide> Image: "busybox", <ide> }, <del> hostConfig: containertypes.HostConfig{ <del> Mounts: []mounttypes.Mount{ <add> hostConfig: container.HostConfig{ <add> Mounts: []mount.Mount{ <ide> { <ide> Type: "volume", <ide> Source: "not-supported-on-windows", <ide> Target: destPath, <del> VolumeOptions: &mounttypes.VolumeOptions{ <del> DriverConfig: &mounttypes.Driver{ <add> VolumeOptions: &mount.VolumeOptions{ <add> DriverConfig: &mount.Driver{ <ide> Name: "local", <ide> Options: map[string]string{"type": "tmpfs"}, <ide> }, <ide> func (s *DockerSuite) TestContainersAPICreateMountsValidation(c *testing.T) { <ide> if DaemonIsLinux() { <ide> cases = append(cases, []testCase{ <ide> { <del> config: containertypes.Config{ <add> config: container.Config{ <ide> Image: "busybox", <ide> }, <del> hostConfig: containertypes.HostConfig{ <del> Mounts: []mounttypes.Mount{ <add> hostConfig: container.HostConfig{ <add> Mounts: []mount.Mount{ <ide> { <ide> Type: "volume", <ide> Source: "missing-device-opt", <ide> Target: destPath, <del> VolumeOptions: &mounttypes.VolumeOptions{ <del> DriverConfig: &mounttypes.Driver{ <add> VolumeOptions: &mount.VolumeOptions{ <add> DriverConfig: &mount.Driver{ <ide> Name: "local", <ide> Options: map[string]string{"foobar": "foobaz"}, <ide> }, <ide> func (s *DockerSuite) TestContainersAPICreateMountsValidation(c *testing.T) { <ide> msg: `invalid option: "foobar"`, <ide> }, <ide> { <del> config: containertypes.Config{ <add> config: container.Config{ <ide> Image: "busybox", <ide> }, <del> hostConfig: containertypes.HostConfig{ <del> Mounts: []mounttypes.Mount{ <add> hostConfig: container.HostConfig{ <add> Mounts: []mount.Mount{ <ide> { <ide> Type: "volume", <ide> Source: "missing-device-opt", <ide> Target: destPath, <del> VolumeOptions: &mounttypes.VolumeOptions{ <del> DriverConfig: &mounttypes.Driver{ <add> VolumeOptions: &mount.VolumeOptions{ <add> DriverConfig: &mount.Driver{ <ide> Name: "local", <ide> Options: map[string]string{"type": "tmpfs"}, <ide> }, <ide> func (s *DockerSuite) TestContainersAPICreateMountsValidation(c *testing.T) { <ide> msg: `missing required option: "device"`, <ide> }, <ide> { <del> config: containertypes.Config{ <add> config: container.Config{ <ide> Image: "busybox", <ide> }, <del> hostConfig: containertypes.HostConfig{ <del> Mounts: []mounttypes.Mount{ <add> hostConfig: container.HostConfig{ <add> Mounts: []mount.Mount{ <ide> { <ide> Type: "volume", <ide> Source: "missing-type-opt", <ide> Target: destPath, <del> VolumeOptions: &mounttypes.VolumeOptions{ <del> DriverConfig: &mounttypes.Driver{ <add> VolumeOptions: &mount.VolumeOptions{ <add> DriverConfig: &mount.Driver{ <ide> Name: "local", <ide> Options: map[string]string{"device": "tmpfs"}, <ide> }, <ide> func (s *DockerSuite) TestContainersAPICreateMountsValidation(c *testing.T) { <ide> msg: `missing required option: "type"`, <ide> }, <ide> { <del> config: containertypes.Config{ <add> config: container.Config{ <ide> Image: "busybox", <ide> }, <del> hostConfig: containertypes.HostConfig{ <del> Mounts: []mounttypes.Mount{ <add> hostConfig: container.HostConfig{ <add> Mounts: []mount.Mount{ <ide> { <ide> Type: "volume", <ide> Source: "hello4", <ide> Target: destPath, <del> VolumeOptions: &mounttypes.VolumeOptions{ <del> DriverConfig: &mounttypes.Driver{ <add> VolumeOptions: &mount.VolumeOptions{ <add> DriverConfig: &mount.Driver{ <ide> Name: "local", <ide> Options: map[string]string{"o": "size=1", "type": "tmpfs", "device": "tmpfs"}, <ide> }, <ide> func (s *DockerSuite) TestContainersAPICreateMountsValidation(c *testing.T) { <ide> msg: "", <ide> }, <ide> { <del> config: containertypes.Config{ <add> config: container.Config{ <ide> Image: "busybox", <ide> }, <del> hostConfig: containertypes.HostConfig{ <del> Mounts: []mounttypes.Mount{{ <add> hostConfig: container.HostConfig{ <add> Mounts: []mount.Mount{{ <ide> Type: "tmpfs", <ide> Target: destPath}}}, <ide> msg: "", <ide> }, <ide> { <del> config: containertypes.Config{ <add> config: container.Config{ <ide> Image: "busybox", <ide> }, <del> hostConfig: containertypes.HostConfig{ <del> Mounts: []mounttypes.Mount{{ <add> hostConfig: container.HostConfig{ <add> Mounts: []mount.Mount{{ <ide> Type: "tmpfs", <ide> Target: destPath, <del> TmpfsOptions: &mounttypes.TmpfsOptions{ <add> TmpfsOptions: &mount.TmpfsOptions{ <ide> SizeBytes: 4096 * 1024, <ide> Mode: 0700, <ide> }}}}, <ide> msg: "", <ide> }, <ide> { <del> config: containertypes.Config{ <add> config: container.Config{ <ide> Image: "busybox", <ide> }, <del> hostConfig: containertypes.HostConfig{ <del> Mounts: []mounttypes.Mount{{ <add> hostConfig: container.HostConfig{ <add> Mounts: []mount.Mount{{ <ide> Type: "tmpfs", <ide> Source: "/shouldnotbespecified", <ide> Target: destPath}}}, <ide> func (s *DockerSuite) TestContainersAPICreateMountsValidation(c *testing.T) { <ide> for i, x := range cases { <ide> x := x <ide> c.Run(fmt.Sprintf("case %d", i), func(c *testing.T) { <del> _, err = apiClient.ContainerCreate(context.Background(), &x.config, &x.hostConfig, &networktypes.NetworkingConfig{}, nil, "") <add> _, err = apiClient.ContainerCreate(context.Background(), &x.config, &x.hostConfig, &network.NetworkingConfig{}, nil, "") <ide> if len(x.msg) > 0 { <ide> assert.ErrorContains(c, err, x.msg, "%v", cases[i].config) <ide> } else { <ide> func (s *DockerSuite) TestContainerAPICreateMountsBindRead(c *testing.T) { <ide> defer os.RemoveAll(tmpDir) <ide> err = os.WriteFile(filepath.Join(tmpDir, "bar"), []byte("hello"), 0666) <ide> assert.NilError(c, err) <del> config := containertypes.Config{ <add> config := container.Config{ <ide> Image: "busybox", <ide> Cmd: []string{"/bin/sh", "-c", "cat /foo/bar"}, <ide> } <del> hostConfig := containertypes.HostConfig{ <del> Mounts: []mounttypes.Mount{ <add> hostConfig := container.HostConfig{ <add> Mounts: []mount.Mount{ <ide> {Type: "bind", Source: tmpDir, Target: destPath}, <ide> }, <ide> } <ide> cli, err := client.NewClientWithOpts(client.FromEnv) <ide> assert.NilError(c, err) <ide> defer cli.Close() <ide> <del> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, nil, "test") <add> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &network.NetworkingConfig{}, nil, "test") <ide> assert.NilError(c, err) <ide> <ide> out, _ := dockerCmd(c, "start", "-a", "test") <ide> func (s *DockerSuite) TestContainersAPICreateMountsCreate(c *testing.T) { <ide> } <ide> <ide> type testCase struct { <del> spec mounttypes.Mount <add> spec mount.Mount <ide> expected types.MountPoint <ide> } <ide> <ide> func (s *DockerSuite) TestContainersAPICreateMountsCreate(c *testing.T) { <ide> // use literal strings here for `Type` instead of the defined constants in the volume package to keep this honest <ide> // Validation of the actual `Mount` struct is done in another test is not needed here <ide> { <del> spec: mounttypes.Mount{Type: "volume", Target: destPath}, <add> spec: mount.Mount{Type: "volume", Target: destPath}, <ide> expected: types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", RW: true, Destination: destPath, Mode: selinuxSharedLabel}, <ide> }, <ide> { <del> spec: mounttypes.Mount{Type: "volume", Target: destPath + slash}, <add> spec: mount.Mount{Type: "volume", Target: destPath + slash}, <ide> expected: types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", RW: true, Destination: destPath, Mode: selinuxSharedLabel}, <ide> }, <ide> { <del> spec: mounttypes.Mount{Type: "volume", Target: destPath, Source: "test1"}, <add> spec: mount.Mount{Type: "volume", Target: destPath, Source: "test1"}, <ide> expected: types.MountPoint{Type: "volume", Name: "test1", RW: true, Destination: destPath, Mode: selinuxSharedLabel}, <ide> }, <ide> { <del> spec: mounttypes.Mount{Type: "volume", Target: destPath, ReadOnly: true, Source: "test2"}, <add> spec: mount.Mount{Type: "volume", Target: destPath, ReadOnly: true, Source: "test2"}, <ide> expected: types.MountPoint{Type: "volume", Name: "test2", RW: false, Destination: destPath, Mode: selinuxSharedLabel}, <ide> }, <ide> { <del> spec: mounttypes.Mount{Type: "volume", Target: destPath, Source: "test3", VolumeOptions: &mounttypes.VolumeOptions{DriverConfig: &mounttypes.Driver{Name: volume.DefaultDriverName}}}, <add> spec: mount.Mount{Type: "volume", Target: destPath, Source: "test3", VolumeOptions: &mount.VolumeOptions{DriverConfig: &mount.Driver{Name: volume.DefaultDriverName}}}, <ide> expected: types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", Name: "test3", RW: true, Destination: destPath, Mode: selinuxSharedLabel}, <ide> }, <ide> } <ide> func (s *DockerSuite) TestContainersAPICreateMountsCreate(c *testing.T) { <ide> defer os.RemoveAll(tmpDir1) <ide> cases = append(cases, []testCase{ <ide> { <del> spec: mounttypes.Mount{ <add> spec: mount.Mount{ <ide> Type: "bind", <ide> Source: tmpDir1, <ide> Target: destPath, <ide> func (s *DockerSuite) TestContainersAPICreateMountsCreate(c *testing.T) { <ide> }, <ide> }, <ide> { <del> spec: mounttypes.Mount{Type: "bind", Source: tmpDir1, Target: destPath, ReadOnly: true}, <add> spec: mount.Mount{Type: "bind", Source: tmpDir1, Target: destPath, ReadOnly: true}, <ide> expected: types.MountPoint{Type: "bind", RW: false, Destination: destPath, Source: tmpDir1}, <ide> }, <ide> }...) <ide> func (s *DockerSuite) TestContainersAPICreateMountsCreate(c *testing.T) { <ide> <ide> cases = append(cases, []testCase{ <ide> { <del> spec: mounttypes.Mount{Type: "bind", Source: tmpDir3, Target: destPath}, <add> spec: mount.Mount{Type: "bind", Source: tmpDir3, Target: destPath}, <ide> expected: types.MountPoint{Type: "bind", RW: true, Destination: destPath, Source: tmpDir3}, <ide> }, <ide> { <del> spec: mounttypes.Mount{Type: "bind", Source: tmpDir3, Target: destPath, ReadOnly: true}, <add> spec: mount.Mount{Type: "bind", Source: tmpDir3, Target: destPath, ReadOnly: true}, <ide> expected: types.MountPoint{Type: "bind", RW: false, Destination: destPath, Source: tmpDir3}, <ide> }, <ide> { <del> spec: mounttypes.Mount{Type: "bind", Source: tmpDir3, Target: destPath, ReadOnly: true, BindOptions: &mounttypes.BindOptions{Propagation: "shared"}}, <add> spec: mount.Mount{Type: "bind", Source: tmpDir3, Target: destPath, ReadOnly: true, BindOptions: &mount.BindOptions{Propagation: "shared"}}, <ide> expected: types.MountPoint{Type: "bind", RW: false, Destination: destPath, Source: tmpDir3, Propagation: "shared"}, <ide> }, <ide> }...) <ide> func (s *DockerSuite) TestContainersAPICreateMountsCreate(c *testing.T) { <ide> if testEnv.OSType != "windows" { // Windows does not support volume populate <ide> cases = append(cases, []testCase{ <ide> { <del> spec: mounttypes.Mount{Type: "volume", Target: destPath, VolumeOptions: &mounttypes.VolumeOptions{NoCopy: true}}, <add> spec: mount.Mount{Type: "volume", Target: destPath, VolumeOptions: &mount.VolumeOptions{NoCopy: true}}, <ide> expected: types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", RW: true, Destination: destPath, Mode: selinuxSharedLabel}, <ide> }, <ide> { <del> spec: mounttypes.Mount{Type: "volume", Target: destPath + slash, VolumeOptions: &mounttypes.VolumeOptions{NoCopy: true}}, <add> spec: mount.Mount{Type: "volume", Target: destPath + slash, VolumeOptions: &mount.VolumeOptions{NoCopy: true}}, <ide> expected: types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", RW: true, Destination: destPath, Mode: selinuxSharedLabel}, <ide> }, <ide> { <del> spec: mounttypes.Mount{Type: "volume", Target: destPath, Source: "test4", VolumeOptions: &mounttypes.VolumeOptions{NoCopy: true}}, <add> spec: mount.Mount{Type: "volume", Target: destPath, Source: "test4", VolumeOptions: &mount.VolumeOptions{NoCopy: true}}, <ide> expected: types.MountPoint{Type: "volume", Name: "test4", RW: true, Destination: destPath, Mode: selinuxSharedLabel}, <ide> }, <ide> { <del> spec: mounttypes.Mount{Type: "volume", Target: destPath, Source: "test5", ReadOnly: true, VolumeOptions: &mounttypes.VolumeOptions{NoCopy: true}}, <add> spec: mount.Mount{Type: "volume", Target: destPath, Source: "test5", ReadOnly: true, VolumeOptions: &mount.VolumeOptions{NoCopy: true}}, <ide> expected: types.MountPoint{Type: "volume", Name: "test5", RW: false, Destination: destPath, Mode: selinuxSharedLabel}, <ide> }, <ide> }...) <ide> func (s *DockerSuite) TestContainersAPICreateMountsCreate(c *testing.T) { <ide> c.Run(fmt.Sprintf("%d config: %v", i, x.spec), func(c *testing.T) { <ide> container, err := apiclient.ContainerCreate( <ide> ctx, <del> &containertypes.Config{Image: testImg}, <del> &containertypes.HostConfig{Mounts: []mounttypes.Mount{x.spec}}, <del> &networktypes.NetworkingConfig{}, <add> &container.Config{Image: testImg}, <add> &container.HostConfig{Mounts: []mount.Mount{x.spec}}, <add> &network.NetworkingConfig{}, <ide> nil, <ide> "") <ide> assert.NilError(c, err) <ide> func containerExit(apiclient client.APIClient, name string) func(poll.LogT) poll <ide> func (s *DockerSuite) TestContainersAPICreateMountsTmpfs(c *testing.T) { <ide> testRequires(c, DaemonIsLinux) <ide> type testCase struct { <del> cfg mounttypes.Mount <add> cfg mount.Mount <ide> expectedOptions []string <ide> } <ide> target := "/foo" <ide> cases := []testCase{ <ide> { <del> cfg: mounttypes.Mount{ <add> cfg: mount.Mount{ <ide> Type: "tmpfs", <ide> Target: target}, <ide> expectedOptions: []string{"rw", "nosuid", "nodev", "noexec", "relatime"}, <ide> }, <ide> { <del> cfg: mounttypes.Mount{ <add> cfg: mount.Mount{ <ide> Type: "tmpfs", <ide> Target: target, <del> TmpfsOptions: &mounttypes.TmpfsOptions{ <add> TmpfsOptions: &mount.TmpfsOptions{ <ide> SizeBytes: 4096 * 1024, Mode: 0700}}, <ide> expectedOptions: []string{"rw", "nosuid", "nodev", "noexec", "relatime", "size=4096k", "mode=700"}, <ide> }, <ide> func (s *DockerSuite) TestContainersAPICreateMountsTmpfs(c *testing.T) { <ide> assert.NilError(c, err) <ide> defer cli.Close() <ide> <del> config := containertypes.Config{ <add> config := container.Config{ <ide> Image: "busybox", <ide> Cmd: []string{"/bin/sh", "-c", fmt.Sprintf("mount | grep 'tmpfs on %s'", target)}, <ide> } <ide> for i, x := range cases { <ide> cName := fmt.Sprintf("test-tmpfs-%d", i) <del> hostConfig := containertypes.HostConfig{ <del> Mounts: []mounttypes.Mount{x.cfg}, <add> hostConfig := container.HostConfig{ <add> Mounts: []mount.Mount{x.cfg}, <ide> } <ide> <del> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, nil, cName) <add> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &network.NetworkingConfig{}, nil, cName) <ide> assert.NilError(c, err) <ide> out, _ := dockerCmd(c, "start", "-a", cName) <ide> for _, option := range x.expectedOptions {
2
Ruby
Ruby
extract common formula helper
4adecd73b64de53913262870a4855e13ae085b81
<ide><path>Library/Homebrew/test/test_formula_spec_selection.rb <ide> require 'formula' <ide> <ide> class FormulaSpecSelectionTests < Test::Unit::TestCase <del> def formula(*args, &block) <del> @_f = Class.new(Formula, &block).new(*args) <del> end <del> <ide> def assert_spec_selected(spec) <ide> assert_equal @_f.send(spec), @_f.active_spec <ide> end <ide><path>Library/Homebrew/test/test_formula_validation.rb <ide> require 'formula' <ide> <ide> class FormulaValidationTests < Test::Unit::TestCase <del> def formula(*args, &block) <del> Class.new(Formula, &block).new(*args) <del> end <del> <ide> def assert_invalid(attr, &block) <ide> e = assert_raises(FormulaValidationError, &block) <ide> assert_equal attr, e.attr <ide><path>Library/Homebrew/test/testing_env.rb <ide> def assert_empty(obj, msg=nil) <ide> assert(obj.empty?, msg) <ide> end if RUBY_VERSION.to_f <= 1.8 <ide> end <add> <add>class Test::Unit::TestCase <add> def formula(*args, &block) <add> @_f = Class.new(Formula, &block).new(*args) <add> end <add>end
3
Javascript
Javascript
handle bad length argument in constructor
f6bce20e5e4e1fb26b1a35661c278f0b65569900
<ide><path>lib/buffer.js <ide> SlowBuffer.prototype.slice = function(start, end) { <ide> }; <ide> <ide> <add>function coerce(length) { <add> // Coerce length to a number (possibly NaN), round up <add> // in case it's fractional (e.g. 123.456) then do a <add> // double negate to coerce a NaN to 0. Easy, right? <add> length = ~~Math.ceil(+length); <add> return length < 0 ? 0 : length; <add>} <add> <add> <ide> // Buffer <ide> <ide> function Buffer(subject, encoding, offset) { <ide> function Buffer(subject, encoding, offset) { <ide> <ide> // Are we slicing? <ide> if (typeof offset === 'number') { <del> this.length = encoding; <add> this.length = coerce(encoding); <ide> this.parent = subject; <ide> this.offset = offset; <ide> } else { <ide> // Find the length <ide> switch (type = typeof subject) { <ide> case 'number': <del> this.length = subject; <add> this.length = coerce(subject); <ide> break; <ide> <ide> case 'string': <ide> this.length = Buffer.byteLength(subject, encoding); <ide> break; <ide> <ide> case 'object': // Assume object is an array <del> this.length = subject.length; <add> this.length = coerce(subject.length); <ide> break; <ide> <ide> default: <ide><path>test/simple/test-buffer.js <ide> buf.write('0123456789', 'binary'); <ide> assert.equal(Buffer._charsWritten, 9); <ide> buf.write('123456', 'base64'); <ide> assert.equal(Buffer._charsWritten, 6); <add> <add>// Check for fractional length args, junk length args, etc. <add>// https://github.com/joyent/node/issues/1758 <add>Buffer(3.3).toString(); // throws bad argument error in commit 43cb4ec <add>assert.equal(Buffer(-1).length, 0); <add>assert.equal(Buffer(NaN).length, 0); <add>assert.equal(Buffer(3.3).length, 4); <add>assert.equal(Buffer({length:3.3}).length, 4); <add>assert.equal(Buffer({length:"BAM"}).length, 0); <add> <add>// Make sure that strings are not coerced to numbers. <add>assert.equal(Buffer("99").length, 2); <add>assert.equal(Buffer("13.37").length, 5); <ide>\ No newline at end of file
2
Javascript
Javascript
replace css tag with js import
876cbbaf01cef39566e9a35e72e641f57a01f6e0
<ide><path>examples/with-loading/pages/_app.js <ide> import { useEffect } from 'react' <ide> import Link from 'next/link' <del>import Head from 'next/head' <ide> import { useRouter } from 'next/router' <ide> import NProgress from 'nprogress' <add>import '../public/nprogress.css' <ide> <ide> export default function App({ Component, pageProps }) { <ide> const router = useRouter() <ide> export default function App({ Component, pageProps }) { <ide> <ide> return ( <ide> <> <del> <Head> <del> {/* Import CSS for nprogress */} <del> <link rel="stylesheet" type="text/css" href="/nprogress.css" /> <del> </Head> <ide> <nav> <ide> <style jsx>{` <ide> a {
1
Ruby
Ruby
fix #scoped deprecations
1606bee64ade812af1ef5b231e41b44bebddd67f
<ide><path>activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb <ide> def test_class_names <ide> old = ActiveRecord::Base.store_full_sti_class <ide> <ide> ActiveRecord::Base.store_full_sti_class = false <del> post = Namespaced::Post.find_by_title( 'Great stuff', :include => :tagging ) <add> post = Namespaced::Post.includes(:tagging).find_by_title('Great stuff') <ide> assert_nil post.tagging <ide> <ide> ActiveRecord::Base.store_full_sti_class = true <del> post = Namespaced::Post.find_by_title( 'Great stuff', :include => :tagging ) <add> post = Namespaced::Post.includes(:tagging).find_by_title('Great stuff') <ide> assert_instance_of Tagging, post.tagging <ide> ensure <ide> ActiveRecord::Base.store_full_sti_class = old <ide><path>activerecord/test/cases/associations/join_model_test.rb <ide> def test_include_has_many_through <ide> end <ide> <ide> def test_include_polymorphic_has_one <del> post = Post.find_by_id(posts(:welcome).id, :include => :tagging) <add> post = Post.includes(:tagging).find posts(:welcome).id <ide> tagging = taggings(:welcome_general) <ide> assert_no_queries do <ide> assert_equal tagging, post.tagging <ide> end <ide> end <ide> <ide> def test_include_polymorphic_has_one_defined_in_abstract_parent <del> item = Item.find_by_id(items(:dvd).id, :include => :tagging) <add> item = Item.includes(:tagging).find items(:dvd).id <ide> tagging = taggings(:godfather) <ide> assert_no_queries do <ide> assert_equal tagging, item.tagging <ide> def test_has_many_through_polymorphic_has_many <ide> end <ide> <ide> def test_include_has_many_through_polymorphic_has_many <del> author = Author.find_by_id(authors(:david).id, :include => :taggings) <add> author = Author.includes(:taggings).find authors(:david).id <ide> expected_taggings = taggings(:welcome_general, :thinking_general) <ide> assert_no_queries do <ide> assert_equal expected_taggings, author.taggings.uniq.sort_by { |t| t.id } <ide><path>activerecord/test/cases/finder_test.rb <ide> def test_find_by_one_attribute_with_order_option <ide> end <ide> <ide> def test_find_by_one_attribute_with_conditions <del> assert_equal accounts(:rails_core_account), Account.find_by_credit_limit(50, :conditions => ['firm_id = ?', 6]) <add> assert_equal accounts(:rails_core_account), Account.where('firm_id = ?', 6).find_by_credit_limit(50) <ide> end <ide> <ide> def test_find_by_one_attribute_that_is_an_aggregate <ide> def test_find_by_two_attributes_with_one_being_an_aggregate <ide> def test_dynamic_finder_on_one_attribute_with_conditions_returns_same_results_after_caching <ide> # ensure this test can run independently of order <ide> class << Account; self; end.send(:remove_method, :find_by_credit_limit) if Account.public_methods.any? { |m| m.to_s == 'find_by_credit_limit' } <del> a = Account.find_by_credit_limit(50, :conditions => ['firm_id = ?', 6]) <del> assert_equal a, Account.find_by_credit_limit(50, :conditions => ['firm_id = ?', 6]) # find_by_credit_limit has been cached <add> a = Account.where('firm_id = ?', 6).find_by_credit_limit(50) <add> assert_equal a, Account.where('firm_id = ?', 6).find_by_credit_limit(50) # find_by_credit_limit has been cached <ide> end <ide> <ide> def test_find_by_one_attribute_with_several_options <del> assert_equal accounts(:unknown), Account.find_by_credit_limit(50, :order => 'id DESC', :conditions => ['id != ?', 3]) <add> assert_equal accounts(:unknown), Account.order('id DESC').where('id != ?', 3).find_by_credit_limit(50) <ide> end <ide> <ide> def test_find_by_one_missing_attribute <ide> def test_find_last_by_invalid_method_syntax <ide> end <ide> <ide> def test_find_last_by_one_attribute_with_several_options <del> assert_equal accounts(:signals37), Account.find_last_by_credit_limit(50, :order => 'id DESC', :conditions => ['id != ?', 3]) <add> assert_equal accounts(:signals37), Account.order('id DESC').where('id != ?', 3).find_last_by_credit_limit(50) <ide> end <ide> <ide> def test_find_last_by_one_missing_attribute <ide><path>activerecord/test/cases/named_scope_test.rb <ide> def test_active_records_have_scope_named__all__ <ide> end <ide> <ide> def test_active_records_have_scope_named__scoped__ <del> assert !Topic.find(:all, scope = {:conditions => "content LIKE '%Have%'"}).empty? <add> scope = Topic.where("content LIKE '%Have%'") <add> assert !scope.empty? <ide> <del> assert_equal Topic.find(:all, scope), Topic.scoped(scope) <add> assert_equal scope, Topic.scoped(where: "content LIKE '%Have%'") <ide> end <ide> <ide> def test_first_and_last_should_support_find_options <ide> def test_many_should_not_fire_query_if_scope_loaded <ide> end <ide> <ide> def test_many_should_return_false_if_none_or_one <del> topics = Topic.base.scoped(:conditions => {:id => 0}) <add> topics = Topic.base.where(:id => 0) <ide> assert !topics.many? <del> topics = Topic.base.scoped(:conditions => {:id => 1}) <add> topics = Topic.base.where(:id => 1) <ide> assert !topics.many? <ide> end <ide> <ide> def test_should_not_duplicates_where_values <ide> def test_chaining_with_duplicate_joins <ide> join = "INNER JOIN comments ON comments.post_id = posts.id" <ide> post = Post.find(1) <del> assert_equal post.comments.size, Post.scoped(:joins => join).scoped(:joins => join, :conditions => "posts.id = #{post.id}").size <add> assert_equal post.comments.size, Post.joins(join).joins(join).where("posts.id = #{post.id}").size <ide> end <ide> <ide> def test_chaining_should_use_latest_conditions_when_creating
4
Python
Python
add systemv amp, no more log message
2a09d3cdf05b189c08b7de3607f1be1f5d97f96a
<ide><path>glances/amps/glances_systemv.py <add># -*- coding: utf-8 -*- <add># <add># This file is part of Glances. <add># <add># Copyright (C) 2016 Nicolargo <nicolas@nicolargo.com> <add># <add># Glances is free software; you can redistribute it and/or modify <add># it under the terms of the GNU Lesser General Public License as published by <add># the Free Software Foundation, either version 3 of the License, or <add># (at your option) any later version. <add># <add># Glances is distributed in the hope that it will be useful, <add># but WITHOUT ANY WARRANTY; without even the implied warranty of <add># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the <add># GNU Lesser General Public License for more details. <add># <add># You should have received a copy of the GNU Lesser General Public License <add># along with this program. If not, see <http://www.gnu.org/licenses/>. <add> <add>""" <add>SystemV AMP <add>=========== <add> <add>Monitor the state of the Syste V init system and service. <add> <add>How to read the stats <add>--------------------- <add> <add>Running: Number of running services. <add>Stopped: Number of stopped services. <add>Upstart: Number of service managed by Upstart. <add> <add>Source reference: http://askubuntu.com/questions/407075/how-to-read-service-status-all-results <add> <add>Configuration file example <add>-------------------------- <add> <add>[amp_systemv] <add># Systemv <add>enable=true <add>regex=\/sbin\/init <add>refresh=60 <add>one_line=true <add>service_cmd=/usr/bin/service --status-all <add>""" <add> <add>from subprocess import check_output, STDOUT <add> <add>from glances.logger import logger <add>from glances.compat import iteritems <add>from glances.amps.glances_amp import GlancesAmp <add> <add> <add>class Amp(GlancesAmp): <add> """Glances' Systemd AMP.""" <add> <add> NAME = 'SystemV' <add> VERSION = '1.0' <add> DESCRIPTION = 'Get services list from service (initd)' <add> AUTHOR = 'Nicolargo' <add> EMAIL = 'contact@nicolargo.com' <add> <add> # def __init__(self, args=None): <add> # """Init the AMP.""" <add> # super(Amp, self).__init__(args=args) <add> <add> def update(self): <add> """Update the AMP""" <add> <add> if self.should_update(): <add> # Get the systemctl status <add> logger.debug('{0}: Update stats using service {1}'.format(self.NAME, self.get('service_cmd'))) <add> try: <add> res = check_output(self.get('service_cmd').split(), stderr=STDOUT) <add> except OSError as e: <add> logger.debug('{0}: Error while executing service ({1})'.format(self.NAME, e)) <add> else: <add> status = {'running': 0, 'stopped': 0, 'upstart': 0} <add> # For each line <add> for r in res.split('\n'): <add> # Split per space .* <add> l = r.split() <add> if len(l) < 4: <add> continue <add> if l[1] == '+': <add> status['running'] += 1 <add> elif l[1] == '-': <add> status['stopped'] += 1 <add> elif l[1] == '?': <add> status['upstart'] += 1 <add> # Build the output (string) message <add> output = 'Services\n' <add> for k, v in iteritems(status): <add> output += '{0}: {1}\n'.format(k, v) <add> self.set_result(output, separator=' ') <add> <add> return self.result()
1
Python
Python
fix parser test
61a503a61195c465328fcf0f283ce64f923b5c55
<ide><path>spacy/tests/conftest.py <ide> def en_vocab(): <ide> <ide> <ide> @pytest.fixture <del>def en_parser(): <del> return util.get_lang_class('en').Defaults.create_parser() <add>def en_parser(en_vocab): <add> nlp = util.get_lang_class('en')(en_vocab) <add> return nlp.create_pipe('parser') <ide> <ide> <ide> @pytest.fixture
1
Javascript
Javascript
convert `src/display/svg.js` to es6 syntax
47d3620d5a2a90738f4fd6deebceed3d8df71bc2
<ide><path>src/display/svg.js <ide> * limitations under the License. <ide> */ <ide> /* globals __non_webpack_require__ */ <add>/* eslint no-var: error */ <ide> <ide> import { <ide> createObjectURL, FONT_IDENTITY_MATRIX, IDENTITY_MATRIX, ImageKind, isNum, OPS, <ide> import { <ide> import { DOMSVGFactory } from './display_utils'; <ide> import isNodeJS from '../shared/is_node'; <ide> <del>var SVGGraphics = function() { <add>let SVGGraphics = function() { <ide> throw new Error('Not implemented: SVGGraphics'); <ide> }; <ide> <ide> if (typeof PDFJSDev === 'undefined' || PDFJSDev.test('GENERIC')) { <ide> <del>var SVG_DEFAULTS = { <add>const SVG_DEFAULTS = { <ide> fontStyle: 'normal', <ide> fontWeight: 'normal', <ide> fillColor: '#000000', <ide> }; <add>const XML_NS = 'http://www.w3.org/XML/1998/namespace'; <add>const XLINK_NS = 'http://www.w3.org/1999/xlink'; <add>const LINE_CAP_STYLES = ['butt', 'round', 'square']; <add>const LINE_JOIN_STYLES = ['miter', 'round', 'bevel']; <ide> <del>var convertImgDataToPng = (function convertImgDataToPngClosure() { <del> var PNG_HEADER = <add>const convertImgDataToPng = (function() { <add> const PNG_HEADER = <ide> new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); <add> const CHUNK_WRAPPER_SIZE = 12; <ide> <del> var CHUNK_WRAPPER_SIZE = 12; <del> <del> var crcTable = new Int32Array(256); <del> for (var i = 0; i < 256; i++) { <del> var c = i; <del> for (var h = 0; h < 8; h++) { <add> const crcTable = new Int32Array(256); <add> for (let i = 0; i < 256; i++) { <add> let c = i; <add> for (let h = 0; h < 8; h++) { <ide> if (c & 1) { <ide> c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff); <ide> } else { <ide> var convertImgDataToPng = (function convertImgDataToPngClosure() { <ide> } <ide> <ide> function crc32(data, start, end) { <del> var crc = -1; <del> for (var i = start; i < end; i++) { <del> var a = (crc ^ data[i]) & 0xff; <del> var b = crcTable[a]; <add> let crc = -1; <add> for (let i = start; i < end; i++) { <add> const a = (crc ^ data[i]) & 0xff; <add> const b = crcTable[a]; <ide> crc = (crc >>> 8) ^ b; <ide> } <ide> return crc ^ -1; <ide> } <ide> <ide> function writePngChunk(type, body, data, offset) { <del> var p = offset; <del> var len = body.length; <add> let p = offset; <add> const len = body.length; <ide> <ide> data[p] = len >> 24 & 0xff; <ide> data[p + 1] = len >> 16 & 0xff; <ide> var convertImgDataToPng = (function convertImgDataToPngClosure() { <ide> data.set(body, p); <ide> p += body.length; <ide> <del> var crc = crc32(data, offset + 4, p); <del> <add> const crc = crc32(data, offset + 4, p); <ide> data[p] = crc >> 24 & 0xff; <ide> data[p + 1] = crc >> 16 & 0xff; <ide> data[p + 2] = crc >> 8 & 0xff; <ide> data[p + 3] = crc & 0xff; <ide> } <ide> <ide> function adler32(data, start, end) { <del> var a = 1; <del> var b = 0; <del> for (var i = start; i < end; ++i) { <add> let a = 1; <add> let b = 0; <add> for (let i = start; i < end; ++i) { <ide> a = (a + (data[i] & 0xff)) % 65521; <ide> b = (b + a) % 65521; <ide> } <ide> var convertImgDataToPng = (function convertImgDataToPngClosure() { <ide> // Node v0.11.12 zlib.deflateSync is introduced (and returns a Buffer). <ide> // Node v3.0.0 Buffer inherits from Uint8Array. <ide> // Node v8.0.0 zlib.deflateSync accepts Uint8Array as input. <del> var input; <add> let input; <ide> // eslint-disable-next-line no-undef <ide> if (parseInt(process.versions.node) >= 8) { <ide> input = literals; <ide> } else { <ide> // eslint-disable-next-line no-undef <ide> input = new Buffer(literals); <ide> } <del> var output = __non_webpack_require__('zlib') <add> const output = __non_webpack_require__('zlib') <ide> .deflateSync(input, { level: 9, }); <ide> return output instanceof Uint8Array ? output : new Uint8Array(output); <ide> } catch (e) { <ide> var convertImgDataToPng = (function convertImgDataToPngClosure() { <ide> <ide> // An implementation of DEFLATE with compression level 0 (Z_NO_COMPRESSION). <ide> function deflateSyncUncompressed(literals) { <del> var len = literals.length; <del> var maxBlockLength = 0xFFFF; <add> let len = literals.length; <add> const maxBlockLength = 0xFFFF; <ide> <del> var deflateBlocks = Math.ceil(len / maxBlockLength); <del> var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4); <del> var pi = 0; <add> const deflateBlocks = Math.ceil(len / maxBlockLength); <add> const idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4); <add> let pi = 0; <ide> idat[pi++] = 0x78; // compression method and flags <ide> idat[pi++] = 0x9c; // flags <ide> <del> var pos = 0; <add> let pos = 0; <ide> while (len > maxBlockLength) { <ide> // writing non-final DEFLATE blocks type 0 and length of 65535 <ide> idat[pi++] = 0x00; <ide> var convertImgDataToPng = (function convertImgDataToPngClosure() { <ide> idat.set(literals.subarray(pos), pi); <ide> pi += literals.length - pos; <ide> <del> var adler = adler32(literals, 0, literals.length); // checksum <add> const adler = adler32(literals, 0, literals.length); // checksum <ide> idat[pi++] = adler >> 24 & 0xff; <ide> idat[pi++] = adler >> 16 & 0xff; <ide> idat[pi++] = adler >> 8 & 0xff; <ide> var convertImgDataToPng = (function convertImgDataToPngClosure() { <ide> } <ide> <ide> function encode(imgData, kind, forceDataSchema, isMask) { <del> var width = imgData.width; <del> var height = imgData.height; <del> var bitDepth, colorType, lineSize; <del> var bytes = imgData.data; <add> const width = imgData.width; <add> const height = imgData.height; <add> let bitDepth, colorType, lineSize; <add> const bytes = imgData.data; <ide> <ide> switch (kind) { <ide> case ImageKind.GRAYSCALE_1BPP: <ide> var convertImgDataToPng = (function convertImgDataToPngClosure() { <ide> } <ide> <ide> // prefix every row with predictor 0 <del> var literals = new Uint8Array((1 + lineSize) * height); <del> var offsetLiterals = 0, offsetBytes = 0; <del> var y, i; <del> for (y = 0; y < height; ++y) { <add> const literals = new Uint8Array((1 + lineSize) * height); <add> let offsetLiterals = 0, offsetBytes = 0; <add> for (let y = 0; y < height; ++y) { <ide> literals[offsetLiterals++] = 0; // no prediction <ide> literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), <ide> offsetLiterals); <ide> var convertImgDataToPng = (function convertImgDataToPngClosure() { <ide> if (kind === ImageKind.GRAYSCALE_1BPP && isMask) { <ide> // inverting for image masks <ide> offsetLiterals = 0; <del> for (y = 0; y < height; y++) { <add> for (let y = 0; y < height; y++) { <ide> offsetLiterals++; // skipping predictor <del> for (i = 0; i < lineSize; i++) { <add> for (let i = 0; i < lineSize; i++) { <ide> literals[offsetLiterals++] ^= 0xFF; <ide> } <ide> } <ide> } <ide> <del> var ihdr = new Uint8Array([ <add> const ihdr = new Uint8Array([ <ide> width >> 24 & 0xff, <ide> width >> 16 & 0xff, <ide> width >> 8 & 0xff, <ide> var convertImgDataToPng = (function convertImgDataToPngClosure() { <ide> 0x00, // filter method <ide> 0x00 // interlace method <ide> ]); <add> const idat = deflateSync(literals); <ide> <del> var idat = deflateSync(literals); <del> <del> // PNG will consists: header, IHDR+data, IDAT+data, and IEND. <del> var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) + <del> ihdr.length + idat.length; <del> var data = new Uint8Array(pngLength); <del> var offset = 0; <add> // PNG consists of: header, IHDR+data, IDAT+data, and IEND. <add> const pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) + <add> ihdr.length + idat.length; <add> const data = new Uint8Array(pngLength); <add> let offset = 0; <ide> data.set(PNG_HEADER, offset); <ide> offset += PNG_HEADER.length; <ide> writePngChunk('IHDR', ihdr, data, offset); <ide> var convertImgDataToPng = (function convertImgDataToPngClosure() { <ide> } <ide> <ide> return function convertImgDataToPng(imgData, forceDataSchema, isMask) { <del> var kind = (imgData.kind === undefined ? <del> ImageKind.GRAYSCALE_1BPP : imgData.kind); <add> const kind = (imgData.kind === undefined ? <add> ImageKind.GRAYSCALE_1BPP : imgData.kind); <ide> return encode(imgData, kind, forceDataSchema, isMask); <ide> }; <ide> })(); <ide> <del>var SVGExtraState = (function SVGExtraStateClosure() { <del> function SVGExtraState() { <add>class SVGExtraState { <add> constructor() { <ide> this.fontSizeScale = 1; <ide> this.fontWeight = SVG_DEFAULTS.fontWeight; <ide> this.fontSize = 0; <ide> var SVGExtraState = (function SVGExtraStateClosure() { <ide> this.maskId = ''; <ide> } <ide> <del> SVGExtraState.prototype = { <del> clone: function SVGExtraState_clone() { <del> return Object.create(this); <del> }, <del> setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) { <del> this.x = x; <del> this.y = y; <del> }, <del> }; <del> return SVGExtraState; <del>})(); <del> <del>SVGGraphics = (function SVGGraphicsClosure() { <del> function opListToTree(opList) { <del> var opTree = []; <del> var tmp = []; <del> var opListLen = opList.length; <del> <del> for (var x = 0; x < opListLen; x++) { <del> if (opList[x].fn === 'save') { <del> opTree.push({ 'fnId': 92, 'fn': 'group', 'items': [], }); <del> tmp.push(opTree); <del> opTree = opTree[opTree.length - 1].items; <del> continue; <del> } <add> clone() { <add> return Object.create(this); <add> } <ide> <del> if (opList[x].fn === 'restore') { <del> opTree = tmp.pop(); <del> } else { <del> opTree.push(opList[x]); <del> } <del> } <del> return opTree; <add> setCurrentPoint(x, y) { <add> this.x = x; <add> this.y = y; <ide> } <add>} <ide> <del> /** <del> * Formats float number. <del> * @param value {number} number to format. <del> * @returns {string} <del> */ <del> function pf(value) { <del> if (Number.isInteger(value)) { <del> return value.toString(); <add>// eslint-disable-next-line no-inner-declarations <add>function opListToTree(opList) { <add> let opTree = []; <add> const tmp = []; <add> <add> for (const opListElement of opList) { <add> if (opListElement.fn === 'save') { <add> opTree.push({ 'fnId': 92, 'fn': 'group', 'items': [], }); <add> tmp.push(opTree); <add> opTree = opTree[opTree.length - 1].items; <add> continue; <ide> } <del> var s = value.toFixed(10); <del> var i = s.length - 1; <del> if (s[i] !== '0') { <del> return s; <add> <add> if (opListElement.fn === 'restore') { <add> opTree = tmp.pop(); <add> } else { <add> opTree.push(opListElement); <ide> } <del> // removing trailing zeros <del> do { <del> i--; <del> } while (s[i] === '0'); <del> return s.substring(0, s[i] === '.' ? i : i + 1); <ide> } <add> return opTree; <add>} <ide> <del> /** <del> * Formats transform matrix. The standard rotation, scale and translate <del> * matrices are replaced by their shorter forms, and for identity matrix <del> * returns empty string to save the memory. <del> * @param m {Array} matrix to format. <del> * @returns {string} <del> */ <del> function pm(m) { <del> if (m[4] === 0 && m[5] === 0) { <del> if (m[1] === 0 && m[2] === 0) { <del> if (m[0] === 1 && m[3] === 1) { <del> return ''; <del> } <del> return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')'; <del> } <del> if (m[0] === m[3] && m[1] === -m[2]) { <del> var a = Math.acos(m[0]) * 180 / Math.PI; <del> return 'rotate(' + pf(a) + ')'; <del> } <del> } else { <del> if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) { <del> return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')'; <add>/** <add> * Format a float number as a string. <add> * <add> * @param value {number} - The float number to format. <add> * @returns {string} <add> */ <add>// eslint-disable-next-line no-inner-declarations <add>function pf(value) { <add> if (Number.isInteger(value)) { <add> return value.toString(); <add> } <add> const s = value.toFixed(10); <add> let i = s.length - 1; <add> if (s[i] !== '0') { <add> return s; <add> } <add> <add> // Remove trailing zeros. <add> do { <add> i--; <add> } while (s[i] === '0'); <add> return s.substring(0, s[i] === '.' ? i : i + 1); <add>} <add> <add>/** <add> * Format a transform matrix as a string. The standard rotation, scale and <add> * translation matrices are replaced by their shorter forms, and for <add> * identity matrices an empty string is returned to save memory. <add> * <add> * @param m {Array} - The transform matrix to format. <add> * @returns {string} <add> */ <add>// eslint-disable-next-line no-inner-declarations <add>function pm(m) { <add> if (m[4] === 0 && m[5] === 0) { <add> if (m[1] === 0 && m[2] === 0) { <add> if (m[0] === 1 && m[3] === 1) { <add> return ''; <ide> } <add> return `scale(${pf(m[0])} ${pf(m[3])})`; <add> } <add> if (m[0] === m[3] && m[1] === -m[2]) { <add> const a = Math.acos(m[0]) * 180 / Math.PI; <add> return `rotate(${pf(a)})`; <add> } <add> } else { <add> if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) { <add> return `translate(${pf(m[4])} ${pf(m[5])})`; <ide> } <del> return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' + <del> pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')'; <ide> } <add> return `matrix(${pf(m[0])} ${pf(m[1])} ${pf(m[2])} ${pf(m[3])} ${pf(m[4])} ` + <add> `${pf(m[5])})`; <add>} <ide> <del> function SVGGraphics(commonObjs, objs, forceDataSchema) { <add>// The counts below are relevant for all pages, so they have to be global <add>// instead of being members of `SVGGraphics` (which is recreated for <add>// each page). <add>let clipCount = 0; <add>let maskCount = 0; <add>let shadingCount = 0; <add> <add>SVGGraphics = class SVGGraphics { <add> constructor(commonObjs, objs, forceDataSchema) { <ide> this.svgFactory = new DOMSVGFactory(); <ide> <ide> this.current = new SVGExtraState(); <ide> SVGGraphics = (function SVGGraphicsClosure() { <ide> this.forceDataSchema = !!forceDataSchema; <ide> } <ide> <del> var XML_NS = 'http://www.w3.org/XML/1998/namespace'; <del> var XLINK_NS = 'http://www.w3.org/1999/xlink'; <del> var LINE_CAP_STYLES = ['butt', 'round', 'square']; <del> var LINE_JOIN_STYLES = ['miter', 'round', 'bevel']; <del> var clipCount = 0; <del> var maskCount = 0; <del> var shadingCount = 0; <del> <del> SVGGraphics.prototype = { <del> save: function SVGGraphics_save() { <del> this.transformStack.push(this.transformMatrix); <del> var old = this.current; <del> this.extraStack.push(old); <del> this.current = old.clone(); <del> }, <del> <del> restore: function SVGGraphics_restore() { <del> this.transformMatrix = this.transformStack.pop(); <del> this.current = this.extraStack.pop(); <del> <del> this.pendingClip = null; <del> this.tgrp = null; <del> }, <del> <del> group: function SVGGraphics_group(items) { <del> this.save(); <del> this.executeOpTree(items); <del> this.restore(); <del> }, <del> <del> loadDependencies: function SVGGraphics_loadDependencies(operatorList) { <del> var fnArray = operatorList.fnArray; <del> var fnArrayLen = fnArray.length; <del> var argsArray = operatorList.argsArray; <del> <del> for (var i = 0; i < fnArrayLen; i++) { <del> if (OPS.dependency === fnArray[i]) { <del> var deps = argsArray[i]; <del> for (var n = 0, nn = deps.length; n < nn; n++) { <del> var obj = deps[n]; <del> var common = obj.substring(0, 2) === 'g_'; <del> var promise; <del> if (common) { <del> promise = new Promise((resolve) => { <del> this.commonObjs.get(obj, resolve); <del> }); <del> } else { <del> promise = new Promise((resolve) => { <del> this.objs.get(obj, resolve); <del> }); <del> } <del> this.current.dependencies.push(promise); <del> } <del> } <del> } <del> return Promise.all(this.current.dependencies); <del> }, <del> <del> transform: function SVGGraphics_transform(a, b, c, d, e, f) { <del> var transformMatrix = [a, b, c, d, e, f]; <del> this.transformMatrix = Util.transform(this.transformMatrix, <del> transformMatrix); <del> this.tgrp = null; <del> }, <del> <del> getSVG: function SVGGraphics_getSVG(operatorList, viewport) { <del> this.viewport = viewport; <del> <del> var svgElement = this._initialize(viewport); <del> return this.loadDependencies(operatorList).then(() => { <del> this.transformMatrix = IDENTITY_MATRIX; <del> var opTree = this.convertOpList(operatorList); <del> this.executeOpTree(opTree); <del> return svgElement; <del> }); <del> }, <add> save() { <add> this.transformStack.push(this.transformMatrix); <add> const old = this.current; <add> this.extraStack.push(old); <add> this.current = old.clone(); <add> } <add> <add> restore() { <add> this.transformMatrix = this.transformStack.pop(); <add> this.current = this.extraStack.pop(); <add> this.pendingClip = null; <add> this.tgrp = null; <add> } <add> <add> group(items) { <add> this.save(); <add> this.executeOpTree(items); <add> this.restore(); <add> } <ide> <del> convertOpList: function SVGGraphics_convertOpList(operatorList) { <del> var argsArray = operatorList.argsArray; <del> var fnArray = operatorList.fnArray; <del> var fnArrayLen = fnArray.length; <del> var REVOPS = []; <del> var opList = []; <add> loadDependencies(operatorList) { <add> const fnArray = operatorList.fnArray; <add> const argsArray = operatorList.argsArray; <ide> <del> for (var op in OPS) { <del> REVOPS[OPS[op]] = op; <add> for (let i = 0, ii = fnArray.length; i < ii; i++) { <add> if (fnArray[i] !== OPS.dependency) { <add> continue; <ide> } <ide> <del> for (var x = 0; x < fnArrayLen; x++) { <del> var fnId = fnArray[x]; <del> opList.push({ <del> 'fnId': fnId, <del> 'fn': REVOPS[fnId], <del> 'args': argsArray[x], <add> for (const obj of argsArray[i]) { <add> const objsPool = obj.startsWith('g_') ? this.commonObjs : this.objs; <add> const promise = new Promise((resolve) => { <add> objsPool.get(obj, resolve); <ide> }); <add> this.current.dependencies.push(promise); <ide> } <del> return opListToTree(opList); <del> }, <del> <del> executeOpTree: function SVGGraphics_executeOpTree(opTree) { <del> var opTreeLen = opTree.length; <del> for (var x = 0; x < opTreeLen; x++) { <del> var fn = opTree[x].fn; <del> var fnId = opTree[x].fnId; <del> var args = opTree[x].args; <del> <del> switch (fnId | 0) { <del> case OPS.beginText: <del> this.beginText(); <del> break; <del> case OPS.dependency: <del> // Handled in loadDependencies, warning should not be thrown <del> break; <del> case OPS.setLeading: <del> this.setLeading(args); <del> break; <del> case OPS.setLeadingMoveText: <del> this.setLeadingMoveText(args[0], args[1]); <del> break; <del> case OPS.setFont: <del> this.setFont(args); <del> break; <del> case OPS.showText: <del> this.showText(args[0]); <del> break; <del> case OPS.showSpacedText: <del> this.showText(args[0]); <del> break; <del> case OPS.endText: <del> this.endText(); <del> break; <del> case OPS.moveText: <del> this.moveText(args[0], args[1]); <del> break; <del> case OPS.setCharSpacing: <del> this.setCharSpacing(args[0]); <del> break; <del> case OPS.setWordSpacing: <del> this.setWordSpacing(args[0]); <del> break; <del> case OPS.setHScale: <del> this.setHScale(args[0]); <del> break; <del> case OPS.setTextMatrix: <del> this.setTextMatrix(args[0], args[1], args[2], <del> args[3], args[4], args[5]); <del> break; <del> case OPS.setTextRise: <del> this.setTextRise(args[0]); <del> break; <del> case OPS.setTextRenderingMode: <del> this.setTextRenderingMode(args[0]); <del> break; <del> case OPS.setLineWidth: <del> this.setLineWidth(args[0]); <del> break; <del> case OPS.setLineJoin: <del> this.setLineJoin(args[0]); <del> break; <del> case OPS.setLineCap: <del> this.setLineCap(args[0]); <del> break; <del> case OPS.setMiterLimit: <del> this.setMiterLimit(args[0]); <del> break; <del> case OPS.setFillRGBColor: <del> this.setFillRGBColor(args[0], args[1], args[2]); <del> break; <del> case OPS.setStrokeRGBColor: <del> this.setStrokeRGBColor(args[0], args[1], args[2]); <del> break; <del> case OPS.setStrokeColorN: <del> this.setStrokeColorN(args); <del> break; <del> case OPS.setFillColorN: <del> this.setFillColorN(args); <del> break; <del> case OPS.shadingFill: <del> this.shadingFill(args[0]); <del> break; <del> case OPS.setDash: <del> this.setDash(args[0], args[1]); <del> break; <del> case OPS.setGState: <del> this.setGState(args[0]); <del> break; <del> case OPS.fill: <del> this.fill(); <del> break; <del> case OPS.eoFill: <del> this.eoFill(); <del> break; <del> case OPS.stroke: <del> this.stroke(); <del> break; <del> case OPS.fillStroke: <del> this.fillStroke(); <del> break; <del> case OPS.eoFillStroke: <del> this.eoFillStroke(); <del> break; <del> case OPS.clip: <del> this.clip('nonzero'); <del> break; <del> case OPS.eoClip: <del> this.clip('evenodd'); <del> break; <del> case OPS.paintSolidColorImageMask: <del> this.paintSolidColorImageMask(); <del> break; <del> case OPS.paintJpegXObject: <del> this.paintJpegXObject(args[0], args[1], args[2]); <del> break; <del> case OPS.paintImageXObject: <del> this.paintImageXObject(args[0]); <del> break; <del> case OPS.paintInlineImageXObject: <del> this.paintInlineImageXObject(args[0]); <del> break; <del> case OPS.paintImageMaskXObject: <del> this.paintImageMaskXObject(args[0]); <del> break; <del> case OPS.paintFormXObjectBegin: <del> this.paintFormXObjectBegin(args[0], args[1]); <del> break; <del> case OPS.paintFormXObjectEnd: <del> this.paintFormXObjectEnd(); <del> break; <del> case OPS.closePath: <del> this.closePath(); <del> break; <del> case OPS.closeStroke: <del> this.closeStroke(); <del> break; <del> case OPS.closeFillStroke: <del> this.closeFillStroke(); <del> break; <del> case OPS.closeEOFillStroke: <del> this.closeEOFillStroke(); <del> break; <del> case OPS.nextLine: <del> this.nextLine(); <del> break; <del> case OPS.transform: <del> this.transform(args[0], args[1], args[2], args[3], <del> args[4], args[5]); <del> break; <del> case OPS.constructPath: <del> this.constructPath(args[0], args[1]); <del> break; <del> case OPS.endPath: <del> this.endPath(); <del> break; <del> case 92: <del> this.group(opTree[x].items); <del> break; <del> default: <del> warn('Unimplemented operator ' + fn); <del> break; <del> } <add> } <add> return Promise.all(this.current.dependencies); <add> } <add> <add> transform(a, b, c, d, e, f) { <add> const transformMatrix = [a, b, c, d, e, f]; <add> this.transformMatrix = Util.transform(this.transformMatrix, <add> transformMatrix); <add> this.tgrp = null; <add> } <add> <add> getSVG(operatorList, viewport) { <add> this.viewport = viewport; <add> <add> const svgElement = this._initialize(viewport); <add> return this.loadDependencies(operatorList).then(() => { <add> this.transformMatrix = IDENTITY_MATRIX; <add> this.executeOpTree(this.convertOpList(operatorList)); <add> return svgElement; <add> }); <add> } <add> <add> convertOpList(operatorList) { <add> const REVOPS = []; <add> for (const op in OPS) { <add> REVOPS[OPS[op]] = op; <add> } <add> <add> const argsArray = operatorList.argsArray; <add> const fnArray = operatorList.fnArray; <add> const opList = []; <add> for (let i = 0, ii = fnArray.length; i < ii; i++) { <add> const fnId = fnArray[i]; <add> opList.push({ <add> 'fnId': fnId, <add> 'fn': REVOPS[fnId], <add> 'args': argsArray[i], <add> }); <add> } <add> return opListToTree(opList); <add> } <add> <add> executeOpTree(opTree) { <add> for (const opTreeElement of opTree) { <add> const fn = opTreeElement.fn; <add> const fnId = opTreeElement.fnId; <add> const args = opTreeElement.args; <add> <add> switch (fnId | 0) { <add> case OPS.beginText: <add> this.beginText(); <add> break; <add> case OPS.dependency: <add> // Handled in `loadDependencies`, so no warning should be shown. <add> break; <add> case OPS.setLeading: <add> this.setLeading(args); <add> break; <add> case OPS.setLeadingMoveText: <add> this.setLeadingMoveText(args[0], args[1]); <add> break; <add> case OPS.setFont: <add> this.setFont(args); <add> break; <add> case OPS.showText: <add> this.showText(args[0]); <add> break; <add> case OPS.showSpacedText: <add> this.showText(args[0]); <add> break; <add> case OPS.endText: <add> this.endText(); <add> break; <add> case OPS.moveText: <add> this.moveText(args[0], args[1]); <add> break; <add> case OPS.setCharSpacing: <add> this.setCharSpacing(args[0]); <add> break; <add> case OPS.setWordSpacing: <add> this.setWordSpacing(args[0]); <add> break; <add> case OPS.setHScale: <add> this.setHScale(args[0]); <add> break; <add> case OPS.setTextMatrix: <add> this.setTextMatrix(args[0], args[1], args[2], <add> args[3], args[4], args[5]); <add> break; <add> case OPS.setTextRise: <add> this.setTextRise(args[0]); <add> break; <add> case OPS.setTextRenderingMode: <add> this.setTextRenderingMode(args[0]); <add> break; <add> case OPS.setLineWidth: <add> this.setLineWidth(args[0]); <add> break; <add> case OPS.setLineJoin: <add> this.setLineJoin(args[0]); <add> break; <add> case OPS.setLineCap: <add> this.setLineCap(args[0]); <add> break; <add> case OPS.setMiterLimit: <add> this.setMiterLimit(args[0]); <add> break; <add> case OPS.setFillRGBColor: <add> this.setFillRGBColor(args[0], args[1], args[2]); <add> break; <add> case OPS.setStrokeRGBColor: <add> this.setStrokeRGBColor(args[0], args[1], args[2]); <add> break; <add> case OPS.setStrokeColorN: <add> this.setStrokeColorN(args); <add> break; <add> case OPS.setFillColorN: <add> this.setFillColorN(args); <add> break; <add> case OPS.shadingFill: <add> this.shadingFill(args[0]); <add> break; <add> case OPS.setDash: <add> this.setDash(args[0], args[1]); <add> break; <add> case OPS.setGState: <add> this.setGState(args[0]); <add> break; <add> case OPS.fill: <add> this.fill(); <add> break; <add> case OPS.eoFill: <add> this.eoFill(); <add> break; <add> case OPS.stroke: <add> this.stroke(); <add> break; <add> case OPS.fillStroke: <add> this.fillStroke(); <add> break; <add> case OPS.eoFillStroke: <add> this.eoFillStroke(); <add> break; <add> case OPS.clip: <add> this.clip('nonzero'); <add> break; <add> case OPS.eoClip: <add> this.clip('evenodd'); <add> break; <add> case OPS.paintSolidColorImageMask: <add> this.paintSolidColorImageMask(); <add> break; <add> case OPS.paintJpegXObject: <add> this.paintJpegXObject(args[0], args[1], args[2]); <add> break; <add> case OPS.paintImageXObject: <add> this.paintImageXObject(args[0]); <add> break; <add> case OPS.paintInlineImageXObject: <add> this.paintInlineImageXObject(args[0]); <add> break; <add> case OPS.paintImageMaskXObject: <add> this.paintImageMaskXObject(args[0]); <add> break; <add> case OPS.paintFormXObjectBegin: <add> this.paintFormXObjectBegin(args[0], args[1]); <add> break; <add> case OPS.paintFormXObjectEnd: <add> this.paintFormXObjectEnd(); <add> break; <add> case OPS.closePath: <add> this.closePath(); <add> break; <add> case OPS.closeStroke: <add> this.closeStroke(); <add> break; <add> case OPS.closeFillStroke: <add> this.closeFillStroke(); <add> break; <add> case OPS.closeEOFillStroke: <add> this.closeEOFillStroke(); <add> break; <add> case OPS.nextLine: <add> this.nextLine(); <add> break; <add> case OPS.transform: <add> this.transform(args[0], args[1], args[2], args[3], args[4], args[5]); <add> break; <add> case OPS.constructPath: <add> this.constructPath(args[0], args[1]); <add> break; <add> case OPS.endPath: <add> this.endPath(); <add> break; <add> case 92: <add> this.group(opTreeElement.items); <add> break; <add> default: <add> warn(`Unimplemented operator ${fn}`); <add> break; <ide> } <del> }, <del> <del> setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) { <del> this.current.wordSpacing = wordSpacing; <del> }, <del> <del> setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) { <del> this.current.charSpacing = charSpacing; <del> }, <del> <del> nextLine: function SVGGraphics_nextLine() { <del> this.moveText(0, this.current.leading); <del> }, <del> <del> setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) { <del> var current = this.current; <del> this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f]; <del> current.textMatrixScale = Math.sqrt(a * a + b * b); <del> <del> this.current.x = this.current.lineX = 0; <del> this.current.y = this.current.lineY = 0; <del> <del> current.xcoords = []; <del> current.tspan = this.svgFactory.createElement('svg:tspan'); <del> current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); <del> current.tspan.setAttributeNS(null, 'font-size', <del> pf(current.fontSize) + 'px'); <del> current.tspan.setAttributeNS(null, 'y', pf(-current.y)); <del> <del> current.txtElement = this.svgFactory.createElement('svg:text'); <del> current.txtElement.appendChild(current.tspan); <del> }, <del> <del> beginText: function SVGGraphics_beginText() { <del> this.current.x = this.current.lineX = 0; <del> this.current.y = this.current.lineY = 0; <del> this.current.textMatrix = IDENTITY_MATRIX; <del> this.current.lineMatrix = IDENTITY_MATRIX; <del> this.current.textMatrixScale = 1; <del> this.current.tspan = this.svgFactory.createElement('svg:tspan'); <del> this.current.txtElement = this.svgFactory.createElement('svg:text'); <del> this.current.txtgrp = this.svgFactory.createElement('svg:g'); <del> this.current.xcoords = []; <del> }, <del> <del> moveText: function SVGGraphics_moveText(x, y) { <del> var current = this.current; <del> this.current.x = this.current.lineX += x; <del> this.current.y = this.current.lineY += y; <del> <del> current.xcoords = []; <del> current.tspan = this.svgFactory.createElement('svg:tspan'); <del> current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); <del> current.tspan.setAttributeNS(null, 'font-size', <del> pf(current.fontSize) + 'px'); <del> current.tspan.setAttributeNS(null, 'y', pf(-current.y)); <del> }, <del> <del> showText: function SVGGraphics_showText(glyphs) { <del> var current = this.current; <del> var font = current.font; <del> var fontSize = current.fontSize; <del> <del> if (fontSize === 0) { <del> return; <add> } <add> } <add> <add> setWordSpacing(wordSpacing) { <add> this.current.wordSpacing = wordSpacing; <add> } <add> <add> setCharSpacing(charSpacing) { <add> this.current.charSpacing = charSpacing; <add> } <add> <add> nextLine() { <add> this.moveText(0, this.current.leading); <add> } <add> <add> setTextMatrix(a, b, c, d, e, f) { <add> const current = this.current; <add> current.textMatrix = current.lineMatrix = [a, b, c, d, e, f]; <add> current.textMatrixScale = Math.sqrt(a * a + b * b); <add> <add> current.x = current.lineX = 0; <add> current.y = current.lineY = 0; <add> <add> current.xcoords = []; <add> current.tspan = this.svgFactory.createElement('svg:tspan'); <add> current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); <add> current.tspan.setAttributeNS(null, 'font-size', <add> `${pf(current.fontSize)}px`); <add> current.tspan.setAttributeNS(null, 'y', pf(-current.y)); <add> <add> current.txtElement = this.svgFactory.createElement('svg:text'); <add> current.txtElement.appendChild(current.tspan); <add> } <add> <add> beginText() { <add> const current = this.current; <add> current.x = current.lineX = 0; <add> current.y = current.lineY = 0; <add> current.textMatrix = IDENTITY_MATRIX; <add> current.lineMatrix = IDENTITY_MATRIX; <add> current.textMatrixScale = 1; <add> current.tspan = this.svgFactory.createElement('svg:tspan'); <add> current.txtElement = this.svgFactory.createElement('svg:text'); <add> current.txtgrp = this.svgFactory.createElement('svg:g'); <add> current.xcoords = []; <add> } <add> <add> moveText(x, y) { <add> const current = this.current; <add> current.x = current.lineX += x; <add> current.y = current.lineY += y; <add> <add> current.xcoords = []; <add> current.tspan = this.svgFactory.createElement('svg:tspan'); <add> current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); <add> current.tspan.setAttributeNS(null, 'font-size', <add> `${pf(current.fontSize)}px`); <add> current.tspan.setAttributeNS(null, 'y', pf(-current.y)); <add> } <add> <add> showText(glyphs) { <add> const current = this.current; <add> const font = current.font; <add> const fontSize = current.fontSize; <add> if (fontSize === 0) { <add> return; <add> } <add> <add> const charSpacing = current.charSpacing; <add> const wordSpacing = current.wordSpacing; <add> const fontDirection = current.fontDirection; <add> const textHScale = current.textHScale * fontDirection; <add> const vertical = font.vertical; <add> const widthAdvanceScale = fontSize * current.fontMatrix[0]; <add> <add> let x = 0; <add> for (const glyph of glyphs) { <add> if (glyph === null) { <add> // Word break <add> x += fontDirection * wordSpacing; <add> continue; <add> } else if (isNum(glyph)) { <add> x += -glyph * fontSize * 0.001; <add> continue; <ide> } <ide> <del> var charSpacing = current.charSpacing; <del> var wordSpacing = current.wordSpacing; <del> var fontDirection = current.fontDirection; <del> var textHScale = current.textHScale * fontDirection; <del> var glyphsLength = glyphs.length; <del> var vertical = font.vertical; <del> var widthAdvanceScale = fontSize * current.fontMatrix[0]; <del> <del> var x = 0, i; <del> for (i = 0; i < glyphsLength; ++i) { <del> var glyph = glyphs[i]; <del> if (glyph === null) { <del> // word break <del> x += fontDirection * wordSpacing; <del> continue; <del> } else if (isNum(glyph)) { <del> x += -glyph * fontSize * 0.001; <del> continue; <del> } <add> const width = glyph.width; <add> const character = glyph.fontChar; <add> const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; <add> const charWidth = width * widthAdvanceScale + spacing * fontDirection; <ide> <del> var width = glyph.width; <del> var character = glyph.fontChar; <del> var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; <del> var charWidth = width * widthAdvanceScale + spacing * fontDirection; <del> <del> if (!glyph.isInFont && !font.missingFile) { <del> x += charWidth; <del> // TODO: To assist with text selection, we should replace the missing <del> // character with a space character if charWidth is not zero. <del> // But we cannot just do "character = ' '", because the ' ' character <del> // might actually map to a different glyph. <del> continue; <del> } <del> current.xcoords.push(current.x + x * textHScale); <del> current.tspan.textContent += character; <add> if (!glyph.isInFont && !font.missingFile) { <ide> x += charWidth; <add> // TODO: To assist with text selection, we should replace the missing <add> // character with a space character if charWidth is not zero. <add> // But we cannot just do "character = ' '", because the ' ' character <add> // might actually map to a different glyph. <add> continue; <ide> } <del> if (vertical) { <del> current.y -= x * textHScale; <del> } else { <del> current.x += x * textHScale; <del> } <add> current.xcoords.push(current.x + x * textHScale); <add> current.tspan.textContent += character; <add> x += charWidth; <add> } <add> if (vertical) { <add> current.y -= x * textHScale; <add> } else { <add> current.x += x * textHScale; <add> } <ide> <del> current.tspan.setAttributeNS(null, 'x', <del> current.xcoords.map(pf).join(' ')); <del> current.tspan.setAttributeNS(null, 'y', pf(-current.y)); <del> current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); <del> current.tspan.setAttributeNS(null, 'font-size', <del> pf(current.fontSize) + 'px'); <del> if (current.fontStyle !== SVG_DEFAULTS.fontStyle) { <del> current.tspan.setAttributeNS(null, 'font-style', current.fontStyle); <add> current.tspan.setAttributeNS(null, 'x', <add> current.xcoords.map(pf).join(' ')); <add> current.tspan.setAttributeNS(null, 'y', pf(-current.y)); <add> current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); <add> current.tspan.setAttributeNS(null, 'font-size', <add> `${pf(current.fontSize)}px`); <add> if (current.fontStyle !== SVG_DEFAULTS.fontStyle) { <add> current.tspan.setAttributeNS(null, 'font-style', current.fontStyle); <add> } <add> if (current.fontWeight !== SVG_DEFAULTS.fontWeight) { <add> current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight); <add> } <add> <add> const fillStrokeMode = current.textRenderingMode & <add> TextRenderingMode.FILL_STROKE_MASK; <add> if (fillStrokeMode === TextRenderingMode.FILL || <add> fillStrokeMode === TextRenderingMode.FILL_STROKE) { <add> if (current.fillColor !== SVG_DEFAULTS.fillColor) { <add> current.tspan.setAttributeNS(null, 'fill', current.fillColor); <ide> } <del> if (current.fontWeight !== SVG_DEFAULTS.fontWeight) { <del> current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight); <add> if (current.fillAlpha < 1) { <add> current.tspan.setAttributeNS(null, 'fill-opacity', current.fillAlpha); <ide> } <add> } else if (current.textRenderingMode === TextRenderingMode.ADD_TO_PATH) { <add> // Workaround for Firefox: We must set fill="transparent" because <add> // fill="none" would generate an empty clipping path. <add> current.tspan.setAttributeNS(null, 'fill', 'transparent'); <add> } else { <add> current.tspan.setAttributeNS(null, 'fill', 'none'); <add> } <ide> <del> const fillStrokeMode = current.textRenderingMode & <del> TextRenderingMode.FILL_STROKE_MASK; <add> if (fillStrokeMode === TextRenderingMode.STROKE || <add> fillStrokeMode === TextRenderingMode.FILL_STROKE) { <add> const lineWidthScale = 1 / (current.textMatrixScale || 1); <add> this._setStrokeAttributes(current.tspan, lineWidthScale); <add> } <ide> <del> if (fillStrokeMode === TextRenderingMode.FILL || <del> fillStrokeMode === TextRenderingMode.FILL_STROKE) { <del> if (current.fillColor !== SVG_DEFAULTS.fillColor) { <del> current.tspan.setAttributeNS(null, 'fill', current.fillColor); <del> } <del> if (current.fillAlpha < 1) { <del> current.tspan.setAttributeNS(null, 'fill-opacity', current.fillAlpha); <del> } <del> } else if (current.textRenderingMode === TextRenderingMode.ADD_TO_PATH) { <del> // Workaround for Firefox: We must set fill="transparent" because <del> // fill="none" would generate an empty clipping path. <del> current.tspan.setAttributeNS(null, 'fill', 'transparent'); <del> } else { <del> current.tspan.setAttributeNS(null, 'fill', 'none'); <del> } <add> // Include the text rise in the text matrix since the `pm` function <add> // creates the SVG element's `translate` entry (work on a copy to avoid <add> // altering the original text matrix). <add> let textMatrix = current.textMatrix; <add> if (current.textRise !== 0) { <add> textMatrix = textMatrix.slice(); <add> textMatrix[5] += current.textRise; <add> } <ide> <del> if (fillStrokeMode === TextRenderingMode.STROKE || <del> fillStrokeMode === TextRenderingMode.FILL_STROKE) { <del> const lineWidthScale = 1 / (current.textMatrixScale || 1); <del> this._setStrokeAttributes(current.tspan, lineWidthScale); <del> } <add> current.txtElement.setAttributeNS(null, 'transform', <add> `${pm(textMatrix)} scale(1, -1)`); <add> current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve'); <add> current.txtElement.appendChild(current.tspan); <add> current.txtgrp.appendChild(current.txtElement); <ide> <del> // Include the text rise in the text matrix since the `pm` function <del> // creates the SVG element's `translate` entry (work on a copy to avoid <del> // altering the original text matrix). <del> let textMatrix = current.textMatrix; <del> if (current.textRise !== 0) { <del> textMatrix = textMatrix.slice(); <del> textMatrix[5] += current.textRise; <del> } <add> this._ensureTransformGroup().appendChild(current.txtElement); <add> } <ide> <del> current.txtElement.setAttributeNS(null, 'transform', <del> pm(textMatrix) + ' scale(1, -1)'); <del> current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve'); <del> current.txtElement.appendChild(current.tspan); <del> current.txtgrp.appendChild(current.txtElement); <del> <del> this._ensureTransformGroup().appendChild(current.txtElement); <del> }, <del> <del> setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) { <del> this.setLeading(-y); <del> this.moveText(x, y); <del> }, <del> <del> addFontStyle: function SVGGraphics_addFontStyle(fontObj) { <del> if (!this.cssStyle) { <del> this.cssStyle = this.svgFactory.createElement('svg:style'); <del> this.cssStyle.setAttributeNS(null, 'type', 'text/css'); <del> this.defs.appendChild(this.cssStyle); <del> } <add> setLeadingMoveText(x, y) { <add> this.setLeading(-y); <add> this.moveText(x, y); <add> } <add> <add> addFontStyle(fontObj) { <add> if (!this.cssStyle) { <add> this.cssStyle = this.svgFactory.createElement('svg:style'); <add> this.cssStyle.setAttributeNS(null, 'type', 'text/css'); <add> this.defs.appendChild(this.cssStyle); <add> } <ide> <del> var url = createObjectURL(fontObj.data, fontObj.mimetype, <add> const url = createObjectURL(fontObj.data, fontObj.mimetype, <ide> this.forceDataSchema); <del> this.cssStyle.textContent += <del> '@font-face { font-family: "' + fontObj.loadedName + '";' + <del> ' src: url(' + url + '); }\n'; <del> }, <del> <del> setFont: function SVGGraphics_setFont(details) { <del> var current = this.current; <del> var fontObj = this.commonObjs.get(details[0]); <del> var size = details[1]; <del> this.current.font = fontObj; <del> <del> if (this.embedFonts && fontObj.data && <del> !this.embeddedFonts[fontObj.loadedName]) { <del> this.addFontStyle(fontObj); <del> this.embeddedFonts[fontObj.loadedName] = fontObj; <del> } <add> this.cssStyle.textContent += <add> `@font-face { font-family: "${fontObj.loadedName}";` + <add> ` src: url(${url}); }\n`; <add> } <add> <add> setFont(details) { <add> const current = this.current; <add> const fontObj = this.commonObjs.get(details[0]); <add> let size = details[1]; <add> current.font = fontObj; <add> <add> if (this.embedFonts && fontObj.data && <add> !this.embeddedFonts[fontObj.loadedName]) { <add> this.addFontStyle(fontObj); <add> this.embeddedFonts[fontObj.loadedName] = fontObj; <add> } <ide> <del> current.fontMatrix = (fontObj.fontMatrix ? <del> fontObj.fontMatrix : FONT_IDENTITY_MATRIX); <add> current.fontMatrix = (fontObj.fontMatrix ? <add> fontObj.fontMatrix : FONT_IDENTITY_MATRIX); <ide> <del> var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') : <add> const bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') : <ide> (fontObj.bold ? 'bold' : 'normal'); <del> var italic = fontObj.italic ? 'italic' : 'normal'; <add> const italic = fontObj.italic ? 'italic' : 'normal'; <ide> <del> if (size < 0) { <del> size = -size; <del> current.fontDirection = -1; <del> } else { <del> current.fontDirection = 1; <del> } <del> current.fontSize = size; <del> current.fontFamily = fontObj.loadedName; <del> current.fontWeight = bold; <del> current.fontStyle = italic; <del> <del> current.tspan = this.svgFactory.createElement('svg:tspan'); <del> current.tspan.setAttributeNS(null, 'y', pf(-current.y)); <del> current.xcoords = []; <del> }, <del> <del> endText() { <del> const current = this.current; <del> if ((current.textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG) && <del> current.txtElement && current.txtElement.hasChildNodes()) { <del> // If no glyphs are shown (i.e. no child nodes), no clipping occurs. <del> current.element = current.txtElement; <del> this.clip('nonzero'); <del> this.endPath(); <del> } <del> }, <add> if (size < 0) { <add> size = -size; <add> current.fontDirection = -1; <add> } else { <add> current.fontDirection = 1; <add> } <add> current.fontSize = size; <add> current.fontFamily = fontObj.loadedName; <add> current.fontWeight = bold; <add> current.fontStyle = italic; <add> <add> current.tspan = this.svgFactory.createElement('svg:tspan'); <add> current.tspan.setAttributeNS(null, 'y', pf(-current.y)); <add> current.xcoords = []; <add> } <ide> <del> // Path properties <del> setLineWidth: function SVGGraphics_setLineWidth(width) { <del> if (width > 0) { <del> this.current.lineWidth = width; <del> } <del> }, <del> setLineCap: function SVGGraphics_setLineCap(style) { <del> this.current.lineCap = LINE_CAP_STYLES[style]; <del> }, <del> setLineJoin: function SVGGraphics_setLineJoin(style) { <del> this.current.lineJoin = LINE_JOIN_STYLES[style]; <del> }, <del> setMiterLimit: function SVGGraphics_setMiterLimit(limit) { <del> this.current.miterLimit = limit; <del> }, <del> setStrokeAlpha: function SVGGraphics_setStrokeAlpha(strokeAlpha) { <del> this.current.strokeAlpha = strokeAlpha; <del> }, <del> setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) { <del> var color = Util.makeCssRgb(r, g, b); <del> this.current.strokeColor = color; <del> }, <del> setFillAlpha: function SVGGraphics_setFillAlpha(fillAlpha) { <del> this.current.fillAlpha = fillAlpha; <del> }, <del> setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) { <del> var color = Util.makeCssRgb(r, g, b); <del> this.current.fillColor = color; <del> this.current.tspan = this.svgFactory.createElement('svg:tspan'); <del> this.current.xcoords = []; <del> }, <del> setStrokeColorN: function SVGGraphics_setStrokeColorN(args) { <del> this.current.strokeColor = this._makeColorN_Pattern(args); <del> }, <del> setFillColorN: function SVGGraphics_setFillColorN(args) { <del> this.current.fillColor = this._makeColorN_Pattern(args); <del> }, <del> shadingFill: function SVGGraphics_shadingFill(args) { <del> var viewport = this.viewport; <del> var width = viewport.width; <del> var height = viewport.height; <del> var inv = Util.inverseTransform(this.transformMatrix); <del> var bl = Util.applyTransform([0, 0], inv); <del> var br = Util.applyTransform([0, height], inv); <del> var ul = Util.applyTransform([width, 0], inv); <del> var ur = Util.applyTransform([width, height], inv); <del> var x0 = Math.min(bl[0], br[0], ul[0], ur[0]); <del> var y0 = Math.min(bl[1], br[1], ul[1], ur[1]); <del> var x1 = Math.max(bl[0], br[0], ul[0], ur[0]); <del> var y1 = Math.max(bl[1], br[1], ul[1], ur[1]); <del> <del> var rect = this.svgFactory.createElement('svg:rect'); <del> rect.setAttributeNS(null, 'x', x0); <del> rect.setAttributeNS(null, 'y', y0); <del> rect.setAttributeNS(null, 'width', x1 - x0); <del> rect.setAttributeNS(null, 'height', y1 - y0); <del> rect.setAttributeNS(null, 'fill', this._makeShadingPattern(args)); <del> this._ensureTransformGroup().appendChild(rect); <del> }, <del> _makeColorN_Pattern: function SVGGraphics_makeColorN_Pattern(args) { <del> if (args[0] === 'TilingPattern') { <del> warn('Unimplemented: TilingPattern'); <del> return null; <del> } <del> return this._makeShadingPattern(args); <del> }, <del> _makeShadingPattern: function SVGGraphics_makeShadingPattern(args) { <del> switch (args[0]) { <del> case 'RadialAxial': <del> var shadingId = 'shading' + shadingCount++; <del> var colorStops = args[2]; <del> var gradient; <del> switch (args[1]) { <del> case 'axial': <del> var point0 = args[3]; <del> var point1 = args[4]; <del> gradient = this.svgFactory.createElement('svg:linearGradient'); <del> gradient.setAttributeNS(null, 'id', shadingId); <del> gradient.setAttributeNS(null, 'gradientUnits', 'userSpaceOnUse'); <del> gradient.setAttributeNS(null, 'x1', point0[0]); <del> gradient.setAttributeNS(null, 'y1', point0[1]); <del> gradient.setAttributeNS(null, 'x2', point1[0]); <del> gradient.setAttributeNS(null, 'y2', point1[1]); <del> break; <del> case 'radial': <del> var focalPoint = args[3]; <del> var circlePoint = args[4]; <del> var focalRadius = args[5]; <del> var circleRadius = args[6]; <del> gradient = this.svgFactory.createElement('svg:radialGradient'); <del> gradient.setAttributeNS(null, 'id', shadingId); <del> gradient.setAttributeNS(null, 'gradientUnits', 'userSpaceOnUse'); <del> gradient.setAttributeNS(null, 'cx', circlePoint[0]); <del> gradient.setAttributeNS(null, 'cy', circlePoint[1]); <del> gradient.setAttributeNS(null, 'r', circleRadius); <del> gradient.setAttributeNS(null, 'fx', focalPoint[0]); <del> gradient.setAttributeNS(null, 'fy', focalPoint[1]); <del> gradient.setAttributeNS(null, 'fr', focalRadius); <del> break; <del> default: <del> throw new Error('Unknown RadialAxial type: ' + args[1]); <del> } <del> for (var i = 0, ilen = colorStops.length; i < ilen; ++i) { <del> var cs = colorStops[i]; <del> var stop = this.svgFactory.createElement('svg:stop'); <del> stop.setAttributeNS(null, 'offset', cs[0]); <del> stop.setAttributeNS(null, 'stop-color', cs[1]); <del> gradient.appendChild(stop); <del> } <del> this.defs.appendChild(gradient); <del> return 'url(#' + shadingId + ')'; <del> case 'Mesh': <del> warn('Unimplemented: Mesh'); <del> return null; <del> case 'Dummy': <del> return 'hotpink'; <del> default: <del> throw new Error('Unknown IR type: ' + args[0]); <del> } <del> }, <del> setDash: function SVGGraphics_setDash(dashArray, dashPhase) { <del> this.current.dashArray = dashArray; <del> this.current.dashPhase = dashPhase; <del> }, <del> <del> constructPath: function SVGGraphics_constructPath(ops, args) { <del> var current = this.current; <del> var x = current.x, y = current.y; <del> var d = []; <del> var opLength = ops.length; <del> <del> for (var i = 0, j = 0; i < opLength; i++) { <del> switch (ops[i] | 0) { <del> case OPS.rectangle: <del> x = args[j++]; <del> y = args[j++]; <del> var width = args[j++]; <del> var height = args[j++]; <del> var xw = x + width; <del> var yh = y + height; <del> d.push('M', pf(x), pf(y), 'L', pf(xw), pf(y), 'L', pf(xw), pf(yh), <del> 'L', pf(x), pf(yh), 'Z'); <del> break; <del> case OPS.moveTo: <del> x = args[j++]; <del> y = args[j++]; <del> d.push('M', pf(x), pf(y)); <del> break; <del> case OPS.lineTo: <del> x = args[j++]; <del> y = args[j++]; <del> d.push('L', pf(x), pf(y)); <del> break; <del> case OPS.curveTo: <del> x = args[j + 4]; <del> y = args[j + 5]; <del> d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), <del> pf(args[j + 3]), pf(x), pf(y)); <del> j += 6; <del> break; <del> case OPS.curveTo2: <del> x = args[j + 2]; <del> y = args[j + 3]; <del> d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]), <del> pf(args[j + 2]), pf(args[j + 3])); <del> j += 4; <del> break; <del> case OPS.curveTo3: <del> x = args[j + 2]; <del> y = args[j + 3]; <del> d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y), <del> pf(x), pf(y)); <del> j += 4; <del> break; <del> case OPS.closePath: <del> d.push('Z'); <add> endText() { <add> const current = this.current; <add> if ((current.textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG) && <add> current.txtElement && current.txtElement.hasChildNodes()) { <add> // If no glyphs are shown (i.e. no child nodes), no clipping occurs. <add> current.element = current.txtElement; <add> this.clip('nonzero'); <add> this.endPath(); <add> } <add> } <add> <add> // Path properties <add> setLineWidth(width) { <add> if (width > 0) { <add> this.current.lineWidth = width; <add> } <add> } <add> <add> setLineCap(style) { <add> this.current.lineCap = LINE_CAP_STYLES[style]; <add> } <add> <add> setLineJoin(style) { <add> this.current.lineJoin = LINE_JOIN_STYLES[style]; <add> } <add> <add> setMiterLimit(limit) { <add> this.current.miterLimit = limit; <add> } <add> <add> setStrokeAlpha(strokeAlpha) { <add> this.current.strokeAlpha = strokeAlpha; <add> } <add> <add> setStrokeRGBColor(r, g, b) { <add> this.current.strokeColor = Util.makeCssRgb(r, g, b); <add> } <add> <add> setFillAlpha(fillAlpha) { <add> this.current.fillAlpha = fillAlpha; <add> } <add> <add> setFillRGBColor(r, g, b) { <add> this.current.fillColor = Util.makeCssRgb(r, g, b); <add> this.current.tspan = this.svgFactory.createElement('svg:tspan'); <add> this.current.xcoords = []; <add> } <add> <add> setStrokeColorN(args) { <add> this.current.strokeColor = this._makeColorN_Pattern(args); <add> } <add> <add> setFillColorN(args) { <add> this.current.fillColor = this._makeColorN_Pattern(args); <add> } <add> <add> shadingFill(args) { <add> const width = this.viewport.width; <add> const height = this.viewport.height; <add> const inv = Util.inverseTransform(this.transformMatrix); <add> const bl = Util.applyTransform([0, 0], inv); <add> const br = Util.applyTransform([0, height], inv); <add> const ul = Util.applyTransform([width, 0], inv); <add> const ur = Util.applyTransform([width, height], inv); <add> const x0 = Math.min(bl[0], br[0], ul[0], ur[0]); <add> const y0 = Math.min(bl[1], br[1], ul[1], ur[1]); <add> const x1 = Math.max(bl[0], br[0], ul[0], ur[0]); <add> const y1 = Math.max(bl[1], br[1], ul[1], ur[1]); <add> <add> const rect = this.svgFactory.createElement('svg:rect'); <add> rect.setAttributeNS(null, 'x', x0); <add> rect.setAttributeNS(null, 'y', y0); <add> rect.setAttributeNS(null, 'width', x1 - x0); <add> rect.setAttributeNS(null, 'height', y1 - y0); <add> rect.setAttributeNS(null, 'fill', this._makeShadingPattern(args)); <add> this._ensureTransformGroup().appendChild(rect); <add> } <add> <add> /** <add> * @private <add> */ <add> _makeColorN_Pattern(args) { <add> if (args[0] === 'TilingPattern') { <add> warn('Unimplemented pattern TilingPattern'); <add> return null; <add> } <add> return this._makeShadingPattern(args); <add> } <add> <add> /** <add> * @private <add> */ <add> _makeShadingPattern(args) { <add> switch (args[0]) { <add> case 'RadialAxial': <add> const shadingId = `shading${shadingCount++}`; <add> const colorStops = args[2]; <add> let gradient; <add> <add> switch (args[1]) { <add> case 'axial': <add> const point0 = args[3]; <add> const point1 = args[4]; <add> gradient = this.svgFactory.createElement('svg:linearGradient'); <add> gradient.setAttributeNS(null, 'id', shadingId); <add> gradient.setAttributeNS(null, 'gradientUnits', 'userSpaceOnUse'); <add> gradient.setAttributeNS(null, 'x1', point0[0]); <add> gradient.setAttributeNS(null, 'y1', point0[1]); <add> gradient.setAttributeNS(null, 'x2', point1[0]); <add> gradient.setAttributeNS(null, 'y2', point1[1]); <add> break; <add> case 'radial': <add> const focalPoint = args[3]; <add> const circlePoint = args[4]; <add> const focalRadius = args[5]; <add> const circleRadius = args[6]; <add> gradient = this.svgFactory.createElement('svg:radialGradient'); <add> gradient.setAttributeNS(null, 'id', shadingId); <add> gradient.setAttributeNS(null, 'gradientUnits', 'userSpaceOnUse'); <add> gradient.setAttributeNS(null, 'cx', circlePoint[0]); <add> gradient.setAttributeNS(null, 'cy', circlePoint[1]); <add> gradient.setAttributeNS(null, 'r', circleRadius); <add> gradient.setAttributeNS(null, 'fx', focalPoint[0]); <add> gradient.setAttributeNS(null, 'fy', focalPoint[1]); <add> gradient.setAttributeNS(null, 'fr', focalRadius); <ide> break; <add> default: <add> throw new Error(`Unknown RadialAxial type: ${args[1]}`); <ide> } <del> } <add> for (const colorStop of colorStops) { <add> const stop = this.svgFactory.createElement('svg:stop'); <add> stop.setAttributeNS(null, 'offset', colorStop[0]); <add> stop.setAttributeNS(null, 'stop-color', colorStop[1]); <add> gradient.appendChild(stop); <add> } <add> this.defs.appendChild(gradient); <add> return `url(#${shadingId})`; <add> case 'Mesh': <add> warn('Unimplemented pattern Mesh'); <add> return null; <add> case 'Dummy': <add> return 'hotpink'; <add> default: <add> throw new Error(`Unknown IR type: ${args[0]}`); <add> } <add> } <ide> <del> d = d.join(' '); <add> setDash(dashArray, dashPhase) { <add> this.current.dashArray = dashArray; <add> this.current.dashPhase = dashPhase; <add> } <ide> <del> if (current.path && opLength > 0 && ops[0] !== OPS.rectangle && <del> ops[0] !== OPS.moveTo) { <del> // If a path does not start with an OPS.rectangle or OPS.moveTo, it has <del> // probably been divided into two OPS.constructPath operators by <del> // OperatorList. Append the commands to the previous path element. <del> d = current.path.getAttributeNS(null, 'd') + d; <del> } else { <del> current.path = this.svgFactory.createElement('svg:path'); <del> this._ensureTransformGroup().appendChild(current.path); <add> constructPath(ops, args) { <add> const current = this.current; <add> let x = current.x, y = current.y; <add> let d = []; <add> let j = 0; <add> <add> for (const op of ops) { <add> switch (op | 0) { <add> case OPS.rectangle: <add> x = args[j++]; <add> y = args[j++]; <add> const width = args[j++]; <add> const height = args[j++]; <add> const xw = x + width; <add> const yh = y + height; <add> d.push('M', pf(x), pf(y), 'L', pf(xw), pf(y), 'L', pf(xw), pf(yh), <add> 'L', pf(x), pf(yh), 'Z'); <add> break; <add> case OPS.moveTo: <add> x = args[j++]; <add> y = args[j++]; <add> d.push('M', pf(x), pf(y)); <add> break; <add> case OPS.lineTo: <add> x = args[j++]; <add> y = args[j++]; <add> d.push('L', pf(x), pf(y)); <add> break; <add> case OPS.curveTo: <add> x = args[j + 4]; <add> y = args[j + 5]; <add> d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), <add> pf(args[j + 3]), pf(x), pf(y)); <add> j += 6; <add> break; <add> case OPS.curveTo2: <add> x = args[j + 2]; <add> y = args[j + 3]; <add> d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]), <add> pf(args[j + 2]), pf(args[j + 3])); <add> j += 4; <add> break; <add> case OPS.curveTo3: <add> x = args[j + 2]; <add> y = args[j + 3]; <add> d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y), <add> pf(x), pf(y)); <add> j += 4; <add> break; <add> case OPS.closePath: <add> d.push('Z'); <add> break; <ide> } <add> } <add> <add> d = d.join(' '); <add> <add> if (current.path && ops.length > 0 && ops[0] !== OPS.rectangle && <add> ops[0] !== OPS.moveTo) { <add> // If a path does not start with an OPS.rectangle or OPS.moveTo, it has <add> // probably been divided into two OPS.constructPath operators by <add> // OperatorList. Append the commands to the previous path element. <add> d = current.path.getAttributeNS(null, 'd') + d; <add> } else { <add> current.path = this.svgFactory.createElement('svg:path'); <add> this._ensureTransformGroup().appendChild(current.path); <add> } <add> <add> current.path.setAttributeNS(null, 'd', d); <add> current.path.setAttributeNS(null, 'fill', 'none'); <add> <add> // Saving a reference in current.element so that it can be addressed <add> // in 'fill' and 'stroke' <add> current.element = current.path; <add> current.setCurrentPoint(x, y); <add> } <add> <add> endPath() { <add> const current = this.current; <add> <add> // Painting operators end a path. <add> current.path = null; <ide> <add> if (!this.pendingClip) { <add> return; <add> } <add> <add> // Add the current path to a clipping path. <add> const clipId = `clippath${clipCount++}`; <add> const clipPath = this.svgFactory.createElement('svg:clipPath'); <add> clipPath.setAttributeNS(null, 'id', clipId); <add> clipPath.setAttributeNS(null, 'transform', pm(this.transformMatrix)); <add> <add> // A deep clone is needed when text is used as a clipping path. <add> const clipElement = current.element.cloneNode(true); <add> if (this.pendingClip === 'evenodd') { <add> clipElement.setAttributeNS(null, 'clip-rule', 'evenodd'); <add> } else { <add> clipElement.setAttributeNS(null, 'clip-rule', 'nonzero'); <add> } <add> this.pendingClip = null; <add> clipPath.appendChild(clipElement); <add> this.defs.appendChild(clipPath); <add> <add> if (current.activeClipUrl) { <add> // The previous clipping group content can go out of order -- resetting <add> // cached clipGroups. <add> current.clipGroup = null; <add> this.extraStack.forEach(function(prev) { <add> prev.clipGroup = null; <add> }); <add> // Intersect with the previous clipping path. <add> clipPath.setAttributeNS(null, 'clip-path', current.activeClipUrl); <add> } <add> current.activeClipUrl = `url(#${clipId})`; <add> <add> this.tgrp = null; <add> } <add> <add> clip(type) { <add> this.pendingClip = type; <add> } <add> <add> closePath() { <add> const current = this.current; <add> if (current.path) { <add> const d = `${current.path.getAttributeNS(null, 'd')}Z`; <ide> current.path.setAttributeNS(null, 'd', d); <del> current.path.setAttributeNS(null, 'fill', 'none'); <add> } <add> } <ide> <del> // Saving a reference in current.element so that it can be addressed <del> // in 'fill' and 'stroke' <del> current.element = current.path; <del> current.setCurrentPoint(x, y); <del> }, <add> setLeading(leading) { <add> this.current.leading = -leading; <add> } <ide> <del> endPath: function SVGGraphics_endPath() { <del> // Painting operators end a path. <del> this.current.path = null; <add> setTextRise(textRise) { <add> this.current.textRise = textRise; <add> } <ide> <del> if (!this.pendingClip) { <del> return; <del> } <del> var current = this.current; <del> // Add current path to clipping path <del> var clipId = 'clippath' + clipCount; <del> clipCount++; <del> var clipPath = this.svgFactory.createElement('svg:clipPath'); <del> clipPath.setAttributeNS(null, 'id', clipId); <del> clipPath.setAttributeNS(null, 'transform', pm(this.transformMatrix)); <del> // A deep clone is needed when text is used as a clipping path. <del> const clipElement = current.element.cloneNode(true); <del> if (this.pendingClip === 'evenodd') { <del> clipElement.setAttributeNS(null, 'clip-rule', 'evenodd'); <del> } else { <del> clipElement.setAttributeNS(null, 'clip-rule', 'nonzero'); <del> } <del> this.pendingClip = null; <del> clipPath.appendChild(clipElement); <del> this.defs.appendChild(clipPath); <del> <del> if (current.activeClipUrl) { <del> // The previous clipping group content can go out of order -- resetting <del> // cached clipGroups. <del> current.clipGroup = null; <del> this.extraStack.forEach(function (prev) { <del> prev.clipGroup = null; <del> }); <del> // Intersect with the previous clipping path. <del> clipPath.setAttributeNS(null, 'clip-path', current.activeClipUrl); <add> setTextRenderingMode(textRenderingMode) { <add> this.current.textRenderingMode = textRenderingMode; <add> } <add> <add> setHScale(scale) { <add> this.current.textHScale = scale / 100; <add> } <add> <add> setGState(states) { <add> for (const [key, value] of states) { <add> switch (key) { <add> case 'LW': <add> this.setLineWidth(value); <add> break; <add> case 'LC': <add> this.setLineCap(value); <add> break; <add> case 'LJ': <add> this.setLineJoin(value); <add> break; <add> case 'ML': <add> this.setMiterLimit(value); <add> break; <add> case 'D': <add> this.setDash(value[0], value[1]); <add> break; <add> case 'Font': <add> this.setFont(value); <add> break; <add> case 'CA': <add> this.setStrokeAlpha(value); <add> break; <add> case 'ca': <add> this.setFillAlpha(value); <add> break; <add> default: <add> warn(`Unimplemented graphic state operator ${key}`); <add> break; <ide> } <del> current.activeClipUrl = 'url(#' + clipId + ')'; <add> } <add> } <ide> <del> this.tgrp = null; <del> }, <add> fill() { <add> const current = this.current; <add> if (current.element) { <add> current.element.setAttributeNS(null, 'fill', current.fillColor); <add> current.element.setAttributeNS(null, 'fill-opacity', current.fillAlpha); <add> this.endPath(); <add> } <add> } <ide> <del> clip: function SVGGraphics_clip(type) { <del> this.pendingClip = type; <del> }, <add> stroke() { <add> const current = this.current; <add> if (current.element) { <add> this._setStrokeAttributes(current.element); <add> current.element.setAttributeNS(null, 'fill', 'none'); <add> this.endPath(); <add> } <add> } <ide> <del> closePath: function SVGGraphics_closePath() { <del> var current = this.current; <del> if (current.path) { <del> var d = current.path.getAttributeNS(null, 'd'); <del> d += 'Z'; <del> current.path.setAttributeNS(null, 'd', d); <del> } <del> }, <add> /** <add> * @private <add> */ <add> _setStrokeAttributes(element, lineWidthScale = 1) { <add> const current = this.current; <add> let dashArray = current.dashArray; <add> if (lineWidthScale !== 1 && dashArray.length > 0) { <add> dashArray = dashArray.map(function(value) { <add> return lineWidthScale * value; <add> }); <add> } <add> element.setAttributeNS(null, 'stroke', current.strokeColor); <add> element.setAttributeNS(null, 'stroke-opacity', current.strokeAlpha); <add> element.setAttributeNS(null, 'stroke-miterlimit', pf(current.miterLimit)); <add> element.setAttributeNS(null, 'stroke-linecap', current.lineCap); <add> element.setAttributeNS(null, 'stroke-linejoin', current.lineJoin); <add> element.setAttributeNS(null, 'stroke-width', <add> pf(lineWidthScale * current.lineWidth) + 'px'); <add> element.setAttributeNS(null, 'stroke-dasharray', <add> dashArray.map(pf).join(' ')); <add> element.setAttributeNS(null, 'stroke-dashoffset', <add> pf(lineWidthScale * current.dashPhase) + 'px'); <add> } <ide> <del> setLeading: function SVGGraphics_setLeading(leading) { <del> this.current.leading = -leading; <del> }, <add> eoFill() { <add> if (this.current.element) { <add> this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd'); <add> } <add> this.fill(); <add> } <ide> <del> setTextRise: function SVGGraphics_setTextRise(textRise) { <del> this.current.textRise = textRise; <del> }, <add> fillStroke() { <add> // Order is important since stroke wants fill to be none. <add> // First stroke, then if fill needed, it will be overwritten. <add> this.stroke(); <add> this.fill(); <add> } <ide> <del> setTextRenderingMode(textRenderingMode) { <del> this.current.textRenderingMode = textRenderingMode; <del> }, <add> eoFillStroke() { <add> if (this.current.element) { <add> this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd'); <add> } <add> this.fillStroke(); <add> } <ide> <del> setHScale: function SVGGraphics_setHScale(scale) { <del> this.current.textHScale = scale / 100; <del> }, <add> closeStroke() { <add> this.closePath(); <add> this.stroke(); <add> } <ide> <del> setGState: function SVGGraphics_setGState(states) { <del> for (var i = 0, ii = states.length; i < ii; i++) { <del> var state = states[i]; <del> var key = state[0]; <del> var value = state[1]; <add> closeFillStroke() { <add> this.closePath(); <add> this.fillStroke(); <add> } <ide> <del> switch (key) { <del> case 'LW': <del> this.setLineWidth(value); <del> break; <del> case 'LC': <del> this.setLineCap(value); <del> break; <del> case 'LJ': <del> this.setLineJoin(value); <del> break; <del> case 'ML': <del> this.setMiterLimit(value); <del> break; <del> case 'D': <del> this.setDash(value[0], value[1]); <del> break; <del> case 'Font': <del> this.setFont(value); <del> break; <del> case 'CA': <del> this.setStrokeAlpha(value); <del> break; <del> case 'ca': <del> this.setFillAlpha(value); <del> break; <del> default: <del> warn('Unimplemented graphic state ' + key); <del> break; <del> } <del> } <del> }, <del> <del> fill: function SVGGraphics_fill() { <del> var current = this.current; <del> if (current.element) { <del> current.element.setAttributeNS(null, 'fill', current.fillColor); <del> current.element.setAttributeNS(null, 'fill-opacity', current.fillAlpha); <del> this.endPath(); <del> } <del> }, <add> closeEOFillStroke() { <add> this.closePath(); <add> this.eoFillStroke(); <add> } <ide> <del> stroke: function SVGGraphics_stroke() { <del> var current = this.current; <add> paintSolidColorImageMask() { <add> const rect = this.svgFactory.createElement('svg:rect'); <add> rect.setAttributeNS(null, 'x', '0'); <add> rect.setAttributeNS(null, 'y', '0'); <add> rect.setAttributeNS(null, 'width', '1px'); <add> rect.setAttributeNS(null, 'height', '1px'); <add> rect.setAttributeNS(null, 'fill', this.current.fillColor); <ide> <del> if (current.element) { <del> this._setStrokeAttributes(current.element); <add> this._ensureTransformGroup().appendChild(rect); <add> } <ide> <del> current.element.setAttributeNS(null, 'fill', 'none'); <add> paintJpegXObject(objId, w, h) { <add> const imgObj = this.objs.get(objId); <add> const imgEl = this.svgFactory.createElement('svg:image'); <add> imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src); <add> imgEl.setAttributeNS(null, 'width', pf(w)); <add> imgEl.setAttributeNS(null, 'height', pf(h)); <add> imgEl.setAttributeNS(null, 'x', '0'); <add> imgEl.setAttributeNS(null, 'y', pf(-h)); <add> imgEl.setAttributeNS(null, 'transform', <add> `scale(${pf(1 / w)} ${pf(-1 / h)})`); <add> <add> this._ensureTransformGroup().appendChild(imgEl); <add> } <ide> <del> this.endPath(); <del> } <del> }, <del> <del> /** <del> * @private <del> */ <del> _setStrokeAttributes(element, lineWidthScale = 1) { <del> const current = this.current; <del> let dashArray = current.dashArray; <del> if (lineWidthScale !== 1 && dashArray.length > 0) { <del> dashArray = dashArray.map(function(value) { <del> return lineWidthScale * value; <del> }); <del> } <del> element.setAttributeNS(null, 'stroke', current.strokeColor); <del> element.setAttributeNS(null, 'stroke-opacity', current.strokeAlpha); <del> element.setAttributeNS(null, 'stroke-miterlimit', <del> pf(current.miterLimit)); <del> element.setAttributeNS(null, 'stroke-linecap', current.lineCap); <del> element.setAttributeNS(null, 'stroke-linejoin', current.lineJoin); <del> element.setAttributeNS(null, 'stroke-width', <del> pf(lineWidthScale * current.lineWidth) + 'px'); <del> element.setAttributeNS(null, 'stroke-dasharray', <del> dashArray.map(pf).join(' ')); <del> element.setAttributeNS(null, 'stroke-dashoffset', <del> pf(lineWidthScale * current.dashPhase) + 'px'); <del> }, <del> <del> eoFill: function SVGGraphics_eoFill() { <del> if (this.current.element) { <del> this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd'); <del> } <del> this.fill(); <del> }, <del> <del> fillStroke: function SVGGraphics_fillStroke() { <del> // Order is important since stroke wants fill to be none. <del> // First stroke, then if fill needed, it will be overwritten. <del> this.stroke(); <del> this.fill(); <del> }, <del> <del> eoFillStroke: function SVGGraphics_eoFillStroke() { <del> if (this.current.element) { <del> this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd'); <del> } <del> this.fillStroke(); <del> }, <del> <del> closeStroke: function SVGGraphics_closeStroke() { <del> this.closePath(); <del> this.stroke(); <del> }, <del> <del> closeFillStroke: function SVGGraphics_closeFillStroke() { <del> this.closePath(); <del> this.fillStroke(); <del> }, <del> <del> closeEOFillStroke() { <del> this.closePath(); <del> this.eoFillStroke(); <del> }, <del> <del> paintSolidColorImageMask: <del> function SVGGraphics_paintSolidColorImageMask() { <del> var current = this.current; <del> var rect = this.svgFactory.createElement('svg:rect'); <del> rect.setAttributeNS(null, 'x', '0'); <del> rect.setAttributeNS(null, 'y', '0'); <del> rect.setAttributeNS(null, 'width', '1px'); <del> rect.setAttributeNS(null, 'height', '1px'); <del> rect.setAttributeNS(null, 'fill', current.fillColor); <del> <del> this._ensureTransformGroup().appendChild(rect); <del> }, <del> <del> paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) { <del> var imgObj = this.objs.get(objId); <del> var imgEl = this.svgFactory.createElement('svg:image'); <del> imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src); <del> imgEl.setAttributeNS(null, 'width', pf(w)); <del> imgEl.setAttributeNS(null, 'height', pf(h)); <del> imgEl.setAttributeNS(null, 'x', '0'); <del> imgEl.setAttributeNS(null, 'y', pf(-h)); <del> imgEl.setAttributeNS(null, 'transform', <del> 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')'); <add> paintImageXObject(objId) { <add> const imgData = this.objs.get(objId); <add> if (!imgData) { <add> warn(`Dependent image with object ID ${objId} is not ready yet`); <add> return; <add> } <add> this.paintInlineImageXObject(imgData); <add> } <ide> <add> paintInlineImageXObject(imgData, mask) { <add> const width = imgData.width; <add> const height = imgData.height; <add> <add> const imgSrc = convertImgDataToPng(imgData, this.forceDataSchema, !!mask); <add> const cliprect = this.svgFactory.createElement('svg:rect'); <add> cliprect.setAttributeNS(null, 'x', '0'); <add> cliprect.setAttributeNS(null, 'y', '0'); <add> cliprect.setAttributeNS(null, 'width', pf(width)); <add> cliprect.setAttributeNS(null, 'height', pf(height)); <add> this.current.element = cliprect; <add> this.clip('nonzero'); <add> <add> const imgEl = this.svgFactory.createElement('svg:image'); <add> imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc); <add> imgEl.setAttributeNS(null, 'x', '0'); <add> imgEl.setAttributeNS(null, 'y', pf(-height)); <add> imgEl.setAttributeNS(null, 'width', pf(width) + 'px'); <add> imgEl.setAttributeNS(null, 'height', pf(height) + 'px'); <add> imgEl.setAttributeNS(null, 'transform', <add> `scale(${pf(1 / width)} ${pf(-1 / height)})`); <add> if (mask) { <add> mask.appendChild(imgEl); <add> } else { <ide> this._ensureTransformGroup().appendChild(imgEl); <del> }, <add> } <add> } <ide> <del> paintImageXObject: function SVGGraphics_paintImageXObject(objId) { <del> var imgData = this.objs.get(objId); <del> if (!imgData) { <del> warn('Dependent image isn\'t ready yet'); <del> return; <del> } <del> this.paintInlineImageXObject(imgData); <del> }, <del> <del> paintInlineImageXObject: <del> function SVGGraphics_paintInlineImageXObject(imgData, mask) { <del> var width = imgData.width; <del> var height = imgData.height; <del> <del> var imgSrc = convertImgDataToPng(imgData, this.forceDataSchema, !!mask); <del> var cliprect = this.svgFactory.createElement('svg:rect'); <del> cliprect.setAttributeNS(null, 'x', '0'); <del> cliprect.setAttributeNS(null, 'y', '0'); <add> paintImageMaskXObject(imgData) { <add> const current = this.current; <add> const width = imgData.width; <add> const height = imgData.height; <add> const fillColor = current.fillColor; <add> <add> current.maskId = `mask${maskCount++}`; <add> const mask = this.svgFactory.createElement('svg:mask'); <add> mask.setAttributeNS(null, 'id', current.maskId); <add> <add> const rect = this.svgFactory.createElement('svg:rect'); <add> rect.setAttributeNS(null, 'x', '0'); <add> rect.setAttributeNS(null, 'y', '0'); <add> rect.setAttributeNS(null, 'width', pf(width)); <add> rect.setAttributeNS(null, 'height', pf(height)); <add> rect.setAttributeNS(null, 'fill', fillColor); <add> rect.setAttributeNS(null, 'mask', `url(#${current.maskId})`); <add> <add> this.defs.appendChild(mask); <add> this._ensureTransformGroup().appendChild(rect); <add> <add> this.paintInlineImageXObject(imgData, mask); <add> } <add> <add> paintFormXObjectBegin(matrix, bbox) { <add> if (Array.isArray(matrix) && matrix.length === 6) { <add> this.transform(matrix[0], matrix[1], matrix[2], <add> matrix[3], matrix[4], matrix[5]); <add> } <add> <add> if (bbox) { <add> const width = bbox[2] - bbox[0]; <add> const height = bbox[3] - bbox[1]; <add> <add> const cliprect = this.svgFactory.createElement('svg:rect'); <add> cliprect.setAttributeNS(null, 'x', bbox[0]); <add> cliprect.setAttributeNS(null, 'y', bbox[1]); <ide> cliprect.setAttributeNS(null, 'width', pf(width)); <ide> cliprect.setAttributeNS(null, 'height', pf(height)); <ide> this.current.element = cliprect; <ide> this.clip('nonzero'); <del> var imgEl = this.svgFactory.createElement('svg:image'); <del> imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc); <del> imgEl.setAttributeNS(null, 'x', '0'); <del> imgEl.setAttributeNS(null, 'y', pf(-height)); <del> imgEl.setAttributeNS(null, 'width', pf(width) + 'px'); <del> imgEl.setAttributeNS(null, 'height', pf(height) + 'px'); <del> imgEl.setAttributeNS(null, 'transform', <del> 'scale(' + pf(1 / width) + ' ' + <del> pf(-1 / height) + ')'); <del> if (mask) { <del> mask.appendChild(imgEl); <del> } else { <del> this._ensureTransformGroup().appendChild(imgEl); <del> } <del> }, <del> <del> paintImageMaskXObject: <del> function SVGGraphics_paintImageMaskXObject(imgData) { <del> var current = this.current; <del> var width = imgData.width; <del> var height = imgData.height; <del> var fillColor = current.fillColor; <del> <del> current.maskId = 'mask' + maskCount++; <del> var mask = this.svgFactory.createElement('svg:mask'); <del> mask.setAttributeNS(null, 'id', current.maskId); <del> <del> var rect = this.svgFactory.createElement('svg:rect'); <del> rect.setAttributeNS(null, 'x', '0'); <del> rect.setAttributeNS(null, 'y', '0'); <del> rect.setAttributeNS(null, 'width', pf(width)); <del> rect.setAttributeNS(null, 'height', pf(height)); <del> rect.setAttributeNS(null, 'fill', fillColor); <del> rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId + ')'); <del> this.defs.appendChild(mask); <del> <del> this._ensureTransformGroup().appendChild(rect); <del> <del> this.paintInlineImageXObject(imgData, mask); <del> }, <del> <del> paintFormXObjectBegin: <del> function SVGGraphics_paintFormXObjectBegin(matrix, bbox) { <del> if (Array.isArray(matrix) && matrix.length === 6) { <del> this.transform(matrix[0], matrix[1], matrix[2], <del> matrix[3], matrix[4], matrix[5]); <del> } <add> this.endPath(); <add> } <add> } <ide> <del> if (bbox) { <del> var width = bbox[2] - bbox[0]; <del> var height = bbox[3] - bbox[1]; <del> <del> var cliprect = this.svgFactory.createElement('svg:rect'); <del> cliprect.setAttributeNS(null, 'x', bbox[0]); <del> cliprect.setAttributeNS(null, 'y', bbox[1]); <del> cliprect.setAttributeNS(null, 'width', pf(width)); <del> cliprect.setAttributeNS(null, 'height', pf(height)); <del> this.current.element = cliprect; <del> this.clip('nonzero'); <del> this.endPath(); <del> } <del> }, <del> <del> paintFormXObjectEnd: <del> function SVGGraphics_paintFormXObjectEnd() {}, <del> <del> /** <del> * @private <del> */ <del> _initialize(viewport) { <del> let svg = this.svgFactory.create(viewport.width, viewport.height); <del> <del> // Create the definitions element. <del> let definitions = this.svgFactory.createElement('svg:defs'); <del> svg.appendChild(definitions); <del> this.defs = definitions; <del> <del> // Create the root group element, which acts a container for all other <del> // groups and applies the viewport transform. <del> let rootGroup = this.svgFactory.createElement('svg:g'); <del> rootGroup.setAttributeNS(null, 'transform', pm(viewport.transform)); <del> svg.appendChild(rootGroup); <del> <del> // For the construction of the SVG image we are only interested in the <del> // root group, so we expose it as the entry point of the SVG image for <del> // the other code in this class. <del> this.svg = rootGroup; <del> <del> return svg; <del> }, <del> <del> /** <del> * @private <del> */ <del> _ensureClipGroup: function SVGGraphics_ensureClipGroup() { <del> if (!this.current.clipGroup) { <del> var clipGroup = this.svgFactory.createElement('svg:g'); <del> clipGroup.setAttributeNS(null, 'clip-path', <del> this.current.activeClipUrl); <del> this.svg.appendChild(clipGroup); <del> this.current.clipGroup = clipGroup; <del> } <del> return this.current.clipGroup; <del> }, <del> <del> /** <del> * @private <del> */ <del> _ensureTransformGroup: function SVGGraphics_ensureTransformGroup() { <del> if (!this.tgrp) { <del> this.tgrp = this.svgFactory.createElement('svg:g'); <del> this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); <del> if (this.current.activeClipUrl) { <del> this._ensureClipGroup().appendChild(this.tgrp); <del> } else { <del> this.svg.appendChild(this.tgrp); <del> } <add> paintFormXObjectEnd() {} <add> <add> /** <add> * @private <add> */ <add> _initialize(viewport) { <add> const svg = this.svgFactory.create(viewport.width, viewport.height); <add> <add> // Create the definitions element. <add> const definitions = this.svgFactory.createElement('svg:defs'); <add> svg.appendChild(definitions); <add> this.defs = definitions; <add> <add> // Create the root group element, which acts a container for all other <add> // groups and applies the viewport transform. <add> const rootGroup = this.svgFactory.createElement('svg:g'); <add> rootGroup.setAttributeNS(null, 'transform', pm(viewport.transform)); <add> svg.appendChild(rootGroup); <add> <add> // For the construction of the SVG image we are only interested in the <add> // root group, so we expose it as the entry point of the SVG image for <add> // the other code in this class. <add> this.svg = rootGroup; <add> <add> return svg; <add> } <add> <add> /** <add> * @private <add> */ <add> _ensureClipGroup() { <add> if (!this.current.clipGroup) { <add> const clipGroup = this.svgFactory.createElement('svg:g'); <add> clipGroup.setAttributeNS(null, 'clip-path', this.current.activeClipUrl); <add> this.svg.appendChild(clipGroup); <add> this.current.clipGroup = clipGroup; <add> } <add> return this.current.clipGroup; <add> } <add> <add> /** <add> * @private <add> */ <add> _ensureTransformGroup() { <add> if (!this.tgrp) { <add> this.tgrp = this.svgFactory.createElement('svg:g'); <add> this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); <add> if (this.current.activeClipUrl) { <add> this._ensureClipGroup().appendChild(this.tgrp); <add> } else { <add> this.svg.appendChild(this.tgrp); <ide> } <del> return this.tgrp; <del> }, <del> }; <del> return SVGGraphics; <del>})(); <add> } <add> return this.tgrp; <add> } <add>}; <ide> <ide> } <ide>
1
Javascript
Javascript
improve reliability in http2-session-timeout
d2ffcac55db928e3b525c558259f69142521d435
<ide><path>test/sequential/test-http2-session-timeout.js <ide> const common = require('../common'); <ide> if (!common.hasCrypto) <ide> common.skip('missing crypto'); <del>const h2 = require('http2'); <add>const http2 = require('http2'); <ide> <ide> const serverTimeout = common.platformTimeout(200); <del>const callTimeout = common.platformTimeout(20); <ide> const mustNotCall = common.mustNotCall(); <ide> <del>const server = h2.createServer(); <add>const server = http2.createServer(); <ide> server.timeout = serverTimeout; <ide> <ide> server.on('request', (req, res) => res.end()); <ide> server.listen(0, common.mustCall(() => { <ide> const port = server.address().port; <ide> <ide> const url = `http://localhost:${port}`; <del> const client = h2.connect(url); <add> const client = http2.connect(url); <ide> const startTime = process.hrtime(); <ide> makeReq(); <ide> <ide> server.listen(0, common.mustCall(() => { <ide> const diff = process.hrtime(startTime); <ide> const milliseconds = (diff[0] * 1e3 + diff[1] / 1e6); <ide> if (milliseconds < serverTimeout * 2) { <del> setTimeout(makeReq, callTimeout); <add> setImmediate(makeReq); <ide> } else { <ide> server.removeListener('timeout', mustNotCall); <ide> server.close();
1
Java
Java
fix a small typo in parallelflowable
ab0c59094d11142cea4fef70169f053e062d85ec
<ide><path>src/main/java/io/reactivex/parallel/ParallelFlowable.java <ide> * Abstract base class for Parallel publishers that take an array of Subscribers. <ide> * <p> <ide> * Use {@code from()} to start processing a regular Publisher in 'rails'. <del> * Use {@code runOn()} to introduce where each 'rail' shoud run on thread-vise. <add> * Use {@code runOn()} to introduce where each 'rail' should run on thread-vise. <ide> * Use {@code sequential()} to merge the sources back into a single Flowable. <ide> * <ide> * @param <T> the value type
1
Ruby
Ruby
use placeholder for `type_condition` predicate
6a1a1e66ea7a917942bd8369fa8dbfedce391dab
<ide><path>activerecord/lib/active_record/inheritance.rb <ide> def type_condition(table = arel_table) <ide> sti_column = arel_attribute(inheritance_column, table) <ide> sti_names = ([self] + descendants).map(&:sti_name) <ide> <del> sti_column.in(sti_names) <add> predicate_builder.build(sti_column, sti_names) <ide> end <ide> <ide> # Detect the subclass from the inheritance column of attrs. If the inheritance column value
1
Mixed
Go
add networkdb docs
05c05ea5e9d92d44f4581a183691e0aa3d34568f
<ide><path>libnetwork/docs/networkdb.md <add>NetworkDB <add>========= <add> <add>There are two databases used in libnetwork: <add> <add>- A persistent database that stores the network configuration requested by the user. This is typically the SwarmKit managers' raft store. <add>- A non-persistent peer-to-peer gossip-based database that keeps track of the current runtime state. This is NetworkDB. <add> <add>NetworkDB is based on the [SWIM][] protocol, which is implemented by the [memberlist][] library. <add>`memberlist` manages cluster membership (nodes can join and leave), as well as message encryption. <add>Members of the cluster send each other ping messages from time to time, allowing the cluster to detect when a node has become unavailable. <add> <add>The information held by each node in NetworkDB is: <add> <add>- The set of nodes currently in the cluster (plus nodes that have recently left or failed). <add>- For each peer node, the set of networks to which that node is connected. <add>- For each of the node's currently-in-use networks, a set of named tables of key/value pairs. <add> Note that nodes only keep track of tables for networks to which they belong. <add> <add>Updates spread through the cluster from node to node, and nodes may have inconsistent views at any given time. <add>They will eventually converge (quickly, if the network is operating well). <add>Nodes look up information using their local networkdb instance. Queries are not sent to remote nodes. <add> <add>NetworkDB does not impose any structure on the tables; they are just maps from `string` keys to `[]byte` values. <add>Other components in libnetwork use the tables for their own purposes. <add>For example, there are tables for service discovery and load balancing, <add>and the [overlay](overlay.md) driver uses NetworkDB to store routing information. <add>Updates to a network's tables are only shared between nodes that are on that network. <add> <add>All libnetwork nodes join the gossip cluster. <add>To do this, they need the IP address and port of at least one other member of the cluster. <add>In the case of a SwarmKit cluster, for example, each Docker engine will use the IP addresses of the swarm managers as the initial join addresses. <add>The `Join` method can be used to update these bootstrap IPs if they change while the system is running. <add> <add>When joining the cluster, the new node will initially synchronise its cluster-wide state (known nodes and networks, but not tables) with at least one other node. <add>The state will be mostly kept up-to-date by small UDP gossip messages, but each node will also periodically perform a push-pull TCP sync with another random node. <add>In a push-pull sync, the initiator sends all of its cluster-wide state to the target, and the target then sends all of its own state back in response. <add> <add>Once part of the gossip cluster, a node will also send a `NodeEventTypeJoin` message, which is a custom message defined by NetworkDB. <add>This is not actually needed now, but keeping it is useful for backwards compatibility with nodes running previous versions. <add> <add>While a node is active in the cluster, it can join and leave networks. <add>When a node wants to join a network, it will send a `NetworkEventTypeJoin` message via gossip to the whole cluster. <add>It will also perform a bulk-sync of the network-specific state (the tables) with every other node on the network being joined. <add>This will allow it to get all the network-specific information quickly. <add>The tables will mostly be kept up-to-date by UDP gossip messages between the nodes on that network, but <add>each node in the network will also periodically do a full TCP bulk sync of the tables with another random node on the same network. <add> <add>Note that there are two similar, but separate, gossip-and-periodic-sync mechanisms here: <add> <add>1. memberlist-provided gossip and push-pull sync of cluster-wide state, involving all nodes in the cluster. <add>2. networkdb-provided gossip and bulk sync of network tables, for each network, involving just those nodes in that network. <add> <add>When a node wishes to leave a network, it will send a `NetworkEventTypeLeave` via gossip. It will then delete the network's table data. <add>When a node hears that another node is leaving a network, it deletes all table entries belonging to the leaving node. <add>Deleting an entry in this case means marking it for deletion for a while, so that we can detect and ignore any older events that may arrive about it. <add> <add>When a node wishes to leave the cluster, it will send a `NodeEventTypeLeave` message via gossip. <add>Nodes receiving this will mark the node as "left". <add>The leaving node will then send a memberlist leave message too. <add>If we receive the memberlist leave message without first getting the `NodeEventTypeLeave` one, we mark the node as failed (for a while). <add>Every node periodically attempts to reconnect to failed nodes, and will do a push-pull sync of cluster-wide state on success. <add>On success we also send the node a `NodeEventTypeJoin` and then do a bulk sync of network-specific state for all networks that we have in common. <add> <add>[SWIM]: http://ieeexplore.ieee.org/document/1028914/ <add>[memberlist]: https://github.com/hashicorp/memberlist <ide><path>libnetwork/networkdb/cluster.go <ide> func (nDB *NetworkDB) reconnectNode() { <ide> nDB.bulkSync([]string{node.Name}, true) <ide> } <ide> <del>// For timing the entry deletion in the repaer APIs that doesn't use monotonic clock <add>// For timing the entry deletion in the reaper APIs that doesn't use monotonic clock <ide> // source (time.Now, Sub etc.) should be avoided. Hence we use reapTime in every <ide> // entry which is set initially to reapInterval and decremented by reapPeriod every time <ide> // the reaper runs. NOTE nDB.reapTableEntries updates the reapTime with a readlock. This
2
Javascript
Javascript
exclude the ripgrep module from the v8 snapshots
d35aef3bf0753fadb016b174be27083e6515d4a3
<ide><path>script/lib/generate-startup-snapshot.js <ide> module.exports = function (packagedAppPath) { <ide> requiredModuleRelativePath === path.join('..', 'node_modules', 'winreg', 'lib', 'registry.js') || <ide> requiredModuleRelativePath === path.join('..', 'node_modules', '@atom', 'fuzzy-native', 'lib', 'main.js') || <ide> requiredModuleRelativePath === path.join('..', 'node_modules', '@atom', 'notify', 'lib', 'bin-path.js') || <add> requiredModuleRelativePath === path.join('..', 'node_modules', 'vscode-ripgrep', 'lib', 'index.js') || <ide> // The startup-time script is used by both the renderer and the main process and having it in the <ide> // snapshot causes issues. <ide> requiredModuleRelativePath === path.join('..', 'src', 'startup-time.js')
1
PHP
PHP
add missing return false
5e77fe839e1894f0137ccc9a54e8f2e4a3656153
<ide><path>lib/Cake/Error/BaseErrorHandler.php <ide> public function handleError($code, $description, $file = null, $line = null, $co <ide> } <ide> $this->_displayError($data, $debug); <ide> $this->_logError($log, $data); <add> return false; <ide> } <ide> <ide> /**
1
Python
Python
fix corner case with joining processes/queues
415b363eb8da243d42ee350f2aba981f338f46b6
<ide><path>airflow/jobs.py <ide> def _execute(self): <ide> self.logger.info("Starting {} scheduler jobs".format(len(jobs))) <ide> for j in jobs: <ide> j.start() <add> <add> while any(j.is_alive() for j in jobs): <add> while not tis_q.empty(): <add> ti_key, pickle_id = tis_q.get() <add> dag = dagbag.dags[ti_key[0]] <add> task = dag.get_task(ti_key[1]) <add> ti = TI(task, ti_key[2]) <add> self.executor.queue_task_instance(ti, pickle_id=pickle_id) <add> <ide> for j in jobs: <ide> j.join() <ide> <del> while not tis_q.empty(): <del> ti_key, pickle_id = tis_q.get() <del> dag = dagbag.dags[ti_key[0]] <del> task = dag.get_task(ti_key[1]) <del> ti = TI(task, ti_key[2]) <del> self.executor.queue_task_instance(ti, pickle_id=pickle_id) <del> <ide> self.logger.info("Done queuing tasks, calling the executor's " <ide> "heartbeat") <ide> duration_sec = (datetime.now() - loop_start_dttm).total_seconds()
1
Python
Python
add get_secure_random_string utility function
53a67432c963a5dd95c4f796a1888e287018764b
<ide><path>libcloud/test/test_utils.py <ide> from libcloud.utils.py3 import urlquote <ide> from libcloud.compute.types import Provider <ide> from libcloud.compute.providers import DRIVERS <add>from libcloud.utils.misc import get_secure_random_string <ide> <ide> <ide> WARNINGS_BUFFER = [] <ide> def test_unicode_urlquote(self): <ide> uri = urlquote(b('~abc')) <ide> self.assertEqual(b(uri), b('%7Eabc')) <ide> <add> def test_get_secure_random_string(self): <add> for i in range(1, 500): <add> value = get_secure_random_string(size=i) <add> self.assertEqual(len(value), i) <add> <ide> <ide> if __name__ == '__main__': <ide> sys.exit(unittest.main()) <ide><path>libcloud/utils/misc.py <ide> # See the License for the specific language governing permissions and <ide> # limitations under the License. <ide> <add>import os <add>import sys <add>import binascii <add> <add> <ide> __all__ = [ <ide> 'get_driver', <ide> 'set_driver', <ide> 'str2dicts', <ide> 'dict2str', <ide> 'reverse_dict', <del> 'lowercase_keys' <add> 'lowercase_keys', <add> 'get_secure_random_string' <ide> ] <ide> <del>import sys <del> <ide> <ide> def get_driver(drivers, provider): <ide> """ <ide> def reverse_dict(dictionary): <ide> <ide> def lowercase_keys(dictionary): <ide> return dict(((k.lower(), v) for k, v in dictionary.items())) <add> <add> <add>def get_secure_random_string(size): <add> """ <add> Return a string of ``size`` random bytes. Returned string is suitable for <add> cryptographic use. <add> <add> :param size: Size of the generated string. <add> :type size: ``int`` <add> <add> :return: Random string. <add> :rtype: ``str`` <add> """ <add> value = os.urandom(size) <add> value = binascii.hexlify(value) <add> value = value.decode('utf-8')[:size] <add> return value
2
Python
Python
use mse in stateful example
58ca064f9321ad4e6db09d9e8b22db4a3d8fc7dc
<ide><path>examples/stateful_lstm.py <ide> def gen_cosine_amp(amp=100, period=25, x0=0, xn=50000, step=1, k=0.0001): <ide> return_sequences=False, <ide> stateful=True)) <ide> model.add(Dense(1)) <del>model.compile(loss='rmse', optimizer='rmsprop') <add>model.compile(loss='mse', optimizer='rmsprop') <ide> <ide> print('Training') <ide> for i in range(epochs):
1
Java
Java
remove outdated databufferfactory properties
03a997c9d4ce6815d3a07c4d4b20b3f18554ed7c
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/view/AbstractView.java <ide> <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <del>import reactor.core.publisher.Flux; <ide> import reactor.core.publisher.Mono; <ide> <ide> import org.springframework.context.ApplicationContext; <ide> import org.springframework.context.ApplicationContextAware; <del>import org.springframework.core.io.buffer.DataBuffer; <del>import org.springframework.core.io.buffer.DataBufferFactory; <del>import org.springframework.core.io.buffer.DefaultDataBufferFactory; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.ui.ModelMap; <ide> import org.springframework.util.Assert; <ide> public abstract class AbstractView implements View, ApplicationContextAware { <ide> <ide> private final List<MediaType> mediaTypes = new ArrayList<>(4); <ide> <del> private DataBufferFactory bufferAllocator = new DefaultDataBufferFactory(); <del> <ide> private ApplicationContext applicationContext; <ide> <ide> <ide> public List<MediaType> getSupportedMediaTypes() { <ide> return this.mediaTypes; <ide> } <ide> <del> /** <del> * Configure the {@link DataBufferFactory} to use for write I/O. <del> * <p>By default this is set to {@link DefaultDataBufferFactory}. <del> * @param bufferAllocator the factory to use <del> */ <del> public void setBufferAllocator(DataBufferFactory bufferAllocator) { <del> Assert.notNull(bufferAllocator, "'bufferAllocator' is required."); <del> this.bufferAllocator = bufferAllocator; <del> } <del> <del> /** <del> * Return the configured buffer factory, never {@code null}. <del> */ <del> public DataBufferFactory getBufferAllocator() { <del> return this.bufferAllocator; <del> } <del> <ide> @Override <ide> public void setApplicationContext(ApplicationContext applicationContext) { <ide> this.applicationContext = applicationContext; <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/view/UrlBasedViewResolver.java <ide> protected boolean canHandle(String viewName, Locale locale) { <ide> protected AbstractUrlBasedView createUrlBasedView(String viewName) { <ide> AbstractUrlBasedView view = (AbstractUrlBasedView) BeanUtils.instantiateClass(getViewClass()); <ide> view.setSupportedMediaTypes(getSupportedMediaTypes()); <del> view.setBufferAllocator(getBufferAllocator()); <ide> view.setUrl(getPrefix() + viewName + getSuffix()); <ide> return view; <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/view/ViewResolverSupport.java <ide> import org.springframework.context.ApplicationContext; <ide> import org.springframework.context.ApplicationContextAware; <ide> import org.springframework.core.Ordered; <del>import org.springframework.core.io.buffer.DataBufferFactory; <del>import org.springframework.core.io.buffer.DefaultDataBufferFactory; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.util.Assert; <ide> <ide> public abstract class ViewResolverSupport implements ApplicationContextAware, Or <ide> <ide> private List<MediaType> mediaTypes = new ArrayList<>(4); <ide> <del> private DataBufferFactory bufferAllocator = new DefaultDataBufferFactory(); <del> <ide> private ApplicationContext applicationContext; <ide> <ide> private int order = Integer.MAX_VALUE; <ide> public List<MediaType> getSupportedMediaTypes() { <ide> return this.mediaTypes; <ide> } <ide> <del> /** <del> * Configure the {@link DataBufferFactory} to use for write I/O. <del> * <p>By default this is set to {@link DefaultDataBufferFactory}. <del> * @param bufferAllocator the factory to use <del> */ <del> public void setBufferAllocator(DataBufferFactory bufferAllocator) { <del> Assert.notNull(bufferAllocator, "'bufferAllocator' is required."); <del> this.bufferAllocator = bufferAllocator; <del> } <del> <del> /** <del> * Return the configured buffer factory, never {@code null}. <del> */ <del> public DataBufferFactory getBufferAllocator() { <del> return this.bufferAllocator; <del> } <del> <ide> @Override <ide> public void setApplicationContext(ApplicationContext applicationContext) { <ide> this.applicationContext = applicationContext; <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/view/freemarker/FreeMarkerView.java <ide> protected Mono<Void> renderInternal(Map<String, Object> renderAttributes, Server <ide> logger.debug("Rendering FreeMarker template [" + getUrl() + "]."); <ide> } <ide> Locale locale = Locale.getDefault(); // TODO <del> DataBuffer dataBuffer = getBufferAllocator().allocateBuffer(); <add> DataBuffer dataBuffer = exchange.getResponse().bufferFactory().allocateBuffer(); <ide> try { <ide> Writer writer = new OutputStreamWriter(dataBuffer.asOutputStream()); <ide> getTemplate(locale).process(freeMarkerModel, writer); <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingIntegrationTests.java <ide> import org.springframework.web.reactive.result.view.freemarker.FreeMarkerViewResolver; <ide> import org.springframework.web.server.adapter.WebHttpHandlerBuilder; <ide> <del>import static org.junit.Assert.*; <add>import static org.junit.Assert.assertArrayEquals; <add>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.assertTrue; <ide> <ide> <ide> /** <ide> private void createXml(String requestUrl) throws Exception { <ide> @SuppressWarnings("unused") <ide> static class FrameworkConfig { <ide> <del> private DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory(); <del> <del> <ide> @Bean <ide> public RequestMappingHandlerMapping handlerMapping() { <ide> return new RequestMappingHandlerMapping(); <ide> public ViewResolutionResultHandler viewResolverResultHandler() { <ide> <ide> @Bean <ide> public ViewResolver freeMarkerViewResolver() { <del> FreeMarkerViewResolver viewResolver = new FreeMarkerViewResolver("", ".ftl"); <del> viewResolver.setBufferAllocator(this.dataBufferFactory); <del> return viewResolver; <add> return new FreeMarkerViewResolver("", ".ftl"); <ide> } <ide> <ide> @Bean <ide> public Observable<Person> observableCapitalize(@RequestBody Observable<Person> p <ide> <ide> @RequestMapping("/stream-create") <ide> public Publisher<Void> streamCreate(@RequestBody Flux<Person> personStream) { <del> return personStream.toList().doOnSuccess(persons::addAll).then(); <add> return personStream.asList().doOnSuccess(persons::addAll).then(); <ide> } <ide> <ide> @RequestMapping("/person-capitalize")
5
Ruby
Ruby
begin documenting environment variables
db76a0f4cc3838658919570b3453edbcb9ed2fcd
<ide><path>Library/Homebrew/dev-cmd/test-bot.rb <ide> # --ci-pr: Shortcut for Homebrew pull request CI options. <ide> # --ci-testing: Shortcut for Homebrew testing CI options. <ide> # --ci-upload: Homebrew CI bottle upload. <add># <add># Influential environment variables include: <add># TRAVIS_REPO_SLUG: same as --tap <add># GIT_URL: if set to URL of a tap remote, same as --tap <ide> <ide> require "formula" <ide> require "utils" <ide> def sanitize_output_for_xml(output) <ide> output <ide> end <ide> end <del>
1
Ruby
Ruby
use commands module
49dcbee99c46d92d65e9132a555ed3fc2865c1e6
<ide><path>Library/Homebrew/cmd/command.rb <ide> #: * `command` <cmd>: <ide> #: Display the path to the file which is used when invoking `brew` <cmd>. <ide> <add>require "commands" <add> <ide> module Homebrew <ide> def command <ide> abort "This command requires a command argument" if ARGV.empty? <ide> cmd = ARGV.first <ide> cmd = HOMEBREW_INTERNAL_COMMAND_ALIASES.fetch(cmd, cmd) <ide> <del> if (path = internal_command_path cmd) <add> if (path = Commands.path(cmd)) <ide> puts path <ide> elsif (path = which("brew-#{cmd}") || which("brew-#{cmd}.rb")) <ide> puts path <ide> else <ide> odie "Unknown command: #{cmd}" <ide> end <ide> end <del> <del> private <del> <del> def internal_command_path(cmd) <del> extensions = %w[rb sh] <del> paths = extensions.map { |ext| HOMEBREW_LIBRARY_PATH/"cmd/#{cmd}.#{ext}" } <del> paths += extensions.map { |ext| HOMEBREW_LIBRARY_PATH/"dev-cmd/#{cmd}.#{ext}" } <del> paths.find { |p| p.file? } <del> end <ide> end
1
Ruby
Ruby
fix testfixtures autoload
3276286de5c6a28d1e32333e1dabbb0abced510c
<ide><path>activerecord/lib/active_record.rb <ide> module ActiveRecord <ide> autoload :Store <ide> autoload :Suppressor <ide> autoload :TestDatabases <del> autoload :TestFixtures <add> autoload :TestFixtures, "active_record/fixtures" <ide> autoload :Timestamp <ide> autoload :TouchLater <ide> autoload :Transactions
1
Javascript
Javascript
get draco version
22f2fae48a7b1f393529e2c4257abc0a9a3e08b9
<ide><path>examples/js/loaders/sea3d/SEA3DDraco.js <ide> SEA3D.GeometryDraco = function ( name, data, sea3d ) { <ide> var module = SEA3D.GeometryDraco.getModule(), <ide> dracoData = new Int8Array( data.concat( data.position, data.bytesAvailable ).buffer ); <ide> <add> //data.position += 5; // jump "DRACO" magic string <add> //var version = data.readUByte() + '.' + data.readUByte(); // draco version <add> <ide> var decoder = new module.Decoder(); <ide> <ide> var buffer = new module.DecoderBuffer(); <ide> buffer.Init( dracoData, dracoData.length ); <del> <del> var geometryType = decoder.GetEncodedGeometryType( buffer ); <del> <add> <ide> var mesh = new module.Mesh(); <ide> <ide> var decodingStatus = decoder.DecodeBufferToMesh( buffer, mesh );
1
Ruby
Ruby
fix filename case
56aec9494cbe76849140da5b2c4c33c2b42dbbef
<ide><path>Library/Homebrew/test/test_patching.rb <ide> def test_patch_array <ide> def patches <ide> [PATCH_URL_A] <ide> end <del> end.brew { assert_patched 'libexec/noop' } <add> end.brew { assert_patched 'libexec/NOOP' } <ide> end <ide> end <ide> <ide> def test_patch_hash <ide> def patches <ide> { :p1 => PATCH_URL_A } <ide> end <del> end.brew { assert_patched 'libexec/noop' } <add> end.brew { assert_patched 'libexec/NOOP' } <ide> end <ide> end <ide> <ide> def test_patch_hash_array <ide> def patches <ide> { :p1 => [PATCH_URL_A] } <ide> end <del> end.brew { assert_patched 'libexec/noop' } <add> end.brew { assert_patched 'libexec/NOOP' } <ide> end <ide> end <ide> <ide> def test_patch_string <ide> shutup do <ide> formula do <ide> patch PATCH_A_CONTENTS <del> end.brew { assert_patched 'libexec/noop' } <add> end.brew { assert_patched 'libexec/NOOP' } <ide> end <ide> end <ide> <ide> def test_patch_string_with_strip <ide> shutup do <ide> formula do <ide> patch :p0, PATCH_B_CONTENTS <del> end.brew { assert_patched 'libexec/noop' } <add> end.brew { assert_patched 'libexec/NOOP' } <ide> end <ide> end <ide> <ide> def test_patch_DATA_constant <ide> def patches <ide> Formula::DATA <ide> end <del> end.brew { assert_patched "libexec/noop" } <add> end.brew { assert_patched "libexec/NOOP" } <ide> end <ide> end <ide> end
1
Javascript
Javascript
remove unnnecessary test
4181cc962399cbce4d4b36a2f95bd6c696f168b1
<ide><path>packages/ember-views/tests/views/view/view_lifecycle_test.js <ide> QUnit.module("views/view/view_lifecycle_test - in render", { <ide> } <ide> }); <ide> <del>QUnit.skip("appendChild should work inside a template", function() { <del> run(function() { <del> view = EmberView.create({ <del> template(context, options) { <del> var buffer = options.data.buffer; <del> <del> buffer.push("<h1>Hi!</h1>"); <del> <del> options.data.view.appendChild(EmberView, { <del> template: compile("Inception reached") <del> }); <del> <del> buffer.push("<div class='footer'>Wait for the kick</div>"); <del> } <del> }); <del> <del> view.appendTo("#qunit-fixture"); <del> }); <del> <del> ok(view.$('h1').length === 1 && view.$('div').length === 2, <del> "The appended child is visible"); <del>}); <del> <ide> QUnit.skip("rerender should throw inside a template", function() { <ide> throws(function() { <ide> run(function() {
1