content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
PHP
PHP
use symfony as a last resort exception handler
f2cd3c3396590944db2d789bf496f875a2bff0aa
<ide><path>src/Illuminate/Foundation/Exceptions/Handler.php <ide> protected function convertExceptionToResponse(Exception $e) <ide> $headers = $this->isHttpException($e) ? $e->getHeaders() : []; <ide> $statusCode = $this->isHttpException($e) ? $e->getStatusCode() : 500; <ide> <del> if (config('app.debug')) { <del> return SymfonyResponse::create( <del> $this->renderExceptionWithWhoops($e), $statusCode, $headers <del> ); <del> } else { <del> return SymfonyResponse::create( <del> $this->renderExceptionWithSymfony($e), $statusCode, $headers <del> ); <add> $showStackTraces = config('app.debug'); <add> <add> try { <add> $content = $showStackTraces <add> ? $this->renderExceptionWithWhoops($e) <add> : $this->renderExceptionWithSymfony($e, $showStackTraces); <add> } finally { <add> $content = $content ?? $this->renderExceptionWithSymfony($e, $showStackTraces); <ide> } <add> <add> return SymfonyResponse::create( <add> $content, $statusCode, $headers <add> ); <ide> } <ide> <ide> /** <ide> protected function renderExceptionWithWhoops(Exception $e) <ide> * @param \Exception $e <ide> * @return string <ide> */ <del> protected function renderExceptionWithSymfony(Exception $e) <add> protected function renderExceptionWithSymfony(Exception $e, $showStackTraces) <ide> { <ide> $e = FlattenException::create($e); <ide> <del> return (new SymfonyExceptionHandler(false))->getHtml($e); <add> return (new SymfonyExceptionHandler($showStackTraces))->getHtml($e); <ide> } <ide> <ide> /**
1
Javascript
Javascript
remove spurious jsdoc entry
0264f2395f39648969742ef80cb81fd301e840d1
<ide><path>lib/internal/source_map/source_map.js <ide> class SourceMap { <ide> return cloneSourceMapV3(this.#payload); <ide> } <ide> <del> /** <del> * @param {SourceMapV3} mappingPayload <del> */ <ide> #parseMappingPayload = () => { <ide> if (this.#payload.sections) { <ide> this.#parseSections(this.#payload.sections);
1
Ruby
Ruby
reuse `test_args` method
eadf17881d4210a593aaad3db4ea793c13ca66e6
<ide><path>Library/Homebrew/dev-cmd/test.rb <ide> module Homebrew <ide> module_function <ide> <del> def test_args <del> Homebrew::CLI::Parser.new do <del> usage_banner <<~EOS <del> `test` [<options>] <formula> <del> <del> Run the test method provided by an installed formula. <del> There is no standard output or return code, but generally it should notify the <del> user if something is wrong with the installed formula. <del> <del> *Example:* `brew install jruby && brew test jruby` <del> EOS <del> switch "--devel", <del> description: "Test the development version of a formula." <del> switch "--HEAD", <del> description: "Test the head version of a formula." <del> switch "--keep-tmp", <del> description: "Retain the temporary files created for the test." <del> switch :verbose <del> switch :debug <del> conflicts "--devel", "--HEAD" <add> module Test <add> def self.args <add> Homebrew::CLI::Parser.new do <add> usage_banner <<~EOS <add> `test` [<options>] <formula> <add> <add> Run the test method provided by an installed formula. <add> There is no standard output or return code, but generally it should notify the <add> user if something is wrong with the installed formula. <add> <add> *Example:* `brew install jruby && brew test jruby` <add> EOS <add> switch "--devel", <add> description: "Test the development version of a formula." <add> switch "--HEAD", <add> description: "Test the head version of a formula." <add> switch "--keep-tmp", <add> description: "Retain the temporary files created for the test." <add> switch :verbose <add> switch :debug <add> conflicts "--devel", "--HEAD" <add> end <ide> end <ide> end <ide> <ide> def test <del> test_args.parse <add> Test.args.parse <ide> <ide> raise FormulaUnspecifiedError if ARGV.named.empty? <ide> <ide><path>Library/Homebrew/test.rb <ide> require "formula_assertions" <ide> require "fcntl" <ide> require "socket" <del>require "cli/parser" <del> <del>def test_args <del> Homebrew::CLI::Parser.new do <del> switch :force <del> switch :verbose <del> switch :debug <del> end <del>end <add>require "dev-cmd/test" <ide> <ide> TEST_TIMEOUT_SECONDS = 5 * 60 <ide> <ide> begin <del> test_args.parse <add> Homebrew::Test.args.parse <add> <ide> error_pipe = UNIXSocket.open(ENV["HOMEBREW_ERROR_PIPE"], &:recv_io) <ide> error_pipe.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) <ide>
2
PHP
PHP
add @throws to logoutotherdevices()
ef4541d51a805eb711e14af897515aa7b2ed3569
<ide><path>src/Illuminate/Auth/SessionGuard.php <ide> protected function rehashUserPassword($password, $attribute) <ide> * @param string $password <ide> * @param string $attribute <ide> * @return bool|null <add> * <add> * @throws AuthenticationException If the password is invalid. <ide> */ <ide> public function logoutOtherDevices($password, $attribute = 'password') <ide> {
1
Python
Python
fix tests for python 2
10462816bce5e0ddd470eed50bf048c36b451513
<ide><path>spacy/tests/test_underscore.py <ide> def test_underscore_raises_for_dup(obj): <ide> {'default': None, 'method': lambda: None}, <ide> {'getter': True}]) <ide> def test_underscore_raises_for_invalid(invalid_kwargs): <add> invalid_kwargs['force'] = True <ide> doc = Doc(Vocab(), words=['hello', 'world']) <ide> with pytest.raises(ValueError): <del> doc.set_extension('test', **invalid_kwargs, force=True) <add> doc.set_extension('test', **invalid_kwargs) <ide> <ide> <ide> @pytest.mark.parametrize('valid_kwargs', [ <ide> def test_underscore_raises_for_invalid(invalid_kwargs): <ide> {'default': None}, <ide> {'method': lambda: None}]) <ide> def test_underscore_accepts_valid(valid_kwargs): <add> valid_kwargs['force'] = True <ide> doc = Doc(Vocab(), words=['hello', 'world']) <del> doc.set_extension('test', **valid_kwargs, force=True) <add> doc.set_extension('test', **valid_kwargs)
1
Javascript
Javascript
fix typos in test/parallel
c6051a08fa5cd9c9d152af64e42e36d690084420
<ide><path>test/parallel/test-fs-symlink-longpath.js <ide> const longPath = path.join(...[tmpDir].concat(Array(30).fill('1234567890'))); <ide> fs.mkdirSync(longPath, { recursive: true }); <ide> <ide> // Test if we can have symlinks to files and folders with long filenames <del>const targetDirtectory = path.join(longPath, 'target-directory'); <del>fs.mkdirSync(targetDirtectory); <add>const targetDirectory = path.join(longPath, 'target-directory'); <add>fs.mkdirSync(targetDirectory); <ide> const pathDirectory = path.join(tmpDir, 'new-directory'); <del>fs.symlink(targetDirtectory, pathDirectory, 'dir', common.mustSucceed(() => { <add>fs.symlink(targetDirectory, pathDirectory, 'dir', common.mustSucceed(() => { <ide> assert(fs.existsSync(pathDirectory)); <ide> })); <ide> <ide><path>test/parallel/test-net-socket-timeout.js <ide> for (let i = 0; i < validDelays.length; i++) { <ide> } <ide> <ide> for (let i = 0; i < invalidCallbacks.length; i++) { <del> [0, 1].forEach((mesc) => <add> [0, 1].forEach((msec) => <ide> assert.throws( <del> () => s.setTimeout(mesc, invalidCallbacks[i]), <add> () => s.setTimeout(msec, invalidCallbacks[i]), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError', <ide><path>test/parallel/test-queue-microtask-uncaught-asynchooks.js <ide> let µtaskId; <ide> const events = []; <ide> <ide> async_hooks.createHook({ <del> init(id, type, triggerId, resoure) { <add> init(id, type, triggerId, resource) { <ide> if (type === 'Microtask') { <ide> µtaskId = id; <ide> events.push('init'); <ide><path>test/parallel/test-stream-duplex-from.js <ide> const { Blob } = require('buffer'); <ide> // Ensure that Duplex.from works for blobs <ide> { <ide> const blob = new Blob(['blob']); <del> const expecteByteLength = blob.size; <add> const expectedByteLength = blob.size; <ide> const duplex = Duplex.from(blob); <ide> duplex.on('data', common.mustCall((arrayBuffer) => { <del> assert.strictEqual(arrayBuffer.byteLength, expecteByteLength); <add> assert.strictEqual(arrayBuffer.byteLength, expectedByteLength); <ide> })); <ide> } <ide> <ide><path>test/parallel/test-stream-writable-change-default-encoding.js <ide> assert.throws(() => { <ide> message: 'Unknown encoding: {}' <ide> }); <ide> <del>(function checkVairableCaseEncoding() { <add>(function checkVariableCaseEncoding() { <ide> const m = new MyWritable(function(isBuffer, type, enc) { <ide> assert.strictEqual(enc, 'ascii'); <ide> }, { decodeStrings: false });
5
Python
Python
update tf lm examples
3f2e636850aba0fa7d163a27db6fc790e504b184
<ide><path>examples/tensorflow/language-modeling/run_clm.py <ide> import random <ide> import sys <ide> from dataclasses import dataclass, field <del>from functools import partial <ide> from itertools import chain <ide> from pathlib import Path <ide> from typing import Optional <ide> <ide> import datasets <del>import numpy as np <ide> import tensorflow as tf <ide> from datasets import load_dataset <ide> from sklearn.model_selection import train_test_split <ide> TF_MODEL_FOR_CAUSAL_LM_MAPPING, <ide> AutoConfig, <ide> AutoTokenizer, <add> DefaultDataCollator, <ide> HfArgumentParser, <ide> TFAutoModelForCausalLM, <ide> TFTrainingArguments, <ide> class DataTrainingArguments: <ide> default=None, <ide> metadata={"help": "The number of processes to use for the preprocessing."}, <ide> ) <del> mlm_probability: float = field( <del> default=0.15, metadata={"help": "Ratio of tokens to mask for masked language modeling loss"} <del> ) <ide> line_by_line: bool = field( <ide> default=False, <ide> metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."}, <ide> def on_epoch_end(self, epoch, logs=None): <ide> self.model.save_pretrained(self.output_dir) <ide> <ide> <del># endregion <del> <del># region Data generator <del>def sample_generator(dataset, tokenizer): <del> # Trim off the last partial batch if present <del> sample_ordering = np.random.permutation(len(dataset)) <del> for sample_idx in sample_ordering: <del> example = dataset[int(sample_idx)] <del> # Handle dicts with proper padding and conversion to tensor. <del> example = {key: tf.convert_to_tensor(arr, dtype_hint=tf.int64) for key, arr in example.items()} <del> yield example, example["labels"] # TF needs some kind of labels, even if we don't use them <del> return <del> <del> <ide> # endregion <ide> <ide> <ide> def group_texts(examples): <ide> <ide> # region TF Dataset preparation <ide> num_replicas = training_args.strategy.num_replicas_in_sync <del> train_generator = partial(sample_generator, train_dataset, tokenizer) <del> train_signature = { <del> feature: tf.TensorSpec(shape=(None,), dtype=tf.int64) <del> for feature in train_dataset.features <del> if feature != "special_tokens_mask" <del> } <del> train_sig = (train_signature, train_signature["labels"]) <add> data_collator = DefaultDataCollator(return_tensors="tf") <ide> options = tf.data.Options() <ide> options.experimental_distribute.auto_shard_policy = tf.data.experimental.AutoShardPolicy.OFF <del> tf_train_dataset = ( <del> tf.data.Dataset.from_generator(train_generator, output_signature=train_sig) <del> .with_options(options) <del> .batch(batch_size=num_replicas * training_args.per_device_train_batch_size, drop_remainder=True) <del> .repeat(int(training_args.num_train_epochs)) <del> ) <del> eval_generator = partial(sample_generator, eval_dataset, tokenizer) <del> eval_signature = { <del> feature: tf.TensorSpec(shape=(None,), dtype=tf.int64) <del> for feature in eval_dataset.features <del> if feature != "special_tokens_mask" <del> } <del> eval_sig = (eval_signature, eval_signature["labels"]) <del> tf_eval_dataset = ( <del> tf.data.Dataset.from_generator(eval_generator, output_signature=eval_sig) <del> .with_options(options) <del> .batch(batch_size=num_replicas * training_args.per_device_eval_batch_size, drop_remainder=True) <del> .repeat(int(training_args.num_train_epochs)) <del> ) <add> <add> tf_train_dataset = train_dataset.to_tf_dataset( <add> # labels are passed as input, as we will use the model's internal loss <add> columns=[col for col in train_dataset.features if col != "special_tokens_mask"], <add> shuffle=True, <add> batch_size=num_replicas * training_args.per_device_train_batch_size, <add> collate_fn=data_collator, <add> drop_remainder=True, <add> ).with_options(options) <add> <add> tf_eval_dataset = eval_dataset.to_tf_dataset( <add> # labels are passed as input, as we will use the model's internal loss <add> columns=[col for col in eval_dataset.features if col != "special_tokens_mask"], <add> shuffle=False, <add> batch_size=num_replicas * training_args.per_device_train_batch_size, <add> collate_fn=data_collator, <add> drop_remainder=True, <add> ).with_options(options) <ide> # endregion <ide> <ide> # region Optimizer and loss <ide> def group_texts(examples): <ide> weight_decay_rate=training_args.weight_decay, <ide> ) <ide> <del> def dummy_loss(y_true, y_pred): <del> return tf.reduce_mean(y_pred) <del> <del> model.compile(optimizer=optimizer, loss={"loss": dummy_loss}) <add> # no user-specified loss = will use the model internal loss <add> model.compile(optimizer=optimizer) <ide> # endregion <ide> <ide> # region Training and validation <ide><path>examples/tensorflow/language-modeling/run_mlm.py <ide> import random <ide> import sys <ide> from dataclasses import dataclass, field <del>from functools import partial <ide> from itertools import chain <ide> from pathlib import Path <ide> from typing import Optional <ide> <ide> import datasets <del>import numpy as np <ide> import tensorflow as tf <ide> from datasets import load_dataset <ide> from sklearn.model_selection import train_test_split <ide> TF_MODEL_FOR_MASKED_LM_MAPPING, <ide> AutoConfig, <ide> AutoTokenizer, <add> DataCollatorForLanguageModeling, <ide> HfArgumentParser, <ide> TFAutoModelForMaskedLM, <ide> TFTrainingArguments, <ide> def on_epoch_end(self, epoch, logs=None): <ide> self.model.save_pretrained(self.output_dir) <ide> <ide> <del># endregion <del> <del># region Data generator <del>def sample_generator(dataset, tokenizer, mlm_probability=0.15, pad_to_multiple_of=None): <del> if tokenizer.mask_token is None: <del> raise ValueError("This tokenizer does not have a mask token which is necessary for masked language modeling. ") <del> # Trim off the last partial batch if present <del> sample_ordering = np.random.permutation(len(dataset)) <del> for sample_idx in sample_ordering: <del> example = dataset[int(sample_idx)] <del> # Handle dicts with proper padding and conversion to tensor. <del> example = tokenizer.pad(example, return_tensors="np", pad_to_multiple_of=pad_to_multiple_of) <del> special_tokens_mask = example.pop("special_tokens_mask", None) <del> example["input_ids"], example["labels"] = mask_tokens( <del> example["input_ids"], mlm_probability, tokenizer, special_tokens_mask=special_tokens_mask <del> ) <del> if tokenizer.pad_token_id is not None: <del> example["labels"][example["labels"] == tokenizer.pad_token_id] = -100 <del> example = {key: tf.convert_to_tensor(arr) for key, arr in example.items()} <del> <del> yield example, example["labels"] # TF needs some kind of labels, even if we don't use them <del> return <del> <del> <del>def mask_tokens(inputs, mlm_probability, tokenizer, special_tokens_mask): <del> """ <del> Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original. <del> """ <del> labels = np.copy(inputs) <del> # We sample a few tokens in each sequence for MLM training (with probability `self.mlm_probability`) <del> probability_matrix = np.random.random_sample(labels.shape) <del> special_tokens_mask = special_tokens_mask.astype(np.bool_) <del> <del> probability_matrix[special_tokens_mask] = 0.0 <del> masked_indices = probability_matrix > (1 - mlm_probability) <del> labels[~masked_indices] = -100 # We only compute loss on masked tokens <del> <del> # 80% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK]) <del> indices_replaced = (np.random.random_sample(labels.shape) < 0.8) & masked_indices <del> inputs[indices_replaced] = tokenizer.convert_tokens_to_ids(tokenizer.mask_token) <del> <del> # 10% of the time, we replace masked input tokens with random word <del> indices_random = (np.random.random_sample(labels.shape) < 0.5) & masked_indices & ~indices_replaced <del> random_words = np.random.randint(low=0, high=len(tokenizer), size=np.count_nonzero(indices_random), dtype=np.int64) <del> inputs[indices_random] = random_words <del> <del> # The rest of the time (10% of the time) we keep the masked input tokens unchanged <del> return inputs, labels <del> <del> <ide> # endregion <ide> <ide> <ide> def group_texts(examples): <ide> <ide> # region TF Dataset preparation <ide> num_replicas = training_args.strategy.num_replicas_in_sync <del> train_generator = partial(sample_generator, train_dataset, tokenizer) <del> train_signature = { <del> feature: tf.TensorSpec(shape=(None,), dtype=tf.int64) <del> for feature in train_dataset.features <del> if feature != "special_tokens_mask" <del> } <del> train_signature["labels"] = train_signature["input_ids"] <del> train_signature = (train_signature, train_signature["labels"]) <add> data_collator = DataCollatorForLanguageModeling( <add> tokenizer=tokenizer, mlm_probability=data_args.mlm_probability, return_tensors="tf" <add> ) <ide> options = tf.data.Options() <ide> options.experimental_distribute.auto_shard_policy = tf.data.experimental.AutoShardPolicy.OFF <del> tf_train_dataset = ( <del> tf.data.Dataset.from_generator(train_generator, output_signature=train_signature) <del> .with_options(options) <del> .batch(batch_size=num_replicas * training_args.per_device_train_batch_size, drop_remainder=True) <del> .repeat(int(training_args.num_train_epochs)) <del> ) <del> eval_generator = partial(sample_generator, eval_dataset, tokenizer) <del> eval_signature = { <del> feature: tf.TensorSpec(shape=(None,), dtype=tf.int64) <del> for feature in eval_dataset.features <del> if feature != "special_tokens_mask" <del> } <del> eval_signature["labels"] = eval_signature["input_ids"] <del> eval_signature = (eval_signature, eval_signature["labels"]) <del> tf_eval_dataset = ( <del> tf.data.Dataset.from_generator(eval_generator, output_signature=eval_signature) <del> .with_options(options) <del> .batch(batch_size=num_replicas * training_args.per_device_eval_batch_size, drop_remainder=True) <del> ) <add> <add> tf_train_dataset = train_dataset.to_tf_dataset( <add> # labels are passed as input, as we will use the model's internal loss <add> columns=[col for col in train_dataset.features if col != "special_tokens_mask"] + ["labels"], <add> shuffle=True, <add> batch_size=num_replicas * training_args.per_device_train_batch_size, <add> collate_fn=data_collator, <add> drop_remainder=True, <add> ).with_options(options) <add> <add> tf_eval_dataset = eval_dataset.to_tf_dataset( <add> # labels are passed as input, as we will use the model's internal loss <add> columns=[col for col in eval_dataset.features if col != "special_tokens_mask"] + ["labels"], <add> shuffle=False, <add> batch_size=num_replicas * training_args.per_device_train_batch_size, <add> collate_fn=data_collator, <add> drop_remainder=True, <add> ).with_options(options) <ide> # endregion <ide> <ide> # region Optimizer and loss <ide> def group_texts(examples): <ide> weight_decay_rate=training_args.weight_decay, <ide> ) <ide> <del> def dummy_loss(y_true, y_pred): <del> return tf.reduce_mean(y_pred) <del> <del> model.compile(optimizer=optimizer, loss={"loss": dummy_loss}) <add> # no user-specified loss = will use the model internal loss <add> model.compile(optimizer=optimizer) <ide> # endregion <ide> <ide> # region Training and validation
2
Javascript
Javascript
improve stability of charge forces
5390ac3f853e6f48b4db66dd81e97885bbea530b
<ide><path>d3.layout.js <ide> d3.layout.force = function() { <ide> /* Barnes-Hut criterion. */ <ide> if ((x2 - x1) * dn < theta) { <ide> var k = kc * quad.count * dn * dn; <del> node.x += dx * k; <del> node.y += dy * k; <add> node.px -= dx * k; <add> node.py -= dy * k; <ide> return true; <ide> } <ide> <ide> if (quad.point && isFinite(dn)) { <ide> var k = kc * dn * dn; <del> node.x += dx * k; <del> node.y += dy * k; <add> node.px -= dx * k; <add> node.py -= dy * k; <ide> } <ide> } <ide> }; <ide> d3.layout.force = function() { <ide> function tick() { <ide> var n = nodes.length, <ide> m = links.length, <del> q = d3.geom.quadtree(nodes), <add> q, <ide> i, // current index <ide> o, // current object <ide> s, // current source <ide> d3.layout.force = function() { <ide> } <ide> <ide> // apply gravity forces <del> k = alpha * gravity; <del> x = size[0] / 2; <del> y = size[1] / 2; <del> i = -1; while (++i < n) { <del> o = nodes[i]; <del> o.x += (x - o.x) * k; <del> o.y += (y - o.y) * k; <add> if (k = alpha * gravity) { <add> x = size[0] / 2; <add> y = size[1] / 2; <add> i = -1; if (k) while (++i < n) { <add> o = nodes[i]; <add> o.x += (x - o.x) * k; <add> o.y += (y - o.y) * k; <add> } <ide> } <ide> <del> // compute quadtree center of mass <del> d3_layout_forceAccumulate(q); <del> <del> // apply charge forces <del> k = alpha * charge; <del> i = -1; while (++i < n) { <del> q.visit(repulse(nodes[i], k)); <add> // compute quadtree center of mass and apply charge forces <add> if (k = alpha * charge) { <add> d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes)); <add> i = -1; while (++i < n) { <add> if (!(o = nodes[i]).fixed) { <add> q.visit(repulse(o, k)); <add> } <add> } <ide> } <ide> <ide> // position verlet integration <ide><path>d3.layout.min.js <del>(function(){function bc(a,b){var c=a.x+b[3],d=a.y+b[0],e=a.dx-b[1]-b[3],f=a.dy-b[0]-b[2];e<0&&(c+=e/2,e=0),f<0&&(d+=f/2,f=0);return{x:c,y:d,dx:e,dy:f}}function bb(a){return{x:a.x,y:a.y,dx:a.dx,dy:a.dy}}function ba(a,b,c){return a._tree.ancestor.parent==b.parent?a._tree.ancestor:c}function _(a,b,c){a=a._tree,b=b._tree;var d=c/(b.number-a.number);a.change+=d,b.change-=d,b.shift+=c,b.prelim+=c,b.mod+=c}function $(a){var b=0,c=0,d=a.children,e=d.length,f;while(--e>=0)f=d[e]._tree,f.prelim+=b,f.mod+=b,b+=f.shift+(c+=f.change)}function Z(a,b){function c(a,d){var e=a.children;if(e){var f,g=null,h=-1,i=e.length;while(++h<i)f=e[h],c(f,g),g=f}b(a,d)}c(a,null)}function Y(a,b){return a.depth-b.depth}function X(a,b){return b.x-a.x}function W(a,b){return a.x-b.x}function V(a,b){var c=a.children;if(c){var d,e=c.length,f=-1;while(++f<e)b(d=V(c[f],b),a)>0&&(a=d)}return a}function U(a){return a.children?a.children[a.children.length-1]:a._tree.thread}function T(a){return a.children?a.children[0]:a._tree.thread}function S(a,b){return a.parent==b.parent?1:2}function R(a){var b=a.children;return b?R(b[b.length-1]):a}function Q(a){var b=a.children;return b?Q(b[0]):a}function P(a){return a.reduce(function(a,b){return a+b.x},0)/a.length}function O(a){return 1+d3.max(a,function(a){return a.y})}function N(a,b,c){var d=b.r+c.r,e=a.r+c.r,f=b.x-a.x,g=b.y-a.y,h=Math.sqrt(f*f+g*g),i=(e*e+h*h-d*d)/(2*e*h),j=Math.acos(i),k=i*e,l=Math.sin(j)*e;f/=h,g/=h,c.x=a.x+k*f+l*g,c.y=a.y+k*g-l*f}function M(a,b,c,d){var e=a.children;a.x=b+=d*a.x,a.y=c+=d*a.y,a.r*=d;if(e){var f=-1,g=e.length;while(++f<g)M(e[f],b,c,d)}}function L(a){var b=a.children;b?(b.forEach(L),a.r=I(b)):a.r=Math.sqrt(a.value)}function K(a){delete a._pack_next,delete a._pack_prev}function J(a){a._pack_next=a._pack_prev=a}function I(a){function l(a){b=Math.min(a.x-a.r,b),c=Math.max(a.x+a.r,c),d=Math.min(a.y-a.r,d),e=Math.max(a.y+a.r,e)}var b=Infinity,c=-Infinity,d=Infinity,e=-Infinity,f=a.length,g,h,i,j,k;a.forEach(J),g=a[0],g.x=-g.r,g.y=0,l(g);if(f>1){h=a[1],h.x=h.r,h.y=0,l(h);if(f>2){i=a[2],N(g,h,i),l(i),F(g,i),g._pack_prev=i,F(i,h),h=g._pack_next;for(var m=3;m<f;m++){N(g,h,i=a[m]);var n=0,o=1,p=1;for(j=h._pack_next;j!==h;j=j._pack_next,o++)if(H(j,i)){n=1;break}if(n==1)for(k=g._pack_prev;k!==j._pack_prev;k=k._pack_prev,p++)if(H(k,i)){p<o&&(n=-1,j=k);break}n==0?(F(g,i),h=i,l(i)):n>0?(G(g,j),h=j,m--):(G(j,h),g=j,m--)}}}var q=(b+c)/2,r=(d+e)/2,s=0;for(var m=0;m<f;m++){var t=a[m];t.x-=q,t.y-=r,s=Math.max(s,t.r+Math.sqrt(t.x*t.x+t.y*t.y))}a.forEach(K);return s}function H(a,b){var c=b.x-a.x,d=b.y-a.y,e=a.r+b.r;return e*e-c*c-d*d>.001}function G(a,b){a._pack_next=b,b._pack_prev=a}function F(a,b){var c=a._pack_next;a._pack_next=b,b._pack_prev=a,b._pack_next=c,c._pack_prev=b}function E(a,b){return a.value-b.value}function C(a){return d3.merge(a.map(function(a){return(a.children||[]).map(function(b){return{source:a,target:b}})}))}function B(a,b){return b.value-a.value}function A(a){return a.value}function z(a){return a.children}function y(a,b){a.sort=d3.rebind(a,b.sort),a.children=d3.rebind(a,b.children),a.links=C,a.value=d3.rebind(a,b.value),a.nodes=function(b){D=!0;return(a.nodes=a)(b)};return a}function x(a){return[d3.min(a),d3.max(a)]}function w(a,b){var c=-1,d=+a[0],e=(a[1]-d)/b,f=[];while(++c<=b)f[c]=e*c+d;return f}function v(a,b){return w(a,Math.ceil(Math.log(b.length)/Math.LN2+1))}function u(a,b){return a+b[1]}function t(a){return a.reduce(u,0)}function s(a){var b=1,c=0,d=a[0][1],e,f=a.length;for(;b<f;++b)(e=a[b][1])>d&&(c=b,d=e);return c}function p(a,b,c){a.y0=b,a.y=c}function o(a){return a.y}function n(a){return a.x}function m(a){return 1}function l(a){return 20}function k(a){var b=0,c=0;a.count=0;if(!a.leaf){var d=a.nodes,e=d.length,f=-1,g;while(++f<e){g=d[f];if(g==null)continue;k(g),a.count+=g.count,b+=g.count*g.cx,c+=g.count*g.cy}}a.point&&(a.leaf||(a.point.x+=Math.random()-.5,a.point.y+=Math.random()-.5),a.count++,b+=a.point.x,c+=a.point.y),a.cx=b/a.count,a.cy=c/a.count}function j(){f.px+=d3.event.dx,f.py+=d3.event.dy,e.resume()}function i(){j(),f.fixed&=1,e=f=null}function h(a){a!==f&&(a.fixed&=1)}function g(a){a.fixed|=2}function c(a,c){if(a===c)return a;var d=b(a),e=b(c),f=d.pop(),g=e.pop(),h=null;while(f===g)h=f,f=d.pop(),g=e.pop();return h}function b(a){var b=[],c=a.parent;while(c!=null)b.push(a),a=c,c=c.parent;b.push(a);return b}function a(a){var b=a.source,d=a.target,e=c(b,d),f=[b];while(b!==e)b=b.parent,f.push(b);var g=f.length;while(d!==e)f.splice(g,0,d),d=d.parent;return f}d3.layout={},d3.layout.bundle=function(){return function(b){var c=[],d=-1,e=b.length;while(++d<e)c.push(a(b[d]));return c}},d3.layout.chord=function(){function k(){b.sort(function(a,b){return i(a.target.value,b.target.value)})}function j(){var a={},j=[],l=d3.range(e),m=[],n,o,p,q,r;b=[],c=[],n=0,q=-1;while(++q<e){o=0,r=-1;while(++r<e)o+=d[q][r];j.push(o),m.push(d3.range(e)),n+=o}g&&l.sort(function(a,b){return g(j[a],j[b])}),h&&m.forEach(function(a,b){a.sort(function(a,c){return h(d[b][a],d[b][c])})}),n=(2*Math.PI-f*e)/n,o=0,q=-1;while(++q<e){p=o,r=-1;while(++r<e){var s=l[q],t=m[q][r],u=d[s][t];a[s+"-"+t]={index:s,subindex:t,startAngle:o,endAngle:o+=u*n,value:u}}c.push({index:s,startAngle:p,endAngle:o,value:(o-p)/n}),o+=f}q=-1;while(++q<e){r=q-1;while(++r<e){var v=a[q+"-"+r],w=a[r+"-"+q];(v.value||w.value)&&b.push(v.value<w.value?{source:w,target:v}:{source:v,target:w})}}i&&k()}var a={},b,c,d,e,f=0,g,h,i;a.matrix=function(f){if(!arguments.length)return d;e=(d=f)&&d.length,b=c=null;return a},a.padding=function(d){if(!arguments.length)return f;f=d,b=c=null;return a},a.sortGroups=function(d){if(!arguments.length)return g;g=d,b=c=null;return a},a.sortSubgroups=function(c){if(!arguments.length)return h;h=c,b=null;return a},a.sortChords=function(c){if(!arguments.length)return i;i=c,b&&k();return a},a.chords=function(){b||j();return b},a.groups=function(){c||j();return c};return a},d3.layout.force=function(){function B(b){g(f=b),e=a}function A(){var a=v.length,d=w.length,e=d3.geom.quadtree(v),f,g,h,i,j,l,m,p;for(f=0;f<d;++f){g=w[f],h=g.source,i=g.target,m=i.x-h.x,p=i.y-h.y;if(j=m*m+p*p)j=n*y[f]*((j=Math.sqrt(j))-x[f])/j,m*=j,p*=j,i.x-=m*(l=h.weight/(i.weight+h.weight)),i.y-=p*l,h.x+=m*(l=1-l),h.y+=p*l}l=n*s,m=c[0]/2,p=c[1]/2,f=-1;while(++f<a)g=v[f],g.x+=(m-g.x)*l,g.y+=(p-g.y)*l;k(e),l=n*r,f=-1;while(++f<a)e.visit(z(v[f],l));f=-1;while(++f<a)g=v[f],g.fixed?(g.x=g.px,g.y=g.py):(g.x-=(g.px-(g.px=g.x))*o,g.y-=(g.py-(g.py=g.y))*o);b.tick.dispatch({type:"tick",alpha:n});return(n*=.99)<.005}function z(a,b){return function(c,d,e,f,g){if(c.point!==a){var h=c.cx-a.x,i=c.cy-a.y,j=1/Math.sqrt(h*h+i*i);if((f-d)*j<t){var k=b*c.count*j*j;a.x+=h*k,a.y+=i*k;return!0}if(c.point&&isFinite(j)){var k=b*j*j;a.x+=h*k,a.y+=i*k}}}}var a={},b=d3.dispatch("tick"),c=[1,1],d,n,o=.9,p=l,q=m,r=-30,s=.1,t=.8,u,v=[],w=[],x,y;a.on=function(c,d){b[c].add(d);return a},a.nodes=function(b){if(!arguments.length)return v;v=b;return a},a.links=function(b){if(!arguments.length)return w;w=b;return a},a.size=function(b){if(!arguments.length)return c;c=b;return a},a.linkDistance=function(b){if(!arguments.length)return p;p=d3.functor(b);return a},a.distance=a.linkDistance,a.linkStrength=function(b){if(!arguments.length)return q;q=d3.functor(b);return a},a.friction=function(b){if(!arguments.length)return o;o=b;return a},a.charge=function(b){if(!arguments.length)return r;r=b;return a},a.gravity=function(b){if(!arguments.length)return s;s=b;return a},a.theta=function(b){if(!arguments.length)return t;t=b;return a},a.start=function(){function l(){if(!i){i=[];for(d=0;d<e;++d)i[d]=[];for(d=0;d<f;++d){var a=w[d];i[a.source.index].push(a.target),i[a.target.index].push(a.source)}}return i[b]}function k(a,c){var d=l(b),e=-1,f=d.length,g;while(++e<f)if(!isNaN(g=d[e][a]))return g;return Math.random()*c}var b,d,e=v.length,f=w.length,g=c[0],h=c[1],i,j;for(b=0;b<e;++b)(j=v[b]).index=b,j.weight=0;x=[],y=[];for(b=0;b<f;++b)j=w[b],typeof j.source=="number"&&(j.source=v[j.source]),typeof j.target=="number"&&(j.target=v[j.target]),x[b]=p.call(this,j,b),y[b]=q.call(this,j,b),++j.source.weight,++j.target.weight;for(b=0;b<e;++b)j=v[b],isNaN(j.x)&&(j.x=k("x",g)),isNaN(j.y)&&(j.y=k("y",h)),isNaN(j.px)&&(j.px=j.x),isNaN(j.py)&&(j.py=j.y);return a.resume()},a.resume=function(){n=.1,d3.timer(A);return a},a.stop=function(){n=0;return a},a.drag=function(){d||(d=d3.behavior.drag().on("dragstart",B).on("drag",j).on("dragend",i)),this.on("mouseover.force",g).on("mouseout.force",h).call(d)};return a};var e,f;d3.layout.partition=function(){function e(e,f){var g=a.call(this,e,f);c(g[0],0,b[0],b[1]/d(g[0]));return g}function d(a){var b=a.children,c=0;if(b){var e=-1,f=b.length;while(++e<f)c=Math.max(c,d(b[e]))}return 1+c}function c(a,b,d,e){var f=a.children;a.x=b,a.y=a.depth*e,a.dx=d,a.dy=e;if(f){var g=-1,h=f.length,i,j;d=a.value?d/a.value:0;while(++g<h)c(i=f[g],b,j=i.value*d,e),b+=j}}var a=d3.layout.hierarchy(),b=[1,1];e.size=function(a){if(!arguments.length)return b;b=a;return e};return y(e,a)},d3.layout.pie=function(){function f(f,g){var h=+(typeof c=="function"?c.apply(this,arguments):c),i=(typeof e=="function"?e.apply(this,arguments):e)-c,j=d3.range(f.length);b!=null&&j.sort(function(a,c){return b(f[a],f[c])});var k=f.map(a);i/=k.reduce(function(a,b){return a+b},0);var l=j.map(function(a){return{data:f[a],value:d=k[a],startAngle:h,endAngle:h+=d*i}});return f.map(function(a,b){return l[j[b]]})}var a=Number,b=null,c=0,e=2*Math.PI;f.value=function(b){if(!arguments.length)return a;a=b;return f},f.sort=function(a){if(!arguments.length)return b;b=a;return f},f.startAngle=function(a){if(!arguments.length)return c;c=a;return f},f.endAngle=function(a){if(!arguments.length)return e;e=a;return f};return f},d3.layout.stack=function(){function g(h,i){var j=h.map(function(b,c){return a.call(g,b,c)}),k=j.map(function(a,b){return a.map(function(a,b){return[e.call(g,a,b),f.call(g,a,b)]})}),l=b.call(g,k,i);j=d3.permute(j,l),k=d3.permute(k,l);var m=c.call(g,k,i),n=j.length,o=j[0].length,p,q,r;for(q=0;q<o;++q){d.call(g,j[0][q],r=m[q],k[0][q][1]);for(p=1;p<n;++p)d.call(g,j[p][q],r+=k[p-1][q][1],k[p][q][1])}return h}var a=Object,b=q["default"],c=r.zero,d=p,e=n,f=o;g.values=function(b){if(!arguments.length)return a;a=b;return g},g.order=function(a){if(!arguments.length)return b;b=typeof a=="function"?a:q[a];return g},g.offset=function(a){if(!arguments.length)return c;c=typeof a=="function"?a:r[a];return g},g.x=function(a){if(!arguments.length)return e;e=a;return g},g.y=function(a){if(!arguments.length)return f;f=a;return g},g.out=function(a){if(!arguments.length)return d;d=a;return g};return g};var q={"inside-out":function(a){var b=a.length,c,d,e=a.map(s),f=a.map(t),g=d3.range(b).sort(function(a,b){return e[a]-e[b]}),h=0,i=0,j=[],k=[];for(c=0;c<b;++c)d=g[c],h<i?(h+=f[d],j.push(d)):(i+=f[d],k.push(d));return k.reverse().concat(j)},reverse:function(a){return d3.range(a.length).reverse()},"default":function(a){return d3.range(a.length)}},r={silhouette:function(a){var b=a.length,c=a[0].length,d=[],e=0,f,g,h,i=[];for(g=0;g<c;++g){for(f=0,h=0;f<b;f++)h+=a[f][g][1];h>e&&(e=h),d.push(h)}for(g=0;g<c;++g)i[g]=(e-d[g])/2;return i},wiggle:function(a){var b=a.length,c=a[0],d=c.length,e=0,f,g,h,i,j,k,l,m,n,o=[];o[0]=m=n=0;for(g=1;g<d;++g){for(f=0,i=0;f<b;++f)i+=a[f][g][1];for(f=0,j=0,l=c[g][0]-c[g-1][0];f<b;++f){for(h=0,k=(a[f][g][1]-a[f][g-1][1])/(2*l);h<f;++h)k+=(a[h][g][1]-a[h][g-1][1])/l;j+=k*a[f][g][1]}o[g]=m-=i?j/i*l:0,m<n&&(n=m)}for(g=0;g<d;++g)o[g]-=n;return o},expand:function(a){var b=a.length,c=a[0].length,d=1/b,e,f,g,h=[];for(f=0;f<c;++f){for(e=0,g=0;e<b;e++)g+=a[e][f][1];if(g)for(e=0;e<b;e++)a[e][f][1]/=g;else for(e=0;e<b;e++)a[e][f][1]=d}for(f=0;f<c;++f)h[f]=0;return h},zero:function(a){var b=-1,c=a[0].length,d=[];while(++b<c)d[b]=0;return d}};d3.layout.histogram=function(){function e(e,f){var g=[],h=e.map(b,this),i=c.call(this,h,f),j=d.call(this,i,h,f),k,f=-1,l=h.length,m=j.length-1,n=a?1:1/l,o;while(++f<m)k=g[f]=[],k.dx=j[f+1]-(k.x=j[f]),k.y=0;f=-1;while(++f<l)o=h[f],o>=i[0]&&o<=i[1]&&(k=g[d3.bisect(j,o,1,m)-1],k.y+=n,k.push(e[f]));return g}var a=!0,b=Number,c=x,d=v;e.value=function(a){if(!arguments.length)return b;b=a;return e},e.range=function(a){if(!arguments.length)return c;c=d3.functor(a);return e},e.bins=function(a){if(!arguments.length)return d;d=typeof a=="number"?function(b){return w(b,a)}:d3.functor(a);return e},e.frequency=function(b){if(!arguments.length)return a;a=!!b;return e};return e},d3.layout.hierarchy=function(){function g(a){var b=[];e(a,0,b);return b}function f(a,b){var d=a.children,e=0;if(d){var h=-1,i=d.length,j=b+1;while(++h<i)e+=f(d[h],j)}else c&&(e=+c.call(g,D?a:a.data,b)||0);c&&(a.value=e);return e}function e(f,h,i){var j=b.call(g,f,h),k=D?f:{data:f};k.depth=h,i.push(k);if(j){var l=-1,m=j.length,n=k.children=[],o=0,p=h+1;while(++l<m)d=e(j[l],p,i),d.parent=k,n.push(d),o+=d.value;a&&n.sort(a),c&&(k.value=o)}else c&&(k.value=+c.call(g,f,h)||0);return k}var a=B,b=z,c=A;g.sort=function(b){if(!arguments.length)return a;a=b;return g},g.children=function(a){if(!arguments.length)return b;b=a;return g},g.value=function(a){if(!arguments.length)return c;c=a;return g},g.revalue=function(a){f(a,0);return a};return g};var D=!1;d3.layout.pack=function(){function c(c,d){var e=a.call(this,c,d),f=e[0];f.x=0,f.y=0,L(f);var g=b[0],h=b[1],i=1/Math.max(2*f.r/g,2*f.r/h);M(f,g/2,h/2,i);return e}var a=d3.layout.hierarchy().sort(E),b=[1,1];c.size=function(a){if(!arguments.length)return b;b=a;return c};return y(c,a)},d3.layout.cluster=function(){function d(d,e){var f=a.call(this,d,e),g=f[0],h,i=0,j,k;Z(g,function(a){a.children?(a.x=P(a.children),a.y=O(a.children)):(a.x=h?i+=b(a,h):0,a.y=0,h=a)});var l=Q(g),m=R(g),n=l.x-b(l,m)/2,o=m.x+b(m,l)/2;Z(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=(1-a.y/g.y)*c[1]});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=S,c=[1,1];d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return y(d,a)},d3.layout.tree=function(){function d(d,e){function j(a,c,d){if(c){var e=a,f=a,g=c,h=a.parent.children[0],i=e._tree.mod,j=f._tree.mod,k=g._tree.mod,l=h._tree.mod,m;while(g=U(g),e=T(e),g&&e)h=T(h),f=U(f),f._tree.ancestor=a,m=g._tree.prelim+k-e._tree.prelim-i+b(g,e),m>0&&(_(ba(g,a,d),a,m),i+=m,j+=m),k+=g._tree.mod,i+=e._tree.mod,l+=h._tree.mod,j+=f._tree.mod;g&&!U(f)&&(f._tree.thread=g,f._tree.mod+=k-j),e&&!T(h)&&(h._tree.thread=e,h._tree.mod+=i-l,d=a)}return d}function i(a,b){a.x=a._tree.prelim+b;var c=a.children;if(c){var d=-1,e=c.length;b+=a._tree.mod;while(++d<e)i(c[d],b)}}function h(a,c){var d=a.children,e=a._tree;if(d&&(f=d.length)){var f,g=d[0],i,k=g,l,m=-1;while(++m<f)l=d[m],h(l,i),k=j(l,i,k),i=l;$(a);var n=.5*(g._tree.prelim+l._tree.prelim);c?(e.prelim=c._tree.prelim+b(a,c),e.mod=e.prelim-n):e.prelim=n}else c&&(e.prelim=c._tree.prelim+b(a,c))}var f=a.call(this,d,e),g=f[0];Z(g,function(a,b){a._tree={ancestor:a,prelim:0,mod:0,change:0,shift:0,number:b?b._tree.number+1:0}}),h(g),i(g,-g._tree.prelim);var k=V(g,X),l=V(g,W),m=V(g,Y),n=k.x-b(k,l)/2,o=l.x+b(l,k)/2,p=m.depth||1;Z(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=a.depth/p*c[1],delete a._tree});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=S,c=[1,1];d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return y(d,a)},d3.layout.treemap=function(){function n(b){var d=g||a(b),e=d[0];e.x=0,e.y=0,e.dx=c[0],e.dy=c[1],g&&a.revalue(e),i([e],e.dx*e.dy/e.value),(g?k:j)(e),f&&(g=d);return d}function m(a,c,d,e){var f=-1,g=a.length,h=d.x,i=d.y,j=c?b(a.area/c):0,k;if(c==d.dx){if(e||j>d.dy)j=j?d.dy:0;while(++f<g)k=a[f],k.x=h,k.y=i,k.dy=j,h+=k.dx=j?b(k.area/j):0;k.z=!0,k.dx+=d.x+d.dx-h,d.y+=j,d.dy-=j}else{if(e||j>d.dx)j=j?d.dx:0;while(++f<g)k=a[f],k.x=h,k.y=i,k.dx=j,i+=k.dy=j?b(k.area/j):0;k.z=!1,k.dy+=d.y+d.dy-i,d.x+=j,d.dx-=j}}function l(a,b){var c=a.area,d,e=0,f=Infinity,g=-1,i=a.length;while(++g<i){if(!(d=a[g].area))continue;d<f&&(f=d),d>e&&(e=d)}c*=c,b*=b;return c?Math.max(b*e*h/c,c/(b*f*h)):Infinity}function k(a){if(!!a.children){var b=e(a),c=a.children.slice(),d,f=[];i(c,b.dx*b.dy/a.value),f.area=0;while(d=c.pop())f.push(d),f.area+=d.area,d.z!=null&&(m(f,d.z?b.dx:b.dy,b,!c.length),f.length=f.area=0);a.children.forEach(k)}}function j(a){if(!!a.children){var b=e(a),c=[],d=a.children.slice(),f,g=Infinity,h,k=Math.min(b.dx,b.dy),n;i(d,b.dx*b.dy/a.value),c.area=0;while((n=d.length)>0)c.push(f=d[n-1]),c.area+=f.area,(h=l(c,k))<=g?(d.pop(),g=h):(c.area-=c.pop().area,m(c,k,b,!1),k=Math.min(b.dx,b.dy),c.length=c.area=0,g=Infinity);c.length&&(m(c,k,b,!0),c.length=c.area=0),a.children.forEach(j)}}function i(a,b){var c=-1,d=a.length,e,f;while(++c<d)f=(e=a[c]).value*(b<0?0:b),e.area=isNaN(f)||f<=0?0:f}var a=d3.layout.hierarchy(),b=Math.round,c=[1,1],d=null,e=bb,f=!1,g,h=.5*(1+Math.sqrt(5));n.size=function(a){if(!arguments.length)return c;c=a;return n},n.padding=function(a){function c(b){return bc(b,a)}function b(b){var c=a.call(n,b,b.depth);return c==null?bb(b):bc(b,typeof c=="number"?[c,c,c,c]:c)}if(!arguments.length)return d;var f;e=(d=a)==null?bb:(f=typeof a)==="function"?b:f==="number"?(a=[a,a,a,a],c):c;return n},n.round=function(a){if(!arguments.length)return b!=Number;b=a?Math.round:Number;return n},n.sticky=function(a){if(!arguments.length)return f;f=a,g=null;return n},n.ratio=function(a){if(!arguments.length)return h;h=a;return n};return y(n,a)}})() <ide>\ No newline at end of file <add>(function(){function bc(a,b){var c=a.x+b[3],d=a.y+b[0],e=a.dx-b[1]-b[3],f=a.dy-b[0]-b[2];e<0&&(c+=e/2,e=0),f<0&&(d+=f/2,f=0);return{x:c,y:d,dx:e,dy:f}}function bb(a){return{x:a.x,y:a.y,dx:a.dx,dy:a.dy}}function ba(a,b,c){return a._tree.ancestor.parent==b.parent?a._tree.ancestor:c}function _(a,b,c){a=a._tree,b=b._tree;var d=c/(b.number-a.number);a.change+=d,b.change-=d,b.shift+=c,b.prelim+=c,b.mod+=c}function $(a){var b=0,c=0,d=a.children,e=d.length,f;while(--e>=0)f=d[e]._tree,f.prelim+=b,f.mod+=b,b+=f.shift+(c+=f.change)}function Z(a,b){function c(a,d){var e=a.children;if(e){var f,g=null,h=-1,i=e.length;while(++h<i)f=e[h],c(f,g),g=f}b(a,d)}c(a,null)}function Y(a,b){return a.depth-b.depth}function X(a,b){return b.x-a.x}function W(a,b){return a.x-b.x}function V(a,b){var c=a.children;if(c){var d,e=c.length,f=-1;while(++f<e)b(d=V(c[f],b),a)>0&&(a=d)}return a}function U(a){return a.children?a.children[a.children.length-1]:a._tree.thread}function T(a){return a.children?a.children[0]:a._tree.thread}function S(a,b){return a.parent==b.parent?1:2}function R(a){var b=a.children;return b?R(b[b.length-1]):a}function Q(a){var b=a.children;return b?Q(b[0]):a}function P(a){return a.reduce(function(a,b){return a+b.x},0)/a.length}function O(a){return 1+d3.max(a,function(a){return a.y})}function N(a,b,c){var d=b.r+c.r,e=a.r+c.r,f=b.x-a.x,g=b.y-a.y,h=Math.sqrt(f*f+g*g),i=(e*e+h*h-d*d)/(2*e*h),j=Math.acos(i),k=i*e,l=Math.sin(j)*e;f/=h,g/=h,c.x=a.x+k*f+l*g,c.y=a.y+k*g-l*f}function M(a,b,c,d){var e=a.children;a.x=b+=d*a.x,a.y=c+=d*a.y,a.r*=d;if(e){var f=-1,g=e.length;while(++f<g)M(e[f],b,c,d)}}function L(a){var b=a.children;b?(b.forEach(L),a.r=I(b)):a.r=Math.sqrt(a.value)}function K(a){delete a._pack_next,delete a._pack_prev}function J(a){a._pack_next=a._pack_prev=a}function I(a){function l(a){b=Math.min(a.x-a.r,b),c=Math.max(a.x+a.r,c),d=Math.min(a.y-a.r,d),e=Math.max(a.y+a.r,e)}var b=Infinity,c=-Infinity,d=Infinity,e=-Infinity,f=a.length,g,h,i,j,k;a.forEach(J),g=a[0],g.x=-g.r,g.y=0,l(g);if(f>1){h=a[1],h.x=h.r,h.y=0,l(h);if(f>2){i=a[2],N(g,h,i),l(i),F(g,i),g._pack_prev=i,F(i,h),h=g._pack_next;for(var m=3;m<f;m++){N(g,h,i=a[m]);var n=0,o=1,p=1;for(j=h._pack_next;j!==h;j=j._pack_next,o++)if(H(j,i)){n=1;break}if(n==1)for(k=g._pack_prev;k!==j._pack_prev;k=k._pack_prev,p++)if(H(k,i)){p<o&&(n=-1,j=k);break}n==0?(F(g,i),h=i,l(i)):n>0?(G(g,j),h=j,m--):(G(j,h),g=j,m--)}}}var q=(b+c)/2,r=(d+e)/2,s=0;for(var m=0;m<f;m++){var t=a[m];t.x-=q,t.y-=r,s=Math.max(s,t.r+Math.sqrt(t.x*t.x+t.y*t.y))}a.forEach(K);return s}function H(a,b){var c=b.x-a.x,d=b.y-a.y,e=a.r+b.r;return e*e-c*c-d*d>.001}function G(a,b){a._pack_next=b,b._pack_prev=a}function F(a,b){var c=a._pack_next;a._pack_next=b,b._pack_prev=a,b._pack_next=c,c._pack_prev=b}function E(a,b){return a.value-b.value}function C(a){return d3.merge(a.map(function(a){return(a.children||[]).map(function(b){return{source:a,target:b}})}))}function B(a,b){return b.value-a.value}function A(a){return a.value}function z(a){return a.children}function y(a,b){a.sort=d3.rebind(a,b.sort),a.children=d3.rebind(a,b.children),a.links=C,a.value=d3.rebind(a,b.value),a.nodes=function(b){D=!0;return(a.nodes=a)(b)};return a}function x(a){return[d3.min(a),d3.max(a)]}function w(a,b){var c=-1,d=+a[0],e=(a[1]-d)/b,f=[];while(++c<=b)f[c]=e*c+d;return f}function v(a,b){return w(a,Math.ceil(Math.log(b.length)/Math.LN2+1))}function u(a,b){return a+b[1]}function t(a){return a.reduce(u,0)}function s(a){var b=1,c=0,d=a[0][1],e,f=a.length;for(;b<f;++b)(e=a[b][1])>d&&(c=b,d=e);return c}function p(a,b,c){a.y0=b,a.y=c}function o(a){return a.y}function n(a){return a.x}function m(a){return 1}function l(a){return 20}function k(a){var b=0,c=0;a.count=0;if(!a.leaf){var d=a.nodes,e=d.length,f=-1,g;while(++f<e){g=d[f];if(g==null)continue;k(g),a.count+=g.count,b+=g.count*g.cx,c+=g.count*g.cy}}a.point&&(a.leaf||(a.point.x+=Math.random()-.5,a.point.y+=Math.random()-.5),a.count++,b+=a.point.x,c+=a.point.y),a.cx=b/a.count,a.cy=c/a.count}function j(){f.px+=d3.event.dx,f.py+=d3.event.dy,e.resume()}function i(){j(),f.fixed&=1,e=f=null}function h(a){a!==f&&(a.fixed&=1)}function g(a){a.fixed|=2}function c(a,c){if(a===c)return a;var d=b(a),e=b(c),f=d.pop(),g=e.pop(),h=null;while(f===g)h=f,f=d.pop(),g=e.pop();return h}function b(a){var b=[],c=a.parent;while(c!=null)b.push(a),a=c,c=c.parent;b.push(a);return b}function a(a){var b=a.source,d=a.target,e=c(b,d),f=[b];while(b!==e)b=b.parent,f.push(b);var g=f.length;while(d!==e)f.splice(g,0,d),d=d.parent;return f}d3.layout={},d3.layout.bundle=function(){return function(b){var c=[],d=-1,e=b.length;while(++d<e)c.push(a(b[d]));return c}},d3.layout.chord=function(){function k(){b.sort(function(a,b){return i(a.target.value,b.target.value)})}function j(){var a={},j=[],l=d3.range(e),m=[],n,o,p,q,r;b=[],c=[],n=0,q=-1;while(++q<e){o=0,r=-1;while(++r<e)o+=d[q][r];j.push(o),m.push(d3.range(e)),n+=o}g&&l.sort(function(a,b){return g(j[a],j[b])}),h&&m.forEach(function(a,b){a.sort(function(a,c){return h(d[b][a],d[b][c])})}),n=(2*Math.PI-f*e)/n,o=0,q=-1;while(++q<e){p=o,r=-1;while(++r<e){var s=l[q],t=m[q][r],u=d[s][t];a[s+"-"+t]={index:s,subindex:t,startAngle:o,endAngle:o+=u*n,value:u}}c.push({index:s,startAngle:p,endAngle:o,value:(o-p)/n}),o+=f}q=-1;while(++q<e){r=q-1;while(++r<e){var v=a[q+"-"+r],w=a[r+"-"+q];(v.value||w.value)&&b.push(v.value<w.value?{source:w,target:v}:{source:v,target:w})}}i&&k()}var a={},b,c,d,e,f=0,g,h,i;a.matrix=function(f){if(!arguments.length)return d;e=(d=f)&&d.length,b=c=null;return a},a.padding=function(d){if(!arguments.length)return f;f=d,b=c=null;return a},a.sortGroups=function(d){if(!arguments.length)return g;g=d,b=c=null;return a},a.sortSubgroups=function(c){if(!arguments.length)return h;h=c,b=null;return a},a.sortChords=function(c){if(!arguments.length)return i;i=c,b&&k();return a},a.chords=function(){b||j();return b},a.groups=function(){c||j();return c};return a},d3.layout.force=function(){function B(b){g(f=b),e=a}function A(){var a=v.length,d=w.length,e,f,g,h,i,j,l,m,p;for(f=0;f<d;++f){g=w[f],h=g.source,i=g.target,m=i.x-h.x,p=i.y-h.y;if(j=m*m+p*p)j=n*y[f]*((j=Math.sqrt(j))-x[f])/j,m*=j,p*=j,i.x-=m*(l=h.weight/(i.weight+h.weight)),i.y-=p*l,h.x+=m*(l=1-l),h.y+=p*l}if(l=n*s){m=c[0]/2,p=c[1]/2,f=-1;if(l)while(++f<a)g=v[f],g.x+=(m-g.x)*l,g.y+=(p-g.y)*l}if(l=n*r){k(e=d3.geom.quadtree(v)),f=-1;while(++f<a)(g=v[f]).fixed||e.visit(z(g,l))}f=-1;while(++f<a)g=v[f],g.fixed?(g.x=g.px,g.y=g.py):(g.x-=(g.px-(g.px=g.x))*o,g.y-=(g.py-(g.py=g.y))*o);b.tick.dispatch({type:"tick",alpha:n});return(n*=.99)<.005}function z(a,b){return function(c,d,e,f,g){if(c.point!==a){var h=c.cx-a.x,i=c.cy-a.y,j=1/Math.sqrt(h*h+i*i);if((f-d)*j<t){var k=b*c.count*j*j;a.px-=h*k,a.py-=i*k;return!0}if(c.point&&isFinite(j)){var k=b*j*j;a.px-=h*k,a.py-=i*k}}}}var a={},b=d3.dispatch("tick"),c=[1,1],d,n,o=.9,p=l,q=m,r=-30,s=.1,t=.8,u,v=[],w=[],x,y;a.on=function(c,d){b[c].add(d);return a},a.nodes=function(b){if(!arguments.length)return v;v=b;return a},a.links=function(b){if(!arguments.length)return w;w=b;return a},a.size=function(b){if(!arguments.length)return c;c=b;return a},a.linkDistance=function(b){if(!arguments.length)return p;p=d3.functor(b);return a},a.distance=a.linkDistance,a.linkStrength=function(b){if(!arguments.length)return q;q=d3.functor(b);return a},a.friction=function(b){if(!arguments.length)return o;o=b;return a},a.charge=function(b){if(!arguments.length)return r;r=b;return a},a.gravity=function(b){if(!arguments.length)return s;s=b;return a},a.theta=function(b){if(!arguments.length)return t;t=b;return a},a.start=function(){function l(){if(!i){i=[];for(d=0;d<e;++d)i[d]=[];for(d=0;d<f;++d){var a=w[d];i[a.source.index].push(a.target),i[a.target.index].push(a.source)}}return i[b]}function k(a,c){var d=l(b),e=-1,f=d.length,g;while(++e<f)if(!isNaN(g=d[e][a]))return g;return Math.random()*c}var b,d,e=v.length,f=w.length,g=c[0],h=c[1],i,j;for(b=0;b<e;++b)(j=v[b]).index=b,j.weight=0;x=[],y=[];for(b=0;b<f;++b)j=w[b],typeof j.source=="number"&&(j.source=v[j.source]),typeof j.target=="number"&&(j.target=v[j.target]),x[b]=p.call(this,j,b),y[b]=q.call(this,j,b),++j.source.weight,++j.target.weight;for(b=0;b<e;++b)j=v[b],isNaN(j.x)&&(j.x=k("x",g)),isNaN(j.y)&&(j.y=k("y",h)),isNaN(j.px)&&(j.px=j.x),isNaN(j.py)&&(j.py=j.y);return a.resume()},a.resume=function(){n=.1,d3.timer(A);return a},a.stop=function(){n=0;return a},a.drag=function(){d||(d=d3.behavior.drag().on("dragstart",B).on("drag",j).on("dragend",i)),this.on("mouseover.force",g).on("mouseout.force",h).call(d)};return a};var e,f;d3.layout.partition=function(){function e(e,f){var g=a.call(this,e,f);c(g[0],0,b[0],b[1]/d(g[0]));return g}function d(a){var b=a.children,c=0;if(b){var e=-1,f=b.length;while(++e<f)c=Math.max(c,d(b[e]))}return 1+c}function c(a,b,d,e){var f=a.children;a.x=b,a.y=a.depth*e,a.dx=d,a.dy=e;if(f){var g=-1,h=f.length,i,j;d=a.value?d/a.value:0;while(++g<h)c(i=f[g],b,j=i.value*d,e),b+=j}}var a=d3.layout.hierarchy(),b=[1,1];e.size=function(a){if(!arguments.length)return b;b=a;return e};return y(e,a)},d3.layout.pie=function(){function f(f,g){var h=+(typeof c=="function"?c.apply(this,arguments):c),i=(typeof e=="function"?e.apply(this,arguments):e)-c,j=d3.range(f.length);b!=null&&j.sort(function(a,c){return b(f[a],f[c])});var k=f.map(a);i/=k.reduce(function(a,b){return a+b},0);var l=j.map(function(a){return{data:f[a],value:d=k[a],startAngle:h,endAngle:h+=d*i}});return f.map(function(a,b){return l[j[b]]})}var a=Number,b=null,c=0,e=2*Math.PI;f.value=function(b){if(!arguments.length)return a;a=b;return f},f.sort=function(a){if(!arguments.length)return b;b=a;return f},f.startAngle=function(a){if(!arguments.length)return c;c=a;return f},f.endAngle=function(a){if(!arguments.length)return e;e=a;return f};return f},d3.layout.stack=function(){function g(h,i){var j=h.map(function(b,c){return a.call(g,b,c)}),k=j.map(function(a,b){return a.map(function(a,b){return[e.call(g,a,b),f.call(g,a,b)]})}),l=b.call(g,k,i);j=d3.permute(j,l),k=d3.permute(k,l);var m=c.call(g,k,i),n=j.length,o=j[0].length,p,q,r;for(q=0;q<o;++q){d.call(g,j[0][q],r=m[q],k[0][q][1]);for(p=1;p<n;++p)d.call(g,j[p][q],r+=k[p-1][q][1],k[p][q][1])}return h}var a=Object,b=q["default"],c=r.zero,d=p,e=n,f=o;g.values=function(b){if(!arguments.length)return a;a=b;return g},g.order=function(a){if(!arguments.length)return b;b=typeof a=="function"?a:q[a];return g},g.offset=function(a){if(!arguments.length)return c;c=typeof a=="function"?a:r[a];return g},g.x=function(a){if(!arguments.length)return e;e=a;return g},g.y=function(a){if(!arguments.length)return f;f=a;return g},g.out=function(a){if(!arguments.length)return d;d=a;return g};return g};var q={"inside-out":function(a){var b=a.length,c,d,e=a.map(s),f=a.map(t),g=d3.range(b).sort(function(a,b){return e[a]-e[b]}),h=0,i=0,j=[],k=[];for(c=0;c<b;++c)d=g[c],h<i?(h+=f[d],j.push(d)):(i+=f[d],k.push(d));return k.reverse().concat(j)},reverse:function(a){return d3.range(a.length).reverse()},"default":function(a){return d3.range(a.length)}},r={silhouette:function(a){var b=a.length,c=a[0].length,d=[],e=0,f,g,h,i=[];for(g=0;g<c;++g){for(f=0,h=0;f<b;f++)h+=a[f][g][1];h>e&&(e=h),d.push(h)}for(g=0;g<c;++g)i[g]=(e-d[g])/2;return i},wiggle:function(a){var b=a.length,c=a[0],d=c.length,e=0,f,g,h,i,j,k,l,m,n,o=[];o[0]=m=n=0;for(g=1;g<d;++g){for(f=0,i=0;f<b;++f)i+=a[f][g][1];for(f=0,j=0,l=c[g][0]-c[g-1][0];f<b;++f){for(h=0,k=(a[f][g][1]-a[f][g-1][1])/(2*l);h<f;++h)k+=(a[h][g][1]-a[h][g-1][1])/l;j+=k*a[f][g][1]}o[g]=m-=i?j/i*l:0,m<n&&(n=m)}for(g=0;g<d;++g)o[g]-=n;return o},expand:function(a){var b=a.length,c=a[0].length,d=1/b,e,f,g,h=[];for(f=0;f<c;++f){for(e=0,g=0;e<b;e++)g+=a[e][f][1];if(g)for(e=0;e<b;e++)a[e][f][1]/=g;else for(e=0;e<b;e++)a[e][f][1]=d}for(f=0;f<c;++f)h[f]=0;return h},zero:function(a){var b=-1,c=a[0].length,d=[];while(++b<c)d[b]=0;return d}};d3.layout.histogram=function(){function e(e,f){var g=[],h=e.map(b,this),i=c.call(this,h,f),j=d.call(this,i,h,f),k,f=-1,l=h.length,m=j.length-1,n=a?1:1/l,o;while(++f<m)k=g[f]=[],k.dx=j[f+1]-(k.x=j[f]),k.y=0;f=-1;while(++f<l)o=h[f],o>=i[0]&&o<=i[1]&&(k=g[d3.bisect(j,o,1,m)-1],k.y+=n,k.push(e[f]));return g}var a=!0,b=Number,c=x,d=v;e.value=function(a){if(!arguments.length)return b;b=a;return e},e.range=function(a){if(!arguments.length)return c;c=d3.functor(a);return e},e.bins=function(a){if(!arguments.length)return d;d=typeof a=="number"?function(b){return w(b,a)}:d3.functor(a);return e},e.frequency=function(b){if(!arguments.length)return a;a=!!b;return e};return e},d3.layout.hierarchy=function(){function g(a){var b=[];e(a,0,b);return b}function f(a,b){var d=a.children,e=0;if(d){var h=-1,i=d.length,j=b+1;while(++h<i)e+=f(d[h],j)}else c&&(e=+c.call(g,D?a:a.data,b)||0);c&&(a.value=e);return e}function e(f,h,i){var j=b.call(g,f,h),k=D?f:{data:f};k.depth=h,i.push(k);if(j){var l=-1,m=j.length,n=k.children=[],o=0,p=h+1;while(++l<m)d=e(j[l],p,i),d.parent=k,n.push(d),o+=d.value;a&&n.sort(a),c&&(k.value=o)}else c&&(k.value=+c.call(g,f,h)||0);return k}var a=B,b=z,c=A;g.sort=function(b){if(!arguments.length)return a;a=b;return g},g.children=function(a){if(!arguments.length)return b;b=a;return g},g.value=function(a){if(!arguments.length)return c;c=a;return g},g.revalue=function(a){f(a,0);return a};return g};var D=!1;d3.layout.pack=function(){function c(c,d){var e=a.call(this,c,d),f=e[0];f.x=0,f.y=0,L(f);var g=b[0],h=b[1],i=1/Math.max(2*f.r/g,2*f.r/h);M(f,g/2,h/2,i);return e}var a=d3.layout.hierarchy().sort(E),b=[1,1];c.size=function(a){if(!arguments.length)return b;b=a;return c};return y(c,a)},d3.layout.cluster=function(){function d(d,e){var f=a.call(this,d,e),g=f[0],h,i=0,j,k;Z(g,function(a){a.children?(a.x=P(a.children),a.y=O(a.children)):(a.x=h?i+=b(a,h):0,a.y=0,h=a)});var l=Q(g),m=R(g),n=l.x-b(l,m)/2,o=m.x+b(m,l)/2;Z(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=(1-a.y/g.y)*c[1]});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=S,c=[1,1];d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return y(d,a)},d3.layout.tree=function(){function d(d,e){function j(a,c,d){if(c){var e=a,f=a,g=c,h=a.parent.children[0],i=e._tree.mod,j=f._tree.mod,k=g._tree.mod,l=h._tree.mod,m;while(g=U(g),e=T(e),g&&e)h=T(h),f=U(f),f._tree.ancestor=a,m=g._tree.prelim+k-e._tree.prelim-i+b(g,e),m>0&&(_(ba(g,a,d),a,m),i+=m,j+=m),k+=g._tree.mod,i+=e._tree.mod,l+=h._tree.mod,j+=f._tree.mod;g&&!U(f)&&(f._tree.thread=g,f._tree.mod+=k-j),e&&!T(h)&&(h._tree.thread=e,h._tree.mod+=i-l,d=a)}return d}function i(a,b){a.x=a._tree.prelim+b;var c=a.children;if(c){var d=-1,e=c.length;b+=a._tree.mod;while(++d<e)i(c[d],b)}}function h(a,c){var d=a.children,e=a._tree;if(d&&(f=d.length)){var f,g=d[0],i,k=g,l,m=-1;while(++m<f)l=d[m],h(l,i),k=j(l,i,k),i=l;$(a);var n=.5*(g._tree.prelim+l._tree.prelim);c?(e.prelim=c._tree.prelim+b(a,c),e.mod=e.prelim-n):e.prelim=n}else c&&(e.prelim=c._tree.prelim+b(a,c))}var f=a.call(this,d,e),g=f[0];Z(g,function(a,b){a._tree={ancestor:a,prelim:0,mod:0,change:0,shift:0,number:b?b._tree.number+1:0}}),h(g),i(g,-g._tree.prelim);var k=V(g,X),l=V(g,W),m=V(g,Y),n=k.x-b(k,l)/2,o=l.x+b(l,k)/2,p=m.depth||1;Z(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=a.depth/p*c[1],delete a._tree});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=S,c=[1,1];d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return y(d,a)},d3.layout.treemap=function(){function n(b){var d=g||a(b),e=d[0];e.x=0,e.y=0,e.dx=c[0],e.dy=c[1],g&&a.revalue(e),i([e],e.dx*e.dy/e.value),(g?k:j)(e),f&&(g=d);return d}function m(a,c,d,e){var f=-1,g=a.length,h=d.x,i=d.y,j=c?b(a.area/c):0,k;if(c==d.dx){if(e||j>d.dy)j=j?d.dy:0;while(++f<g)k=a[f],k.x=h,k.y=i,k.dy=j,h+=k.dx=j?b(k.area/j):0;k.z=!0,k.dx+=d.x+d.dx-h,d.y+=j,d.dy-=j}else{if(e||j>d.dx)j=j?d.dx:0;while(++f<g)k=a[f],k.x=h,k.y=i,k.dx=j,i+=k.dy=j?b(k.area/j):0;k.z=!1,k.dy+=d.y+d.dy-i,d.x+=j,d.dx-=j}}function l(a,b){var c=a.area,d,e=0,f=Infinity,g=-1,i=a.length;while(++g<i){if(!(d=a[g].area))continue;d<f&&(f=d),d>e&&(e=d)}c*=c,b*=b;return c?Math.max(b*e*h/c,c/(b*f*h)):Infinity}function k(a){if(!!a.children){var b=e(a),c=a.children.slice(),d,f=[];i(c,b.dx*b.dy/a.value),f.area=0;while(d=c.pop())f.push(d),f.area+=d.area,d.z!=null&&(m(f,d.z?b.dx:b.dy,b,!c.length),f.length=f.area=0);a.children.forEach(k)}}function j(a){if(!!a.children){var b=e(a),c=[],d=a.children.slice(),f,g=Infinity,h,k=Math.min(b.dx,b.dy),n;i(d,b.dx*b.dy/a.value),c.area=0;while((n=d.length)>0)c.push(f=d[n-1]),c.area+=f.area,(h=l(c,k))<=g?(d.pop(),g=h):(c.area-=c.pop().area,m(c,k,b,!1),k=Math.min(b.dx,b.dy),c.length=c.area=0,g=Infinity);c.length&&(m(c,k,b,!0),c.length=c.area=0),a.children.forEach(j)}}function i(a,b){var c=-1,d=a.length,e,f;while(++c<d)f=(e=a[c]).value*(b<0?0:b),e.area=isNaN(f)||f<=0?0:f}var a=d3.layout.hierarchy(),b=Math.round,c=[1,1],d=null,e=bb,f=!1,g,h=.5*(1+Math.sqrt(5));n.size=function(a){if(!arguments.length)return c;c=a;return n},n.padding=function(a){function c(b){return bc(b,a)}function b(b){var c=a.call(n,b,b.depth);return c==null?bb(b):bc(b,typeof c=="number"?[c,c,c,c]:c)}if(!arguments.length)return d;var f;e=(d=a)==null?bb:(f=typeof a)==="function"?b:f==="number"?(a=[a,a,a,a],c):c;return n},n.round=function(a){if(!arguments.length)return b!=Number;b=a?Math.round:Number;return n},n.sticky=function(a){if(!arguments.length)return f;f=a,g=null;return n},n.ratio=function(a){if(!arguments.length)return h;h=a;return n};return y(n,a)}})() <ide>\ No newline at end of file <ide><path>src/layout/force.js <ide> d3.layout.force = function() { <ide> /* Barnes-Hut criterion. */ <ide> if ((x2 - x1) * dn < theta) { <ide> var k = kc * quad.count * dn * dn; <del> node.x += dx * k; <del> node.y += dy * k; <add> node.px -= dx * k; <add> node.py -= dy * k; <ide> return true; <ide> } <ide> <ide> if (quad.point && isFinite(dn)) { <ide> var k = kc * dn * dn; <del> node.x += dx * k; <del> node.y += dy * k; <add> node.px -= dx * k; <add> node.py -= dy * k; <ide> } <ide> } <ide> }; <ide> d3.layout.force = function() { <ide> function tick() { <ide> var n = nodes.length, <ide> m = links.length, <del> q = d3.geom.quadtree(nodes), <add> q, <ide> i, // current index <ide> o, // current object <ide> s, // current source <ide> d3.layout.force = function() { <ide> } <ide> <ide> // apply gravity forces <del> k = alpha * gravity; <del> x = size[0] / 2; <del> y = size[1] / 2; <del> i = -1; while (++i < n) { <del> o = nodes[i]; <del> o.x += (x - o.x) * k; <del> o.y += (y - o.y) * k; <add> if (k = alpha * gravity) { <add> x = size[0] / 2; <add> y = size[1] / 2; <add> i = -1; if (k) while (++i < n) { <add> o = nodes[i]; <add> o.x += (x - o.x) * k; <add> o.y += (y - o.y) * k; <add> } <ide> } <ide> <del> // compute quadtree center of mass <del> d3_layout_forceAccumulate(q); <del> <del> // apply charge forces <del> k = alpha * charge; <del> i = -1; while (++i < n) { <del> q.visit(repulse(nodes[i], k)); <add> // compute quadtree center of mass and apply charge forces <add> if (k = alpha * charge) { <add> d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes)); <add> i = -1; while (++i < n) { <add> if (!(o = nodes[i]).fixed) { <add> q.visit(repulse(o, k)); <add> } <add> } <ide> } <ide> <ide> // position verlet integration
3
Javascript
Javascript
fix casing on store import
e634777027bf8e63cffe85b1ce727895193931b5
<ide><path>shells/browser/shared/src/main.js <ide> import { createElement } from 'react'; <ide> import { unstable_createRoot as createRoot, flushSync } from 'react-dom'; <ide> import Bridge from 'src/bridge'; <del>import Store from 'src/devtools/Store'; <add>import Store from 'src/devtools/store'; <ide> import inject from './inject'; <ide> import { <ide> createViewElementSource,
1
Python
Python
fix gradient test failure
d3ab82cfafb8cd95818375f8cd5fdd7a47833e98
<ide><path>tests/keras/backend/backend_test.py <ide> def test_update_sub(self): <ide> reason='cntk doesn\'t support gradient in this way.') <ide> def test_gradient(self): <ide> val = np.random.random((4, 2)) <del> x_list = [k.variable(val) for k in [KTH, KTF]] <add> x_list = [k.placeholder(shape=(4, 2)) for k in [KTH, KTF]] <ide> z_list = [] <ide> zero_list = [] <ide> for x, k in zip(x_list, [KTH, KTF]): <ide> exp = x * k.exp(x) <ide> loss = k.sum(exp) <ide> zero_loss = k.stop_gradient(loss) <ide> grad = k.gradients(loss, [exp]) <add> <ide> zero_grad = k.gradients(loss + zero_loss, [exp]) <del> z_list.append(k.eval(grad[0])) <del> zero_list.append(k.eval(zero_grad[0])) <add> grad_eval_fn = k.function([x], [grad[0]]) <add> zero_grad_eval_fn = k.function([x], [zero_grad[0]]) <add> z_list.append(grad_eval_fn([val])[0]) <add> zero_list.append(zero_grad_eval_fn([val])[0]) <ide> <ide> assert_list_pairwise(z_list) <ide> assert_list_pairwise(zero_list)
1
PHP
PHP
fix cs error
7cf3fc12e8ce33fe6bc86dd51c478cab4850b808
<ide><path>src/Error/Middleware/ErrorHandlerMiddleware.php <ide> public function __construct($exceptionRenderer = null, array $config = []) <ide> * <ide> * @param \Psr\Http\Message\ServerRequestInterface $request The request. <ide> * @param \Psr\Http\Server\RequestHandlerInterface $handler The request handler. <del> * @return \Cake\Http\ResponseInterface A response. <add> * @return \Psr\Http\Message\ResponseInterface A response. <ide> */ <ide> public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface <ide> { <ide><path>src/Http/Middleware/BodyParserMiddleware.php <ide> public function addParser(array $types, callable $parser): self <ide> * <ide> * @param \Psr\Http\Message\ServerRequestInterface $request The request. <ide> * @param \Psr\Http\Server\RequestHandlerInterface $handler The request handler. <del> * @return \Cake\Http\ResponseInterface A response. <add> * @return \Psr\Http\Message\ResponseInterface A response. <ide> */ <ide> public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface <ide> { <ide><path>src/Http/Middleware/CsrfProtectionMiddleware.php <ide> public function __construct(array $config = []) <ide> * <ide> * @param \Psr\Http\Message\ServerRequestInterface $request The request. <ide> * @param \Psr\Http\Server\RequestHandlerInterface $handler The request handler. <del> * @return \Cake\Http\ResponseInterface A response. <add> * @return \Psr\Http\Message\ResponseInterface A response. <ide> */ <ide> public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface <ide> { <ide><path>src/Http/Middleware/EncryptedCookieMiddleware.php <ide> public function __construct(array $cookieNames, string $key, string $cipherType <ide> * <ide> * @param \Psr\Http\Message\ServerRequestInterface $request The request. <ide> * @param \Psr\Http\Server\RequestHandlerInterface $handler The request handler. <del> * @return \Cake\Http\ResponseInterface A response. <add> * @return \Psr\Http\Message\ResponseInterface A response. <ide> */ <ide> public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface <ide> { <ide><path>src/Http/Middleware/SecurityHeadersMiddleware.php <ide> protected function checkValues(string $value, array $allowed): void <ide> * <ide> * @param \Psr\Http\Message\ServerRequestInterface $request The request. <ide> * @param \Psr\Http\Server\RequestHandlerInterface $handler The request handler. <del> * @return \Cake\Http\ResponseInterface A response. <add> * @return \Psr\Http\Message\ResponseInterface A response. <ide> */ <ide> public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface <ide> { <ide><path>src/Http/Runner.php <ide> class Runner implements RequestHandlerInterface <ide> protected $queue; <ide> <ide> /** <del> * Response prototype to return if queue is exhausted without receiving response. <add> * Fallback handler to use if middleware queue does not generate response. <ide> * <del> * @var \Psr\Http\Message\ResponseInterface <add> * @var \Psr\Http\Server\RequestHandlerInterface|null <ide> */ <del> protected $responsePrototype; <add> protected $fallbackHandler; <ide> <ide> /** <ide> * @param \Cake\Http\MiddlewareQueue $queue The middleware queue <ide> * @param \Psr\Http\Message\ServerRequestInterface $request The Server Request <del> * @param \Psr\Http\Message\RequestHandlerInterface $fallbackHandler Fallback request handler. <add> * @param \Psr\Http\Server\RequestHandlerInterface $fallbackHandler Fallback request handler. <ide> * @return \Psr\Http\Message\ResponseInterface A response object <ide> */ <ide> public function run( <ide><path>src/I18n/Middleware/LocaleSelectorMiddleware.php <ide> public function __construct(array $locales = []) <ide> * <ide> * @param \Psr\Http\Message\ServerRequestInterface $request The request. <ide> * @param \Psr\Http\Server\RequestHandlerInterface $handler The request handler. <del> * @return \Cake\Http\ResponseInterface A response. <add> * @return \Psr\Http\Message\ResponseInterface A response. <ide> */ <ide> public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface <ide> { <ide><path>src/Routing/Middleware/RoutingMiddleware.php <ide> use Cake\Cache\Cache; <ide> use Cake\Core\HttpApplicationInterface; <ide> use Cake\Core\PluginApplicationInterface; <del>use Cake\Http\Middleware\CallableDecoratorMiddleware; <ide> use Cake\Http\MiddlewareQueue; <ide> use Cake\Http\Runner; <ide> use Cake\Routing\Exception\RedirectException; <ide> protected function prepareRouteCollection(): RouteCollection <ide> * <ide> * @param \Psr\Http\Message\ServerRequestInterface $request The request. <ide> * @param \Psr\Http\Server\RequestHandlerInterface $handler The request handler. <del> * @return \Cake\Http\ResponseInterface A response. <add> * @return \Psr\Http\Message\ResponseInterface A response. <ide> */ <ide> public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface <ide> { <ide><path>tests/TestCase/Http/BaseApplicationTest.php <ide> use Cake\Core\Configure; <ide> use Cake\Http\BaseApplication; <ide> use Cake\Http\MiddlewareQueue; <del>use Cake\Http\Runner; <ide> use Cake\Http\ServerRequestFactory; <ide> use Cake\Routing\RouteBuilder; <ide> use Cake\Routing\RouteCollection; <ide><path>tests/TestCase/I18n/Middleware/LocaleSelectorMiddlewareTest.php <ide> use Cake\TestSuite\TestCase; <ide> use Locale; <ide> use TestApp\Http\TestRequestHandler; <del>use Zend\Diactoros\Response; <ide> use Zend\Diactoros\ServerRequestFactory; <ide> <ide> /**
10
Javascript
Javascript
normalize indentation on applymiddleware.spec.js
486413e428f0aa99728895ab8b175e565f8ae2df
<ide><path>test/applyMiddleware.spec.js <ide> describe('applyMiddleware', () => { <ide> }) <ide> }) <ide> <del> it('passes through all arguments of dispatch calls from within middleware', () => { <del> const spy = jest.fn() <del> const testCallArgs = ['test'] <del> function multiArgMiddleware() { <del> return next => (action, callArgs) => { <del> if (Array.isArray(callArgs)) { <del> return action(...callArgs) <del> } <del> return next(action) <del> } <del> } <del> function dummyMiddleware({ dispatch }) { <del> return next => action => dispatch(action, testCallArgs) <add> it('passes through all arguments of dispatch calls from within middleware', () => { <add> const spy = jest.fn() <add> const testCallArgs = ['test'] <add> function multiArgMiddleware() { <add> return next => (action, callArgs) => { <add> if (Array.isArray(callArgs)) { <add> return action(...callArgs) <add> } <add> return next(action) <ide> } <add> } <add> function dummyMiddleware({ dispatch }) { <add> return next => action => dispatch(action, testCallArgs) <add> } <ide> <del> const store = createStore(reducers.todos, applyMiddleware(multiArgMiddleware, dummyMiddleware)) <del> store.dispatch(spy) <del> expect(spy.mock.calls[0]).toEqual(testCallArgs) <del> }) <add> const store = createStore(reducers.todos, applyMiddleware(multiArgMiddleware, dummyMiddleware)) <add> store.dispatch(spy) <add> expect(spy.mock.calls[0]).toEqual(testCallArgs) <add> }) <ide> <ide> it('keeps unwrapped dispatch available while middleware is initializing', () => { <ide> // This is documenting the existing behavior in Redux 3.x.
1
Ruby
Ruby
check conflict names
a0d53f7bc1c78a5425e1fc53bb82fa5f1a0061d8
<ide><path>Library/Homebrew/cmd/audit.rb <ide> def audit_deps <ide> end <ide> end <ide> <add> def audit_conflicts <add> f.conflicts.each do |req| <add> begin <add> conflict_f = Formula.factory req.formula <add> rescue <add> problem "Can't find conflicting formula \"#{req.formula}\"." <add> end <add> end <add> end <ide> <ide> def audit_urls <ide> unless f.homepage =~ %r[^https?://] <ide> def audit <ide> audit_specs <ide> audit_urls <ide> audit_deps <add> audit_conflicts <ide> audit_patches <ide> audit_text <ide> end
1
Java
Java
add jsonp support to mappingjackson2jsonview
5dc27ee134d28c7b25d0f6d3e9059f80c95d4402
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/json/MappingJackson2JsonView.java <ide> import java.io.ByteArrayOutputStream; <ide> import java.io.IOException; <ide> import java.io.OutputStream; <del>import java.util.Collections; <del>import java.util.HashMap; <del>import java.util.Map; <del>import java.util.Set; <add>import java.util.*; <ide> import javax.servlet.http.HttpServletRequest; <ide> import javax.servlet.http.HttpServletResponse; <ide> <ide> import com.fasterxml.jackson.databind.ObjectMapper; <ide> import com.fasterxml.jackson.databind.SerializationFeature; <ide> <add>import org.springframework.http.converter.json.MappingJacksonValue; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.CollectionUtils; <ide> import org.springframework.validation.BindingResult; <ide> * @author Arjen Poutsma <ide> * @author Rossen Stoyanchev <ide> * @author Juergen Hoeller <add> * @author Sebastien Deleuze <ide> * @since 3.1.2 <ide> */ <ide> public class MappingJackson2JsonView extends AbstractView { <ide> public class MappingJackson2JsonView extends AbstractView { <ide> */ <ide> public static final String DEFAULT_CONTENT_TYPE = "application/json"; <ide> <add> public static final String DEFAULT_JSONP_CONTENT_TYPE = "application/javascript"; <add> <add> public static final String[] DEFAULT_JSONP_PARAMETER_NAMES = {"jsonp", "callback"}; <add> <ide> <ide> private ObjectMapper objectMapper = new ObjectMapper(); <ide> <ide> public class MappingJackson2JsonView extends AbstractView { <ide> <ide> private boolean updateContentLength = false; <ide> <add> private String[] jsonpParameterNames; <add> <ide> <ide> /** <ide> * Construct a new {@code MappingJackson2JsonView}, setting the content type to {@code application/json}. <ide> */ <ide> public MappingJackson2JsonView() { <ide> setContentType(DEFAULT_CONTENT_TYPE); <ide> setExposePathVariables(false); <add> this.jsonpParameterNames = DEFAULT_JSONP_PARAMETER_NAMES; <ide> } <ide> <ide> <ide> public void setUpdateContentLength(boolean updateContentLength) { <ide> this.updateContentLength = updateContentLength; <ide> } <ide> <add> /** <add> * Set the names of the request parameters recognized as JSONP ones. <add> * Each time a request has one of those parameters, the resulting JSON will <add> * be wrapped into a function named as specified by the JSONP parameter value. <add> * <add> * Default JSONP parameter names are "jsonp" and "callback". <add> * <add> * @since 4.1 <add> * @see <a href="http://en.wikipedia.org/wiki/JSONP">JSONP Wikipedia article</a> <add> */ <add> public void setJsonpParameterNames(Collection<String> jsonpParameterNames) { <add> Assert.isTrue(!CollectionUtils.isEmpty(jsonpParameterNames), "At least one JSONP query parameter name is required"); <add> this.jsonpParameterNames = jsonpParameterNames.toArray(new String[jsonpParameterNames.size()]); <add> } <ide> <ide> @Override <ide> protected void prepareResponse(HttpServletRequest request, HttpServletResponse response) { <ide> protected void prepareResponse(HttpServletRequest request, HttpServletResponse r <ide> } <ide> } <ide> <add> @Override <add> protected void setResponseContentType(HttpServletRequest request, HttpServletResponse response) { <add> if (getJsonpParameterValue(request) != null) { <add> response.setContentType(DEFAULT_JSONP_CONTENT_TYPE); <add> } <add> else { <add> super.setResponseContentType(request, response); <add> } <add> } <add> <ide> @Override <ide> protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, <ide> HttpServletResponse response) throws Exception { <ide> <ide> OutputStream stream = (this.updateContentLength ? createTemporaryOutputStream() : response.getOutputStream()); <add> <add> Class<?> serializationView = (Class<?>)model.get(JsonView.class.getName()); <add> String jsonpParameterValue = getJsonpParameterValue(request); <ide> Object value = filterModel(model); <del> if (model.containsKey(JsonView.class.getName())) { <del> writeContent(stream, value, this.jsonPrefix, model); <del> } <del> else { <del> writeContent(stream, value, this.jsonPrefix); <add> if(serializationView != null || jsonpParameterValue != null) { <add> MappingJacksonValue container = new MappingJacksonValue(value); <add> container.setSerializationView(serializationView); <add> container.setJsonpFunction(jsonpParameterValue); <add> value = container; <ide> } <add> <add> writeContent(stream, value, this.jsonPrefix); <ide> if (this.updateContentLength) { <ide> writeToResponse(response, (ByteArrayOutputStream) stream); <ide> } <ide> } <ide> <add> private String getJsonpParameterValue(HttpServletRequest request) { <add> String jsonpParameterValue = null; <add> for(String jsonpParameterName : this.jsonpParameterNames) { <add> jsonpParameterValue = request.getParameter(jsonpParameterName); <add> if(jsonpParameterValue != null) { <add> break; <add> } <add> } <add> return jsonpParameterValue; <add> } <add> <ide> /** <ide> * Filter out undesired attributes from the given model. <ide> * The return value can be either another {@link Map} or a single value object. <ide> protected Object filterModel(Map<String, Object> model) { <ide> Map<String, Object> result = new HashMap<String, Object>(model.size()); <ide> Set<String> renderedAttributes = (!CollectionUtils.isEmpty(this.modelKeys) ? this.modelKeys : model.keySet()); <ide> for (Map.Entry<String, Object> entry : model.entrySet()) { <del> if (!(entry.getValue() instanceof BindingResult) && renderedAttributes.contains(entry.getKey())) { <add> if (!(entry.getValue() instanceof BindingResult) <add> && renderedAttributes.contains(entry.getKey()) <add> && !entry.getKey().equals(JsonView.class.getName())) { <ide> result.put(entry.getKey(), entry.getValue()); <ide> } <ide> } <ide> protected Object filterModel(Map<String, Object> model) { <ide> * (as indicated through {@link #setJsonPrefix}/{@link #setPrefixJson}) <ide> * @throws IOException if writing failed <ide> */ <del> protected void writeContent(OutputStream stream, Object value, String jsonPrefix) throws IOException { <del> writeContent(stream, value, jsonPrefix, Collections.<String, Object>emptyMap()); <del> } <del> <del> protected void writeContent(OutputStream stream, Object value, String jsonPrefix, Map<String, Object> model) <add> protected void writeContent(OutputStream stream, Object value, String jsonPrefix) <ide> throws IOException { <ide> <ide> // The following has been deprecated as late as Jackson 2.2 (April 2013); <ide> protected void writeContent(OutputStream stream, Object value, String jsonPrefix <ide> if (jsonPrefix != null) { <ide> generator.writeRaw(jsonPrefix); <ide> } <del> <del> Class<?> serializationView = (Class<?>) model.get(JsonView.class.getName()); <add> Class<?> serializationView = null; <add> String jsonpFunction = null; <add> if (value instanceof MappingJacksonValue) { <add> MappingJacksonValue container = (MappingJacksonValue) value; <add> value = container.getValue(); <add> serializationView = container.getSerializationView(); <add> jsonpFunction = container.getJsonpFunction(); <add> } <add> if (jsonpFunction != null) { <add> generator.writeRaw(jsonpFunction + "(" ); <add> } <ide> if (serializationView != null) { <ide> this.objectMapper.writerWithView(serializationView).writeValue(generator, value); <ide> } <ide> else { <ide> this.objectMapper.writeValue(generator, value); <ide> } <add> if (jsonpFunction != null) { <add> generator.writeRaw(");"); <add> generator.flush(); <add> } <ide> } <ide> <ide> } <ide>\ No newline at end of file <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/view/json/MappingJackson2JsonViewTests.java <ide> package org.springframework.web.servlet.view.json; <ide> <ide> import java.io.IOException; <del>import java.util.Date; <del>import java.util.HashMap; <del>import java.util.HashSet; <del>import java.util.Map; <del>import java.util.Set; <add>import java.util.*; <ide> <ide> import com.fasterxml.jackson.annotation.JsonView; <ide> import org.junit.Before; <ide> * @author Jeremy Grelle <ide> * @author Arjen Poutsma <ide> * @author Rossen Stoyanchev <add> * @author Sebastien Deleuze <ide> */ <ide> public class MappingJackson2JsonViewTests { <ide> <ide> public void renderSimpleBeanWithJsonView() throws Exception { <ide> assertTrue(content.length() > 0); <ide> assertEquals(content.length(), response.getContentLength()); <ide> assertTrue(content.contains("foo")); <del> assertFalse(content.contains("42")); <add> assertFalse(content.contains("boo")); <add> assertFalse(content.contains(JsonView.class.getName())); <add> } <add> <add> @Test <add> public void renderWithJsonpDefaultParameterName() throws Exception { <add> Map<String, Object> model = new HashMap<String, Object>(); <add> model.put("foo", "bar"); <add> request.addParameter("otherparam", "value"); <add> request.addParameter("jsonp", "jsonpCallback"); <add> <add> view.render(model, request, response); <add> <add> String content = response.getContentAsString(); <add> assertEquals("jsonpCallback({\"foo\":\"bar\"});", content); <add> } <add> <add> @Test <add> public void renderWithCallbackDefaultParameterName() throws Exception { <add> Map<String, Object> model = new HashMap<String, Object>(); <add> model.put("foo", "bar"); <add> request.addParameter("otherparam", "value"); <add> request.addParameter("callback", "jsonpCallback"); <add> <add> view.render(model, request, response); <add> <add> String content = response.getContentAsString(); <add> assertEquals("jsonpCallback({\"foo\":\"bar\"});", content); <add> } <add> <add> @Test <add> public void renderWithCustomJsonpParameterName() throws Exception { <add> Map<String, Object> model = new HashMap<String, Object>(); <add> model.put("foo", "bar"); <add> request.addParameter("otherparam", "value"); <add> request.addParameter("custom", "jsonpCallback"); <add> view.setJsonpParameterNames(Arrays.asList("jsonp", "callback", "custom")); <add> <add> view.render(model, request, response); <add> <add> String content = response.getContentAsString(); <add> assertEquals("jsonpCallback({\"foo\":\"bar\"});", content); <ide> } <ide> <ide> private void validateResult() throws Exception { <ide> public interface MyJacksonView2 {}; <ide> public static class TestBeanSimple { <ide> <ide> @JsonView(MyJacksonView1.class) <del> private String value = "foo"; <add> private String property1 = "foo"; <ide> <ide> private boolean test = false; <ide> <ide> @JsonView(MyJacksonView2.class) <del> private long number = 42; <add> private String property2 = "boo"; <ide> <ide> private TestChildBean child = new TestChildBean(); <ide> <del> public String getValue() { <del> return value; <add> public String getProperty1() { <add> return property1; <ide> } <ide> <ide> public boolean getTest() { <ide> return test; <ide> } <ide> <del> public long getNumber() { <del> return number; <add> public String getProperty2() { <add> return property2; <ide> } <ide> <ide> public Date getNow() {
2
Ruby
Ruby
ignore `homebrew_no_github_api` when testing
845cb99e29b7f37573eb9e499b1aed16ee6e7149
<ide><path>Library/Homebrew/dev-cmd/tests.rb <ide> def tests <ide> ENV.delete("HOMEBREW_CASK_OPTS") <ide> ENV.delete("HOMEBREW_TEMP") <ide> ENV.delete("HOMEBREW_LINKAGE_CACHE") <add> ENV.delete("HOMEBREW_NO_GITHUB_API") <ide> ENV["HOMEBREW_NO_ANALYTICS_THIS_RUN"] = "1" <ide> ENV["HOMEBREW_DEVELOPER"] = "1" <ide> ENV["HOMEBREW_NO_COMPAT"] = "1" if args.no_compat? <ide> ENV["HOMEBREW_TEST_GENERIC_OS"] = "1" if args.generic? <del> <del> if args.online? <del> ENV["HOMEBREW_TEST_ONLINE"] = "1" <del> else <del> ENV["HOMEBREW_NO_GITHUB_API"] = "1" <del> end <add> ENV["HOMEBREW_TEST_ONLINE"] = "1" if args.online? <ide> <ide> if args.coverage? <ide> ENV["HOMEBREW_TESTS_COVERAGE"] = "1" <ide><path>Library/Homebrew/test/cask/cli/search_spec.rb <ide> describe Hbc::CLI::Search, :cask do <ide> before do <ide> allow(Tty).to receive(:width).and_return(0) <del> ENV.delete("HOMEBREW_NO_GITHUB_API") <ide> end <ide> <ide> it_behaves_like "a command that handles invalid options"
2
Javascript
Javascript
fix proxy bugs
5c4ca4ccc4ae33bfa9e06c2fd62f6d23b2fe6b66
<ide><path>lib/adapters/http.js <ide> module.exports = function httpAdapter(config) { <ide> <ide> if (proxy) { <ide> options.host = proxy.host; <add> options.hostname = proxy.host; <add> options.headers.host = parsed.hostname; <ide> options.port = proxy.port; <ide> options.path = parsed.protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path; <ide> }
1
Python
Python
fix example of models.py method fit_generator()
858e3a8a84ba17dd607fbaad61f64ce1f588af8b
<ide><path>keras/models.py <ide> def generate_arrays_from_file(path): <ide> # and labels, from each line in the file <ide> x, y = process_line(line) <ide> yield (x, y) <del> f.close() <add> f.close() <ide> <ide> model.fit_generator(generate_arrays_from_file('/my_file.txt'), <ide> steps_per_epoch=1000, epochs=10)
1
Python
Python
fix character type in loading weights.
a18f9f57559c6e91c8f22abd7e05dbcc5603ca24
<ide><path>keras/engine/topology.py <ide> def load_weights_from_hdf5_group(f, layers): <ide> and weights file. <ide> """ <ide> if 'keras_version' in f.attrs: <del> original_keras_version = f.attrs['keras_version'] <add> original_keras_version = f.attrs['keras_version'].decode('utf8') <ide> else: <ide> original_keras_version = '1' <ide> if 'backend' in f.attrs: <del> original_backend = f.attrs['backend'] <add> original_backend = f.attrs['backend'].decode('utf8') <ide> else: <ide> original_backend = None <ide> <ide> def load_weights_from_hdf5_group_by_name(f, layers): <ide> and weights file. <ide> """ <ide> if 'keras_version' in f.attrs: <del> original_keras_version = f.attrs['keras_version'] <add> original_keras_version = f.attrs['keras_version'].decode('utf8') <ide> else: <ide> original_keras_version = '1' <ide> if 'backend' in f.attrs: <del> original_backend = f.attrs['backend'] <add> original_backend = f.attrs['backend'].decode('utf8') <ide> else: <ide> original_backend = None <ide>
1
Python
Python
fix wrong assert
d2ae41529c2319e1b67f05464b7e543cfb2adc2c
<ide><path>tests/test_relations_slug.py <ide> def test_foreign_key_update_with_invalid_null(self): <ide> data = {'id': 1, 'name': 'source-1', 'target': None} <ide> instance = ForeignKeySource.objects.get(pk=1) <ide> serializer = ForeignKeySourceSerializer(instance, data=data) <del> assert serializer.is_valid() <add> assert not serializer.is_valid() <ide> assert serializer.errors == {'target': ['This field may not be null.']} <ide> <ide>
1
Ruby
Ruby
move abstract stuff to autoload
72b365ece9322b323203ef423aef4554b1b27bbc
<ide><path>actionpack/lib/action_controller/abstract.rb <add>module AbstractController <add> autoload :Base, "action_controller/abstract/base" <add> autoload :Callbacks, "action_controller/abstract/callbacks" <add> autoload :Helpers, "action_controller/abstract/helpers" <add> autoload :Layouts, "action_controller/abstract/layouts" <add> autoload :Logger, "action_controller/abstract/logger" <add> autoload :Renderer, "action_controller/abstract/renderer" <add>end <ide>\ No newline at end of file <ide><path>actionpack/test/abstract_controller/test_helper.rb <ide> # Debugging disabled. `gem install ruby-debug` to enable. <ide> end <ide> <del>require 'action_controller/abstract/base' <del>require 'action_controller/abstract/renderer' <del>require 'action_controller/abstract/layouts' <del>require 'action_controller/abstract/callbacks' <del>require 'action_controller/abstract/helpers' <ide>\ No newline at end of file <add>require 'action_controller/abstract' <add># require 'action_controller/abstract/base' <add># require 'action_controller/abstract/renderer' <add># require 'action_controller/abstract/layouts' <add># require 'action_controller/abstract/callbacks' <add># require 'action_controller/abstract/helpers' <ide>\ No newline at end of file
2
Javascript
Javascript
add missing ngchange directive for email type
041f118b01933fa07098f1333be8e2cf1a28f248
<ide><path>src/ng/directive/input.js <ide> var inputType = { <ide> * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the <ide> * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for <ide> * patterns defined as scope expressions. <add> * @param {string=} ngChange Angular expression to be executed when input changes due to user <add> * interaction with the input element. <ide> * <ide> * @example <ide> <doc:example>
1
Javascript
Javascript
dispatch an event on sandbox creation
4ae9064d60551e4911134c0e2eff5df23f927bca
<ide><path>web/app.js <ide> const PDFViewerApplication = { <ide> URL: this.url, <ide> }, <ide> }); <add> <add> if (this.externalServices.isInAutomation) { <add> this.eventBus.dispatch("sandboxcreated", { <add> source: this, <add> }); <add> } <ide> } catch (error) { <ide> console.error(error); <ide> this._destroyScriptingInstance();
1
Ruby
Ruby
remove code related to the rails test command
47a9eea04ab88ef262119c56812e61b069a45e41
<ide><path>railties/lib/rails/commands.rb <ide> "d" => "destroy", <ide> "c" => "console", <ide> "s" => "server", <del> "t" => "test", <ide> "db" => "dbconsole", <ide> "r" => "runner" <ide> } <ide> generate Generate new code (short-cut alias: "g") <ide> console Start the Rails console (short-cut alias: "c") <ide> server Start the Rails server (short-cut alias: "s") <del> test Running the test file (short-cut alias: "t") <ide> dbconsole Start a console for the database specified in config/database.yml <ide> (short-cut alias: "db") <ide> new Create a new Rails application. "rails new my_app" creates a
1
Text
Text
add drf-schema-adapter to 3rd party metadata mods
f1cbf51b43005724a26e15e8c2235dd9622b0b33
<ide><path>docs/api-guide/metadata.md <ide> Then configure your settings to use this custom class: <ide> 'DEFAULT_METADATA_CLASS': 'myproject.apps.core.MinimalMetadata' <ide> } <ide> <add># Third party packages <add> <add>The following third party packages provide additional metadata implementations. <add> <add>## DRF-schema-adapter <add> <add>[drf-schema-adapter][drf-schema-adapter] is a set of tools that makes it easier to provide schema information to frontend frameworks and libraries. It provides a metadata mixin as well as 2 metadata classes and several adapters suitable to generate [json-schema][json-schema] as well as schema information readable by various libraries. <add> <add>You can also write your own adapter to work with your specific frontend. <add>If you whish to do so, it also provides an exporter that can export those schema information to json files. <add> <ide> [cite]: http://tools.ietf.org/html/rfc7231#section-4.3.7 <ide> [no-options]: https://www.mnot.net/blog/2012/10/29/NO_OPTIONS <ide> [json-schema]: http://json-schema.org/ <add>[drf-schema-adapter]: https://github.com/drf-forms/drf-schema-adapter
1
Text
Text
add link to comparison with other frameworks.
d534f00a657c2c4fbeb528b12fa9cd5fd0ff6c5c
<ide><path>guide/english/vue/index.md <ide> Its main attributes are the following: <ide> * It's versatile: you can use it as a simple library or a fully featured framework <ide> * It's performant: it's extremely performant out of the box with very little to almost no optimization required. <ide> <del>### More Information <add>#### More Information <ide> <ide> - [Vue.js Homepage](https://vuejs.org/) <ide> - [GitHub Repo](https://github.com/vuejs/vue/) <ide> - [Vue-cli](https://cli.vuejs.org/) - standard tooling <ide> - [Vue-Router](https://router.vuejs.org/) - officially-supported vue-router library <ide> - [Vuex](https://vuex.vuejs.org/) - state management pattern + library <add>- [Comparison with other frameworks](https://vuejs.org/v2/guide/comparison.html) <add>
1
Python
Python
add workaround in setup.py for newer setuptools
bf148bf9cd1e5cde05353bfdbe11124523555f5c
<ide><path>setup.py <ide> def setup_package(): <ide> else: <ide> #from numpy.distutils.core import setup <ide> from setuptools import setup <add> # workaround for broken --no-build-isolation with newer setuptools, see gh-21288 <add> metadata["packages"] = [] <ide> <ide> try: <ide> setup(**metadata)
1
Ruby
Ruby
move search#search_casks out of extend/os
ba664fa1b4c8f13284c8e5517ec278d456c58bf3
<ide><path>Library/Homebrew/search.rb <ide> def search_formulae(string_or_regex) <ide> end.compact <ide> end <ide> <del> def search_casks(_string_or_regex) <del> [] <add> def search_casks(string_or_regex) <add> if string_or_regex.is_a?(String) && string_or_regex.match?(HOMEBREW_TAP_CASK_REGEX) <add> return begin <add> [Cask::CaskLoader.load(string_or_regex).token] <add> rescue Cask::CaskUnavailableError <add> [] <add> end <add> end <add> <add> cask_tokens = Tap.flat_map(&:cask_tokens).map do |c| <add> c.sub(%r{^homebrew/cask.*/}, "") <add> end <add> <add> results = cask_tokens.extend(Searchable) <add> .search(string_or_regex) <add> <add> results += DidYouMean::SpellChecker.new(dictionary: cask_tokens) <add> .correct(string_or_regex) <add> <add> results.sort.map do |name| <add> cask = Cask::CaskLoader.load(name) <add> if cask.installed? <add> pretty_installed(cask.full_name) <add> else <add> cask.full_name <add> end <add> end.uniq <ide> end <ide> <ide> def search_names(query, string_or_regex, args)
1
Go
Go
remove linux specific calls
3dfc910d7774d57c533b067fbe59d6b24dd803cd
<ide><path>archive/archive.go <ide> import ( <ide> "bytes" <ide> "compress/bzip2" <ide> "compress/gzip" <add> "errors" <ide> "fmt" <ide> "github.com/dotcloud/docker/utils" <ide> "io" <ide> import ( <ide> "syscall" <ide> ) <ide> <del>type Archive io.Reader <del> <del>type Compression int <add>type ( <add> Archive io.Reader <add> Compression int <add> TarOptions struct { <add> Includes []string <add> Compression Compression <add> } <add>) <ide> <del>type TarOptions struct { <del> Includes []string <del> Compression Compression <del>} <add>var ( <add> ErrNotImplemented = errors.New("Function not implemented") <add>) <ide> <ide> const ( <ide> Uncompressed Compression = iota <ide> func createTarFile(path, extractDir string, hdr *tar.Header, reader *tar.Reader) <ide> return fmt.Errorf("Unhandled tar header type %d\n", hdr.Typeflag) <ide> } <ide> <del> if err := syscall.Lchown(path, hdr.Uid, hdr.Gid); err != nil { <add> if err := os.Lchown(path, hdr.Uid, hdr.Gid); err != nil { <ide> return err <ide> } <ide> <ide> // There is no LChmod, so ignore mode for symlink. Also, this <ide> // must happen after chown, as that can modify the file mode <ide> if hdr.Typeflag != tar.TypeSymlink { <del> if err := syscall.Chmod(path, uint32(hdr.Mode&07777)); err != nil { <add> if err := os.Chmod(path, os.FileMode(hdr.Mode&07777)); err != nil { <ide> return err <ide> } <ide> } <ide> <ide> ts := []syscall.Timespec{timeToTimespec(hdr.AccessTime), timeToTimespec(hdr.ModTime)} <ide> // syscall.UtimesNano doesn't support a NOFOLLOW flag atm, and <ide> if hdr.Typeflag != tar.TypeSymlink { <del> if err := syscall.UtimesNano(path, ts); err != nil { <add> if err := UtimesNano(path, ts); err != nil { <ide> return err <ide> } <ide> } else { <ide><path>archive/stat_linux.go <ide> func LUtimesNano(path string, ts []syscall.Timespec) error { <ide> <ide> return nil <ide> } <add> <add>func UtimesNano(path string, ts []syscall.Timespec) error { <add> if err := syscall.UtimesNano(path, ts); err != nil { <add> return err <add> } <add> return nil <add>} <add><path>archive/stat_unsupported.go <del><path>archive/stat_darwin.go <del>// +build !linux !amd64 <add>// +build !linux <ide> <ide> package archive <ide> <ide> func getLastModification(stat *syscall.Stat_t) syscall.Timespec { <ide> } <ide> <ide> func LUtimesNano(path string, ts []syscall.Timespec) error { <del> return nil <add> return ErrNotImplemented <add>} <add> <add>func UtimesNano(path string, ts []syscall.Timespec) error { <add> return ErrNotImplemented <ide> }
3
Javascript
Javascript
remove revision in renderers of examples
6d2c2147dd6df44ad795b4a0742efdcaae672b2a
<ide><path>examples/js/renderers/CSS2DRenderer.js <ide> THREE.CSS2DObject.prototype.constructor = THREE.CSS2DObject; <ide> <ide> THREE.CSS2DRenderer = function () { <ide> <del> console.log( 'THREE.CSS2DRenderer', THREE.REVISION ); <del> <ide> var _width, _height; <ide> var _widthHalf, _heightHalf; <ide> <ide><path>examples/js/renderers/CSS3DRenderer.js <ide> THREE.CSS3DSprite.prototype.constructor = THREE.CSS3DSprite; <ide> <ide> THREE.CSS3DRenderer = function () { <ide> <del> console.log( 'THREE.CSS3DRenderer', THREE.REVISION ); <del> <ide> var _width, _height; <ide> var _widthHalf, _heightHalf; <ide> <ide><path>examples/js/renderers/RaytracingRenderer.js <ide> <ide> THREE.RaytracingRenderer = function ( parameters ) { <ide> <del> console.log( 'THREE.RaytracingRenderer', THREE.REVISION ); <del> <ide> parameters = parameters || {}; <ide> <ide> var scope = this; <ide><path>examples/js/renderers/RaytracingWorker.js <ide> self.onmessage = function ( e ) { <ide> <ide> THREE.RaytracingRendererWorker = function () { <ide> <del> console.log( 'THREE.RaytracingRendererWorker', THREE.REVISION ); <del> <ide> var maxRecursionDepth = 3; <ide> <ide> var canvasWidth, canvasHeight; <ide><path>examples/js/renderers/SVGRenderer.js <ide> THREE.SVGObject.prototype.constructor = THREE.SVGObject; <ide> <ide> THREE.SVGRenderer = function () { <ide> <del> console.log( 'THREE.SVGRenderer', THREE.REVISION ); <del> <ide> var _this = this, <ide> _renderData, _elements, _lights, <ide> _projector = new THREE.Projector(), <ide><path>examples/js/renderers/SoftwareRenderer.js <ide> <ide> THREE.SoftwareRenderer = function ( parameters ) { <ide> <del> console.log( 'THREE.SoftwareRenderer', THREE.REVISION ); <del> <ide> parameters = parameters || {}; <ide> <ide> var canvas = parameters.canvas !== undefined
6
Javascript
Javascript
update the title on bonfire.js
b1f22ef925de68f1cb8e2470a121f7eb704f8035
<ide><path>controllers/bonfire.js <ide> debug = require('debug')('freecc:cntr:bonfires'); <ide> */ <ide> exports.index = function(req, res) { <ide> res.render('bonfire/bonfire.jade', { <del> title: 'Learn to code with Bonfire - Free Code Camp' <add> title: 'Learn to code with Bonfire' <ide> }); <ide> //Bonfire.find({}, null, { sort: { bonfireNumber: 1 } }, function(err, c) { <ide> // if (err) {
1
Python
Python
remove debug code
0d7dd3df7f18974882ff4f4f16c4b9009a61f1b4
<ide><path>glances/processes.py <ide> def update(self): <ide> # User filter <ide> not (self._filter.is_filtered(p.info))] <ide> <del> # !!! TODO: Remove <del> self.processlist[0]['cpu_percent'] = None <del> # !!! /TODO <del> <del> <ide> # Sort the processes list by the current sort_key <ide> self.processlist = sort_stats(self.processlist, <ide> sortedby=self.sort_key,
1
Python
Python
add more assertions
af89afc658fc5156766ea55f95dab07f304e2312
<ide><path>libcloud/test/compute/test_ec2.py <ide> def test_regions_and_signature_versions(self): <ide> self.assertEqual(driver.signature_version, "4") <ide> <ide> # Verify that signature_version can be overriden via constructor argument <add> driver = EC2NodeDriver(*EC2_PARAMS, region="us-east-1", signature_version="2") <add> self.assertEqual(driver.signature_version, "2") <add> <ide> driver = EC2NodeDriver(*EC2_PARAMS, region="us-east-1", signature_version="4") <ide> self.assertEqual(driver.signature_version, "4") <ide> <ide> driver = EC2NodeDriver(*EC2_PARAMS, region="eu-central-1", signature_version="2") <ide> self.assertEqual(driver.signature_version, "2") <ide> <add> driver = EC2NodeDriver(*EC2_PARAMS, region="eu-central-1", signature_version="4") <add> self.assertEqual(driver.signature_version, "4") <add> <ide> def test_instantiate_driver_with_token(self): <ide> token = 'temporary_credentials_token' <ide> driver = EC2NodeDriver(*EC2_PARAMS, **{'region': self.region, 'token': token})
1
Javascript
Javascript
add resolvemodel to the default resolver
e08d638d4033457d3c21f2458ff64e7714bd9dbd
<ide><path>packages/ember-application/lib/system/resolver.js <ide> var get = Ember.get, <ide> 'view:blog/post' //=> Blog.PostView <ide> 'view:basic' //=> Ember.View <ide> 'foo:post' //=> App.PostFoo <add> 'model:post' //=> App.Post <ide> ``` <ide> <ide> @class DefaultResolver <ide> Ember.DefaultResolver = Ember.Object.extend({ <ide> this.useRouterNaming(parsedName); <ide> return this.resolveOther(parsedName); <ide> }, <add> <add> /** <add> @protected <add> @method resolveModel <add> */ <add> resolveModel: function(parsedName){ <add> var className = classify(parsedName.name), <add> factory = get(parsedName.root, className); <add> <add> if (factory) { return factory; } <add> }, <ide> /** <ide> Look up the specified object (from parsedName) on the appropriate <ide> namespace (usually on the Application) <ide><path>packages/ember-application/tests/system/dependency_injection/default_resolver_test.js <ide> test('the default resolver looks up arbitrary types on the namespace', function( <ide> equal(locator.resolve('manager:foo'), application.FooManager, "looks up FooManager on application"); <ide> }); <ide> <add>test("the default resolver resolves models on the namespace", function() { <add> application.Post = Ember.Object.extend({}); <add> equal(locator.lookupFactory('model:post'), application.Post, "looks up Post model on application"); <add>});
2
Javascript
Javascript
implement tests
ddbfd26da0c87badf632f85bc2c4b0a88d9da8c2
<ide><path>test/unit/src/core/Object3D.tests.js <ide> import { <ide> w, <ide> eps <ide> } from '../math/Constants.tests.js'; <add>import { EventDispatcher } from '../../../../src/core/EventDispatcher.js'; <ide> <ide> const matrixEquals4 = ( a, b ) => { <ide> <ide> export default QUnit.module( 'Core', () => { <ide> }; <ide> <ide> // INHERITANCE <del> QUnit.todo( 'Extending', ( assert ) => { <del> <del> assert.ok( false, 'everything\'s gonna be alright' ); <add> QUnit.test( 'Extending', ( assert ) => { <ide> <add> var object = new Object3D(); <add> <add> assert.strictEqual( object instanceof EventDispatcher, true, 'Object3D extends from EventDispatcher' ); <add> <ide> } ); <ide> <ide> // INSTANCING <ide><path>test/unit/src/objects/Bone.tests.js <ide> /* global QUnit */ <ide> <del>// import { Bone } from '../../../../src/objects/Bone.js'; <add>import { Object3D } from '../../../../src/core/Object3D.js'; <add>import { Bone } from '../../../../src/objects/Bone.js'; <ide> <ide> export default QUnit.module( 'Objects', () => { <ide> <ide> QUnit.module( 'Bone', () => { <ide> <ide> // INHERITANCE <del> QUnit.todo( 'Extending', ( assert ) => { <add> QUnit.test( 'Extending', ( assert ) => { <ide> <del> assert.ok( false, 'everything\'s gonna be alright' ); <add> var bone = new Bone(); <add> <add> assert.strictEqual( bone instanceof Object3D, true, 'Bone extends from Object3D' ); <ide> <ide> } ); <ide> <ide><path>test/unit/src/objects/Group.tests.js <ide> /* global QUnit */ <ide> <del>// import { Group } from '../../../../src/objects/Group.js'; <add>import { Object3D } from '../../../../src/core/Object3D.js'; <add>import { Group } from '../../../../src/objects/Group.js'; <ide> <ide> export default QUnit.module( 'Objects', () => { <ide> <ide> QUnit.module( 'Group', () => { <ide> <ide> // INHERITANCE <del> QUnit.todo( 'Extending', ( assert ) => { <add> QUnit.test( 'Extending', ( assert ) => { <ide> <del> assert.ok( false, 'everything\'s gonna be alright' ); <add> var group = new Group(); <add> <add> assert.strictEqual( group instanceof Object3D, true, 'Group extends from Object3D' ); <ide> <ide> } ); <ide> <ide><path>test/unit/src/objects/Line.tests.js <ide> /* global QUnit */ <ide> <del>// import { Line } from '../../../../src/objects/Line.js'; <add>import { Object3D } from '../../../../src/core/Object3D.js'; <add>import { Line } from '../../../../src/objects/Line.js'; <ide> <ide> export default QUnit.module( 'Objects', () => { <ide> <ide> QUnit.module( 'Line', () => { <ide> <ide> // INHERITANCE <del> QUnit.todo( 'Extending', ( assert ) => { <add> QUnit.test( 'Extending', ( assert ) => { <ide> <del> assert.ok( false, 'everything\'s gonna be alright' ); <add> var line = new Line(); <add> <add> assert.strictEqual( line instanceof Object3D, true, 'Line extends from Object3D' ); <ide> <ide> } ); <ide> <ide><path>test/unit/src/objects/LineLoop.tests.js <ide> /* global QUnit */ <ide> <del>// import { LineLoop } from '../../../../src/objects/LineLoop.js'; <add>import { Object3D } from '../../../../src/core/Object3D.js'; <add>import { Line } from '../../../../src/objects/Line.js'; <add>import { LineLoop } from '../../../../src/objects/LineLoop.js'; <ide> <ide> export default QUnit.module( 'Objects', () => { <ide> <ide> QUnit.module( 'LineLoop', () => { <ide> <ide> // INHERITANCE <del> QUnit.todo( 'Extending', ( assert ) => { <del> <del> assert.ok( false, 'everything\'s gonna be alright' ); <add> QUnit.test( 'Extending', ( assert ) => { <ide> <add> var lineLoop = new LineLoop(); <add> <add> assert.strictEqual( lineLoop instanceof Object3D, true, 'LineLoop extends from Object3D' ); <add> assert.strictEqual( lineLoop instanceof Line, true, 'LineLoop extends from Line' ); <add> <ide> } ); <ide> <ide> // INSTANCING <ide><path>test/unit/src/objects/LineSegments.tests.js <ide> /* global QUnit */ <ide> <del>// import { LineSegments } from '../../../../src/objects/LineSegments.js'; <add>import { Object3D } from '../../../../src/core/Object3D.js'; <add>import { Line } from '../../../../src/objects/Line.js'; <add>import { LineSegments } from '../../../../src/objects/LineSegments.js'; <ide> <ide> export default QUnit.module( 'Objects', () => { <ide> <ide> QUnit.module( 'LineSegments', () => { <ide> <ide> // INHERITANCE <del> QUnit.todo( 'Extending', ( assert ) => { <add> QUnit.test( 'Extending', ( assert ) => { <ide> <del> assert.ok( false, 'everything\'s gonna be alright' ); <add> var lineSegments = new LineSegments(); <add> <add> assert.strictEqual( lineSegments instanceof Object3D, true, 'LineSegments extends from Object3D' ); <add> assert.strictEqual( lineSegments instanceof Line, true, 'LineSegments extends from Line' ); <ide> <ide> } ); <ide> <ide><path>test/unit/src/objects/Mesh.tests.js <ide> /* global QUnit */ <ide> <add>import { Object3D } from '../../../../src/core/Object3D.js'; <ide> import { Mesh } from '../../../../src/objects/Mesh.js'; <ide> import { Raycaster } from '../../../../src/core/Raycaster.js'; <ide> import { PlaneGeometry } from '../../../../src/geometries/PlaneGeometry.js'; <ide> export default QUnit.module( 'Objects', () => { <ide> QUnit.module( 'Mesh', () => { <ide> <ide> // INHERITANCE <del> QUnit.todo( 'Extending', ( assert ) => { <add> QUnit.test( 'Extending', ( assert ) => { <ide> <del> assert.ok( false, 'everything\'s gonna be alright' ); <add> var mesh = new Mesh(); <add> <add> assert.strictEqual( mesh instanceof Object3D, true, 'Mesh extends from Object3D' ); <ide> <ide> } ); <ide> <ide><path>test/unit/src/objects/Points.tests.js <ide> /* global QUnit */ <ide> <del>// import { Points } from '../../../../src/objects/Points.js'; <add>import { Object3D } from '../../../../src/core/Object3D.js'; <add>import { Points } from '../../../../src/objects/Points.js'; <ide> <ide> export default QUnit.module( 'Objects', () => { <ide> <ide> QUnit.module( 'Points', () => { <ide> <ide> // INHERITANCE <del> QUnit.todo( 'isPoints', ( assert ) => { <add> QUnit.test( 'isPoints', ( assert ) => { <ide> <del> assert.ok( false, 'everything\'s gonna be alright' ); <add> var points = new Points(); <add> <add> assert.strictEqual( points instanceof Object3D, true, 'Points extends from Object3D' ); <ide> <ide> } ); <ide> <ide><path>test/unit/src/objects/SkinnedMesh.tests.js <ide> /* global QUnit */ <ide> <del>// import { SkinnedMesh } from '../../../../src/objects/SkinnedMesh.js'; <add>import { Object3D } from '../../../../src/core/Object3D.js'; <add>import { Mesh } from '../../../../src/objects/Mesh.js'; <add>import { SkinnedMesh } from '../../../../src/objects/SkinnedMesh.js'; <ide> <ide> export default QUnit.module( 'Objects', () => { <ide> <ide> QUnit.module( 'SkinnedMesh', () => { <ide> <ide> // INHERITANCE <del> QUnit.todo( 'Extending', ( assert ) => { <add> QUnit.test( 'Extending', ( assert ) => { <ide> <del> assert.ok( false, 'everything\'s gonna be alright' ); <add> var skinnedMesh = new SkinnedMesh(); <add> <add> assert.strictEqual( skinnedMesh instanceof Object3D, true, 'SkinnedMesh extends from Object3D' ); <add> assert.strictEqual( skinnedMesh instanceof Mesh, true, 'SkinnedMesh extends from Mesh' ); <ide> <ide> } ); <ide> <ide><path>test/unit/src/objects/Sprite.tests.js <ide> /* global QUnit */ <ide> <del>// import { Sprite } from '../../../../src/objects/Sprite.js'; <add>import { Object3D } from '../../../../src/core/Object3D.js'; <add>import { Sprite } from '../../../../src/objects/Sprite.js'; <ide> <ide> export default QUnit.module( 'Objects', () => { <ide> <ide> QUnit.module( 'Sprite', () => { <ide> <ide> // INHERITANCE <del> QUnit.todo( 'Extending', ( assert ) => { <add> QUnit.test( 'Extending', ( assert ) => { <ide> <del> assert.ok( false, 'everything\'s gonna be alright' ); <add> var sprite = new Sprite(); <add> <add> assert.strictEqual( sprite instanceof Object3D, true, 'Sprite extends from Object3D' ); <ide> <ide> } ); <ide>
10
Python
Python
replace custom tf embeddings by keras embeddings
00cbadb870fb74b0eee4197fe9b62afbca457670
<ide><path>src/transformers/modeling_tf_utils.py <ide> def load_tf_weights(model, resolved_archive_file, ignore_mismatched_sizes=False, <ide> # If not, make the value to None <ide> saved_weight_value = saved_weights.get(symbolic_weight_name, None) <ide> <add> # Retrocompatibility patch: some embeddings are stored with the weights name (e.g. Bart's <add> # `model.shared/embeddings:0` are stored as `model.shared/weights:0`) <add> if saved_weight_value is None and symbolic_weight_name.endswith("embeddings:0"): <add> symbolic_weight_name = symbolic_weight_name[:-12] + "weight:0" <add> saved_weight_value = saved_weights.get(symbolic_weight_name, None) <add> <ide> # Add the updated name to the final list for computing missing/unexpected values <ide> symbolic_weights_names.add(symbolic_weight_name) <ide> <ide> def get_lm_head(self) -> tf.keras.layers.Layer: <ide> """ <ide> return None <ide> <del> def resize_token_embeddings(self, new_num_tokens=None) -> tf.Variable: <add> def resize_token_embeddings( <add> self, new_num_tokens: Optional[int] = None <add> ) -> Union[tf.keras.layers.Embedding, tf.Variable]: <ide> """ <ide> Resizes input token embeddings matrix of the model if `new_num_tokens != config.vocab_size`. <ide> <ide> def resize_token_embeddings(self, new_num_tokens=None) -> tf.Variable: <ide> new_num_tokens (`int`, *optional*): <ide> The number of new tokens in the embedding matrix. Increasing the size will add newly initialized <ide> vectors at the end. Reducing the size will remove vectors from the end. If not provided or `None`, just <del> returns a pointer to the input tokens `tf.Variable` module of the model without doing anything. <add> returns a pointer to the input tokens without doing anything. <ide> <ide> Return: <del> `tf.Variable`: Pointer to the input tokens Embeddings Module of the model. <add> `tf.Variable` or `tf.keras.layers.Embedding`: Pointer to the input tokens of the model. <ide> """ <add> # TODO (joao): flagged for replacement (by `_v2_resized_token_embeddings`) due to embeddings refactor <add> <add> # Run the new code path if the model has a keras embeddings layer <add> if isinstance(self.get_input_embeddings(), tf.keras.layers.Embedding): <add> return self._v2_resized_token_embeddings(new_num_tokens) <add> <ide> if new_num_tokens is None or new_num_tokens == self.config.vocab_size: <ide> return self._get_word_embedding_weight(self.get_input_embeddings()) <ide> <ide> def resize_token_embeddings(self, new_num_tokens=None) -> tf.Variable: <ide> <ide> return model_embeds <ide> <add> def _v2_resized_token_embeddings(self, new_num_tokens: Optional[int] = None) -> tf.keras.layers.Embedding: <add> """ <add> Resizes input token embeddings matrix of the model if `new_num_tokens != config.vocab_size`. <add> <add> Arguments: <add> new_num_tokens (`int`, *optional*): <add> The number of new tokens in the embedding matrix. Increasing the size will add newly initialized <add> vectors at the end. Reducing the size will remove vectors from the end. If not provided or `None`, just <add> returns a pointer to the input tokens without doing anything. <add> <add> Return: <add> `tf.keras.layers.Embedding`: Pointer to the input tokens of the model. <add> """ <add> if new_num_tokens is None or new_num_tokens == self.config.vocab_size: <add> return self.get_input_embeddings() <add> <add> model_embeds = self._v2_resize_token_embeddings(new_num_tokens) <add> <add> # Update base model and current model config <add> self.config.vocab_size = new_num_tokens <add> <add> return model_embeds <add> <ide> def _get_word_embedding_weight(model, embedding_layer): <add> # TODO (joao): flagged for delection due to embeddings refactor <add> <ide> # If the variable holds the weights themselves, return them <ide> if isinstance(embedding_layer, tf.Tensor): <ide> return embedding_layer <ide> def _get_word_embedding_weight(model, embedding_layer): <ide> return None <ide> <ide> def _resize_token_embeddings(self, new_num_tokens): <add> # TODO (joao): flagged for replacement (by `_v2_resize_token_embeddings`) due to embeddings refactor <ide> old_embeddings = self._get_word_embedding_weight(self.get_input_embeddings()) <ide> new_embeddings = self._get_resized_embeddings(old_embeddings, new_num_tokens) <ide> <ide> def _resize_token_embeddings(self, new_num_tokens): <ide> <ide> return self.get_input_embeddings() <ide> <add> def _v2_resize_token_embeddings(self, new_num_tokens): <add> old_embeddings = self.get_input_embeddings() <add> new_embeddings = self._v2_get_resized_embeddings(old_embeddings, new_num_tokens) <add> self.set_input_embeddings(new_embeddings) <add> <add> # If word embeddings are not tied, make sure that lm head bias is resized as well <add> if self.get_bias() is not None: <add> old_lm_head_bias = self.get_bias() <add> new_lm_head_bias = self._get_resized_lm_head_bias(old_lm_head_bias, new_num_tokens) <add> self.set_bias(new_lm_head_bias) <add> <add> # If word embeddings are not tied, make sure that lm head decoder is resized as well. <add> tied_weights = self.get_input_embeddings() == self.get_output_embeddings() <add> if self.get_output_embeddings() is not None and not tied_weights: <add> old_lm_head_decoder = self._get_word_embedding_weight(self.get_output_embeddings()) <add> # TODO (joao): this one probably needs a v2 version with other models <add> new_lm_head_decoder = self._get_resized_lm_head_decoder(old_lm_head_decoder, new_num_tokens) <add> self.set_output_embeddings(new_lm_head_decoder) <add> <add> return self.get_input_embeddings() <add> <ide> def _get_resized_lm_head_bias(self, old_lm_head_bias, new_num_tokens): <ide> """ <ide> Build a resized bias from the old ones. Increasing the size will add newly initialized vectors at the end. <ide> def _get_resized_embeddings(self, old_embeddings, new_num_tokens=None) -> tf.Var <ide> `tf.Variable`: Pointer to the resized Embedding Module or the old Embedding Module if `new_num_tokens` is <ide> `None` <ide> """ <add> # TODO (joao): flagged for replacement (by `_v2_get_resized_embeddings`) due to embeddings refactor <ide> old_embedding_dim = shape_list(old_embeddings)[1] <ide> init_range = getattr(self.config, "initializer_range", 0.02) <ide> embeddings_mask, current_embeddings = init_copy_embeddings(old_embeddings, new_num_tokens) <ide> def _get_resized_embeddings(self, old_embeddings, new_num_tokens=None) -> tf.Var <ide> <ide> return new_embeddings <ide> <add> def _v2_get_resized_embeddings( <add> self, old_embeddings: tf.keras.layers.Embedding, new_num_tokens: int <add> ) -> tf.keras.layers.Embedding: <add> """ <add> Build a resized Embedding layer from a provided Embedding layer. Increasing the size will add newly initialized <add> vectors at the end. Reducing the size will remove vectors from the end. <add> <add> Args: <add> old_embeddings (`tf.keras.layers.Embedding`): <add> Old embeddings to be resized. <add> new_num_tokens (`int`, *optional*): <add> New number of tokens in the embedding matrix. <add> <add> Return: <add> `tf.keras.layers.Embedding`: Resized Embedding layer. <add> """ <add> # Get a new (initialized) embeddings layer <add> init_range = getattr(self.config, "initializer_range", 0.02) <add> new_embeddings = tf.keras.layers.Embedding( <add> input_dim=new_num_tokens, <add> output_dim=old_embeddings.output_dim, <add> embeddings_initializer=get_initializer(init_range), <add> name=old_embeddings.embeddings.name[:-13], # exact same scoped name except "/embeddings:0" <add> ) <add> new_embeddings(tf.constant([[0]])) <add> <add> # Copy the old embeddings to the new embeddings <add> if old_embeddings.input_dim >= new_num_tokens: <add> init_embeddings = old_embeddings.embeddings[:new_num_tokens] <add> else: <add> init_embeddings = tf.concat( <add> [old_embeddings.embeddings, new_embeddings.embeddings[old_embeddings.input_dim :]], axis=0 <add> ) <add> new_embeddings.embeddings.assign(init_embeddings) <add> return new_embeddings <add> <ide> def prune_heads(self, heads_to_prune): <ide> """ <ide> Prunes heads of the base model. <ide> class TFSharedEmbeddings(tf.keras.layers.Layer): <ide> kwargs: <ide> Additional keyword arguments passed along to the `__init__` of `tf.keras.layers.Layer`. <ide> """ <add> # TODO (joao): flagged for delection due to embeddings refactor <ide> <ide> def __init__(self, vocab_size: int, hidden_size: int, initializer_range: Optional[float] = None, **kwargs): <ide> super().__init__(**kwargs) <ide> class TFWrappedEmbeddings: <ide> saving/storing the correct weights <ide> """ <ide> <add> # TODO (joao): flagged for delection due to embeddings refactor <add> <ide> def __init__(self, layer, abs_scope_name=None): <ide> self._layer = layer <ide> self._abs_scope_name = abs_scope_name <ide><path>src/transformers/models/bart/modeling_tf_bart.py <ide> TFCausalLanguageModelingLoss, <ide> TFModelInputType, <ide> TFPreTrainedModel, <del> TFSharedEmbeddings, <del> TFWrappedEmbeddings, <ide> keras_serializable, <ide> unpack_inputs, <ide> ) <ide> def _expand_mask(mask: tf.Tensor, tgt_len: Optional[int] = None): <ide> return (one_cst - expanded_mask) * LARGE_NEGATIVE <ide> <ide> <del>class TFBartLearnedPositionalEmbedding(TFSharedEmbeddings): <add>class TFBartLearnedPositionalEmbedding(tf.keras.layers.Embedding): <ide> """ <ide> This module learns positional embeddings up to a fixed maximum size. <ide> """ <ide> def call( <ide> position_ids = tf.range(seq_len, delta=1, name="range") <ide> position_ids += past_key_values_length <ide> <del> return super().call(position_ids + self.offset) <add> offset_dtype = position_ids.dtype if isinstance(position_ids, tf.Tensor) else tf.int32 <add> return super().call(position_ids + tf.constant(self.offset, dtype=offset_dtype)) <ide> <ide> <ide> class TFBartAttention(tf.keras.layers.Layer): <ide> class TFBartEncoder(tf.keras.layers.Layer): <ide> config: BartConfig <ide> """ <ide> <del> def __init__(self, config: BartConfig, embed_tokens: Optional[TFSharedEmbeddings] = None, **kwargs): <add> def __init__(self, config: BartConfig, embed_tokens: Optional[tf.keras.layers.Embedding] = None, **kwargs): <ide> super().__init__(**kwargs) <ide> self.config = config <ide> self.dropout = tf.keras.layers.Dropout(config.dropout) <ide> def __init__(self, config: BartConfig, embed_tokens: Optional[TFSharedEmbeddings <ide> self.layers = [TFBartEncoderLayer(config, name=f"layers.{i}") for i in range(config.encoder_layers)] <ide> self.layernorm_embedding = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="layernorm_embedding") <ide> <del> def get_embed_tokens(self): <del> return self.embed_tokens <del> <del> def set_embed_tokens(self, embed_tokens): <del> self.embed_tokens = embed_tokens <del> <ide> @unpack_inputs <ide> def call( <ide> self, <ide> def call( <ide> raise ValueError("You have to specify either input_ids or inputs_embeds") <ide> <ide> if inputs_embeds is None: <del> inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale <add> with tf.name_scope(self.embed_tokens.name + "/"): <add> inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale <ide> <ide> embed_pos = self.embed_positions(input_shape) <ide> hidden_states = inputs_embeds + embed_pos <ide> class TFBartDecoder(tf.keras.layers.Layer): <ide> embed_tokens: output embedding <ide> """ <ide> <del> def __init__(self, config: BartConfig, embed_tokens: Optional[TFSharedEmbeddings] = None, **kwargs): <add> def __init__(self, config: BartConfig, embed_tokens: Optional[tf.keras.layers.Embedding] = None, **kwargs): <ide> super().__init__(**kwargs) <ide> self.config = config <ide> self.padding_idx = config.pad_token_id <ide> def __init__(self, config: BartConfig, embed_tokens: Optional[TFSharedEmbeddings <ide> <ide> self.dropout = tf.keras.layers.Dropout(config.dropout) <ide> <del> def get_embed_tokens(self): <del> return self.embed_tokens <del> <del> def set_embed_tokens(self, embed_tokens): <del> self.embed_tokens = embed_tokens <del> <ide> @unpack_inputs <ide> def call( <ide> self, <ide> def call( <ide> positions = self.embed_positions(input_shape, position_ids=position_ids) <ide> <ide> if inputs_embeds is None: <del> inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale <add> with tf.name_scope(self.embed_tokens.name + "/"): <add> inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale <ide> <ide> hidden_states = inputs_embeds <ide> <ide> class TFBartMainLayer(tf.keras.layers.Layer): <ide> def __init__(self, config: BartConfig, load_weight_prefix=None, **kwargs): <ide> super().__init__(**kwargs) <ide> self.config = config <del> self.shared = TFSharedEmbeddings(config.vocab_size, config.d_model, config.pad_token_id, name="model.shared") <del> <del> # set tf scope correctly <del> if load_weight_prefix is None: <del> load_weight_prefix = "model.shared" <del> <del> with tf.compat.v1.variable_scope(load_weight_prefix) as shared_abs_scope_name: <del> pass <add> load_weight_prefix = "model.shared" if load_weight_prefix is None else load_weight_prefix <add> self.shared = tf.keras.layers.Embedding(config.vocab_size, config.d_model, name=load_weight_prefix) <ide> <del> # Wraps layer to avoid problems with weight restoring and ensuring we're in the correct TF scope. <del> embed_tokens = TFWrappedEmbeddings(self.shared, abs_scope_name=shared_abs_scope_name) <del> embed_tokens.vocab_size = self.shared.vocab_size <del> embed_tokens.hidden_size = self.shared.hidden_size <del> <del> self.encoder = TFBartEncoder(config, embed_tokens, name="encoder") <del> self.decoder = TFBartDecoder(config, embed_tokens, name="decoder") <add> self.encoder = TFBartEncoder(config, self.shared, name="encoder") <add> self.decoder = TFBartDecoder(config, self.shared, name="decoder") <ide> <ide> def get_input_embeddings(self): <ide> return self.shared <ide> <ide> def set_input_embeddings(self, new_embeddings): <del> self.shared.weight = new_embeddings <del> self.shared.vocab_size = self.shared.weight.shape[0] <del> # retrieve correct absolute scope for embed token wrapper <del> with tf.compat.v1.variable_scope("model.shared") as shared_abs_scope_name: <del> pass <del> # Wraps layer to avoid problems with weight restoring and ensuring we're in the correct TF scope. <del> embed_tokens = TFWrappedEmbeddings(self.shared, abs_scope_name=shared_abs_scope_name) <del> self.encoder.set_embed_tokens(embed_tokens) <del> self.decoder.set_embed_tokens(embed_tokens) <add> self.shared = new_embeddings <add> self.encoder.embed_tokens = self.shared <add> self.decoder.embed_tokens = self.shared <ide> <ide> @unpack_inputs <ide> def call( <ide> def call(self, x): <ide> BART_START_DOCSTRING, <ide> ) <ide> class TFBartForConditionalGeneration(TFBartPretrainedModel, TFCausalLanguageModelingLoss): <del> _keys_to_ignore_on_load_unexpected = [ <del> r"model.encoder.embed_tokens.weight", <del> r"model.decoder.embed_tokens.weight", <del> ] <del> <add> _keys_to_ignore_on_load_missing = [r"final_logits_bias"] <ide> _requires_load_weight_prefix = True <ide> <ide> def __init__(self, config, load_weight_prefix=None, *inputs, **kwargs): <ide> def set_output_embeddings(self, value): <ide> self.set_input_embeddings(value) <ide> <ide> def get_bias(self): <del> return {"final_logits_bias": self.final_logits_bias} <add> return {"final_logits_bias": self.bias_layer.bias} <ide> <ide> def set_bias(self, value): <del> self.final_logits_bias = value["final_logits_bias"] <add> self.bias_layer.bias = value["final_logits_bias"] <ide> <ide> @add_start_docstrings_to_model_forward(BART_INPUTS_DOCSTRING) <ide> @replace_return_docstrings(output_type=TFSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC) <ide> def call( <ide> return_dict=return_dict, <ide> training=training, <ide> ) <del> lm_logits = self.model.shared(outputs[0], mode="linear") <add> # TODO (joao): the line below is for models with tied embeddings. The previous TFBart had tied embeddings. <add> # The PT Bart does not have tied embeddings. Untie the weights while keeping loading retrocompatibility. <add> lm_logits = tf.matmul(outputs[0], self.model.shared.weights, transpose_b=True) <ide> lm_logits = self.bias_layer(lm_logits) <ide> masked_lm_loss = None if labels is None else self.hf_compute_loss(labels, lm_logits) <ide> <ide><path>src/transformers/models/mbart/modeling_tf_mbart.py <ide> def call( <ide> position_ids = tf.range(seq_len, delta=1, name="range") <ide> position_ids += past_key_values_length <ide> <del> return super().call(position_ids + self.offset) <add> offset_dtype = position_ids.dtype if isinstance(position_ids, tf.Tensor) else tf.int32 <add> return super().call(position_ids + tf.constant(self.offset, dtype=offset_dtype)) <ide> <ide> <ide> # Copied from transformers.models.bart.modeling_tf_bart.TFBartAttention with Bart->MBart <ide><path>tests/models/bart/test_modeling_tf_bart.py <ide> def test_model_common_attributes(self): <ide> name = model.get_bias() <ide> assert name is None <ide> <del> def test_resize_token_embeddings(self): <del> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() <del> <del> def _get_word_embedding_weight(model, embedding_layer): <del> if hasattr(embedding_layer, "weight"): <del> return embedding_layer.weight <del> else: <del> # Here we build the word embeddings weights if not exists. <del> # And then we retry to get the attribute once built. <del> model(model.dummy_inputs) <del> if hasattr(embedding_layer, "weight"): <del> return embedding_layer.weight <del> else: <del> return None <del> <del> for model_class in self.all_model_classes: <del> for size in [config.vocab_size - 10, config.vocab_size + 10, None]: <del> # build the embeddings <del> model = model_class(config=config) <del> old_input_embeddings = _get_word_embedding_weight(model, model.get_input_embeddings()) <del> old_output_embeddings = _get_word_embedding_weight(model, model.get_output_embeddings()) <del> old_final_logits_bias = model.get_bias() <del> <del> # reshape the embeddings <del> model.resize_token_embeddings(size) <del> new_input_embeddings = _get_word_embedding_weight(model, model.get_input_embeddings()) <del> new_output_embeddings = _get_word_embedding_weight(model, model.get_output_embeddings()) <del> new_final_logits_bias = model.get_bias() <del> <del> # check that the resized embeddings size matches the desired size. <del> assert_size = size if size is not None else config.vocab_size <del> <del> self.assertEqual(new_input_embeddings.shape[0], assert_size) <del> <del> # check that weights remain the same after resizing <del> models_equal = True <del> for p1, p2 in zip(old_input_embeddings.value(), new_input_embeddings.value()): <del> if tf.math.reduce_sum(tf.math.abs(p1 - p2)) > 0: <del> models_equal = False <del> self.assertTrue(models_equal) <del> <del> if old_output_embeddings is not None and new_output_embeddings is not None: <del> self.assertEqual(new_output_embeddings.shape[0], assert_size) <del> <del> models_equal = True <del> for p1, p2 in zip(old_output_embeddings.value(), new_output_embeddings.value()): <del> if tf.math.reduce_sum(tf.math.abs(p1 - p2)) > 0: <del> models_equal = False <del> self.assertTrue(models_equal) <del> <del> if old_final_logits_bias is not None and new_final_logits_bias is not None: <del> old_final_logits_bias = old_final_logits_bias["final_logits_bias"] <del> new_final_logits_bias = new_final_logits_bias["final_logits_bias"] <del> self.assertEqual(new_final_logits_bias.shape[0], 1) <del> self.assertEqual(new_final_logits_bias.shape[1], assert_size) <del> <del> models_equal = True <del> for old, new in zip(old_final_logits_bias.value(), new_final_logits_bias.value()): <del> for p1, p2 in zip(old, new): <del> if tf.math.reduce_sum(tf.math.abs(p1 - p2)) > 0: <del> models_equal = False <del> self.assertTrue(models_equal) <del> <ide> @tooslow <ide> def test_saved_model_creation(self): <ide> pass <ide> def xsum_1_1_model(self): <ide> <ide> def test_xsum_1_1_generation(self): <ide> model = self.xsum_1_1_model <del> assert model.model.decoder.embed_tokens._layer == model.model.shared <add> assert model.model.decoder.embed_tokens == model.model.shared <ide> ARTICLE = ( <ide> "The Palestinian Authority officially became the 123rd member of the International Criminal Court on" <ide> " Wednesday, a step that gives the court jurisdiction over alleged crimes in Palestinian territories. The" <ide> def test_xsum_1_1_generation(self): <ide> def test_xsum_1_1_xla_generation(self): <ide> # same test as above, but with `no_repeat_ngram_size=0` (not compatible with XLA) and XLA comparison enabled <ide> model = self.xsum_1_1_model <del> assert model.model.decoder.embed_tokens._layer == model.model.shared <add> assert model.model.decoder.embed_tokens == model.model.shared <ide> ARTICLE = ( <ide> "The Palestinian Authority officially became the 123rd member of the International Criminal Court on" <ide> " Wednesday, a step that gives the court jurisdiction over alleged crimes in Palestinian territories. The" <ide><path>tests/test_modeling_tf_common.py <ide> def prepare_numpy_arrays(inputs_dict): <ide> self.assert_outputs_same(output_for_dict_input, output_for_kw_input) <ide> <ide> def test_resize_token_embeddings(self): <add> # TODO (joao): after the embeddings refactor is complete, rework this test so as to rely exclusively on <add> # tf.keras.layers.Embedding <add> <ide> if not self.test_resize_embeddings: <ide> return <ide> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() <ide> <ide> def _get_word_embedding_weight(model, embedding_layer): <del> embeds = getattr(embedding_layer, "weight", None) <del> if embeds is not None: <del> return embeds <del> <del> embeds = getattr(embedding_layer, "decoder", None) <del> if embeds is not None: <del> return embeds <del> <del> model(model.dummy_inputs) <del> <del> embeds = getattr(embedding_layer, "weight", None) <del> if embeds is not None: <del> return embeds <del> <del> embeds = getattr(embedding_layer, "decoder", None) <del> if embeds is not None: <del> return embeds <del> <del> return None <add> if isinstance(embedding_layer, tf.keras.layers.Embedding): <add> # builds the embeddings layer <add> model(model.dummy_inputs) <add> return embedding_layer.embeddings <add> else: <add> return model._get_word_embedding_weight(embedding_layer) <ide> <ide> for model_class in self.all_model_classes: <ide> for size in [config.vocab_size - 10, config.vocab_size + 10, None]: <ide> def _get_word_embedding_weight(model, embedding_layer): <ide> <ide> if old_bias is not None and new_bias is not None: <ide> for old_weight, new_weight in zip(old_bias.values(), new_bias.values()): <del> self.assertEqual(new_weight.shape[0], assert_size) <add> self.assertEqual(new_weight.shape[-1], assert_size) <ide> <ide> models_equal = True <del> for p1, p2 in zip(old_weight.value(), new_weight.value()): <add> for p1, p2 in zip(tf.squeeze(old_weight), tf.squeeze(new_weight)): <ide> if tf.math.reduce_sum(tf.math.abs(p1 - p2)) > 0: <ide> models_equal = False <ide> self.assertTrue(models_equal)
5
PHP
PHP
fix database rules with where clauses
53081e92c6c25f99574b9022aec79d9bf8c63801
<ide><path>src/Illuminate/Validation/Rules/DatabaseRule.php <ide> public function queryCallbacks() <ide> protected function formatWheres() <ide> { <ide> return collect($this->wheres)->map(function ($where) { <del> return $where['column'].','.$where['value']; <add> return $where['column'].','.'"'.str_replace('"', '""', $where['value']).'"'; <ide> })->implode(','); <ide> } <ide> } <ide><path>tests/Validation/ValidationExistsRuleTest.php <ide> public function testItCorrectlyFormatsAStringVersionOfTheRule() <ide> { <ide> $rule = new Exists('table'); <ide> $rule->where('foo', 'bar'); <del> $this->assertEquals('exists:table,NULL,foo,bar', (string) $rule); <add> $this->assertEquals('exists:table,NULL,foo,"bar"', (string) $rule); <ide> <ide> $rule = new Exists('table', 'column'); <ide> $rule->where('foo', 'bar'); <del> $this->assertEquals('exists:table,column,foo,bar', (string) $rule); <add> $this->assertEquals('exists:table,column,foo,"bar"', (string) $rule); <ide> } <ide> <ide> public function testItChoosesValidRecordsUsingWhereInRule() <ide><path>tests/Validation/ValidationUniqueRuleTest.php <ide> public function testItCorrectlyFormatsAStringVersionOfTheRule() <ide> { <ide> $rule = new Unique('table'); <ide> $rule->where('foo', 'bar'); <del> $this->assertEquals('unique:table,NULL,NULL,id,foo,bar', (string) $rule); <add> $this->assertEquals('unique:table,NULL,NULL,id,foo,"bar"', (string) $rule); <ide> <ide> $rule = new Unique('table', 'column'); <ide> $rule->ignore('Taylor, Otwell', 'id_column'); <ide> $rule->where('foo', 'bar'); <del> $this->assertEquals('unique:table,column,"Taylor, Otwell",id_column,foo,bar', (string) $rule); <add> $this->assertEquals('unique:table,column,"Taylor, Otwell",id_column,foo,"bar"', (string) $rule); <ide> <ide> $rule = new Unique('table', 'column'); <ide> $rule->ignore('Taylor, Otwell"\'..-"', 'id_column'); <ide> $rule->where('foo', 'bar'); <del> $this->assertEquals('unique:table,column,"Taylor, Otwell\"\\\'..-\"",id_column,foo,bar', (string) $rule); <del> $this->assertEquals('Taylor, Otwell"\'..-"', stripslashes(str_getcsv('table,column,"Taylor, Otwell\"\\\'..-\"",id_column,foo,bar')[2])); <del> $this->assertEquals('id_column', stripslashes(str_getcsv('table,column,"Taylor, Otwell\"\\\'..-\"",id_column,foo,bar')[3])); <add> $this->assertEquals('unique:table,column,"Taylor, Otwell\"\\\'..-\"",id_column,foo,"bar"', (string) $rule); <add> $this->assertEquals('Taylor, Otwell"\'..-"', stripslashes(str_getcsv('table,column,"Taylor, Otwell\"\\\'..-\"",id_column,foo,"bar"')[2])); <add> $this->assertEquals('id_column', stripslashes(str_getcsv('table,column,"Taylor, Otwell\"\\\'..-\"",id_column,foo,"bar"')[3])); <ide> <ide> $rule = new Unique('table', 'column'); <ide> $rule->ignore(null, 'id_column'); <ide> $rule->where('foo', 'bar'); <del> $this->assertEquals('unique:table,column,NULL,id_column,foo,bar', (string) $rule); <add> $this->assertEquals('unique:table,column,NULL,id_column,foo,"bar"', (string) $rule); <ide> <ide> $model = new EloquentModelStub(['id_column' => 1]); <ide> <ide> $rule = new Unique('table', 'column'); <ide> $rule->ignore($model); <ide> $rule->where('foo', 'bar'); <del> $this->assertEquals('unique:table,column,"1",id_column,foo,bar', (string) $rule); <add> $this->assertEquals('unique:table,column,"1",id_column,foo,"bar"', (string) $rule); <ide> <ide> $rule = new Unique('table', 'column'); <ide> $rule->ignore($model, 'id_column'); <ide> $rule->where('foo', 'bar'); <del> $this->assertEquals('unique:table,column,"1",id_column,foo,bar', (string) $rule); <add> $this->assertEquals('unique:table,column,"1",id_column,foo,"bar"', (string) $rule); <add> <add> $rule = new Unique('table'); <add> $rule->where('foo', '"bar"'); <add> $this->assertEquals('unique:table,NULL,NULL,id,foo,"""bar"""', (string) $rule); <ide> } <ide> } <ide>
3
Text
Text
remove outdated video
8e28785913aa645e1ca505330971b60c530d853f
<ide><path>curriculum/challenges/english/01-responsive-web-design/responsive-web-design-principles/make-an-image-responsive.md <ide> id: 587d78b1367417b2b2512b09 <ide> title: Make an Image Responsive <ide> challengeType: 0 <del>videoUrl: 'https://scrimba.com/p/pzrPu4/cz763UD' <ide> forumTopicId: 301140 <ide> dashedName: make-an-image-responsive <ide> ---
1
Text
Text
add teletype highlights from the past week [week]
5bcded4adf608f27e4c4abd27736c12581e3a847
<ide><path>docs/focus/2018-03-19.md <ide> - Begin an npm package, [squeegpg](https://github.com/atom/squeegpg), to wrap GPG interaction and gpg-agent management using the binaries from [squeegpg-native](https://github.com/atom/squeegpg-native). Set up a bunch of yak-shaving tasks like configuring Circle/AppVeyor/Travis CI and installing Greenkeeper. <ide> - Upgrade `fs-extra` and replace our proliferating helper methods with the already-Promisified versions from the newer version. [atom/github#1350](https://github.com/atom/github/pull/1350) <ide> - Teletype <add> - Adjusted teletype-server's caching directives in an effort to reduce or eliminate package initialization errors ( [atom/teletype-server#47](https://github.com/atom/teletype-server/pull/47), [atom/teletype#318](https://github.com/atom/teletype/issues/318)) <add> - Published first draft of RFC for streamlining collaboration set-up, including the ability to give guests a URL that they can use to join your portal, and a "buddy list" for more quickly collaborating with coworkers and friends ([atom/teletype#344](https://github.com/atom/teletype/pull/344)) <ide> - Tree-sitter <ide> - Xray <ide> - Engineering Improvements
1
Text
Text
fix typos in functions guide
0fc2c1c7a45137c23bfb0443cdee1a5b0be14967
<ide><path>docs/guides/videojs.md <ide> var VjsButton = videojs.getComponent('Button'); <ide> // Subclass the component (see 'extend' doc for more info) <ide> var MySpecialButton = videojs.extend(VjsButton, {}); <ide> // Register the new component <del>VjsButton.registerComponent('MySepcialButton', MySepcialButton); <add>videojs.registerComponent('MySpecialButton', MySpecialButton); <ide> // (optionally) add the new component as a default player child <del>myPlayer.addChild('MySepcialButton'); <add>myPlayer.addChild('MySpecialButton'); <ide> ``` <ide> <ide> ## `getTech()` <ide> var html5 = new Html5(options); <ide> var Html5 = videojs.getTech('Html5'); <ide> var MyTech = videojs.extend(Html5, {}); <ide> // Register the new Tech <del>VjsButton.registerTech('Tech', MyTech); <add>videojs.registerTech('MyTech', MyTech); <ide> var player = videojs('myplayer', { <ide> techOrder: ['myTech', 'html5'] <ide> });
1
Python
Python
remove pack_inputs/unpack_inputs in bert
c813d85fad1f39b1705ca39727fb3f5e130e3d58
<ide><path>official/nlp/bert_models.py <ide> def __init__(self, vocab_size, **kwargs): <ide> 'vocab_size': vocab_size, <ide> } <ide> <del> def __call__(self, <del> lm_output, <del> sentence_output=None, <del> lm_label_ids=None, <del> lm_label_weights=None, <del> sentence_labels=None, <del> **kwargs): <del> inputs = tf_utils.pack_inputs([ <del> lm_output, sentence_output, lm_label_ids, lm_label_weights, <del> sentence_labels <del> ]) <del> return super(BertPretrainLossAndMetricLayer, <del> self).__call__(inputs, **kwargs) <del> <ide> def _add_metrics(self, lm_output, lm_labels, lm_label_weights, <ide> lm_example_loss, sentence_output, sentence_labels, <ide> next_sentence_loss): <ide> def _add_metrics(self, lm_output, lm_labels, lm_label_weights, <ide> self.add_metric( <ide> next_sentence_loss, name='next_sentence_loss', aggregation='mean') <ide> <del> def call(self, inputs): <add> def call(self, lm_output, sentence_output, lm_label_ids, lm_label_weights, <add> sentence_labels): <ide> """Implements call() for the layer.""" <del> unpacked_inputs = tf_utils.unpack_inputs(inputs) <del> lm_output = unpacked_inputs[0] <del> sentence_output = unpacked_inputs[1] <del> lm_label_ids = unpacked_inputs[2] <del> lm_label_weights = tf.keras.backend.cast(unpacked_inputs[3], tf.float32) <del> sentence_labels = unpacked_inputs[4] <add> lm_label_weights = tf.keras.backend.cast(lm_label_weights, tf.float32) <ide> <ide> mask_label_loss = losses.weighted_sparse_categorical_crossentropy_loss( <ide> labels=lm_label_ids, predictions=lm_output, weights=lm_label_weights)
1
Text
Text
fix some minor typos
77503a99301bf201f5358edfdf017a88362d4f10
<ide><path>guide/english/react/fragments/index.md <ide> Fragments are a way to return multiple elements from the render method without u <ide> <ide> When attempting to render multiple sibling elements without an enclosing tag in JSX, you will see the error message of `Adjacent JSX elements must be wrapped in an enclosing tag`. <ide> <del>In the past, a frequent solution was to use either a wrapping div or span element, which was not elegant as it would increase the size of DOM tree and this is because of the way JSX works as multiple elements should be wrapped in a div. However, version 16.0 of React introduced the addition of `Fragment`, which makes this no longer necessary. <add>In the past, a frequent solution was to use either a wrapping `div` or `span` element, which was not elegant as it would increase the size of DOM tree and this is because of the way JSX works as multiple elements should be wrapped in a div. However, version 16.0 of React introduced the addition of `Fragment`, which makes this no longer necessary. <ide> <del>`Fragment` acts a wrapper without adding unnecessary divs or spans elements to the DOM. You can use it directly from the React import: <add>`Fragment` acts as a wrapper without adding unnecessary `div` or `span` elements to the DOM. You can use it directly from the React import: <ide> <ide> ```jsx <ide> import React from 'react'; <ide> return ( <ide> ); <ide> ``` <ide> <del>Empty JSX tags cannot be used with attributes, including key. <add>Empty JSX tags cannot be used with any attributes (including key). <ide> <ide> #### More Information: <ide> * [React.Fragment (Official Documentation)](https://reactjs.org/docs/react-api.html#reactfragment)
1
PHP
PHP
fix tests on php 8.2
066c11494c1c081db6f5ca2539d34b61393e8dfd
<ide><path>tests/TestCase/Database/ConnectionTest.php <ide> public function testNestedTransactionRollbackExceptionThrown(): void <ide> return false; <ide> }); <ide> $this->rollbackSourceLine = __LINE__ - 1; <add> if (PHP_VERSION_ID >= 80200) { <add> $this->rollbackSourceLine -= 2; <add> } <ide> <ide> return true; <ide> }); <ide> public function testNestedTransactionStates(): void <ide> return false; <ide> }); <ide> $this->rollbackSourceLine = __LINE__ - 1; <add> if (PHP_VERSION_ID >= 80200) { <add> $this->rollbackSourceLine -= 2; <add> } <ide> <ide> $this->pushNestedTransactionState(); <ide>
1
Javascript
Javascript
add new oninput event
292dd238e70400a16bebd000fc4364c42d3effe7
<ide><path>src/core/ReactEvent.js <ide> function listenAtTopLevel(touchNotMouse) { <ide> trapBubbledEvent(topLevelTypes.topKeyUp, 'keyup', mountAt); <ide> trapBubbledEvent(topLevelTypes.topKeyPress, 'keypress', mountAt); <ide> trapBubbledEvent(topLevelTypes.topKeyDown, 'keydown', mountAt); <add> trapBubbledEvent(topLevelTypes.topInput, 'input', mountAt); <ide> trapBubbledEvent(topLevelTypes.topChange, 'change', mountAt); <ide> trapBubbledEvent( <ide> topLevelTypes.topDOMCharacterDataModified, <ide><path>src/event/EventConstants.js <ide> var topLevelTypes = keyMirror({ <ide> topDOMCharacterDataModified: null, <ide> topDoubleClick: null, <ide> topFocus: null, <add> topInput: null, <ide> topKeyDown: null, <ide> topKeyPress: null, <ide> topKeyUp: null, <ide><path>src/eventPlugins/SimpleEventPlugin.js <ide> var SimpleEventPlugin = { <ide> captured: keyOf({onKeyDownCapture: true}) <ide> } <ide> }, <add> input: { <add> phasedRegistrationNames: { <add> bubbled: keyOf({onInput: true}), <add> captured: keyOf({onInputCapture: true}) <add> } <add> }, <ide> focus: { <ide> phasedRegistrationNames: { <ide> bubbled: keyOf({onFocus: true}), <ide> SimpleEventPlugin.topLevelTypesToAbstract = { <ide> topKeyUp: SimpleEventPlugin.abstractEventTypes.keyUp, <ide> topKeyPress: SimpleEventPlugin.abstractEventTypes.keyPress, <ide> topKeyDown: SimpleEventPlugin.abstractEventTypes.keyDown, <add> topInput: SimpleEventPlugin.abstractEventTypes.input, <ide> topFocus: SimpleEventPlugin.abstractEventTypes.focus, <ide> topBlur: SimpleEventPlugin.abstractEventTypes.blur, <ide> topScroll: SimpleEventPlugin.abstractEventTypes.scroll,
3
PHP
PHP
fix doc block annotation for texthelper
df47b35f72a6d7a287c13289bd1de1b05ad0d42f
<ide><path>src/View/Helper/NumberHelper.php <ide> class NumberHelper extends Helper <ide> ]; <ide> <ide> /** <del> * Cake\I18n\LocalizedNumber instance <add> * Cake\I18n\Number instance <ide> * <ide> * @var \Cake\I18n\Number <ide> */ <del> protected $_engine = null; <add> protected $_engine; <ide> <ide> /** <ide> * Default Constructor <ide><path>src/View/Helper/TextHelper.php <ide> class TextHelper extends Helper <ide> protected $_placeholders = []; <ide> <ide> /** <del> * String utility instance <add> * Cake Utility Text instance <ide> * <del> * @var \stdClass <add> * @var \Cake\Utility\Text <ide> */ <ide> protected $_engine; <ide>
2
Ruby
Ruby
remove unused variable
16648979f72e4543cb62cf803dc6c4c6b03715d4
<ide><path>activerecord/test/cases/enum_test.rb <ide> class EnumTest < ActiveRecord::TestCase <ide> <ide> test "overriding enum method should not raise" do <ide> assert_nothing_raised do <del> klass = Class.new(ActiveRecord::Base) do <add> Class.new(ActiveRecord::Base) do <ide> self.table_name = "books" <ide> <ide> def published!
1
PHP
PHP
fix typo in whether
e10100d0494475ed2aaabba7e037b0e9e31d0ac2
<ide><path>src/Filesystem/Folder.php <ide> public function chmod($path, $mode = false, $recursive = true, array $exceptions <ide> * Returns an array of subdirectories for the provided or current path. <ide> * <ide> * @param string|null $path The directory path to get subdirectories for. <del> * @param bool $fullPath Wheter to return the full path or only the directory name. <add> * @param bool $fullPath Whether to return the full path or only the directory name. <ide> * @return array Array of subdirectories for the provided or current path. <ide> */ <ide> public function subdirectories($path = null, $fullPath = true)
1
Python
Python
set version to v2.2.0.dev19
796072e56050ff0546e2c7c57f41190480774616
<ide><path>spacy/about.py <ide> # fmt: off <ide> __title__ = "spacy" <del>__version__ = "2.2.0" <add>__version__ = "2.2.0.dev19" <ide> __release__ = True <ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download" <ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
1
Javascript
Javascript
add touchable e2e tests
1bc704d4c70f129abf004ae9552ee18268fada20
<ide><path>RNTester/e2e/__tests__/Touchable-test.js <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @emails oncall+react_native <add> * @format <add> */ <add> <add>/* global element, by, expect */ <add> <add>describe('Touchable', () => { <add> beforeAll(async () => { <add> await element(by.id('explorer_search')).replaceText('<Touchable*'); <add> await element( <add> by.label('<Touchable*> and onPress Touchable and onPress examples.'), <add> ).tap(); <add> }); <add> <add> afterAll(async () => { <add> //TODO - remove app state persistency, till then, we must go back to main screen, <add> await element(by.label('Back')).tap(); <add> }); <add> <add> it('Touchable Highlight should be tappable', async () => { <add> const buttonID = 'touchable_highlight_image_button'; <add> const button2ID = 'touchable_highlight_text_button'; <add> const consoleID = 'touchable_highlight_console'; <add> <add> await element(by.id(buttonID)).tap(); <add> await expect(element(by.id(consoleID))).toHaveText( <add> 'TouchableHighlight onPress', <add> ); <add> <add> await element(by.id(buttonID)).tap(); <add> await expect(element(by.id(consoleID))).toHaveText( <add> '2x TouchableHighlight onPress', <add> ); <add> <add> await element(by.id(button2ID)).tap(); <add> await expect(element(by.id(consoleID))).toHaveText( <add> '3x TouchableHighlight onPress', <add> ); <add> }); <add> <add> it('Touchable Without Feedback should be tappable', async () => { <add> const buttonID = 'touchable_without_feedback_button'; <add> const consoleID = 'touchable_without_feedback_console'; <add> <add> await element(by.id(buttonID)).tap(); <add> await expect(element(by.id(consoleID))).toHaveText( <add> 'TouchableWithoutFeedback onPress', <add> ); <add> <add> await element(by.id(buttonID)).tap(); <add> await expect(element(by.id(consoleID))).toHaveText( <add> '2x TouchableWithoutFeedback onPress', <add> ); <add> }); <add> <add> it('Text should be tappable', async () => { <add> const buttonID = 'tappable_text'; <add> const consoleID = 'tappable_text_console'; <add> <add> await element(by.id(buttonID)).tap(); <add> await expect(element(by.id(consoleID))).toHaveText('text onPress'); <add> <add> await element(by.id(buttonID)).tap(); <add> await expect(element(by.id(consoleID))).toHaveText('2x text onPress'); <add> }); <add>}); <ide><path>RNTester/js/TouchableExample.js <ide> exports.examples = [ <ide> 'background color change as well with the activeOpacity and ' + <ide> 'underlayColor props.', <ide> render: function() { <del> return ( <del> <View> <del> <View style={styles.row}> <del> <TouchableHighlight <del> style={styles.wrapper} <del> onPress={() => console.log('stock THW image - highlight')}> <del> <Image source={heartImage} style={styles.image} /> <del> </TouchableHighlight> <del> <TouchableHighlight <del> style={styles.wrapper} <del> activeOpacity={1} <del> tvParallaxProperties={{ <del> pressMagnification: 1.3, <del> pressDuration: 0.6, <del> }} <del> underlayColor="rgb(210, 230, 255)" <del> onPress={() => console.log('custom THW text - highlight')}> <del> <View style={styles.wrapperCustom}> <del> <Text style={styles.text}>Tap Here For Custom Highlight!</Text> <del> </View> <del> </TouchableHighlight> <del> </View> <del> </View> <del> ); <add> return <TouchableHighlightBox />; <ide> }, <ide> }, <ide> { <ide> exports.examples = [ <ide> }, <ide> ]; <ide> <add>class TouchableHighlightBox extends React.Component<{}, $FlowFixMeState> { <add> state = { <add> timesPressed: 0, <add> }; <add> <add> touchableOnPress = () => { <add> this.setState({ <add> timesPressed: this.state.timesPressed + 1, <add> }); <add> }; <add> <add> render() { <add> let textLog = ''; <add> if (this.state.timesPressed > 1) { <add> textLog = this.state.timesPressed + 'x TouchableHighlight onPress'; <add> } else if (this.state.timesPressed > 0) { <add> textLog = 'TouchableHighlight onPress'; <add> } <add> <add> return ( <add> <View> <add> <View style={styles.row}> <add> <TouchableHighlight <add> style={styles.wrapper} <add> testID="touchable_highlight_image_button" <add> onPress={this.touchableOnPress}> <add> <Image source={heartImage} style={styles.image} /> <add> </TouchableHighlight> <add> <TouchableHighlight <add> style={styles.wrapper} <add> testID="touchable_highlight_text_button" <add> activeOpacity={1} <add> tvParallaxProperties={{ <add> pressMagnification: 1.3, <add> pressDuration: 0.6, <add> }} <add> underlayColor="rgb(210, 230, 255)" <add> onPress={this.touchableOnPress}> <add> <View style={styles.wrapperCustom}> <add> <Text style={styles.text}>Tap Here For Custom Highlight!</Text> <add> </View> <add> </TouchableHighlight> <add> </View> <add> <View style={styles.logBox}> <add> <Text testID="touchable_highlight_console">{textLog}</Text> <add> </View> <add> </View> <add> ); <add> } <add>} <add> <ide> class TouchableWithoutFeedbackBox extends React.Component<{}, $FlowFixMeState> { <ide> state = { <ide> timesPressed: 0, <ide> class TouchableWithoutFeedbackBox extends React.Component<{}, $FlowFixMeState> { <ide> <ide> return ( <ide> <View> <del> <TouchableWithoutFeedback onPress={this.textOnPress}> <add> <TouchableWithoutFeedback <add> onPress={this.textOnPress} <add> testID="touchable_without_feedback_button"> <ide> <View style={styles.wrapperCustom}> <ide> <Text style={styles.text}>Tap Here For No Feedback!</Text> <ide> </View> <ide> </TouchableWithoutFeedback> <ide> <View style={styles.logBox}> <del> <Text>{textLog}</Text> <add> <Text testID="touchable_without_feedback_console">{textLog}</Text> <ide> </View> <ide> </View> <ide> ); <ide> class TextOnPressBox extends React.Component<{}, $FlowFixMeState> { <ide> <ide> return ( <ide> <View> <del> <Text style={styles.textBlock} onPress={this.textOnPress}> <add> <Text <add> style={styles.textBlock} <add> testID="tappable_text" <add> onPress={this.textOnPress}> <ide> Text has built-in onPress handling <ide> </Text> <ide> <View style={styles.logBox}> <del> <Text>{textLog}</Text> <add> <Text testID="tappable_text_console">{textLog}</Text> <ide> </View> <ide> </View> <ide> );
2
Text
Text
add tick marks + small grammar change
73874a163f82dfb326c65a3e414d04b180b9074b
<ide><path>guides/source/rails_application_templates.md <ide> After reading this guide, you will know: <ide> Usage <ide> ----- <ide> <del>To apply a template, you need to provide the Rails generator with the location of the template you wish to apply using the -m option. This can either be a path to a file or a URL. <add>To apply a template, you need to provide the Rails generator with the location of the template you wish to apply using the `-m` option. This can either be a path to a file or a URL. <ide> <ide> ```bash <ide> $ rails new blog -m ~/template.rb <ide> $ rails new blog -m http://example.com/template.rb <ide> ``` <ide> <del>You can use the task `app:template` to apply templates to an existing Rails application. The location of the template needs to be passed in to an environment variable named LOCATION. Again, this can either be path to a file or a URL. <add>You can use the `app:template` Rake task to apply templates to an existing Rails application. The location of the template needs to be passed in via the LOCATION environment variable. Again, this can either be path to a file or a URL. <ide> <ide> ```bash <ide> $ bin/rails app:template LOCATION=~/template.rb
1
Javascript
Javascript
return a dummy fill style for nyi shading
56b1f3b333b177a6253ded5d58d99a3e0a61a641
<ide><path>pdf.js <ide> var CanvasGraphics = (function() { <ide> }, <ide> getShading: function(shading) { <ide> shading = this.xref.fetchIfRef(shading); <add> var dict = IsStream(shading) ? shading.dict : shading; <ide> <del> var bbox = shading.get('BBox'); <add> var bbox = dict.get('BBox'); <ide> if (bbox && IsArray(bbox) && 4 == bbox.length) { <ide> this.rectangle.apply(this, bbox); <ide> this.clip(); <ide> this.endPath(); <ide> } <ide> <del> var background = shading.get('Background'); <add> var background = dict.get('Background'); <ide> if (background) <ide> TODO('handle background colors'); <ide> <del> var cs = shading.get('ColorSpace', 'CS'); <add> var cs = dict.get('ColorSpace', 'CS'); <ide> cs = ColorSpace.parse(cs, this.xref, this.res); <ide> <ide> var types = [null, <ide> null, <ide> this.getAxialShading, <ide> this.getRadialShading]; <ide> <del> var typeNum = shading.get('ShadingType'); <add> var typeNum = dict.get('ShadingType'); <ide> var shadingFn = types[typeNum]; <ide> <ide> // Most likely we will not implement other types of shading <ide> // unless the browser supports them <del> if (!shadingFn) <del> TODO("Unknown or NYI type of shading '"+ typeNum +"'"); <add> if (!shadingFn) { <add> warn("Unknown or NYI type of shading '"+ typeNum +"'"); <add> return 'hotpink'; <add> } <ide> <ide> return shadingFn.call(this, shading, cs); <del> }, <add> }, <ide> getAxialShading: function(sh, cs) { <ide> var coordsArr = sh.get('Coords'); <ide> var x0 = coordsArr[0], y0 = coordsArr[1],
1
Go
Go
use rslave instead of rprivate in chrootarchive
5ede64d63fec0b9d4cf921b6f8fb946e65287538
<ide><path>pkg/chrootarchive/chroot_linux.go <ide> func chroot(path string) (err error) { <ide> return fmt.Errorf("Error creating mount namespace before pivot: %v", err) <ide> } <ide> <del> // make everything in new ns private <del> if err := mount.MakeRPrivate("/"); err != nil { <add> // Make everything in new ns slave. <add> // Don't use `private` here as this could race where the mountns gets a <add> // reference to a mount and an unmount from the host does not propagate, <add> // which could potentially cause transient errors for other operations, <add> // even though this should be relatively small window here `slave` should <add> // not cause any problems. <add> if err := mount.MakeRSlave("/"); err != nil { <ide> return err <ide> } <ide>
1
Python
Python
fix linting errors
56e1534a3c14bc34f37da58517ccfe7e1e69e2e4
<ide><path>libcloud/test/common/test_base_driver.py <ide> def _ex_connection_class_kwargs(self): <ide> DummyDriver2.connectionCls = Mock() <ide> DummyDriver2(key='foo') <ide> call_kwargs = DummyDriver2.connectionCls.call_args[1] <del> #self.assertEqual(call_kwargs['timeout'], 13) <del> #self.assertEqual(call_kwargs['retry_delay'], None) <ide> <ide> # 4. Value provided via "_ex_connection_class_kwargs" and constructor, <ide> # constructor should win <ide><path>libcloud/test/test_httplib_ssl.py <ide> import os <ide> import sys <ide> import os.path <del>import ssl <del>import socket <ide> import mock <ide> from mock import patch <ide>
2
Ruby
Ruby
add test for env mod through system call
d2a7314f538f919e9b09e4b27c1f86b7d3d2eda2
<ide><path>Library/Homebrew/rubocops/lines_cop.rb <ide> def audit_formula(_node, _class_node, _parent_class_node, body_node) <ide> problem "\"\#\{prefix}#{match[1]}\" should be \"\#{#{match[2].downcase}}\"" <ide> end <ide> end <add> <ide> find_every_method_call_by_name(body_node, :depends_on).each do |m| <ide> key, value = destructure_hash(parameters(m).first) <ide> next if (key.nil? || value.nil?) <ide> next unless match = regex_match_group(value, %r{(lua|perl|python|ruby)(\d*)}) <ide> problem "#{match[1]} modules should be vendored rather than use deprecated #{m.source}`" <ide> end <ide> <del> # find_every_method_call_by_name(body_node, :system).each do |m| <del> # next unless match = regex_match_group(parameters(m).first, %r{(env|export)(\s+)?}) <del> # problem "Use ENV instead of invoking '#{match[1]}' to modify the environment" <del> # end <del> # <add> find_every_method_call_by_name(body_node, :system).each do |m| <add> next unless match = regex_match_group(parameters(m).first, %r{(env|export)(\s+)?}) <add> problem "Use ENV instead of invoking '#{match[1]}' to modify the environment" <add> end <add> <ide> # find_every_method_call_by_name(body_node, :depends_on).each do |m| <ide> # next unless modifier?(m) <ide> # dep, option = hash_dep(m) <ide><path>Library/Homebrew/test/rubocops/lines_cop_spec.rb <ide> class Foo < Formula <ide> end <ide> end <ide> <add> it "with setting env manually" do <add> source = <<-EOS.undent <add> class Foo < Formula <add> desc "foo" <add> url 'http://example.com/foo-1.0.tgz' <add> system "export", "var=value" <add> end <add> EOS <add> <add> expected_offenses = [{ message: "Use ENV instead of invoking 'export' to modify the environment", <add> severity: :convention, <add> line: 4, <add> column: 10, <add> source: source }] <add> <add> inspect_source(cop, source) <add> <add> expected_offenses.zip(cop.offenses).each do |expected, actual| <add> expect_offense(expected, actual) <add> end <add> end <add> <ide> end <ide> def expect_offense(expected, actual) <ide> expect(actual.message).to eq(expected[:message])
2
Python
Python
fix memory regression in seq2seq example
5f80c15ef53b4c2c10eeec64b2e42e62db130930
<ide><path>examples/seq2seq/finetune_trainer.py <ide> AutoTokenizer, <ide> HfArgumentParser, <ide> MBartTokenizer, <add> MBartTokenizerFast, <ide> Seq2SeqTrainer, <ide> Seq2SeqTrainingArguments, <ide> set_seed, <ide> def main(): <ide> data_args.eval_beams = model.config.num_beams <ide> <ide> # set decoder_start_token_id for MBart <del> if model.config.decoder_start_token_id is None and isinstance(tokenizer, MBartTokenizer): <add> if model.config.decoder_start_token_id is None and isinstance(tokenizer, (MBartTokenizer, MBartTokenizerFast)): <ide> assert ( <ide> data_args.tgt_lang is not None and data_args.src_lang is not None <ide> ), "mBart requires --tgt_lang and --src_lang" <del> model.config.decoder_start_token_id = tokenizer.lang_code_to_id[data_args.tgt_lang] <add> if isinstance(tokenizer, MBartTokenizer): <add> model.config.decoder_start_token_id = tokenizer.lang_code_to_id[data_args.tgt_lang] <add> else: <add> model.config.decoder_start_token_id = tokenizer.convert_tokens_to_ids(data_args.tgt_lang) <ide> <ide> if model_args.freeze_embeds: <ide> freeze_embeds(model) <ide> def main(): <ide> args=training_args, <ide> train_dataset=train_dataset, <ide> eval_dataset=eval_dataset, <del> data_collator=Seq2SeqDataCollator(tokenizer, data_args, training_args.tpu_num_cores), <add> data_collator=Seq2SeqDataCollator( <add> tokenizer, data_args, model.config.decoder_start_token_id, training_args.tpu_num_cores <add> ), <ide> compute_metrics=compute_metrics_fn, <ide> tokenizer=tokenizer, <ide> ) <ide><path>examples/seq2seq/utils.py <ide> from torch.utils.data import Dataset, Sampler <ide> <ide> from sentence_splitter import add_newline_to_end_of_each_sentence <del>from transformers import BartTokenizer, EvalPrediction, PreTrainedTokenizer <add>from transformers import BartTokenizer, EvalPrediction, PreTrainedTokenizer, T5Tokenizer <ide> from transformers.file_utils import cached_property <add>from transformers.models.bart.modeling_bart import shift_tokens_right <ide> <ide> <ide> try: <ide> def collate_fn(self, batch) -> Dict[str, torch.Tensor]: <ide> <ide> <ide> class Seq2SeqDataCollator: <del> def __init__(self, tokenizer, data_args, tpu_num_cores=None): <add> def __init__(self, tokenizer, data_args, decoder_start_token_id, tpu_num_cores=None): <ide> self.tokenizer = tokenizer <ide> self.pad_token_id = tokenizer.pad_token_id <add> self.decoder_start_token_id = decoder_start_token_id <ide> assert ( <ide> self.pad_token_id is not None <ide> ), f"pad_token_id is not defined for ({self.tokenizer.__class__.__name__}), it must be defined." <ide> def __call__(self, batch) -> Dict[str, torch.Tensor]: <ide> labels = trim_batch(labels, self.pad_token_id) <ide> input_ids, attention_mask = trim_batch(input_ids, self.pad_token_id, attention_mask=attention_mask) <ide> <add> if isinstance(self.tokenizer, T5Tokenizer): <add> decoder_input_ids = self._shift_right_t5(labels) <add> else: <add> decoder_input_ids = shift_tokens_right(labels, self.pad_token_id, self.decoder_start_token_id) <add> <ide> batch = { <ide> "input_ids": input_ids, <ide> "attention_mask": attention_mask, <add> "decoder_input_ids": decoder_input_ids, <ide> "labels": labels, <ide> } <ide> return batch <ide><path>src/transformers/trainer.py <ide> def compute_loss(self, model, inputs): <ide> <ide> Subclass and override for custom behavior. <ide> """ <add> if self.label_smoother is not None and "labels" in inputs: <add> labels = inputs.pop("labels") <add> else: <add> labels = None <ide> outputs = model(**inputs) <ide> # Save past state if it exists <ide> # TODO: this needs to be fixed and made cleaner later. <ide> if self.args.past_index >= 0: <ide> self._past = outputs[self.args.past_index] <ide> <del> if self.label_smoother is not None and "labels" in inputs: <del> return self.label_smoother(outputs, inputs["labels"]) <add> if labels is not None: <add> return self.label_smoother(outputs, labels) <ide> else: <ide> # We don't use .loss here since the model may return tuples instead of ModelOutput. <ide> return outputs["loss"] if isinstance(outputs, dict) else outputs[0] <ide><path>src/transformers/trainer_pt_utils.py <ide> class LabelSmoother: <ide> ignore_index: int = -100 <ide> <ide> def __call__(self, model_output, labels): <del> model_loss = model_output["loss"] if isinstance(model_output, dict) else model_output[0] <del> logits = model_output["logits"] if isinstance(model_output, dict) else model_output[1] <add> logits = model_output["logits"] if isinstance(model_output, dict) else model_output[0] <ide> log_probs = -torch.nn.functional.log_softmax(logits, dim=-1) <add> if labels.dim() == log_probs.dim() - 1: <add> labels = labels.unsqueeze(-1) <ide> <del> # Look at the ignored index and mask the corresponding log_probs. <del> padding_mask = labels.unsqueeze(-1).eq(self.ignore_index) <del> log_probs.masked_fill_(padding_mask, 0.0) <add> padding_mask = labels.eq(self.ignore_index) <add> # In case the ignore_index is -100, the gather will fail, so we replace labels by 0. The padding_mask <add> # will ignore them in any case. <add> labels.clamp_min_(0) <add> nll_loss = log_probs.gather(dim=-1, index=labels) <add> smoothed_loss = log_probs.sum(dim=-1, keepdim=True) <add> <add> nll_loss.masked_fill_(padding_mask, 0.0) <add> smoothed_loss.masked_fill_(padding_mask, 0.0) <ide> <ide> # Take the mean over the label dimensions, then divide by the number of active elements (i.e. not-padded): <del> smoothed_loss = log_probs.mean(dim=-1).sum() / (padding_mask.numel() - padding_mask.long().sum()) <del> return (1 - self.epsilon) * model_loss + self.epsilon * smoothed_loss <add> num_active_elements = padding_mask.numel() - padding_mask.long().sum() <add> nll_loss = nll_loss.sum() / num_active_elements <add> smoothed_loss = smoothed_loss.sum() / (num_active_elements * log_probs.shape[-1]) <add> return (1 - self.epsilon) * nll_loss + self.epsilon * smoothed_loss <ide> <ide> <ide> def get_length_grouped_indices(lengths, batch_size, mega_batch_mult=None, generator=None): <ide><path>tests/test_trainer_utils.py <ide> def test_label_smoothing(self): <ide> random_logits = torch.randn(4, 5, num_labels) <ide> random_labels = torch.randint(0, num_labels, (4, 5)) <ide> loss = torch.nn.functional.cross_entropy(random_logits.view(-1, num_labels), random_labels.view(-1)) <del> model_output = SequenceClassifierOutput(loss=loss, logits=random_logits) <add> model_output = SequenceClassifierOutput(logits=random_logits) <ide> label_smoothed_loss = LabelSmoother(0.1)(model_output, random_labels) <ide> log_probs = -torch.nn.functional.log_softmax(random_logits, dim=-1) <ide> expected_loss = (1 - epsilon) * loss + epsilon * log_probs.mean() <ide> def test_label_smoothing(self): <ide> random_labels[2, 3] = -100 <ide> <ide> loss = torch.nn.functional.cross_entropy(random_logits.view(-1, num_labels), random_labels.view(-1)) <del> model_output = SequenceClassifierOutput(loss=loss, logits=random_logits) <add> model_output = SequenceClassifierOutput(logits=random_logits) <ide> label_smoothed_loss = LabelSmoother(0.1)(model_output, random_labels) <ide> log_probs = -torch.nn.functional.log_softmax(random_logits, dim=-1) <ide> # Mask the log probs with the -100 labels
5
Python
Python
rename the quick html generation to 'qhtml'
ca555f0576f8d57c68ab6a88348ce88cfa764918
<ide><path>pavement.py <ide> def clean_docs(options): <ide> <ide> <ide> @task <del>@needs("paver.doctools.html") <add>@needs("clean_docs", "paver.doctools.html") <ide> def html(options): <add> destdir = path("Documentation") <add> destdir.rmtree() <add> builtdocs = sphinx_builddir(options) <add> builtdocs.move(destdir) <add> <add> <add>@task <add>@needs("paver.doctools.html") <add>def qhtml(options): <ide> destdir = path("Documentation") <ide> builtdocs = sphinx_builddir(options) <ide> sh("rsync -az %s/ %s" % (builtdocs, destdir))
1
Text
Text
fix text to follow portuguese language syntax
48f89a06416c24aca4401c42753cb820ae1b29e6
<ide><path>curriculum/challenges/portuguese/01-responsive-web-design/css-flexbox/apply-the-flex-direction-property-to-create-rows-in-the-tweet-embed.portuguese.md <ide> localeTitle: Aplicar a propriedade flex-direction para criar linhas no Tweet Inc <ide> --- <ide> <ide> ## Description <del><section id="description"> O <code>header</code> e o <code>footer</code> do exemplo de incorporação de tweets possuem itens-filhos que podem ser organizados como linhas usando a propriedade <code>flex-direction</code> . Isso informa ao CSS para alinhar os filhos horizontalmente. </section> <add><section id="description"> O <code>header</code> e o <code>footer</code> do exemplo de incorporação de tweets possuem itens-filhos que poderiam ser organizados como linhas usando a propriedade <code>flex-direction</code> . Isso informa ao CSS que alinhe os filhos horizontalmente. </section> <ide> <ide> ## Instructions <del><section id="instructions"> Adicione a propriedade CSS <code>flex-direction</code> ao <code>header</code> e ao <code>footer</code> e defina o valor como row. </section> <add><section id="instructions"> Adicione a propriedade CSS <code>flex-direction</code> ao <code>header</code> e ao <code>footer</code> e defina o valor como *row*. </section> <ide> <ide> ## Tests <ide> <section id='tests'>
1
Text
Text
remove reference to rendering absolute files
b9c05c0fe1468d9917f2136644746ee916797adf
<ide><path>guides/source/layouts_and_rendering.md <ide> render template: "products/show" <ide> <ide> #### Wrapping it up <ide> <del>The above three ways of rendering (rendering another template within the controller, rendering a template within another controller, and rendering an arbitrary file on the file system) are actually variants of the same action. <add>The above two ways of rendering (rendering the template of another action in the same controller, and rendering the template of another action in a different controller) are actually variants of the same operation. <ide> <ide> In fact, in the BooksController class, inside of the update action where we want to render the edit template if the book does not update successfully, all of the following render calls would all render the `edit.html.erb` template in the `views/books` directory: <ide>
1
PHP
PHP
fix fluent interface on route->middleware()
83b7dfd3fa3106b53f85ac4483d33ba2abdc4a34
<ide><path>src/Illuminate/Routing/Route.php <ide> protected function extractOptionalParameters() <ide> * Get or set the middlewares attached to the route. <ide> * <ide> * @param array|string|null $middleware <del> * @return array <add> * @return array|$this <ide> */ <ide> public function middleware($middleware = null) <ide> {
1
PHP
PHP
remove dead tests
b79812894248485a20e28afbffe19d6516746d0d
<ide><path>tests/TestCase/Controller/PagesControllerTest.php <del><?php <del>/** <del> * PagesControllerTest file <del> * <del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * For full copyright and license information, please see the LICENSE.txt <del> * Redistributions of files must retain the above copyright notice <del> * <del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * @link http://cakephp.org CakePHP(tm) Project <del> * @since 1.2.0 <del> * @license http://www.opensource.org/licenses/mit-license.php MIT License <del> */ <del>namespace Cake\Test\TestCase\Controller; <del> <del>use Cake\Core\App; <del>use Cake\Core\Configure; <del>use Cake\Network\Request; <del>use Cake\Network\Response; <del>use Cake\TestSuite\TestCase; <del>use Cake\View\Exception\MissingTemplateException; <del>use TestApp\Controller\PagesController; <del> <del>/** <del> * PagesControllerTest class <del> * <del> */ <del>class PagesControllerTest extends TestCase <del>{ <del> <del> /** <del> * testDisplay method <del> * <del> * @return void <del> */ <del> public function testDisplay() <del> { <del> $Pages = new PagesController(new Request(), new Response()); <del> <del> $Pages->viewBuilder()->templatePath('Posts'); <del> $Pages->display('index'); <del> $this->assertRegExp('/posts index/', $Pages->response->body()); <del> $this->assertEquals('index', $Pages->viewVars['page']); <del> } <del> <del> /** <del> * Test that missing template renders 404 page in production <del> * <del> * @expectedException \Cake\Network\Exception\NotFoundException <del> * @expectedExceptionCode 404 <del> * @return void <del> */ <del> public function testMissingTemplate() <del> { <del> Configure::write('debug', false); <del> $Pages = new PagesController(new Request(), new Response()); <del> $Pages->display('non_existing_page'); <del> } <del> <del> /** <del> * Test that missing template in debug mode renders missing_template error page <del> * <del> * @expectedException \Cake\View\Exception\MissingTemplateException <del> * @expectedExceptionCode 500 <del> * @return void <del> */ <del> public function testMissingTemplateInDebug() <del> { <del> Configure::write('debug', true); <del> $Pages = new PagesController(new Request(), new Response()); <del> $Pages->display('non_existing_page'); <del> } <del>}
1
Python
Python
fix issue #260
3488ebddcf5f3b6761195858939d01e2a5eefbd6
<ide><path>glances/glances.py <ide> batinfo_lib_tag = False <ide> else: <ide> batinfo_lib_tag = True <add>else: <add> batinfo_lib_tag = False <ide> <ide> try: <ide> # HTML output (optional)
1
Javascript
Javascript
restore copyright header
4f883bd0bcdc015e2cf70bcc29bbe05fd5b8a40b
<ide><path>local-cli/link/__tests__/android/applyPatch.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/android/isInstalled.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/android/makeBuildPatch.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/android/makeImportPatch.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/android/makePackagePatch.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/android/makeSettingsPatch.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/android/makeStringsPatch.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/getDependencyConfig.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/getProjectDependencies.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/groupFilesByType.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/ios/addFileToProject.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/ios/addProjectToLibraries.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/ios/addSharedLibraries.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/ios/createGroup.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/ios/getBuildProperty.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/ios/getGroup.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/ios/getHeaderSearchPath.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/ios/getHeadersInFolder.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/ios/getPlist.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/ios/getPlistPath.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/ios/getProducts.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/ios/getTargets.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/ios/hasLibraryImported.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/ios/isInstalled.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/ios/mapHeaderSearchPaths.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/ios/removeProjectFromLibraries.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/ios/removeProjectFromProject.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/ios/removeSharedLibrary.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/ios/writePlist.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/link.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/pods/findLineToAddPod.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/pods/findMarkedLinesInPodfile.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/pods/findPodTargetLine.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/pods/isInstalled.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/pods/removePodEntry.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/__tests__/promiseWaterfall.spec.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/android/copyAssets.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const fs = require('fs-extra'); <ide> const path = require('path'); <ide> const groupFilesByType = require('../groupFilesByType'); <ide><path>local-cli/link/android/fs.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const fs = require('fs-extra'); <ide> <ide> exports.readFile = (file) => <ide><path>local-cli/link/android/isInstalled.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const fs = require('fs'); <ide> const makeBuildPatch = require('./patches/makeBuildPatch'); <ide> <ide><path>local-cli/link/android/patches/applyParams.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/android/patches/applyPatch.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const fs = require('fs'); <ide> <ide> module.exports = function applyPatch(file, patch) { <ide><path>local-cli/link/android/patches/makeBuildPatch.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> module.exports = function makeBuildPatch(name) { <ide> const installPattern = new RegExp( <ide> `\\s{4}(compile)(\\(|\\s)(project)\\(\\\':${name}\\\'\\)(\\)|\\s)` <ide><path>local-cli/link/android/patches/makeImportPatch.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> module.exports = function makeImportPatch(packageImportPath) { <ide> return { <ide> pattern: 'import com.facebook.react.ReactApplication;', <ide><path>local-cli/link/android/patches/makePackagePatch.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const applyParams = require('./applyParams'); <ide> <ide> module.exports = function makePackagePatch(packageInstance, params, prefix) { <ide><path>local-cli/link/android/patches/makeSettingsPatch.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const path = require('path'); <ide> const isWin = process.platform === 'win32'; <ide> <ide><path>local-cli/link/android/patches/makeStringsPatch.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const toCamelCase = require('lodash').camelCase; <ide> <ide> module.exports = function makeStringsPatch(params, prefix) { <ide><path>local-cli/link/android/patches/revokePatch.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const fs = require('fs'); <ide> <ide> module.exports = function revokePatch(file, patch) { <ide><path>local-cli/link/android/registerNativeModule.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const applyPatch = require('./patches/applyPatch'); <ide> const makeStringsPatch = require('./patches/makeStringsPatch'); <ide> const makeSettingsPatch = require('./patches/makeSettingsPatch'); <ide><path>local-cli/link/android/unlinkAssets.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const fs = require('fs-extra'); <ide> const path = require('path'); <ide> const groupFilesByType = require('../groupFilesByType'); <ide><path>local-cli/link/android/unregisterNativeModule.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const fs = require('fs'); <ide> const toCamelCase = require('lodash').camelCase; <ide> <ide><path>local-cli/link/commandStub.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> module.exports = (cb) => cb(); <ide><path>local-cli/link/getDependencyConfig.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> /** <ide> * Given an array of dependencies - it returns their RNPM config <ide> * if they were valid. <ide><path>local-cli/link/getProjectDependencies.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const path = require('path'); <ide> <ide> /** <ide><path>local-cli/link/groupFilesByType.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const groupBy = require('lodash').groupBy; <ide> const mime = require('mime'); <ide> <ide><path>local-cli/link/ios/addFileToProject.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const PbxFile = require('xcode/lib/pbxFile'); <ide> <ide> /** <ide><path>local-cli/link/ios/addProjectToLibraries.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> /** <ide> * Given an array of xcodeproj libraries and pbxFile, <ide> * it appends it to that group <ide><path>local-cli/link/ios/addSharedLibraries.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const createGroupWithMessage = require('./createGroupWithMessage'); <ide> <ide> module.exports = function addSharedLibraries(project, libraries) { <ide><path>local-cli/link/ios/addToHeaderSearchPaths.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const mapHeaderSearchPaths = require('./mapHeaderSearchPaths'); <ide> <ide> module.exports = function addToHeaderSearchPaths(project, path) { <ide><path>local-cli/link/ios/copyAssets.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const fs = require('fs-extra'); <ide> const path = require('path'); <ide> const xcode = require('xcode'); <ide><path>local-cli/link/ios/createGroup.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const getGroup = require('./getGroup'); <ide> <ide> const hasGroup = (pbxGroup, name) => pbxGroup.children.find(group => group.comment === name); <ide><path>local-cli/link/ios/createGroupWithMessage.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const log = require('npmlog'); <ide> <ide> const createGroup = require('./createGroup'); <ide><path>local-cli/link/ios/getBuildProperty.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> /** <ide> * Gets build property from the main target build section <ide> * <ide><path>local-cli/link/ios/getGroup.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const getFirstProject = (project) => project.getFirstProject().firstProject; <ide> <ide> const findGroup = (group, name) => group.children.find(group => group.comment === name); <ide><path>local-cli/link/ios/getHeaderSearchPath.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const path = require('path'); <ide> const union = require('lodash').union; <ide> const last = require('lodash').last; <ide><path>local-cli/link/ios/getHeadersInFolder.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const glob = require('glob'); <ide> const path = require('path'); <ide> <ide><path>local-cli/link/ios/getPlist.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const plistParser = require('plist'); <ide> const getPlistPath = require('./getPlistPath'); <ide> const fs = require('fs'); <ide><path>local-cli/link/ios/getPlistPath.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const path = require('path'); <ide> const getBuildProperty = require('./getBuildProperty'); <ide> <ide><path>local-cli/link/ios/getProducts.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> /** <ide> * Given xcodeproj it returns list of products ending with <ide> * .a extension, so that we know what elements add to target <ide><path>local-cli/link/ios/getTargets.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> /** <ide> * Given xcodeproj it returns list of targets <ide> */ <ide><path>local-cli/link/ios/hasLibraryImported.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> /** <ide> * Given an array of libraries already imported and packageName that will be <ide> * added, returns true or false depending on whether the library is already linked <ide><path>local-cli/link/ios/isInstalled.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const xcode = require('xcode'); <ide> const getGroup = require('./getGroup'); <ide> const hasLibraryImported = require('./hasLibraryImported'); <ide><path>local-cli/link/ios/mapHeaderSearchPaths.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> /** <ide> * Given Xcode project and path, iterate over all build configurations <ide> * and execute func with HEADER_SEARCH_PATHS from current section <ide><path>local-cli/link/ios/registerNativeModule.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const xcode = require('xcode'); <ide> const fs = require('fs'); <ide> const path = require('path'); <ide><path>local-cli/link/ios/removeFromHeaderSearchPaths.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const mapHeaderSearchPaths = require('./mapHeaderSearchPaths'); <ide> <ide> /** <ide><path>local-cli/link/ios/removeFromPbxItemContainerProxySection.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> /** <ide> * For all files that are created and referenced from another `.xcodeproj` - <ide> * a new PBXItemContainerProxy is created that contains `containerPortal` value <ide><path>local-cli/link/ios/removeFromPbxReferenceProxySection.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> /** <ide> * Every file added to the project from another project is attached to <ide> * `PBXItemContainerProxy` through `PBXReferenceProxy`. <ide><path>local-cli/link/ios/removeFromProjectReferences.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> /** <ide> * For each file (.xcodeproj), there's an entry in `projectReferences` created <ide> * that has two entries - `ProjectRef` - reference to a file.uuid and <ide><path>local-cli/link/ios/removeFromStaticLibraries.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const PbxFile = require('xcode/lib/pbxFile'); <ide> const removeFromPbxReferenceProxySection = require('./removeFromPbxReferenceProxySection'); <ide> <ide><path>local-cli/link/ios/removeProductGroup.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> module.exports = function removeProductGroup(project, productGroupId) { <ide> const section = project.hash.project.objects.PBXGroup; <ide> <ide><path>local-cli/link/ios/removeProjectFromLibraries.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> /** <ide> * Given an array of xcodeproj libraries and pbxFile, <ide> * it removes it from that group by comparing basenames <ide><path>local-cli/link/ios/removeProjectFromProject.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const PbxFile = require('xcode/lib/pbxFile'); <ide> const removeFromPbxItemContainerProxySection = require('./removeFromPbxItemContainerProxySection'); <ide> const removeFromProjectReferences = require('./removeFromProjectReferences'); <ide><path>local-cli/link/ios/removeSharedLibraries.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> module.exports = function removeSharedLibraries(project, libraries) { <ide> if (!libraries.length) { <ide> return; <ide><path>local-cli/link/ios/unlinkAssets.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const fs = require('fs-extra'); <ide> const path = require('path'); <ide> const xcode = require('xcode'); <ide><path>local-cli/link/ios/unregisterNativeModule.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const xcode = require('xcode'); <ide> const path = require('path'); <ide> const fs = require('fs'); <ide><path>local-cli/link/ios/writePlist.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const plistParser = require('plist'); <ide> const getPlistPath = require('./getPlistPath'); <ide> const fs = require('fs'); <ide><path>local-cli/link/link.js <ide> /** <del> * Copyright (c) 2013-present, Facebook, Inc. <add> * Copyright (c) 2015-present, Facebook, Inc. <ide> * All rights reserved. <ide> * <ide> * This source code is licensed under the BSD-style license found in the <ide><path>local-cli/link/pods/addPodEntry.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> 'use strict'; <ide> <ide> module.exports = function addPodEntry(podLines, linesToAddEntry, podName, nodePath) { <ide><path>local-cli/link/pods/findLineToAddPod.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> 'use strict'; <ide> <ide> module.exports = function findLineToAddPod(podLines, firstTargetLine) { <ide><path>local-cli/link/pods/findMarkedLinesInPodfile.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> 'use strict'; <ide> const MARKER_TEXT = '# Add new pods below this line'; <ide> <ide><path>local-cli/link/pods/findPodTargetLine.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> 'use strict'; <ide> <ide> module.exports = function findPodTargetLine(podLines, projectName) { <ide><path>local-cli/link/pods/isInstalled.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> 'use strict'; <ide> <ide> const readPodfile = require('./readPodfile'); <ide><path>local-cli/link/pods/readPodfile.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> 'use strict'; <ide> <ide> const fs = require('fs'); <ide><path>local-cli/link/pods/registerNativeModule.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> 'use strict'; <ide> <ide> const readPodfile = require('./readPodfile'); <ide><path>local-cli/link/pods/removePodEntry.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> 'use strict'; <ide> <ide> module.exports = function removePodEntry(podfileContent, podName) { <ide><path>local-cli/link/pods/savePodFile.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> 'use strict'; <ide> <ide> const fs = require('fs'); <ide><path>local-cli/link/pods/unregisterNativeModule.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> 'use strict'; <ide> <ide> const fs = require('fs'); <ide><path>local-cli/link/pollParams.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> var inquirer = require('inquirer'); <ide> <ide> module.exports = (questions) => new Promise((resolve, reject) => { <ide><path>local-cli/link/promiseWaterfall.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> /** <ide> * Given an array of promise creators, executes them in a sequence. <ide> * <ide><path>local-cli/link/promisify.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> module.exports = (func) => new Promise((resolve, reject) => <ide> func((err, res) => err ? reject(err) : resolve(res)) <ide> ); <ide><path>local-cli/link/unlink.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <ide> const log = require('npmlog'); <ide> <ide> const getProjectDependencies = require('./getProjectDependencies');
100
PHP
PHP
add options array
b37b7caa6e74e01da76ca403796835156fe0304e
<ide><path>src/Illuminate/Mail/TransportManager.php <ide> protected function createSesDriver() <ide> 'version' => 'latest', 'service' => 'email', <ide> ]); <ide> <del> return new SesTransport(new SesClient( <del> $this->addSesCredentials($config) <del> )); <add> return new SesTransport( <add> new SesClient($this->addSesCredentials($config)), <add> $config['options'] ?? [] <add> ); <ide> } <ide> <ide> /**
1
Python
Python
require torch when testing examples
eaa6b9afc637d9f2d7ebeb1a89fab2eba4d6c477
<ide><path>tests/test_examples.py <ide> <ide> import os <ide> import unittest <add>from .utils import require_torch <ide> <ide> <ide> def get_examples_from_file(file): <ide> def get_examples_from_file(file): <ide> return ['\n'.join(example) for example in examples] <ide> <ide> <add>@require_torch <ide> class TestCodeExamples(unittest.TestCase): <ide> def test_configuration_examples(self): <ide> transformers_directory = "../src/transformers"
1
Text
Text
fix typos and inline code style
801f892acc21f3a4359c8ebaa4ff3b44dd02b5e0
<ide><path>object_detection/g3doc/running_pets.md <ide> the tarballs, your object_detection directory should appear as follows: <ide> ``` <ide> <ide> The Tensorflow Object Detection API expects data to be in the TFRecord format, <del>so we'll now run the _create_pet_tf_record_ script to convert from the raw <add>so we'll now run the `create_pet_tf_record` script to convert from the raw <ide> Oxford-IIIT Pet dataset into TFRecords. Run the following commands from the <ide> object_detection directory: <ide> <ide> python object_detection/create_pet_tf_record.py \ <ide> Note: It is normal to see some warnings when running this script. You may ignore <ide> them. <ide> <del>Two TFRecord files named pet_train.record and pet_val.record should be generated <add>Two TFRecord files named `pet_train.record` and `pet_val.record` should be generated <ide> in the object_detection/ directory. <ide> <ide> Now that the data has been generated, we'll need to upload it to Google Cloud <ide> Storage so the data can be accessed by ML Engine. Run the following command to <del>copy the files into your GCS bucket (substituting ${YOUR_GCS_BUCKET}): <add>copy the files into your GCS bucket (substituting `${YOUR_GCS_BUCKET}`): <ide> <ide> ``` bash <ide> # From tensorflow/models/ <ide> parameters to initialize our new model. <ide> <ide> Download our [COCO-pretrained Faster R-CNN with Resnet-101 <ide> model](http://storage.googleapis.com/download.tensorflow.org/models/object_detection/faster_rcnn_resnet101_coco_11_06_2017.tar.gz). <del>Unzip the contents of the folder and copy the model.ckpt* files into your GCS <add>Unzip the contents of the folder and copy the `model.ckpt*` files into your GCS <ide> Bucket. <ide> <ide> ``` bash <ide> text editor. <ide> <ide> We'll need to configure some paths in order for the template to work. Search the <ide> file for instances of `PATH_TO_BE_CONFIGURED` and replace them with the <del>appropriate value (typically "gs://${YOUR_GCS_BUCKET}/data/"). Afterwards <add>appropriate value (typically `gs://${YOUR_GCS_BUCKET}/data/`). Afterwards <ide> upload your edited file onto GCS, making note of the path it was uploaded to <ide> (we'll need it when starting the training/eval jobs). <ide> <ide> the following: <ide> ``` <ide> <ide> You can inspect your bucket using the [Google Cloud Storage <del>browser](pantheon.corp.google.com/storage). <add>browser](https://console.cloud.google.com/storage/browser). <ide> <ide> ## Starting Training and Evaluation Jobs on Google Cloud ML Engine <ide> <ide> and `slim/dist/slim-0.1.tar.gz`. <ide> <ide> For running the training Cloud ML job, we'll configure the cluster to use 10 <ide> training jobs (1 master + 9 workers) and three parameters servers. The <del>configuration file can be found at object_detection/samples/cloud/cloud.yml. <add>configuration file can be found at `object_detection/samples/cloud/cloud.yml`. <ide> <ide> To start training, execute the following command from the tensorflow/models/ <ide> directory: <ide> submit training` command is correct. ML Engine does not distinguish between <ide> training and evaluation jobs. <ide> <ide> Users can monitor and stop training and evaluation jobs on the [ML Engine <del>Dasboard](https://console.cloud.google.com/mlengine/jobs). <add>Dashboard](https://console.cloud.google.com/mlengine/jobs). <ide> <ide> ## Monitoring Progress with Tensorboard <ide> <ide> Note: It takes roughly 10 minutes for a job to get started on ML Engine, and <ide> roughly an hour for the system to evaluate the validation dataset. It may take <ide> some time to populate the dashboards. If you do not see any entries after half <ide> an hour, check the logs from the [ML Engine <del>Dasboard](https://pantheon.corp.google.com/mlengine/jobs). <add>Dashboard](https://console.cloud.google.com/mlengine/jobs). <ide> <ide> ## Exporting the Tensorflow Graph <ide> <ide> After your model has been trained, you should export it to a Tensorflow <ide> graph proto. First, you need to identify a candidate checkpoint to export. You <ide> can search your bucket using the [Google Cloud Storage <del>Browser](https://pantheon.corp.google.com/storage/browser). The file should be <del>stored under ${YOUR_GCS_BUCKET}/train. The checkpoint will typically consist of <add>Browser](https://console.cloud.google.com/storage/browser). The file should be <add>stored under `${YOUR_GCS_BUCKET}/train`. The checkpoint will typically consist of <ide> three files: <ide> <ide> * model.ckpt-${CHECKPOINT_NUMBER}.data-00000-of-00001, <ide> python object_detection/export_inference_graph \ <ide> --inference_graph_path output_inference_graph.pb <ide> ``` <ide> <del>Afterwards, you should see a graph named output_inference_graph.pb. <add>Afterwards, you should see a graph named `output_inference_graph.pb`. <ide> <ide> ## What's Next <ide>
1
Ruby
Ruby
use bintray package naming
e5f145ababc6635024260820c98af6e0980a9662
<ide><path>Library/Homebrew/cmd/test-bot.rb <ide> def test_bot <ide> <ide> Dir.glob("*.bottle*.tar.gz") do |filename| <ide> version = Bintray.version filename <del> formula = bottle_filename_formula_name filename <del> existing_bottle = existing_bottles[formula] <add> formula_name = bottle_filename_formula_name filename <add> bintray_package = Bintray.package formula_name <add> existing_bottle = existing_bottles[formula_name] <ide> <ide> # Disable taps temporarily until Bintray sorts our repositories. <ide> next if tap <ide> <del> unless formula_packaged[formula] <del> package_url = "#{bintray_repo_url}/#{formula}" <add> unless formula_packaged[formula_name] <add> package_url = "#{bintray_repo_url}/#{bintray_package}" <ide> unless system "curl", "--silent", "--fail", "--output", "/dev/null", package_url <ide> curl "--silent", "--fail", "-u#{bintray_user}:#{bintray_key}", <ide> "-H", "Content-Type: application/json", <del> "-d", "{\"name\":\"#{formula}\"}", bintray_repo_url <add> "-d", "{\"name\":\"#{bintray_package}\"}", bintray_repo_url <ide> puts <ide> end <del> formula_packaged[formula] = true <add> formula_packaged[formula_name] = true <ide> end <ide> <del> content_url = "https://api.bintray.com/content/homebrew/#{bintray_repo}/#{formula}/#{version}/#{filename}" <add> content_url = "https://api.bintray.com/content/homebrew/#{bintray_repo}/#{bintray_package}/#{version}/#{filename}" <ide> content_url += "?publish=1&override=1" if existing_bottle <ide> curl "--silent", "--fail", "-u#{bintray_user}:#{bintray_key}", <ide> "-T", filename, content_url
1
Mixed
Javascript
add test for fabrictext
f136ae136278c374e24989c693a5b3a0a101178c
<ide><path>Libraries/Text/FabricText.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @providesModule FabricText <add> * @flow <add> * @format <add> */ <add>'use strict'; <add> <add>const React = require('React'); <add>const ReactNative = require('ReactNative'); <add>const ReactNativeViewAttributes = require('ReactNativeViewAttributes'); <add>const TextPropTypes = require('TextPropTypes'); <add>const Touchable = require('Touchable'); <add>const UIManager = require('UIManager'); <add> <add>const {createReactNativeComponentClass} = require('ReactFabricInternals'); <add>const mergeFast = require('mergeFast'); <add>const processColor = require('processColor'); <add>const {ViewContextTypes} = require('ViewContext'); <add> <add>import type {PressEvent} from 'CoreEventTypes'; <add>import type {TextProps} from 'TextProps'; <add>import type {ViewChildContext} from 'ViewContext'; <add> <add>type State = { <add> isHighlighted: boolean, <add>}; <add> <add>type RectOffset = { <add> top: number, <add> left: number, <add> right: number, <add> bottom: number, <add>}; <add> <add>const PRESS_RECT_OFFSET = {top: 20, left: 20, right: 20, bottom: 30}; <add> <add>const viewConfig = { <add> validAttributes: mergeFast(ReactNativeViewAttributes.UIView, { <add> isHighlighted: true, <add> numberOfLines: true, <add> ellipsizeMode: true, <add> allowFontScaling: true, <add> disabled: true, <add> selectable: true, <add> selectionColor: true, <add> adjustsFontSizeToFit: true, <add> minimumFontScale: true, <add> textBreakStrategy: true, <add> }), <add> uiViewClassName: 'RCTText', <add>}; <add> <add>/** <add> * A React component for displaying text. <add> * <add> * See https://facebook.github.io/react-native/docs/text.html <add> */ <add>class Text extends ReactNative.NativeComponent<TextProps, State> { <add> static propTypes = TextPropTypes; <add> static childContextTypes = ViewContextTypes; <add> static contextTypes = ViewContextTypes; <add> <add> static defaultProps = { <add> accessible: true, <add> allowFontScaling: true, <add> ellipsizeMode: 'tail', <add> }; <add> <add> state = mergeFast(Touchable.Mixin.touchableGetInitialState(), { <add> isHighlighted: false, <add> }); <add> <add> viewConfig = viewConfig; <add> <add> getChildContext(): ViewChildContext { <add> return { <add> isInAParentText: true, <add> }; <add> } <add> <add> _handlers: ?Object; <add> <add> _hasPressHandler(): boolean { <add> return !!this.props.onPress || !!this.props.onLongPress; <add> } <add> /** <add> * These are assigned lazily the first time the responder is set to make plain <add> * text nodes as cheap as possible. <add> */ <add> touchableHandleActivePressIn: ?Function; <add> touchableHandleActivePressOut: ?Function; <add> touchableHandlePress: ?Function; <add> touchableHandleLongPress: ?Function; <add> touchableHandleResponderGrant: ?Function; <add> touchableHandleResponderMove: ?Function; <add> touchableHandleResponderRelease: ?Function; <add> touchableHandleResponderTerminate: ?Function; <add> touchableHandleResponderTerminationRequest: ?Function; <add> touchableGetPressRectOffset: ?Function; <add> <add> render(): React.Element<any> { <add> let newProps = this.props; <add> if (this.props.onStartShouldSetResponder || this._hasPressHandler()) { <add> if (!this._handlers) { <add> this._handlers = { <add> onStartShouldSetResponder: (): boolean => { <add> const shouldSetFromProps = <add> this.props.onStartShouldSetResponder && <add> this.props.onStartShouldSetResponder(); <add> const setResponder = shouldSetFromProps || this._hasPressHandler(); <add> if (setResponder && !this.touchableHandleActivePressIn) { <add> // Attach and bind all the other handlers only the first time a touch <add> // actually happens. <add> for (const key in Touchable.Mixin) { <add> if (typeof Touchable.Mixin[key] === 'function') { <add> (this: any)[key] = Touchable.Mixin[key].bind(this); <add> } <add> } <add> this.touchableHandleActivePressIn = () => { <add> if ( <add> this.props.suppressHighlighting || <add> !this._hasPressHandler() <add> ) { <add> return; <add> } <add> this.setState({ <add> isHighlighted: true, <add> }); <add> }; <add> <add> this.touchableHandleActivePressOut = () => { <add> if ( <add> this.props.suppressHighlighting || <add> !this._hasPressHandler() <add> ) { <add> return; <add> } <add> this.setState({ <add> isHighlighted: false, <add> }); <add> }; <add> <add> this.touchableHandlePress = (e: PressEvent) => { <add> this.props.onPress && this.props.onPress(e); <add> }; <add> <add> this.touchableHandleLongPress = (e: PressEvent) => { <add> this.props.onLongPress && this.props.onLongPress(e); <add> }; <add> <add> this.touchableGetPressRectOffset = function(): RectOffset { <add> return this.props.pressRetentionOffset || PRESS_RECT_OFFSET; <add> }; <add> } <add> return setResponder; <add> }, <add> onResponderGrant: function(e: SyntheticEvent<>, dispatchID: string) { <add> // $FlowFixMe TouchableMixin handlers couldn't actually be null <add> this.touchableHandleResponderGrant(e, dispatchID); <add> this.props.onResponderGrant && <add> this.props.onResponderGrant.apply(this, arguments); <add> }.bind(this), <add> onResponderMove: function(e: SyntheticEvent<>) { <add> // $FlowFixMe TouchableMixin handlers couldn't actually be null <add> this.touchableHandleResponderMove(e); <add> this.props.onResponderMove && <add> this.props.onResponderMove.apply(this, arguments); <add> }.bind(this), <add> onResponderRelease: function(e: SyntheticEvent<>) { <add> // $FlowFixMe TouchableMixin handlers couldn't actually be null <add> this.touchableHandleResponderRelease(e); <add> this.props.onResponderRelease && <add> this.props.onResponderRelease.apply(this, arguments); <add> }.bind(this), <add> onResponderTerminate: function(e: SyntheticEvent<>) { <add> // $FlowFixMe TouchableMixin handlers couldn't actually be null <add> this.touchableHandleResponderTerminate(e); <add> this.props.onResponderTerminate && <add> this.props.onResponderTerminate.apply(this, arguments); <add> }.bind(this), <add> onResponderTerminationRequest: function(): boolean { <add> // Allow touchable or props.onResponderTerminationRequest to deny <add> // the request <add> // $FlowFixMe TouchableMixin handlers couldn't actually be null <add> var allowTermination = this.touchableHandleResponderTerminationRequest(); <add> if (allowTermination && this.props.onResponderTerminationRequest) { <add> allowTermination = this.props.onResponderTerminationRequest.apply( <add> this, <add> arguments, <add> ); <add> } <add> return allowTermination; <add> }.bind(this), <add> }; <add> } <add> newProps = { <add> ...this.props, <add> ...this._handlers, <add> isHighlighted: this.state.isHighlighted, <add> }; <add> } <add> if (newProps.selectionColor != null) { <add> newProps = { <add> ...newProps, <add> selectionColor: processColor(newProps.selectionColor), <add> }; <add> } <add> if (Touchable.TOUCH_TARGET_DEBUG && newProps.onPress) { <add> newProps = { <add> ...newProps, <add> style: [this.props.style, {color: 'magenta'}], <add> }; <add> } <add> if (this.context.isInAParentText) { <add> return <RCTVirtualText {...newProps} />; <add> } else { <add> return <RCTText {...newProps} />; <add> } <add> } <add>} <add> <add>var RCTText = createReactNativeComponentClass( <add> viewConfig.uiViewClassName, <add> () => viewConfig, <add>); <add>var RCTVirtualText = RCTText; <add> <add>if (UIManager.RCTVirtualText) { <add> RCTVirtualText = createReactNativeComponentClass('RCTVirtualText', () => ({ <add> validAttributes: mergeFast(ReactNativeViewAttributes.UIView, { <add> isHighlighted: true, <add> }), <add> uiViewClassName: 'RCTVirtualText', <add> })); <add>} <add> <add>module.exports = Text; <ide><path>Libraries/Text/TestFabricText.js <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @providesModule TestFabricText <add> * @flow <add> * @format <add> */ <add>'use strict'; <add> <add>/** <add> * This is a switch on the correct Text to use for Fabric testing purposes <add> */ <add>let TestFabricText; <add>const FabricTestModule = require('NativeModules').FabricTestModule; <add>if (FabricTestModule && FabricTestModule.IS_FABRIC_ENABLED) { <add> TestFabricText = require('FabricText'); <add>} else { <add> TestFabricText = require('Text'); <add>} <add> <add>module.exports = TestFabricText; <ide><path>ReactAndroid/src/main/java/com/facebook/react/common/ArrayUtils.java <ide> public static float[] copyArray(float[] array) { <ide> <ide> public static int[] copyListToArray(List<Integer> list) { <ide> int[] array = new int[list.size()]; <del> for (int t = 0 ; t < list.size() ; t++) { <add> for (int t = 0; t < list.size(); t++) { <ide> array[t] = list.get(t); <ide> } <ide> return array; <ide> } <del> <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricReconciler.java <ide> package com.facebook.react.fabric; <ide> <ide> import android.util.Log; <add>import android.util.SparseArray; <ide> import com.facebook.react.common.ArrayUtils; <ide> import com.facebook.react.uimanager.ReactShadowNode; <ide> import com.facebook.react.uimanager.UIViewOperationQueue; <ide> private void manageChildren( <ide> // It is more efficient to reorder removing and adding all the views in the right order, instead <ide> // of calculating the minimum amount of reorder operations. <ide> Set<Integer> addedTags = new HashSet<>(); <del> ViewAtIndex[] viewsToAdd = new ViewAtIndex[newList.size() - firstRemovedOrAddedViewIndex]; <del> int viewsToAddIndex = 0; <add> List<ViewAtIndex> viewsToAdd = new LinkedList<>(); <ide> for (int k = firstRemovedOrAddedViewIndex; k < newList.size(); k++) { <ide> ReactShadowNode newNode = newList.get(k); <add> if (newNode.isVirtual()) continue; <ide> if (newNode.getNewProps() != null) { <ide> uiViewOperationQueue.enqueueUpdateProperties( <ide> newNode.getReactTag(), newNode.getViewClass(), newNode.getNewProps()); <ide> } <del> viewsToAdd[viewsToAddIndex++] = new ViewAtIndex(newNode.getReactTag(), k); <add> viewsToAdd.add(new ViewAtIndex(newNode.getReactTag(), k)); <ide> List previousChildrenList = newNode.getOriginalReactShadowNode() == null ? null : newNode.getOriginalReactShadowNode().getChildrenList(); <ide> manageChildren(newNode, previousChildrenList, newNode.getChildrenList()); <ide> newNode.setOriginalReactShadowNode(newNode); <ide> private void manageChildren( <ide> int indicesToRemoveIndex = 0; <ide> for (int j = firstRemovedOrAddedViewIndex; j < prevList.size(); j++) { <ide> ReactShadowNode nodeToRemove = prevList.get(j); <add> if (nodeToRemove.isVirtual()) continue; <ide> indicesToRemove[indicesToRemoveIndex++] = j; <ide> if (!addedTags.contains(nodeToRemove.getReactTag())) { <ide> tagsToDelete.add(nodeToRemove.getReactTag()); <ide> private void manageChildren( <ide> } <ide> <ide> int[] tagsToDeleteArray = ArrayUtils.copyListToArray(tagsToDelete); <add> ViewAtIndex[] viewsToAddArray = viewsToAdd.toArray(new ViewAtIndex[viewsToAdd.size()]); <ide> if (DEBUG) { <ide> Log.d( <ide> TAG, <ide> "manageChildren.enqueueManageChildren parent: " + parent.getReactTag() + <ide> "\n\tIndices2Remove: " + Arrays.toString(indicesToRemove) + <del> "\n\tViews2Add: " + Arrays.toString(viewsToAdd) + <add> "\n\tViews2Add: " + Arrays.toString(viewsToAddArray) + <ide> "\n\tTags2Delete: " + Arrays.toString(tagsToDeleteArray)); <ide> } <del> uiViewOperationQueue.enqueueManageChildren( <del> parent.getReactTag(), indicesToRemove, viewsToAdd, tagsToDeleteArray); <add> // TODO (t27180994): Mutate views synchronously on main thread <add> if (indicesToRemove.length > 0 || viewsToAddArray.length > 0 || tagsToDeleteArray.length > 0) { <add> uiViewOperationQueue.enqueueManageChildren( <add> parent.getReactTag(), indicesToRemove, viewsToAddArray, tagsToDeleteArray); <add> } <ide> } <ide> <ide> }
4
Javascript
Javascript
add single source of truth for package versions
6736a38b9abdd19a015929c0279783c92b30d372
<ide><path>ReactVersions.js <add>'use strict'; <add> <add>// This module is the single source of truth for versioning packages that we <add>// publish to npm. <add>// <add>// Packages will not be published unless they are added here. <add>// <add>// The @latest channel uses the version as-is, e.g.: <add>// <add>// 18.0.0 <add>// <add>// The @next channel appends additional information, with the scheme <add>// <version>-<label>-<commit_sha>, e.g.: <add>// <add>// 18.0.0-next-a1c2d3e4 <add>// <add>// (TODO: ^ this isn't enabled quite yet. We still use <version>-<commit_sha>.) <add>// <add>// The @experimental channel doesn't include a version, only a sha, e.g.: <add>// <add>// 0.0.0-experimental-a1c2d3e4 <add> <add>// TODO: Main includes breaking changes. Bump this to 18.0.0. <add>const ReactVersion = '17.0.3'; <add> <add>// The label used by the @next channel. Represents the upcoming release's <add>// stability. Could be "alpha", "beta", "rc", etc. <add>const nextChannelLabel = 'next'; <add> <add>const stablePackages = { <add> 'create-subscription': ReactVersion, <add> 'eslint-plugin-react-hooks': '4.2.1', <add> 'jest-react': '0.12.1', <add> react: ReactVersion, <add> 'react-art': ReactVersion, <add> 'react-dom': ReactVersion, <add> 'react-is': ReactVersion, <add> 'react-reconciler': '0.27.0', <add> 'react-refresh': '0.11.0', <add> 'react-test-renderer': ReactVersion, <add> 'use-subscription': '1.6.0', <add> scheduler: '0.21.0', <add>}; <add> <add>// These packages do not exist in the @next or @latest channel, only <add>// @experimental. We don't use semver, just the commit sha, so this is just a <add>// list of package names instead of a map. <add>const experimentalPackages = [ <add> 'react-fetch', <add> 'react-fs', <add> 'react-pg', <add> 'react-server-dom-webpack', <add> 'react-server', <add>]; <add> <add>// TODO: Export a map of every package and its version. <add>module.exports = { <add> ReactVersion, <add> nextChannelLabel, <add> stablePackages, <add> experimentalPackages, <add>}; <ide><path>packages/shared/ReactVersion.js <ide> // TODO: 17.0.3 has not been released to NPM; <ide> // It exists as a placeholder so that DevTools can support work tag changes between releases. <ide> // When we next publish a release (either 17.0.3 or 17.1.0), update the matching TODO in backend/renderer.js <add>// TODO: This module is used both by the release scripts and to expose a version <add>// at runtime. We should instead inject the version number as part of the build <add>// process, and use the ReactVersions.js module as the single source of truth. <ide> export default '17.0.3'; <ide><path>scripts/release/utils.js <ide> const getCommitFromCurrentBuild = async () => { <ide> }; <ide> <ide> const getPublicPackages = isExperimental => { <add> // TODO: Use ReactVersions.js as source of truth. <ide> if (isExperimental) { <ide> return [ <ide> 'create-subscription', <ide><path>scripts/rollup/build-all-release-channels.js <ide> const {spawnSync} = require('child_process'); <ide> const path = require('path'); <ide> const tmp = require('tmp'); <ide> <add>const { <add> ReactVersion, <add> stablePackages, <add> experimentalPackages, <add>} = require('../../ReactVersions'); <add> <ide> // Runs the build script for both stable and experimental release channels, <ide> // by configuring an environment variable. <ide> <ide> const sha = ( <ide> spawnSync('git', ['show', '-s', '--format=%h']).stdout + '' <ide> ).trim(); <del>const ReactVersion = JSON.parse(fs.readFileSync('packages/react/package.json')) <del> .version; <ide> <ide> if (process.env.CIRCLE_NODE_TOTAL) { <ide> // In CI, we use multiple concurrent processes. Allocate half the processes to <ide> if (process.env.CIRCLE_NODE_TOTAL) { <ide> if (index < halfTotal) { <ide> const nodeTotal = halfTotal; <ide> const nodeIndex = index; <del> const version = '0.0.0-' + sha; <ide> updateTheReactVersionThatDevToolsReads(ReactVersion + '-' + sha); <ide> buildForChannel('stable', nodeTotal, nodeIndex); <del> processStable('./build', version); <add> processStable('./build'); <ide> } else { <ide> const nodeTotal = total - halfTotal; <ide> const nodeIndex = index - halfTotal; <del> const version = '0.0.0-experimental-' + sha; <ide> updateTheReactVersionThatDevToolsReads( <ide> ReactVersion + '-experimental-' + sha <ide> ); <ide> buildForChannel('experimental', nodeTotal, nodeIndex); <del> processExperimental('./build', version); <add> processExperimental('./build'); <ide> } <ide> <ide> // TODO: Currently storing artifacts as `./build2` so that it doesn't conflict <ide> if (process.env.CIRCLE_NODE_TOTAL) { <ide> } else { <ide> // Running locally, no concurrency. Move each channel's build artifacts into <ide> // a temporary directory so that they don't conflict. <del> const stableVersion = '0.0.0-' + sha; <add> updateTheReactVersionThatDevToolsReads(ReactVersion + '-' + sha); <ide> buildForChannel('stable', '', ''); <ide> const stableDir = tmp.dirSync().name; <ide> crossDeviceRenameSync('./build', stableDir); <del> processStable(stableDir, stableVersion); <del> <del> const experimentalVersion = '0.0.0-experimental-' + sha; <add> processStable(stableDir); <add> updateTheReactVersionThatDevToolsReads(ReactVersion + '-experimental-' + sha); <ide> buildForChannel('experimental', '', ''); <ide> const experimentalDir = tmp.dirSync().name; <ide> crossDeviceRenameSync('./build', experimentalDir); <del> processExperimental(experimentalDir, experimentalVersion); <add> processExperimental(experimentalDir); <ide> <ide> // Then merge the experimental folder into the stable one. processExperimental <ide> // will have already removed conflicting files. <ide> function buildForChannel(channel, nodeTotal, nodeIndex) { <ide> }); <ide> } <ide> <del>function processStable(buildDir, version) { <add>function processStable(buildDir) { <ide> if (fs.existsSync(buildDir + '/node_modules')) { <del> updatePackageVersions(buildDir + '/node_modules', version); <add> const defaultVersionIfNotFound = '0.0.0' + '-' + sha; <add> const versionsMap = new Map(); <add> for (const moduleName in stablePackages) { <add> // TODO: Use version declared in ReactVersions module instead of 0.0.0. <add> // const version = stablePackages[moduleName]; <add> // versionsMap.set(moduleName, version + '-' + nextChannelLabel + '-' + sha); <add> versionsMap.set(moduleName, defaultVersionIfNotFound); <add> } <add> updatePackageVersions( <add> buildDir + '/node_modules', <add> versionsMap, <add> defaultVersionIfNotFound <add> ); <ide> fs.renameSync(buildDir + '/node_modules', buildDir + '/oss-stable'); <ide> } <ide> <ide> function processStable(buildDir, version) { <ide> <ide> function processExperimental(buildDir, version) { <ide> if (fs.existsSync(buildDir + '/node_modules')) { <del> updatePackageVersions(buildDir + '/node_modules', version); <add> const defaultVersionIfNotFound = '0.0.0' + '-' + 'experimental' + '-' + sha; <add> const versionsMap = new Map(); <add> for (const moduleName in stablePackages) { <add> versionsMap.set(moduleName, defaultVersionIfNotFound); <add> } <add> for (const moduleName of experimentalPackages) { <add> versionsMap.set(moduleName, defaultVersionIfNotFound); <add> } <add> updatePackageVersions( <add> buildDir + '/node_modules', <add> versionsMap, <add> defaultVersionIfNotFound <add> ); <ide> fs.renameSync(buildDir + '/node_modules', buildDir + '/oss-experimental'); <ide> } <ide> <ide> function crossDeviceRenameSync(source, destination) { <ide> * to match this version for all of the 'React' packages <ide> * (packages available in this repo). <ide> */ <del>function updatePackageVersions(modulesDir, version) { <del> const allReactModuleNames = fs.readdirSync('packages'); <add>function updatePackageVersions( <add> modulesDir, <add> versionsMap, <add> defaultVersionIfNotFound <add>) { <ide> for (const moduleName of fs.readdirSync(modulesDir)) { <add> let version = versionsMap.get(moduleName); <add> if (version === undefined) { <add> // TODO: If the module is not in the version map, we should exclude it <add> // from the build artifacts. <add> version = defaultVersionIfNotFound; <add> } <ide> const packageJSONPath = path.join(modulesDir, moduleName, 'package.json'); <ide> const stats = fs.statSync(packageJSONPath); <ide> if (stats.isFile()) { <ide> function updatePackageVersions(modulesDir, version) { <ide> <ide> if (packageInfo.dependencies) { <ide> for (const dep of Object.keys(packageInfo.dependencies)) { <del> // if it's a react package (available in the current repo), update the version <del> // TODO: is this too broad? Assumes all of the packages were built. <del> if (allReactModuleNames.includes(dep)) { <add> if (modulesDir.includes(dep)) { <ide> packageInfo.dependencies[dep] = version; <ide> } <ide> } <ide> } <ide> if (packageInfo.peerDependencies) { <ide> for (const dep of Object.keys(packageInfo.peerDependencies)) { <del> if (allReactModuleNames.includes(dep)) { <add> if (modulesDir.includes(dep)) { <ide> packageInfo.peerDependencies[dep] = version; <ide> } <ide> }
4
Text
Text
give better instructions on alignment p-tags
dbdc7042714582e4eb541b9a38f69cd4b94c4b8c
<ide><path>curriculum/challenges/english/01-responsive-web-design/basic-html-and-html5/introduction-to-html5-elements.md <ide> Example usage, a `main` element with two child elements nested inside it: <ide> <ide> # --instructions-- <ide> <del>Create a second `p` element after the existing `p` element with the following kitty ipsum text: `Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched.` <add>Create a second `p` element with the following kitty ipsum text: `Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched.` <ide> <del>Then, create a `main` element and nest the two `p` elements inside the `main` element. <add>Then, create a `main` element and nest only the two `p` elements inside the `main` element. <ide> <ide> # --hints-- <ide>
1
Ruby
Ruby
run tests under actual os version
2e2d9221901e072bf9aa684ffebcb441af01d93f
<ide><path>Library/Homebrew/test/testing_env.rb <ide> RUBY_PATH = RUBY_BIN + RbConfig::CONFIG['ruby_install_name'] + RbConfig::CONFIG['EXEEXT'] <ide> <ide> MACOS = true <del>MACOS_VERSION = ENV.fetch('MACOS_VERSION', 10.6) <del>MACOS_FULL_VERSION = '10.6.8' <add>MACOS_FULL_VERSION = `/usr/bin/sw_vers -productVersion`.chomp <add>MACOS_VERSION = ENV.fetch('MACOS_VERSION') { MACOS_FULL_VERSION[/10\.\d+/] }.to_f <ide> <ide> ORIGINAL_PATHS = ENV['PATH'].split(':').map{ |p| Pathname.new(p).expand_path rescue nil }.compact.freeze <ide>
1
Python
Python
switch metrics in run_ner to datasets
46ed56cfd1544296feb73b707022149cf03f8c5e
<ide><path>examples/test_examples.py <ide> def test_run_ner(self): <ide> <ide> with patch.object(sys, "argv", testargs): <ide> result = run_ner.main() <del> self.assertGreaterEqual(result["eval_accuracy_score"], 0.75) <add> self.assertGreaterEqual(result["eval_accuracy"], 0.75) <ide> self.assertGreaterEqual(result["eval_precision"], 0.75) <ide> self.assertLess(result["eval_loss"], 0.5) <ide> <ide><path>examples/token-classification/run_ner.py <ide> from typing import Optional <ide> <ide> import numpy as np <del>from datasets import ClassLabel, load_dataset <del>from seqeval.metrics import accuracy_score, f1_score, precision_score, recall_score <add>from datasets import ClassLabel, load_dataset, load_metric <ide> <ide> import transformers <ide> from transformers import ( <ide> class DataTrainingArguments: <ide> "one (in which case the other tokens will have a padding index)." <ide> }, <ide> ) <add> return_entity_level_metrics: bool = field( <add> default=False, <add> metadata={"help": "Whether to return all the entity levels during evaluation or just the overall ones."}, <add> ) <ide> <ide> def __post_init__(self): <ide> if self.dataset_name is None and self.train_file is None and self.validation_file is None: <ide> def tokenize_and_align_labels(examples): <ide> data_collator = DataCollatorForTokenClassification(tokenizer) <ide> <ide> # Metrics <add> metric = load_metric("seqeval") <add> <ide> def compute_metrics(p): <ide> predictions, labels = p <ide> predictions = np.argmax(predictions, axis=2) <ide> def compute_metrics(p): <ide> for prediction, label in zip(predictions, labels) <ide> ] <ide> <del> return { <del> "accuracy_score": accuracy_score(true_labels, true_predictions), <del> "precision": precision_score(true_labels, true_predictions), <del> "recall": recall_score(true_labels, true_predictions), <del> "f1": f1_score(true_labels, true_predictions), <del> } <add> results = metric.compute(predictions=true_predictions, references=true_labels) <add> if data_args.return_entity_level_metrics: <add> # Unpack nested dictionaries <add> final_results = {} <add> for key, value in results.items(): <add> if isinstance(value, dict): <add> for n, v in value.items(): <add> final_results[f"{key}_{n}"] = v <add> else: <add> final_results[key] = value <add> return final_results <add> else: <add> return { <add> "precision": results["overall_precision"], <add> "recall": results["overall_recall"], <add> "f1": results["overall_f1"], <add> "accuracy": results["overall_accuracy"], <add> } <ide> <ide> # Initialize our Trainer <ide> trainer = Trainer(
2
Python
Python
display conf as a json in the dagrun list view
e6a0a5374dabc431542113633148445e4c5159b9
<ide><path>airflow/www/utils.py <ide> def dt(attr): # pylint: disable=invalid-name <ide> # pylint: enable=invalid-name <ide> <ide> <add>def json_f(attr_name): <add> """Returns a formatted string with HTML for given JSON serializable""" <add> def json_(attr): <add> f = attr.get(attr_name) <add> serialized = json.dumps(f) <add> return Markup('<nobr>{}</nobr>').format(serialized) # noqa <add> return json_ <add> <add> <ide> def dag_link(attr): <ide> """Generates a URL to the Graph View for a Dag.""" <ide> dag_id = attr.get('dag_id') <ide><path>airflow/www/views.py <ide> class DagRunModelView(AirflowModelView): <ide> 'start_date': wwwutils.datetime_f('start_date'), <ide> 'dag_id': wwwutils.dag_link, <ide> 'run_id': wwwutils.dag_run_link, <add> 'conf': wwwutils.json_f('conf'), <ide> } <ide> <ide> @action('muldelete', "Delete", "Are you sure you want to delete selected records?", <ide><path>tests/www/test_views.py <ide> def test_list_dagrun_includes_conf(self): <ide> self.assertEqual(dr.conf, {"include": "me"}) <ide> <ide> resp = self.client.get('/dagrun/list', follow_redirects=True) <del> self.check_content_in_response("{&#39;include&#39;: &#39;me&#39;}", resp) <add> self.check_content_in_response("{&#34;include&#34;: &#34;me&#34;}", resp) <ide> <ide> <ide> class TestDecorators(TestBase):
3
Javascript
Javascript
expose clonewithprops on addons
1167aeb453233c50b8f4de67319246235adbfa87
<ide><path>src/browser/ReactWithAddons.js <ide> var ReactCSSTransitionGroup = require('ReactCSSTransitionGroup'); <ide> var ReactTransitionGroup = require('ReactTransitionGroup'); <ide> <ide> var cx = require('cx'); <add>var cloneWithProps = require('cloneWithProps'); <ide> <ide> React.addons = { <del> classSet: cx, <ide> LinkedStateMixin: LinkedStateMixin, <ide> CSSTransitionGroup: ReactCSSTransitionGroup, <del> TransitionGroup: ReactTransitionGroup <add> TransitionGroup: ReactTransitionGroup, <add> <add> classSet: cx, <add> cloneWithProps: cloneWithProps <ide> }; <ide> <ide> module.exports = React;
1
Text
Text
fix typo in step 96 of learn css variables project
62b7e90b75e97e7f45fea24d329c6afcb27c9607
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-css-variables-by-building-a-city-skyline/5d822fd413a79914d39e9929.md <ide> dashedName: step-96 <ide> <ide> # --description-- <ide> <del>Only three more building to go. Nest two new `div` elements within the `.fb4` element and give them the classes of `fb4a` and `fb4b`, in that order. Remember that you sort of flipped the location of `.fb4` and `.fb5`, so it's the rightmost purple building you are working on now. <add>Only three more buildings to go. Nest two new `div` elements within the `.fb4` element and give them the classes of `fb4a` and `fb4b`, in that order. Remember that you sort of flipped the location of `.fb4` and `.fb5`, so it's the rightmost purple building you are working on now. <ide> <ide> # --hints-- <ide>
1
Java
Java
fix regression in abstractjackson2decoder
113db2fb2f6a1ad73d37bfe83c5dbbb22edb296e
<ide><path>spring-web/src/main/java/org/springframework/http/codec/json/AbstractJackson2Decoder.java <ide> public List<MimeType> getDecodableMimeTypes() { <ide> return getMimeTypes(); <ide> } <ide> <add> @Override <add> public List<MimeType> getDecodableMimeTypes(ResolvableType targetType) { <add> return getMimeTypes(targetType); <add> } <ide> <ide> // Jackson2CodecSupport <ide> <ide><path>spring-web/src/test/java/org/springframework/http/codec/json/Jackson2JsonDecoderTests.java <ide> /* <del> * Copyright 2002-2021 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> public void canDecode() { <ide> <ide> @Test <ide> public void canDecodeWithObjectMapperRegistrationForType() { <del> MediaType halJsonMediaType = MediaType.parseMediaType("application/hal+json"); <add> MediaType halJsonMediaType = MediaType.parseMediaType("application/hal+json"); <ide> MediaType halFormsJsonMediaType = MediaType.parseMediaType("application/prs.hal-forms+json"); <ide> <ide> assertThat(decoder.canDecode(ResolvableType.forClass(Pojo.class), halJsonMediaType)).isTrue(); <ide> public void decodableMimeTypesIsImmutable() { <ide> decoder.getMimeTypes().add(new MimeType("text", "ecmascript"))); <ide> } <ide> <add> @Test <add> public void decodableMimeTypesWithObjectMapperRegistration() { <add> MimeType mimeType1 = MediaType.parseMediaType("application/hal+json"); <add> MimeType mimeType2 = new MimeType("text", "javascript", StandardCharsets.UTF_8); <add> <add> Jackson2JsonDecoder decoder = new Jackson2JsonDecoder(new ObjectMapper(), mimeType2); <add> decoder.registerObjectMappersForType(Pojo.class, map -> map.put(mimeType1, new ObjectMapper())); <add> <add> assertThat(decoder.getDecodableMimeTypes(ResolvableType.forClass(Pojo.class))) <add> .containsExactly(mimeType1); <add> } <add> <ide> @Override <ide> @Test <ide> public void decode() {
2
Text
Text
add plugin debug docs
94c40a30747ce77dc2191627645fec9c71a90a99
<ide><path>docs/extend/index.md <ide> title: Managed plugin system <ide> <ide> * [Installing and using a plugin](index.md#installing-and-using-a-plugin) <ide> * [Developing a plugin](index.md#developing-a-plugin) <add>* [Debugging plugins](index.md#debugging-plugins) <ide> <ide> Docker Engine's plugins system allows you to install, start, stop, and remove <del>plugins using Docker Engine. This mechanism is currently only available for <del>volume drivers, but more plugin driver types will be available in future releases. <add>plugins using Docker Engine. <ide> <ide> For information about the legacy plugin system available in Docker Engine 1.12 <ide> and earlier, see [Understand legacy Docker Engine plugins](legacy_plugins.md). <ide> Consider the following `config.json` file. <ide> "types": ["docker.volumedriver/1.0"], <ide> "socket": "sshfs.sock" <ide> }, <del> "capabilities": ["CAP_SYS_ADMIN"] <add> "linux": { <add> "capabilities": ["CAP_SYS_ADMIN"] <add> } <ide> } <ide> ``` <ide> <ide> in subdirectory `rootfs`. <ide> After that the plugin `<plugin-name>` will show up in `docker plugin ls`. <ide> Plugins can be pushed to remote registries with <ide> `docker plugin push <plugin-name>`. <add> <add> <add>## Debugging plugins <add> <add>Stdout of a plugin is redirected to dockerd logs. Such entries have a <add>`plugin=<ID>` suffix. Here are a few examples of commands for pluginID <add>`f52a3df433b9aceee436eaada0752f5797aab1de47e5485f1690a073b860ff62` and their <add>corresponding log entries in the docker daemon logs. <add> <add>```bash <add>$ docker plugin install tiborvass/sample-volume-plugins <add> <add>INFO[0036] Starting... Found 0 volumes on startup plugin=f52a3df433b9aceee436eaada0752f5797aab1de47e5485f1690a073b860ff62 <add>``` <add> <add>```bash <add>$ docker volume create -d tiborvass/sample-volume-plugins samplevol <add> <add>INFO[0193] Create Called... Ensuring directory /data/samplevol exists on host... plugin=f52a3df433b9aceee436eaada0752f5797aab1de47e5485f1690a073b860ff62 <add>INFO[0193] open /var/lib/docker/plugin-data/local-persist.json: no such file or directory plugin=f52a3df433b9aceee436eaada0752f5797aab1de47e5485f1690a073b860ff62 <add>INFO[0193] Created volume samplevol with mountpoint /data/samplevol plugin=f52a3df433b9aceee436eaada0752f5797aab1de47e5485f1690a073b860ff62 <add>INFO[0193] Path Called... Returned path /data/samplevol plugin=f52a3df433b9aceee436eaada0752f5797aab1de47e5485f1690a073b860ff62 <add>``` <add> <add>```bash <add>$ docker run -v samplevol:/tmp busybox sh <add> <add>INFO[0421] Get Called... Found samplevol plugin=f52a3df433b9aceee436eaada0752f5797aab1de47e5485f1690a073b860ff62 <add>INFO[0421] Mount Called... Mounted samplevol plugin=f52a3df433b9aceee436eaada0752f5797aab1de47e5485f1690a073b860ff62 <add>INFO[0421] Path Called... Returned path /data/samplevol plugin=f52a3df433b9aceee436eaada0752f5797aab1de47e5485f1690a073b860ff62 <add>INFO[0421] Unmount Called... Unmounted samplevol plugin=f52a3df433b9aceee436eaada0752f5797aab1de47e5485f1690a073b860ff62 <add>``` <add> <add>#### Using docker-runc to obtain logfiles and shell into the plugin. <add> <add>`docker-runc`, the default docker container runtime can be used for debugging <add>plugins. This is specifically useful to collect plugin logs if they are <add>redirected to a file. <add> <add>```bash <add>$ docker-runc list <add>ID PID STATUS BUNDLE CREATED <add>f52a3df433b9aceee436eaada0752f5797aab1de47e5485f1690a073b860ff62 2679 running /run/docker/libcontainerd/f52a3df433b9aceee436eaada0752f5797aab1de47e5485f1690a073b860ff62 2017-02-06T21:53:03.031537592Z <add>r <add>``` <add> <add>```bash <add>$ docker-runc exec f52a3df433b9aceee436eaada0752f5797aab1de47e5485f1690a073b860ff62 cat /var/log/plugin.log <add>``` <add> <add>If the plugin has a built-in shell, then exec into the plugin can be done as <add>follows: <add>```bash <add>$ docker-runc exec -t f52a3df433b9aceee436eaada0752f5797aab1de47e5485f1690a073b860ff62 sh <add>``` <add>
1
PHP
PHP
improve code readbility
084ab254e7715d4d595ca6319bd48fad975940bd
<ide><path>src/Cache/Engine/FileEngine.php <ide> <ide> use Cake\Cache\CacheEngine; <ide> use Cake\Utility\Inflector; <add>use CallbackFilterIterator; <ide> use Exception; <ide> use LogicException; <ide> use RecursiveDirectoryIterator; <ide> public function key($key) <ide> public function clearGroup($group) <ide> { <ide> $this->_File = null; <add> <add> $prefix = (string)$this->_config['prefix']; <add> <ide> $directoryIterator = new RecursiveDirectoryIterator($this->_config['path']); <ide> $contents = new RecursiveIteratorIterator( <ide> $directoryIterator, <ide> RecursiveIteratorIterator::CHILD_FIRST <ide> ); <del> foreach ($contents as $object) { <del> $containsGroup = strpos($object->getPathname(), DIRECTORY_SEPARATOR . $group . DIRECTORY_SEPARATOR) !== false; <del> $hasPrefix = true; <del> if (strlen($this->_config['prefix']) !== 0) { <del> $hasPrefix = strpos($object->getBasename(), $this->_config['prefix']) === 0; <del> } <del> if ($object->isFile() && $containsGroup && $hasPrefix) { <del> $path = $object->getPathname(); <del> $object = null; <del> //@codingStandardsIgnoreStart <del> @unlink($path); <del> //@codingStandardsIgnoreEnd <add> $filtered = new CallbackFilterIterator( <add> $contents, <add> function ($current) use ($group, $prefix) { <add> if (!$current->isFile()) { <add> return false; <add> } <add> <add> $hasPrefix = $prefix === '' <add> || strpos($current->getBasename(), $prefix) === 0; <add> if ($hasPrefix === false) { <add> return false; <add> } <add> <add> $pos = strpos( <add> $current->getPathname(), <add> DIRECTORY_SEPARATOR . $group . DIRECTORY_SEPARATOR <add> ); <add> <add> return $pos !== false; <ide> } <add> ); <add> foreach ($filtered as $object) { <add> $path = $object->getPathname(); <add> $object = null; <add> // @codingStandardsIgnoreLine <add> @unlink($path); <ide> } <ide> <ide> return true;
1
Ruby
Ruby
define `arel_visitor` method on all adapters
dd58c3bf23ded02a2d8fbf7a20f577486b8cba9f
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb <ide> def collector <ide> end <ide> <ide> def arel_visitor # :nodoc: <del> (Arel::Visitors::VISITORS[@config[:adapter]] || Arel::Visitors::ToSql).new(self) <add> Arel::Visitors::ToSql.new(self) <ide> end <ide> <ide> def valid_type?(type) <ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb <ide> def schema_creation <ide> MySQL::SchemaCreation.new(self) <ide> end <ide> <add> def arel_visitor # :nodoc: <add> Arel::Visitors::MySQL.new(self) <add> end <add> <ide> ## <ide> # :singleton-method: <ide> # By default, the Mysql2Adapter will consider all columns of type <tt>tinyint(1)</tt> <ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb <ide> def schema_creation # :nodoc: <ide> PostgreSQL::SchemaCreation.new self <ide> end <ide> <add> def arel_visitor # :nodoc: <add> Arel::Visitors::PostgreSQL.new(self) <add> end <add> <ide> # Returns true, since this connection adapter supports prepared statement <ide> # caching. <ide> def supports_statement_cache? <ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb <ide> def schema_creation # :nodoc: <ide> SQLite3::SchemaCreation.new self <ide> end <ide> <add> def arel_visitor # :nodoc: <add> Arel::Visitors::SQLite.new(self) <add> end <add> <ide> def initialize(connection, logger, connection_options, config) <ide> super(connection, logger, config) <ide>
4
Javascript
Javascript
fix devtools v4.1 editable hook regression
9b3cde9b627e91f9d4a81093384d579928474c37
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/EditableValue.js <ide> type OverrideValueFn = (path: Array<string | number>, value: any) => void; <ide> <ide> type EditableValueProps = {| <ide> className?: string, <del> dataType: string, <ide> initialValue: any, <ide> overrideValueFn: OverrideValueFn, <ide> path: Array<string | number>, <ide> |}; <ide> <ide> export default function EditableValue({ <ide> className = '', <del> dataType, <ide> initialValue, <ide> overrideValueFn, <ide> path, <ide><path>packages/react-devtools-shared/src/devtools/views/Components/HooksTree.js <ide> function HookView({canEditHooks, hook, id, inspectPath, path}: HookViewProps) { <ide> </span> <ide> {typeof overrideValueFn === 'function' ? ( <ide> <EditableValue <del> dataType={type} <add> initialValue={value} <ide> overrideValueFn={overrideValueFn} <ide> path={[]} <del> value={value} <ide> /> <ide> ) : ( <ide> // $FlowFixMe Cannot create span element because in property children <ide><path>packages/react-devtools-shared/src/devtools/views/Components/KeyValue.js <ide> export default function KeyValue({ <ide> </span> <ide> {isEditable ? ( <ide> <EditableValue <del> dataType={dataType} <add> initialValue={value} <ide> overrideValueFn={((overrideValueFn: any): OverrideValueFn)} <ide> path={path} <del> initialValue={value} <ide> /> <ide> ) : ( <ide> <span className={styles.Value}>{displayValue}</span> <ide><path>packages/react-devtools-shared/src/devtools/views/hooks.js <ide> */ <ide> <ide> import throttle from 'lodash.throttle'; <del>import { <del> useCallback, <del> useEffect, <del> useLayoutEffect, <del> useMemo, <del> useState, <del>} from 'react'; <add>import {useCallback, useEffect, useLayoutEffect, useState} from 'react'; <ide> import {unstable_batchedUpdates as batchedUpdates} from 'react-dom'; <ide> import { <ide> localStorageGetItem, <ide> export function useEditableValue( <ide> const [parsedValue, setParsedValue] = useState(initialValue); <ide> const [isValid, setIsValid] = useState(initialIsValid); <ide> <del> const reset = useCallback(() => { <del> setEditableValue(smartStringify(initialValue)); <del> setParsedValue(initialValue); <del> setIsValid(initialIsValid); <del> }, []); <add> const reset = useCallback( <add> () => { <add> setEditableValue(smartStringify(initialValue)); <add> setParsedValue(initialValue); <add> setIsValid(initialIsValid); <add> }, <add> [initialValue, initialIsValid], <add> ); <ide> <ide> const update = useCallback(newValue => { <ide> let isNewValueValid = false; <ide> export function useEditableValue( <ide> }); <ide> }, []); <ide> <del> return useMemo( <del> () => ({ <del> editableValue, <del> hasPendingChanges: smartStringify(initialValue) !== editableValue, <del> isValid, <del> parsedValue, <del> reset, <del> update, <del> }), <del> [editableValue, initialValue, isValid, parsedValue], <del> ); <add> return { <add> editableValue, <add> hasPendingChanges: smartStringify(initialValue) !== editableValue, <add> isValid, <add> parsedValue, <add> reset, <add> update, <add> }; <ide> } <ide> <ide> export function useIsOverflowing(
4
Ruby
Ruby
add lib/dtrace to non-owned directories
040d655d8d23a6f90003f7c8e15574ab8d2aea1d
<ide><path>Library/Homebrew/keg.rb <ide> def link mode=OpenStruct.new <ide> # pkg-config database gets explicitly created <ide> when 'pkgconfig' then :mkpath <ide> # lib/language folders also get explicitly created <add> when 'dtrace' then :mkpath <ide> when /^gdk-pixbuf/ then :mkpath <ide> when 'ghc' then :mkpath <ide> when 'lua' then :mkpath
1
Text
Text
fix image scaling
e36b7bbd289ce1de56fd972be55d4f508b515b2c
<ide><path>threejs/lessons/threejs-align-html-elements-to-3d.md <ide> There are a couple of issues we probably want to deal with. <ide> One is that if we rotate the objects so they overlap all the labels <ide> overlap as well. <ide> <del><img src="resources/images/overlapping-labels.png" class="threejs_center" style="width: 307px;"> <add><div class="threejs_center"><img src="resources/images/overlapping-labels.png" style="width: 307px;"></div> <ide> <ide> Another is that if we zoom way out so that the objects go outside <ide> the frustum the labels will still appear. <ide> I [wrote some code](https://github.com/greggman/threejsfundamentals/blob/master/ <ide> to load the data, and generate country outlines and some JSON data with the names <ide> of the countries and their locations. <ide> <del><img src="../resources/data/world/country-outlines-4k.png" style="background: black; width: 700px"> <add><div class="threejs_center"><img src="../resources/data/world/country-outlines-4k.png" style="background: black; width: 700px"></div> <ide> <ide> The JSON data is an array of entries something like this <ide>
1
PHP
PHP
add various kinds of non length based indexes
55f7c98fbed3ff6b5fd51a2ae78314940e7db6d7
<ide><path>lib/Cake/Database/Schema/MysqlSchema.php <ide> public function indexSql(Table $table, $name) { <ide> ); <ide> return sprintf('PRIMARY KEY (%s)', implode(', ', $columns)); <ide> } <add> if ($data['type'] === Table::INDEX_UNIQUE) { <add> $out = 'UNIQUE KEY '; <add> } <add> if ($data['type'] === Table::INDEX_INDEX) { <add> $out = 'KEY '; <add> } <add> if ($data['type'] === Table::INDEX_FULLTEXT) { <add> $out = 'FULLTEXT KEY '; <add> } <add> // TODO finish MySQL indexes with length <add> $out .= $this->_driver->quoteIdentifier($name); <add> <add> $columns = array_map( <add> [$this->_driver, 'quoteIdentifier'], <add> $data['columns'] <add> ); <add> return $out . ' (' . implode(', ', $columns) . ')'; <add> /* <add> $out = ''; <add> if ($name === 'PRIMARY') { <add> $out .= 'PRIMARY '; <add> $name = null; <add> } else { <add> if (!empty($value['unique'])) { <add> $out .= 'UNIQUE '; <add> } <add> $name = $this->startQuote . $name . $this->endQuote; <add> } <add> if (isset($value['type']) && strtolower($value['type']) === 'fulltext') { <add> $out .= 'FULLTEXT '; <add> } <add> $out .= 'KEY ' . $name . ' ('; <add> <add> if (is_array($value['column'])) { <add> if (isset($value['length'])) { <add> $vals = array(); <add> foreach ($value['column'] as $column) { <add> $name = $this->name($column); <add> if (isset($value['length'])) { <add> $name .= $this->_buildIndexSubPart($value['length'], $column); <add> } <add> $vals[] = $name; <add> } <add> $out .= implode(', ', $vals); <add> } else { <add> $out .= implode(', ', array_map(array(&$this, 'name'), $value['column'])); <add> } <add> } else { <add> $out .= $this->name($value['column']); <add> if (isset($value['length'])) { <add> $out .= $this->_buildIndexSubPart($value['length'], $value['column']); <add> } <add> } <add> $out .= ')'; <add> $join[] = $out; <add> */ <ide> } <ide> <ide> } <ide><path>lib/Cake/Database/Schema/Table.php <ide> class Table { <ide> self::INDEX_INDEX, <ide> self::INDEX_UNIQUE, <ide> self::INDEX_FOREIGN, <add> self::INDEX_FULLTEXT, <ide> ]; <ide> <ide> const INDEX_PRIMARY = 'primary'; <ide> const INDEX_INDEX = 'index'; <ide> const INDEX_UNIQUE = 'unique'; <add> const INDEX_FULLTEXT = 'fulltext'; <ide> const INDEX_FOREIGN = 'foreign'; <ide> <ide> /** <ide><path>lib/Cake/Test/TestCase/Database/Schema/MysqlSchemaTest.php <ide> public function testColumnSqlPrimaryKey() { <ide> } <ide> <ide> /** <del> * Integration test for converting a Schema\Table into MySQL table creates. <add> * Provider for table creation tests. <ide> * <del> * @return void <add> * @return array <ide> */ <del> public function testCreateTableSql() { <del> $table = (new Table('posts'))->addColumn('id', [ <add> public static function createTableProvider() { <add> $basic = (new Table('posts'))->addColumn('id', [ <ide> 'type' => 'integer', <ide> 'null' => false <ide> ]) <ide> public function testCreateTableSql() { <ide> 'columns' => ['id'] <ide> ]); <ide> <del> $driver = $this->_getMockedDriver(); <del> $connection = $this->getMock('Cake\Database\Connection', array(), array(), '', false); <del> $connection->expects($this->any())->method('driver') <del> ->will($this->returnValue($driver)); <del> <del> $result = $table->createTableSql($connection); <del> $expected = <<<SQL <add> $basicExpected = <<<SQL <ide> CREATE TABLE `posts` ( <ide> `id` INTEGER NOT NULL AUTO_INCREMENT, <ide> `title` VARCHAR(255) NOT NULL COMMENT "The title", <ide> public function testCreateTableSql() { <ide> PRIMARY KEY (`id`) <ide> ); <ide> SQL; <add> <add> $uniqueKey = (new Table('articles_authors')) <add> ->addColumn('author_id', [ <add> 'type' => 'integer', <add> 'null' => false <add> ]) <add> ->addColumn('article_id', [ <add> 'type' => 'integer', <add> 'null' => false, <add> ]) <add> ->addIndex('unique_idx', [ <add> 'type' => 'unique', <add> 'columns' => ['author_id', 'article_id'] <add> ]); <add> $uniqueExpected = <<<SQL <add>CREATE TABLE `articles_authors` ( <add>`author_id` INTEGER NOT NULL, <add>`article_id` INTEGER NOT NULL, <add>UNIQUE KEY `unique_idx` (`author_id`, `article_id`) <add>); <add>SQL; <add> $simpleKey = (new Table('things')) <add> ->addColumn('thing_id', [ <add> 'type' => 'integer', <add> ]) <add> ->addIndex('thing_id_idx', [ <add> 'type' => 'index', <add> 'columns' => ['thing_id'] <add> ]); <add> $simpleKeyExpected = <<<SQL <add>CREATE TABLE `things` ( <add>`thing_id` INTEGER, <add>KEY `thing_id_idx` (`thing_id`) <add>); <add>SQL; <add> <add> $fullText = (new Table('things')) <add> ->addColumn('stuff', [ <add> 'type' => 'text', <add> ]) <add> ->addIndex('stuff_idx', [ <add> 'type' => 'fulltext', <add> 'columns' => ['stuff'] <add> ]); <add> $fullTextExpected = <<<SQL <add>CREATE TABLE `things` ( <add>`stuff` TEXT, <add>FULLTEXT KEY `stuff_idx` (`stuff`) <add>); <add>SQL; <add> return [ <add> [$basic, $basicExpected], <add> [$uniqueKey, $uniqueExpected], <add> [$fullText, $fullTextExpected], <add> [$simpleKey, $simpleKeyExpected], <add> ]; <add> } <add> <add>/** <add> * Integration test for converting a Schema\Table into MySQL table creates. <add> * <add> * @dataProvider createTableProvider <add> * @return void <add> */ <add> public function testCreateTableSql($table, $expected) { <add> $driver = $this->_getMockedDriver(); <add> $connection = $this->getMock('Cake\Database\Connection', array(), array(), '', false); <add> $connection->expects($this->any())->method('driver') <add> ->will($this->returnValue($driver)); <add> <add> $result = $table->createTableSql($connection); <ide> $this->assertEquals($expected, $result); <ide> } <ide> <ide> protected function _getMockedDriver() { <ide> ->will($this->returnCallback(function ($value) { <ide> return '"' . $value . '"'; <ide> })); <add> $mock->expects($this->any()) <add> ->method('quoteIdentifier') <add> ->will($this->returnCallback(function ($value) { <add> return '`' . $value . '`'; <add> })); <ide> $driver->connection($mock); <ide> return $driver; <ide> }
3
Ruby
Ruby
chage `date_time` type ` to `datetime`
a7d6aa389343ee258f19a4fe71869f7ebf3a6a4d
<ide><path>activerecord/lib/active_record/type.rb <ide> def current_adapter_name <ide> register(:binary, Type::Binary, override: false) <ide> register(:boolean, Type::Boolean, override: false) <ide> register(:date, Type::Date, override: false) <del> register(:date_time, Type::DateTime, override: false) <add> register(:datetime, Type::DateTime, override: false) <ide> register(:decimal, Type::Decimal, override: false) <ide> register(:float, Type::Float, override: false) <ide> register(:integer, Type::Integer, override: false)
1
Javascript
Javascript
improve assertion for non-array passed to #each
bfdbf858e25af9bcda3cdc888798532af336eeac
<ide><path>packages/ember-handlebars/lib/helpers/each.js <ide> Ember.Handlebars.EachView = Ember.CollectionView.extend(Ember._Metamorph, { <ide> return this._super(); <ide> }, <ide> <add> _assertArrayLike: function(content) { <add> Ember.assert("The value that #each loops over must be an Array. You passed " + content.constructor + ", but it should have been an ArrayController", !Ember.ControllerMixin.detect(content) || (content && content.isGenerated) || content instanceof Ember.ArrayController); <add> Ember.assert("The value that #each loops over must be an Array. You passed " + ((Ember.ControllerMixin.detect(content) && content.get('model') !== undefined) ? ("" + content.get('model') + " (wrapped in " + content + ")") : ("" + content)), Ember.Array.detect(content)); <add> }, <add> <ide> disableContentObservers: function(callback) { <ide> Ember.removeBeforeObserver(this, 'content', null, '_contentWillChange'); <ide> Ember.removeObserver(this, 'content', null, '_contentDidChange'); <ide><path>packages/ember-routing/lib/system/controller_for.js <ide> Ember.generateController = function(container, controllerName, context) { <ide> if (context && Ember.isArray(context)) { <ide> DefaultController = container.resolve('controller:array'); <ide> controller = DefaultController.extend({ <add> isGenerated: true, <ide> content: context <ide> }); <ide> } else if (context) { <ide> DefaultController = container.resolve('controller:object'); <ide> controller = DefaultController.extend({ <add> isGenerated: true, <ide> content: context <ide> }); <ide> } else { <ide> DefaultController = container.resolve('controller:basic'); <del> controller = DefaultController.extend(); <add> controller = DefaultController.extend({ <add> isGenerated: true <add> }); <ide> } <ide> <ide> controller.toString = function() { <ide> return "(generated " + controllerName + " controller)"; <ide> }; <ide> <add> controller.isGenerated = true; <add> <ide> fullName = 'controller:' + controllerName; <ide> container.register(fullName, controller); <ide> <ide><path>packages/ember-views/lib/views/collection_view.js <ide> Ember.CollectionView = Ember.ContainerView.extend(/** @scope Ember.CollectionVie <ide> var content = get(this, 'content'); <ide> <ide> if (content) { <del> Ember.assert(fmt("an Ember.CollectionView's content must implement Ember.Array. You passed %@", [content]), Ember.Array.detect(content)); <add> this._assertArrayLike(content); <ide> content.addArrayObserver(this); <ide> } <ide> <ide> var len = content ? get(content, 'length') : 0; <ide> this.arrayDidChange(content, 0, null, len); <ide> }, 'content'), <ide> <add> _assertArrayLike: function(content) { <add> Ember.assert(fmt("an Ember.CollectionView's content must implement Ember.Array. You passed %@", [content]), Ember.Array.detect(content)); <add> }, <add> <ide> destroy: function() { <ide> if (!this._super()) { return; } <ide>
3
Python
Python
modify unit tests for 32 bit support
18e73ab359968875e7df6a0b45e788feee8fd716
<ide><path>numpy/core/tests/test_dtype.py <ide> def test_invalid_types(self): <ide> # For now, display a deprecation warning for invalid <ide> # type sizes. In the future this should be changed <ide> # to an exception. <del> for typestr in ['O3', 'O5', 'O7', 'b3', 'h4', 'I5', 'l4', <del> 'L4', 'q16', 'Q16', 'e3', 'f5', 'g12']: <add> <add> for typestr in ['O3', 'O5', 'O7', 'b3', 'h4', 'I5', <add> 'e3', 'f5', 'g12']: <ide> #print typestr <ide> assert_warns(DeprecationWarning, np.dtype, typestr) <ide> <add> if np.dtype('l').itemsize == 8: <add> assert_warns(DeprecationWarning, np.dtype, 'l4') <add> assert_warns(DeprecationWarning, np.dtype, 'L4') <add> else: <add> assert_warns(DeprecationWarning, np.dtype, 'l8') <add> assert_warns(DeprecationWarning, np.dtype, 'L8') <add> <add> if np.dtype('q').itemsize == 8: <add> assert_warns(DeprecationWarning, np.dtype, 'q4') <add> assert_warns(DeprecationWarning, np.dtype, 'Q4') <add> else: <add> assert_warns(DeprecationWarning, np.dtype, 'q8') <add> assert_warns(DeprecationWarning, np.dtype, 'Q8') <add> <ide> assert_raises(TypeError, np.dtype, 't8', 'NA[u4,0xffffffff]') <ide> <ide> def test_bad_param(self):
1
PHP
PHP
improve performance of truncation strategy
579aedc56fe7ae4990d78b4d6473f5da17d93ac9
<ide><path>src/TestSuite/Fixture/TruncationStrategy.php <ide> class TruncationStrategy implements ResetStrategyInterface <ide> * <ide> * @var array <ide> */ <del> protected $tables = []; <add> protected static $tables = []; <ide> <ide> /** <ide> * @var \Cake\TestSuite\Fixture\FixtureLoader <ide> public function teardownTest(): void <ide> protected function getTableSchema(Connection $db, string $table): TableSchemaInterface <ide> { <ide> $name = $db->configName(); <del> if (isset($this->tables[$name][$table])) { <del> return $this->tables[$name][$table]; <add> if (isset(static::$tables[$name][$table])) { <add> return static::$tables[$name][$table]; <ide> } <ide> $schema = $db->getSchemaCollection(); <ide> $tableSchema = $schema->describe($table); <del> $this->tables[$name][$table] = $tableSchema; <add> static::$tables[$name][$table] = $tableSchema; <ide> <ide> return $tableSchema; <ide> }
1
Text
Text
focus document template
76bf882f80fb23f9f1ee7c305c99c236575c0b3f
<ide><path>docs/focus/2018-04-02.md <add>## Highlights from the past week <add> <add>- Atom IDE <add>- GitHub Package <add>- Teletype <add>- Xray <add>- Reactor Duty <add> <add>## Focus for week ahead <add> <add>- Atom IDE <add>- GitHub Package <add>- Teletype <add>- Xray <add>- Reactor Duty
1
Text
Text
modify list section
b18560f8d6cfda241c4436ca568fa8ff0349e095
<ide><path>guide/english/r/subsetting-data/index.md <ide> df[c(1, 3), ] <ide> ## 3 3 1 c <ide> ``` <ide> <del>To get content of a list use `[[` operator like: <add>To get contents of a list use `[[` or `$` operator like: <ide> <ide> ```r <del>a <- list(a = 1, b = 2) <del>a[[1]] <del>## [1] 1 <add>sample_list <- list(char = "List-in-R", num = c(1:9), bool = TRUE) <add>sample_list[[1]] <add>## [1] "List-in-R" <ide> <del>a[["a"]] <del>## [1] 1 <add>sample_list[["num"]] <add>## [1] 1 2 3 4 5 6 7 8 9 <add> <add>sample_list$bool <add>## [1] TRUE <ide> ``` <ide> <ide> ## Resources <ide> a[["a"]] <ide> * [R Documentation](https://www.rdocumentation.org/packages/base/versions/3.5.1/topics/subset) <ide> * [R Bloggers](https://www.r-bloggers.com/5-ways-to-subset-a-data-frame-in-r/) <ide> * [Advanced R](http://adv-r.had.co.nz/Subsetting.html) <add> * [Spoken Tutorials](https://spoken-tutorial.org/watch/R/Indexing%2Band%2BSlicing%2BData%2BFrames/English/)
1
Python
Python
remove feature extraction config
11655fafdd42eb56ad94e09ecd84d4dc2d1041ae
<ide><path>src/transformers/models/wav2vec2/configuration_wav2vec2.py <ide> class Wav2Vec2Config(PretrainedConfig): <ide> Whether do apply `stable` layer norm architecture of the Transformer encoder. ``do_stable_layer_norm is <ide> True`` corresponds to applying layer norm before the attention layer, whereas ``do_stable_layer_norm is <ide> False`` corresponds to applying layer norm after the attention layer. <del> freeze_feat_extract_train (:obj:`bool`, `optional`, defaults to :obj:`True`): <del> Whether to freeze the weights of the feature extractor when training. <ide> apply_spec_augment (:obj:`bool`, `optional`, defaults to :obj:`True`): <ide> Whether to apply *SpecAugment* data augmentation to the outputs of the feature extractor. For reference see <ide> `SpecAugment: A Simple Data Augmentation Method for Automatic Speech Recognition <ide> def __init__( <ide> num_conv_pos_embeddings=128, <ide> num_conv_pos_embedding_groups=16, <ide> do_stable_layer_norm=False, <del> freeze_feat_extract_train=True, <ide> apply_spec_augment=True, <ide> mask_time_prob=0.05, <ide> mask_time_length=10, <ide> def __init__( <ide> self.initializer_range = initializer_range <ide> self.vocab_size = vocab_size <ide> self.do_stable_layer_norm = do_stable_layer_norm <del> self.freeze_feat_extract_train = freeze_feat_extract_train <ide> self.gradient_checkpointing = gradient_checkpointing <ide> <ide> if (
1
Javascript
Javascript
add known issue test for path parse issue
407069a29ddaa27664292070a306b0c63cc87f37
<ide><path>test/known_issues/test-path-parse-6229.js <add>'use strict'; <add>// Refs: https://github.com/nodejs/node/issues/6229 <add> <add>require('../common'); <add>const assert = require('assert'); <add>const path = require('path'); <add> <add>{ <add> // The path `/foo/bar` is not the same path as `/foo/bar/` <add> const parsed1 = path.posix.parse('/foo/bar'); <add> const parsed2 = path.posix.parse('/foo/bar/'); <add> <add> assert.strictEqual(parsed1.root, '/'); <add> assert.strictEqual(parsed1.dir, '/foo'); <add> assert.strictEqual(parsed1.base, 'bar'); <add> <add> assert.strictEqual(parsed2.root, '/'); <add> assert.strictEqual(parsed2.dir, '/foo/bar'); <add> assert.strictEqual(parsed2.base, ''); <add>} <add> <add>{ <add> // The path `\\foo\\bar` is not the same path as `\\foo\\bar\\` <add> const parsed1 = path.win32.parse('\\foo\\bar'); <add> const parsed2 = path.win32.parse('\\foo\\bar\\'); <add> <add> assert.strictEqual(parsed1.root, '\\'); <add> assert.strictEqual(parsed1.dir, '\\foo'); <add> assert.strictEqual(parsed1.base, 'bar'); <add> <add> assert.strictEqual(parsed2.root, '\\'); <add> assert.strictEqual(parsed2.dir, '\\foo\\bar'); <add> assert.strictEqual(parsed2.base, ''); <add>}
1
Ruby
Ruby
use formatter for all urls
884b26850615d5624e09762e1ae8bc5b104a934a
<ide><path>Library/Homebrew/blacklist.rb <ide> def blacklisted?(name) <ide> Homebrew provides pip via: `brew install python`. However you will then <ide> have two Pythons installed on your Mac, so alternatively you can install <ide> pip via the instructions at: <del> https://pip.readthedocs.io/en/stable/installing/ <add> #{Formatter.url("https://pip.readthedocs.io/en/stable/installing/")} <ide> EOS <ide> when "pil" then <<-EOS.undent <ide> Instead of PIL, consider `pip install pillow` or `brew install Homebrew/python/pillow`. <ide> EOS <ide> when "macruby" then <<-EOS.undent <ide> MacRuby is not packaged and is on an indefinite development hiatus. <ide> You can read more about it at: <del> https://github.com/MacRuby/MacRuby <add> #{Formatter.url("https://github.com/MacRuby/MacRuby")} <ide> EOS <ide> when /(lib)?lzma/ <ide> "lzma is now part of the xz formula." <ide> def blacklisted?(name) <ide> To install Clojure you should install Leiningen: <ide> brew install leiningen <ide> and then follow the tutorial: <del> https://github.com/technomancy/leiningen/blob/stable/doc/TUTORIAL.md <add> #{Formatter.url("https://github.com/technomancy/leiningen/blob/stable/doc/TUTORIAL.md")} <ide> EOS <ide> when "osmium" then <<-EOS.undent <ide> The creator of Osmium requests that it not be packaged and that people <ide> def blacklisted?(name) <ide> brew install typesafe-activator <ide> <ide> You can read more about this change at: <del> https://www.playframework.com/documentation/2.3.x/Migration23 <del> https://www.playframework.com/documentation/2.3.x/Highlights23 <add> #{Formatter.url("https://www.playframework.com/documentation/2.3.x/Migration23")} <add> #{Formatter.url("https://www.playframework.com/documentation/2.3.x/Highlights23")} <ide> EOS <ide> when "haskell-platform" then <<-EOS.undent <ide> We no longer package haskell-platform. Consider installing ghc <ide><path>Library/Homebrew/cask/lib/hbc/dsl/caveats.rb <ide> def malware(radar_number) <ide> <ide> A report has been made to Apple about this app. Their certificate will hopefully be revoked. <ide> See the public report at <del> https://openradar.appspot.com/#{radar_number} <add> #{Formatter.url("https://openradar.appspot.com/#{radar_number}")} <ide> <ide> If this report is accurate, please duplicate it at <del> https://bugreport.apple.com/ <add> #{Formatter.url("https://bugreport.apple.com/")} <ide> If this report is a mistake, please let us know by opening an issue at <del> https://github.com/caskroom/homebrew-cask/issues/new <add> #{Formatter.url("https://github.com/caskroom/homebrew-cask/issues/new")} <ide> <ide> EOS <ide> end <ide><path>Library/Homebrew/cmd/help.rb <ide> def command_help(path) <ide> HOMEBREW_HELP <ide> else <ide> help_lines.map do |line| <del> line.slice(2..-1). <del> sub(/^ \* /, "#{Tty.bold}brew#{Tty.reset} "). <del> gsub(/`(.*?)`/, "#{Tty.bold}\\1#{Tty.reset}"). <del> gsub(/<(.*?)>/, "#{Tty.underline}\\1#{Tty.reset}"). <del> gsub("@hide_from_man_page", "") <add> line.slice(2..-1) <add> .sub(/^ \* /, "#{Tty.bold}brew#{Tty.reset} ") <add> .gsub(/`(.*?)`/, "#{Tty.bold}\\1#{Tty.reset}") <add> .gsub(%r{<([^\s]+?://[^\s]+?)>}) { |url| Formatter.url(url) } <add> .gsub(/<(.*?)>/, "#{Tty.underline}\\1#{Tty.reset}") <add> .gsub("@hide_from_man_page", "") <ide> end.join.strip <ide> end <ide> end <ide><path>Library/Homebrew/cmd/update-report.rb <ide> def migrate_legacy_repository_if_necessary <ide> Please try to resolve this error yourself and then run `brew update` again to <ide> complete the migration. If you need help please +1 an existing error or comment <ide> with your new error in issue: <del> #{Tty.em}https://github.com/Homebrew/brew/issues/987#{Tty.reset} <add> #{Formatter.url("https://github.com/Homebrew/brew/issues/987")} <ide> EOS <ide> $stderr.puts e.backtrace <ide> end <ide><path>Library/Homebrew/diagnostic.rb <ide> def check_user_curlrc <ide> If you have trouble downloading packages with Homebrew, then maybe this <ide> is the problem? If the following command doesn't work, then try removing <ide> your curlrc: <del> curl https://github.com <add> curl #{Formatter.url("https://github.com")} <ide> EOS <ide> end <ide> <ide> def check_dyld_vars <ide> <ide> Setting DYLD_INSERT_LIBRARIES can cause Go builds to fail. <ide> Having this set is common if you use this software: <del> http://asepsis.binaryage.com/ <add> #{Formatter.url("http://asepsis.binaryage.com/")} <ide> EOS <ide> end <ide> <ide> def check_git_origin <ide> Without a correctly configured origin, Homebrew won't update <ide> properly. You can solve this by adding the Homebrew remote: <ide> cd #{HOMEBREW_REPOSITORY} <del> git remote add origin https://github.com/Homebrew/brew.git <add> git remote add origin #{Formatter.url("https://github.com/Homebrew/brew.git")} <ide> EOS <ide> elsif origin !~ %r{Homebrew/brew(\.git)?$} <ide> <<-EOS.undent <ide> def check_git_origin <ide> <ide> Unless you have compelling reasons, consider setting the <ide> origin remote to point at the main repository, located at: <del> https://github.com/Homebrew/brew.git <add> #{Formatter.url("https://github.com/Homebrew/brew.git")} <ide> EOS <ide> end <ide> end <ide> def check_for_pydistutils_cfg_in_home <ide> <<-EOS.undent <ide> A .pydistutils.cfg file was found in $HOME, which may cause Python <ide> builds to fail. See: <del> https://bugs.python.org/issue6138 <del> https://bugs.python.org/issue4655 <add> #{Formatter.url("https://bugs.python.org/issue6138")} <add> #{Formatter.url("https://bugs.python.org/issue4655")} <ide> EOS <ide> end <ide> <ide><path>Library/Homebrew/exceptions.rb <ide> def fetch_issues <ide> def dump <ide> if !ARGV.verbose? <ide> puts <del> puts Formatter.error("READ THIS: #{Formatter.url(OS::ISSUES_URL)}") <add> puts Formatter.error(Formatter.url(OS::ISSUES_URL), label: "READ THIS") <ide> if formula.tap <ide> case formula.tap.name <ide> when "homebrew/boneyard" <ide> def dump <ide> else <ide> if issues_url = formula.tap.issues_url <ide> puts "If reporting this issue please do so at (not Homebrew/brew):" <del> puts " #{issues_url}" <add> puts " #{Formatter.url(issues_url)}" <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/requirements.rb <ide> def message <ide> EOS <ide> else <ide> message + <<-EOS.undent <del> Xcode can be installed from https://developer.apple.com/xcode/downloads/ <add> Xcode can be installed from #{Formatter.url("https://developer.apple.com/xcode/downloads/")} <ide> EOS <ide> end <ide> end <ide><path>Library/Homebrew/utils/github.rb <ide> def api_credentials_error_message(response_headers) <ide> onoe <<-EOS.undent <ide> Your macOS keychain GitHub credentials do not have sufficient scope! <ide> Scopes they have: #{credentials_scopes} <del> Create a personal access token: https://github.com/settings/tokens <add> Create a personal access token: #{Formatter.url("https://github.com/settings/tokens")} <ide> and then set HOMEBREW_GITHUB_API_TOKEN as the authentication method instead. <ide> EOS <ide> when :environment <ide> onoe <<-EOS.undent <ide> Your HOMEBREW_GITHUB_API_TOKEN does not have sufficient scope! <ide> Scopes it has: #{credentials_scopes} <del> Create a new personal access token: https://github.com/settings/tokens <add> Create a new personal access token: #{Formatter.url("https://github.com/settings/tokens")} <ide> and then set the new HOMEBREW_GITHUB_API_TOKEN as the authentication method instead. <ide> EOS <ide> end
8
Ruby
Ruby
maintain proleptic gregorian in time#advance
0c6ddbe7b0056cb5c17d6b483c0e5a7cbd596b97
<ide><path>activesupport/lib/active_support/core_ext/time/calculations.rb <ide> def change(options) <ide> end <ide> end <ide> <del> # Uses Date to provide precise Time calculations for years, months, and days. <del> # The +options+ parameter takes a hash with any of these keys: <tt>:years</tt>, <del> # <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>, <del> # <tt>:minutes</tt>, <tt>:seconds</tt>. <add> # Uses Date to provide precise Time calculations for years, months, and days <add> # according to the proleptic Gregorian calendar. The +options+ parameter <add> # takes a hash with any of these keys: <tt>:years</tt>, <tt>:months</tt>, <add> # <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>, <tt>:minutes</tt>, <add> # <tt>:seconds</tt>. <ide> def advance(options) <ide> unless options[:weeks].nil? <ide> options[:weeks], partial_weeks = options[:weeks].divmod(1) <ide> def advance(options) <ide> end <ide> <ide> d = to_date.advance(options) <add> d = d.gregorian if d.julian? <ide> time_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day) <ide> seconds_to_advance = \ <ide> options.fetch(:seconds, 0) + <ide><path>activesupport/test/core_ext/time_ext_test.rb <ide> def test_advance_with_nsec <ide> assert_equal t, t.advance(:months => 0) <ide> end <ide> <add> def test_advance_gregorian_proleptic <add> assert_equal Time.local(1582,10,14,15,15,10), Time.local(1582,10,15,15,15,10).advance(:days => -1) <add> assert_equal Time.local(1582,10,15,15,15,10), Time.local(1582,10,14,15,15,10).advance(:days => 1) <add> assert_equal Time.local(1582,10,5,15,15,10), Time.local(1582,10,4,15,15,10).advance(:days => 1) <add> assert_equal Time.local(1582,10,4,15,15,10), Time.local(1582,10,5,15,15,10).advance(:days => -1) <add> end <add> <ide> def test_last_week <ide> with_env_tz 'US/Eastern' do <ide> assert_equal Time.local(2005,2,21), Time.local(2005,3,1,15,15,10).last_week
2
Text
Text
fix broken link in docs
8a11e5805af2ab40163ed531b0faccf559bccf82
<ide><path>README.md <ide> Contribution <ide> <ide> Use [Github issues](https://github.com/facebook/immutable-js/issues) for requests. <ide> <del>We actively welcome pull requests, learn how to [contribute](./.github/CONTRIBUTING.md). <add>We actively welcome pull requests, learn how to [contribute](https://github.com/facebook/immutable-js/blob/master/.github/CONTRIBUTING.md). <ide> <ide> <ide> Changelog
1
Python
Python
try the correct noreversematch location
11610e7c3c4330b863c9da5d843b6d874c2958e9
<ide><path>rest_framework/relations.py <ide> from __future__ import unicode_literals <del>from django.core.exceptions import ObjectDoesNotExist, ValidationError, NoReverseMatch <del>from django.core.urlresolvers import resolve, get_script_prefix <add>from django.core.exceptions import ObjectDoesNotExist, ValidationError <add>from django.core.urlresolvers import resolve, get_script_prefix, NoReverseMatch <ide> from django import forms <ide> from django.forms import widgets <ide> from django.forms.models import ModelChoiceIterator <ide><path>rest_framework/templatetags/rest_framework.py <ide> from __future__ import unicode_literals, absolute_import <ide> from django import template <del>from django.core.exceptions import NoReverseMatch <del>from django.core.urlresolvers import reverse <add>from django.core.urlresolvers import reverse, NoReverseMatch <ide> from django.http import QueryDict <ide> from django.utils.html import escape <ide> from django.utils.safestring import SafeData, mark_safe
2
Python
Python
improve saving strategy of sentencepiece tokenizer
ade7371a41145c53fe90f66da7e5606f96068e98
<ide><path>src/transformers/models/albert/tokenization_albert.py <ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = <ide> save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] <ide> ) <ide> <del> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file): <add> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file): <ide> copyfile(self.vocab_file, out_vocab_file) <add> elif not os.path.isfile(self.vocab_file): <add> with open(out_vocab_file, "wb") as fi: <add> content_spiece_model = self.sp_model.serialized_model_proto() <add> fi.write(content_spiece_model) <ide> <ide> return (out_vocab_file,) <ide><path>src/transformers/models/bartpho/tokenization_bartpho.py <ide> def __init__( <ide> self.sp_model.Load(str(vocab_file)) <ide> <ide> # Load the reduced vocab <del> self.fairseq_tokens_to_ids = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3} <add> <add> # Keep order of special tokens for backward compatibility <add> self.fairseq_tokens_to_ids = {} <add> cnt = 0 <add> for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: <add> if str(token) not in self.fairseq_tokens_to_ids: <add> self.fairseq_tokens_to_ids[str(token)] = cnt <add> cnt += 1 <ide> with open(monolingual_vocab_file, "r", encoding="utf-8") as f: <ide> for line in f.readlines(): <ide> token = line.strip().split()[0] <ide> self.fairseq_tokens_to_ids[token] = len(self.fairseq_tokens_to_ids) <del> self.fairseq_tokens_to_ids["<mask>"] = len(self.fairseq_tokens_to_ids) <add> if str(mask_token) not in self.fairseq_tokens_to_ids: <add> self.fairseq_tokens_to_ids[str(mask_token)] = len(self.fairseq_tokens_to_ids) <ide> <ide> self.fairseq_ids_to_tokens = {v: k for k, v in self.fairseq_tokens_to_ids.items()} <ide> <ide> def _convert_token_to_id(self, token): <ide> if token in self.fairseq_tokens_to_ids: <ide> return self.fairseq_tokens_to_ids[token] <ide> else: <del> return self.fairseq_tokens_to_ids["<unk>"] <add> return self.unk_token_id <ide> <ide> def _convert_id_to_token(self, index): <ide> """Converts an index (integer) in a token (str) using the vocab.""" <ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = <ide> (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["monolingual_vocab_file"], <ide> ) <ide> <del> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file): <add> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file): <ide> copyfile(self.vocab_file, out_vocab_file) <del> <del> if os.path.abspath(self.monolingual_vocab_file) != os.path.abspath(out_monolingual_vocab_file): <add> elif not os.path.isfile(self.vocab_file): <add> with open(out_vocab_file, "wb") as fi: <add> content_spiece_model = self.sp_model.serialized_model_proto() <add> fi.write(content_spiece_model) <add> <add> if os.path.abspath(self.monolingual_vocab_file) != os.path.abspath( <add> out_monolingual_vocab_file <add> ) and os.path.isfile(self.monolingual_vocab_file): <ide> copyfile(self.monolingual_vocab_file, out_monolingual_vocab_file) <add> elif not os.path.isfile(self.monolingual_vocab_file): <add> with open(out_monolingual_vocab_file, "w", encoding="utf-8") as fp: <add> for token in self.fairseq_tokens_to_ids: <add> if token not in self.all_special_tokens: <add> fp.write(f"{str(token)} \n") <ide> <ide> return out_vocab_file, out_monolingual_vocab_file <ide><path>src/transformers/models/bert_generation/tokenization_bert_generation.py <ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = <ide> save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] <ide> ) <ide> <del> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file): <add> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file): <ide> copyfile(self.vocab_file, out_vocab_file) <add> elif not os.path.isfile(self.vocab_file): <add> with open(out_vocab_file, "wb") as fi: <add> content_spiece_model = self.sp_model.serialized_model_proto() <add> fi.write(content_spiece_model) <ide> <ide> return (out_vocab_file,) <ide><path>src/transformers/models/big_bird/tokenization_big_bird.py <ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = <ide> save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] <ide> ) <ide> <del> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file): <add> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file): <ide> copyfile(self.vocab_file, out_vocab_file) <add> elif not os.path.isfile(self.vocab_file): <add> with open(out_vocab_file, "wb") as fi: <add> content_spiece_model = self.sp_model.serialized_model_proto() <add> fi.write(content_spiece_model) <ide> <ide> return (out_vocab_file,) <ide> <ide><path>src/transformers/models/camembert/tokenization_camembert.py <ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = <ide> save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] <ide> ) <ide> <del> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file): <add> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file): <ide> copyfile(self.vocab_file, out_vocab_file) <add> elif not os.path.isfile(self.vocab_file): <add> with open(out_vocab_file, "wb") as fi: <add> content_spiece_model = self.sp_model.serialized_model_proto() <add> fi.write(content_spiece_model) <ide> <ide> return (out_vocab_file,) <ide><path>src/transformers/models/fnet/tokenization_fnet.py <ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = <ide> save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] <ide> ) <ide> <del> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file): <add> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file): <ide> copyfile(self.vocab_file, out_vocab_file) <add> elif not os.path.isfile(self.vocab_file): <add> with open(out_vocab_file, "wb") as fi: <add> content_spiece_model = self.sp_model.serialized_model_proto() <add> fi.write(content_spiece_model) <ide> <ide> return (out_vocab_file,) <ide><path>src/transformers/models/layoutxlm/tokenization_layoutxlm.py <ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = <ide> save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] <ide> ) <ide> <del> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file): <add> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file): <ide> copyfile(self.vocab_file, out_vocab_file) <add> elif not os.path.isfile(self.vocab_file): <add> with open(out_vocab_file, "wb") as fi: <add> content_spiece_model = self.sp_model.serialized_model_proto() <add> fi.write(content_spiece_model) <ide> <ide> return (out_vocab_file,) <ide> <ide><path>src/transformers/models/m2m_100/tokenization_m2m_100.py <ide> # limitations under the License. <ide> """Tokenization classes for M2M100.""" <ide> import json <add>import os <ide> from contextlib import contextmanager <ide> from pathlib import Path <ide> from shutil import copyfile <ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = <ide> <ide> save_json(self.encoder, vocab_save_path) <ide> <del> if not spm_save_path.exists(): <add> if os.path.abspath(self.spm_file) != os.path.abspath(spm_save_path) and os.path.isfile(self.spm_file): <ide> copyfile(self.spm_file, spm_save_path) <add> elif not os.path.isfile(self.spm_file): <add> with open(spm_save_path, "wb") as fi: <add> content_spiece_model = self.sp_model.serialized_model_proto() <add> fi.write(content_spiece_model) <ide> <ide> return (str(vocab_save_path), str(spm_save_path)) <ide> <ide><path>src/transformers/models/marian/tokenization_marian.py <ide> # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <ide> # See the License for the specific language governing permissions and <ide> # limitations under the License. <del> <ide> import json <add>import os <ide> import re <ide> import warnings <ide> from contextlib import contextmanager <ide> import sentencepiece <ide> <ide> from ...tokenization_utils import PreTrainedTokenizer <add>from ...utils import logging <add> <ide> <add>logger = logging.get_logger(__name__) <ide> <ide> VOCAB_FILES_NAMES = { <ide> "source_spm": "source.spm", <ide> def vocab_size(self) -> int: <ide> return len(self.encoder) <ide> <ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]: <del> save_dir = Path(save_directory) <del> assert save_dir.is_dir(), f"{save_directory} should be a directory" <del> save_json( <del> self.encoder, <del> save_dir / ((filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab"]), <add> if not os.path.isdir(save_directory): <add> logger.error(f"Vocabulary path ({save_directory}) should be a directory") <add> return <add> saved_files = [] <add> out_vocab_file = os.path.join( <add> save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab"] <ide> ) <ide> <del> for orig, f in zip(["source.spm", "target.spm"], self.spm_files): <del> dest_path = save_dir / ((filename_prefix + "-" if filename_prefix else "") + Path(f).name) <del> if not dest_path.exists(): <del> copyfile(f, save_dir / orig) <del> <del> return tuple( <del> save_dir / ((filename_prefix + "-" if filename_prefix else "") + f) for f in self.vocab_files_names <del> ) <add> save_json(self.encoder, out_vocab_file) <add> saved_files.append(out_vocab_file) <add> <add> for spm_save_filename, spm_orig_path, spm_model in zip( <add> [VOCAB_FILES_NAMES["source_spm"], VOCAB_FILES_NAMES["target_spm"]], <add> self.spm_files, <add> [self.spm_source, self.spm_target], <add> ): <add> spm_save_path = os.path.join( <add> save_directory, (filename_prefix + "-" if filename_prefix else "") + spm_save_filename <add> ) <add> if os.path.abspath(spm_orig_path) != os.path.abspath(spm_save_path) and os.path.isfile(spm_orig_path): <add> copyfile(spm_orig_path, spm_save_path) <add> saved_files.append(spm_save_path) <add> elif not os.path.isfile(spm_orig_path): <add> with open(spm_save_path, "wb") as fi: <add> content_spiece_model = spm_model.serialized_model_proto() <add> fi.write(content_spiece_model) <add> saved_files.append(spm_save_path) <add> <add> return tuple(saved_files) <ide> <ide> def get_vocab(self) -> Dict: <ide> vocab = self.encoder.copy() <ide><path>src/transformers/models/mbart/tokenization_mbart.py <ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = <ide> save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] <ide> ) <ide> <del> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file): <add> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file): <ide> copyfile(self.vocab_file, out_vocab_file) <add> elif not os.path.isfile(self.vocab_file): <add> with open(out_vocab_file, "wb") as fi: <add> content_spiece_model = self.sp_model.serialized_model_proto() <add> fi.write(content_spiece_model) <ide> <ide> return (out_vocab_file,) <ide> <ide><path>src/transformers/models/mbart50/tokenization_mbart50.py <ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = <ide> save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] <ide> ) <ide> <del> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file): <add> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file): <ide> copyfile(self.vocab_file, out_vocab_file) <add> elif not os.path.isfile(self.vocab_file): <add> with open(out_vocab_file, "wb") as fi: <add> content_spiece_model = self.sp_model.serialized_model_proto() <add> fi.write(content_spiece_model) <ide> <ide> return (out_vocab_file,) <ide> <ide><path>src/transformers/models/pegasus/tokenization_pegasus.py <ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = <ide> save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] <ide> ) <ide> <del> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file): <add> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file): <ide> copyfile(self.vocab_file, out_vocab_file) <add> elif not os.path.isfile(self.vocab_file): <add> with open(out_vocab_file, "wb") as fi: <add> content_spiece_model = self.sp_model.serialized_model_proto() <add> fi.write(content_spiece_model) <ide> <ide> return (out_vocab_file,) <ide><path>src/transformers/models/reformer/tokenization_reformer.py <ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = <ide> save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] <ide> ) <ide> <del> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file): <add> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file): <ide> copyfile(self.vocab_file, out_vocab_file) <add> elif not os.path.isfile(self.vocab_file): <add> with open(out_vocab_file, "wb") as fi: <add> content_spiece_model = self.sp_model.serialized_model_proto() <add> fi.write(content_spiece_model) <ide> <ide> return (out_vocab_file,) <ide><path>src/transformers/models/speech_to_text/tokenization_speech_to_text.py <ide> # See the License for the specific language governing permissions and <ide> # limitations under the License. <ide> """Tokenization classes for Speech2Text.""" <del> <ide> import json <add>import os <ide> from pathlib import Path <ide> from shutil import copyfile <ide> from typing import Any, Dict, List, Optional, Tuple, Union <ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = <ide> <ide> save_json(self.encoder, vocab_save_path) <ide> <del> if not spm_save_path.exists(): <add> if os.path.abspath(self.spm_file) != os.path.abspath(spm_save_path) and os.path.isfile(self.spm_file): <ide> copyfile(self.spm_file, spm_save_path) <add> elif not os.path.isfile(self.spm_file): <add> with open(spm_save_path, "wb") as fi: <add> content_spiece_model = self.sp_model.serialized_model_proto() <add> fi.write(content_spiece_model) <ide> <ide> return (str(vocab_save_path), str(spm_save_path)) <ide> <ide><path>src/transformers/models/t5/tokenization_t5.py <ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = <ide> save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] <ide> ) <ide> <del> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file): <add> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file): <ide> copyfile(self.vocab_file, out_vocab_file) <del> logger.info(f"Copy vocab file to {out_vocab_file}") <add> elif not os.path.isfile(self.vocab_file): <add> with open(out_vocab_file, "wb") as fi: <add> content_spiece_model = self.sp_model.serialized_model_proto() <add> fi.write(content_spiece_model) <ide> <ide> return (out_vocab_file,) <ide><path>src/transformers/models/xlm_prophetnet/tokenization_xlm_prophetnet.py <ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = <ide> save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] <ide> ) <ide> <del> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file): <add> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file): <ide> copyfile(self.vocab_file, out_vocab_file) <add> elif not os.path.isfile(self.vocab_file): <add> with open(out_vocab_file, "wb") as fi: <add> content_spiece_model = self.sp_model.serialized_model_proto() <add> fi.write(content_spiece_model) <ide> <ide> return (out_vocab_file,) <ide> <ide><path>src/transformers/models/xlm_roberta/tokenization_xlm_roberta.py <ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = <ide> save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] <ide> ) <ide> <del> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file): <add> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file): <ide> copyfile(self.vocab_file, out_vocab_file) <add> elif not os.path.isfile(self.vocab_file): <add> with open(out_vocab_file, "wb") as fi: <add> content_spiece_model = self.sp_model.serialized_model_proto() <add> fi.write(content_spiece_model) <ide> <ide> return (out_vocab_file,) <ide><path>src/transformers/models/xlnet/tokenization_xlnet.py <ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = <ide> save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] <ide> ) <ide> <del> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file): <add> if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file): <ide> copyfile(self.vocab_file, out_vocab_file) <add> elif not os.path.isfile(self.vocab_file): <add> with open(out_vocab_file, "wb") as fi: <add> content_spiece_model = self.sp_model.serialized_model_proto() <add> fi.write(content_spiece_model) <ide> <ide> return (out_vocab_file,) <ide><path>tests/test_tokenization_common.py <ide> def test_pickle_subword_regularization_tokenizer(self) -> None: <ide> self.assertEqual(tokenizer_new.sp_model_kwargs, sp_model_kwargs) <ide> self.check_subword_sampling(tokenizer_new) <ide> <add> def test_save_sentencepiece_tokenizer(self) -> None: <add> if not self.test_sentencepiece or not self.test_slow_tokenizer: <add> return <add> # We want to verify that we will be able to save the tokenizer even if the original files that were used to <add> # build the tokenizer have been deleted in the meantime. <add> text = "This is text to test the tokenizer." <add> <add> tokenizer_slow_1 = self.get_tokenizer() <add> encoding_tokenizer_slow_1 = tokenizer_slow_1(text) <add> <add> tmpdirname_1 = tempfile.mkdtemp() <add> tmpdirname_2 = tempfile.mkdtemp() <add> <add> tokenizer_slow_1.save_pretrained(tmpdirname_1) <add> tokenizer_slow_2 = self.tokenizer_class.from_pretrained(tmpdirname_1) <add> encoding_tokenizer_slow_2 = tokenizer_slow_2(text) <add> <add> shutil.rmtree(tmpdirname_1) <add> tokenizer_slow_2.save_pretrained(tmpdirname_2) <add> <add> tokenizer_slow_3 = self.tokenizer_class.from_pretrained(tmpdirname_2) <add> encoding_tokenizer_slow_3 = tokenizer_slow_3(text) <add> shutil.rmtree(tmpdirname_2) <add> <add> self.assertEqual(encoding_tokenizer_slow_1, encoding_tokenizer_slow_2) <add> self.assertEqual(encoding_tokenizer_slow_1, encoding_tokenizer_slow_3) <add> <ide> def test_model_input_names_signature(self): <ide> accepted_model_main_input_names = [ <ide> "input_ids", # nlp models <ide><path>tests/test_tokenization_layoutxlm.py <ide> def get_input_output_texts(self, tokenizer): <ide> output_text = "unwanted, running" <ide> return input_text, output_text <ide> <add> # override test in `test_tokenization_common.py` because of the required input format of the `__call__`` method of <add> # this tokenizer <add> def test_save_sentencepiece_tokenizer(self) -> None: <add> if not self.test_sentencepiece or not self.test_slow_tokenizer: <add> return <add> # We want to verify that we will be able to save the tokenizer even if the original files that were used to <add> # build the tokenizer have been deleted in the meantime. <add> words, boxes = self.get_words_and_boxes() <add> <add> tokenizer_slow_1 = self.get_tokenizer() <add> encoding_tokenizer_slow_1 = tokenizer_slow_1( <add> words, <add> boxes=boxes, <add> ) <add> <add> tmpdirname_1 = tempfile.mkdtemp() <add> tmpdirname_2 = tempfile.mkdtemp() <add> <add> tokenizer_slow_1.save_pretrained(tmpdirname_1) <add> tokenizer_slow_2 = self.tokenizer_class.from_pretrained(tmpdirname_1) <add> encoding_tokenizer_slow_2 = tokenizer_slow_2( <add> words, <add> boxes=boxes, <add> ) <add> <add> shutil.rmtree(tmpdirname_1) <add> tokenizer_slow_2.save_pretrained(tmpdirname_2) <add> <add> tokenizer_slow_3 = self.tokenizer_class.from_pretrained(tmpdirname_2) <add> encoding_tokenizer_slow_3 = tokenizer_slow_3( <add> words, <add> boxes=boxes, <add> ) <add> shutil.rmtree(tmpdirname_2) <add> <add> self.assertEqual(encoding_tokenizer_slow_1, encoding_tokenizer_slow_2) <add> self.assertEqual(encoding_tokenizer_slow_1, encoding_tokenizer_slow_3) <add> <ide> @slow <ide> def test_sequence_builders(self): <ide> tokenizer = self.tokenizer_class.from_pretrained("microsoft/layoutxlm-base") <ide><path>tests/test_tokenization_mbart.py <ide> class MBartTokenizationTest(TokenizerTesterMixin, unittest.TestCase): <ide> tokenizer_class = MBartTokenizer <ide> rust_tokenizer_class = MBartTokenizerFast <ide> test_rust_tokenizer = True <add> test_sentencepiece = True <ide> <ide> def setUp(self): <ide> super().setUp()
21
Javascript
Javascript
move message listener to worker objects
58561cf6a8ce6ac907973c3813cb52134ec8d4c2
<ide><path>tools/jslint.js <ide> if (cluster.isMaster) { <ide> sendWork(worker); <ide> }); <ide> <del> cluster.on('message', function(worker, results) { <del> if (typeof results !== 'number') { <del> // The worker sent us results that are not all successes <del> if (!workerConfig.sendAll) <del> failures += results.length; <del> outFn(formatter(results) + '\r\n'); <del> printProgress(); <del> } else { <del> successes += results; <del> } <del> // Try to give the worker more work to do <del> sendWork(worker); <del> }); <del> <ide> process.on('exit', function() { <ide> if (showProgress) { <ide> curPath = 'Done'; <ide> if (cluster.isMaster) { <ide> }); <ide> <ide> for (i = 0; i < numCPUs; ++i) <del> cluster.fork(); <add> cluster.fork().on('message', onWorkerMessage); <add> <add> function onWorkerMessage(results) { <add> if (typeof results !== 'number') { <add> // The worker sent us results that are not all successes <add> if (!workerConfig.sendAll) <add> failures += results.length; <add> outFn(formatter(results) + '\r\n'); <add> printProgress(); <add> } else { <add> successes += results; <add> } <add> // Try to give the worker more work to do <add> sendWork(this); <add> } <ide> <ide> function sendWork(worker) { <ide> if (!files || !files.length) {
1
PHP
PHP
add tests for begintransaction() retrying
33c6f9a19e0e19d8d1610e26c00d8acad58a5d71
<ide><path>src/Illuminate/Database/Connection.php <ide> public function beginTransaction() <ide> { <ide> if ($this->transactions == 0) { <ide> try { <del> $this->getPdo()->beginTransaction(); <add> $this->pdo->beginTransaction(); <ide> } catch (Exception $e) { <ide> if ($this->causedByLostConnection($e)) { <ide> $this->reconnect(); <del> $this->getPdo()->beginTransaction(); <add> $this->pdo->beginTransaction(); <ide> } else { <ide> throw $e; <ide> } <ide><path>tests/Database/DatabaseConnectionTest.php <ide> public function testTransactionLevelNotIncrementedOnTransactionException() <ide> } <ide> } <ide> <add> public function testBeginTransactionMethodRetriesOnFailure() <add> { <add> $pdo = $this->getMock('DatabaseConnectionTestMockPDO'); <add> $pdo->expects($this->exactly(2))->method('beginTransaction'); <add> $pdo->expects($this->at(0))->method('beginTransaction')->will($this->throwException(new ErrorException('server has gone away'))); <add> $connection = $this->getMockConnection(['reconnect'], $pdo); <add> $connection->expects($this->once())->method('reconnect'); <add> $connection->beginTransaction(); <add> $this->assertEquals(1, $connection->transactionLevel()); <add> } <add> <add> public function testBeginTransactionMethodNeverRetriesIfWithinTransaction() <add> { <add> $pdo = $this->getMock('DatabaseConnectionTestMockPDO'); <add> $pdo->expects($this->once())->method('beginTransaction'); <add> $pdo->expects($this->once())->method('exec')->will($this->throwException(new Exception)); <add> $connection = $this->getMockConnection([], $pdo); <add> $queryGrammar = $this->getMock('Illuminate\Database\Query\Grammars\Grammar'); <add> $queryGrammar->expects($this->once())->method('supportsSavepoints')->will($this->returnValue(true)); <add> $connection->setQueryGrammar($queryGrammar); <add> $connection->expects($this->never())->method('reconnect'); <add> $connection->beginTransaction(); <add> $this->assertEquals(1, $connection->transactionLevel()); <add> try { <add> $connection->beginTransaction(); <add> } catch (Exception $e) { <add> $this->assertEquals(1, $connection->transactionLevel()); <add> } <add> } <add> <ide> /** <ide> * @expectedException RuntimeException <ide> */
2
Javascript
Javascript
add uploadtexture to webglrenderer
3c1c8318005efeea385ef641424c2e5cd6f4f6b7
<ide><path>src/renderers/WebGLRenderer.js <ide> THREE.WebGLRenderer = function ( parameters ) { <ide> <ide> }; <ide> <del> this.setTexture = function ( texture, slot ) { <add> this.uploadTexture = function ( texture ) { <ide> <del> if ( texture.needsUpdate ) { <add> if ( ! texture.__webglInit ) { <ide> <del> if ( ! texture.__webglInit ) { <add> texture.__webglInit = true; <ide> <del> texture.__webglInit = true; <add> texture.addEventListener( 'dispose', onTextureDispose ); <ide> <del> texture.addEventListener( 'dispose', onTextureDispose ); <add> texture.__webglTexture = _gl.createTexture(); <ide> <del> texture.__webglTexture = _gl.createTexture(); <add> _this.info.memory.textures ++; <ide> <del> _this.info.memory.textures ++; <add> } <ide> <del> } <add> _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture ); <ide> <del> _gl.activeTexture( _gl.TEXTURE0 + slot ); <del> _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture ); <add> _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); <add> _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha ); <add> _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment ); <ide> <del> _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); <del> _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha ); <del> _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment ); <add> var image = texture.image, <add> isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ), <add> glFormat = paramThreeToGL( texture.format ), <add> glType = paramThreeToGL( texture.type ); <ide> <del> var image = texture.image, <del> isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ), <del> glFormat = paramThreeToGL( texture.format ), <del> glType = paramThreeToGL( texture.type ); <add> setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo ); <ide> <del> setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo ); <add> var mipmap, mipmaps = texture.mipmaps; <ide> <del> var mipmap, mipmaps = texture.mipmaps; <add> if ( texture instanceof THREE.DataTexture ) { <ide> <del> if ( texture instanceof THREE.DataTexture ) { <add> // use manually created mipmaps if available <add> // if there are no manual mipmaps <add> // set 0 level mipmap and then use GL to generate other mipmap levels <ide> <del> // use manually created mipmaps if available <del> // if there are no manual mipmaps <del> // set 0 level mipmap and then use GL to generate other mipmap levels <add> if ( mipmaps.length > 0 && isImagePowerOfTwo ) { <ide> <del> if ( mipmaps.length > 0 && isImagePowerOfTwo ) { <add> for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { <ide> <del> for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { <add> mipmap = mipmaps[ i ]; <add> _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); <ide> <del> mipmap = mipmaps[ i ]; <del> _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); <add> } <ide> <del> } <add> texture.generateMipmaps = false; <add> <add> } else { <ide> <del> texture.generateMipmaps = false; <add> _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data ); <ide> <del> } else { <add> } <add> <add> } else if ( texture instanceof THREE.CompressedTexture ) { <ide> <del> _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data ); <add> for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { <ide> <add> mipmap = mipmaps[ i ]; <add> if ( texture.format !== THREE.RGBAFormat ) { <add> _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); <add> } else { <add> _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); <ide> } <ide> <del> } else if ( texture instanceof THREE.CompressedTexture ) { <add> } <add> <add> } else { // regular Texture (image, video, canvas) <add> <add> // use manually created mipmaps if available <add> // if there are no manual mipmaps <add> // set 0 level mipmap and then use GL to generate other mipmap levels <add> <add> if ( mipmaps.length > 0 && isImagePowerOfTwo ) { <ide> <ide> for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { <ide> <ide> mipmap = mipmaps[ i ]; <del> if ( texture.format !== THREE.RGBAFormat ) { <del> _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); <del> } else { <del> _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); <del> } <add> _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap ); <ide> <ide> } <ide> <del> } else { // regular Texture (image, video, canvas) <add> texture.generateMipmaps = false; <ide> <del> // use manually created mipmaps if available <del> // if there are no manual mipmaps <del> // set 0 level mipmap and then use GL to generate other mipmap levels <del> <del> if ( mipmaps.length > 0 && isImagePowerOfTwo ) { <add> } else { <ide> <del> for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { <add> _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image ); <ide> <del> mipmap = mipmaps[ i ]; <del> _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap ); <add> } <ide> <del> } <add> } <ide> <del> texture.generateMipmaps = false; <add> if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); <ide> <del> } else { <add> texture.needsUpdate = false; <ide> <del> _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image ); <add> if ( texture.onUpdate ) texture.onUpdate(); <ide> <del> } <add> }; <ide> <del> } <add> this.setTexture = function ( texture, slot ) { <ide> <del> if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); <add> _gl.activeTexture( _gl.TEXTURE0 + slot ); <ide> <del> texture.needsUpdate = false; <add> if ( texture.needsUpdate ) { <ide> <del> if ( texture.onUpdate ) texture.onUpdate(); <add> _this.uploadTexture( texture ); <ide> <ide> } else { <ide> <del> _gl.activeTexture( _gl.TEXTURE0 + slot ); <ide> _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture ); <ide> <ide> }
1
Text
Text
update the docs for --link accept container id
750373875e25455acb046001cb0582873a90bd73
<ide><path>docs/man/docker-create.1.md <ide> IMAGE [COMMAND] [ARG...] <ide> 'host': use the host shared memory,semaphores and message queues inside the container. Note: the host mode gives the container full access to local shared memory and is therefore considered insecure. <ide> <ide> **--link**=[] <del> Add link to another container in the form of name:alias <add> Add link to another container in the form of <name or id>:alias <ide> <ide> **--lxc-conf**=[] <ide> (lxc exec-driver only) Add custom lxc options --lxc-conf="lxc.cgroup.cpuset.cpus = 0,1" <ide><path>docs/man/docker-run.1.md <ide> ENTRYPOINT. <ide> 'host': use the host shared memory,semaphores and message queues inside the container. Note: the host mode gives the container full access to local shared memory and is therefore considered insecure. <ide> <ide> **--link**=[] <del> Add link to another container in the form of name:alias <add> Add link to another container in the form of <name or id>:alias <ide> <ide> If the operator <ide> uses **--link** when starting the new client container, then the client <ide><path>docs/sources/articles/networking.md <ide> Finally, several networking options can only be provided when calling <ide> [Configuring DNS](#dns) and <ide> [How Docker networks a container](#container-networking) <ide> <del> * `--link=CONTAINER_NAME:ALIAS` — see <add> * `--link=CONTAINER_NAME_or_ID:ALIAS` — see <ide> [Configuring DNS](#dns) and <ide> [Communication between containers](#between-containers) <ide> <ide> Four different options affect container domain name services. <ide> outside the container. It will not appear in `docker ps` nor in the <ide> `/etc/hosts` file of any other container. <ide> <del> * `--link=CONTAINER_NAME:ALIAS` — using this option as you `run` a <add> * `--link=CONTAINER_NAME_or_ID:ALIAS` — using this option as you `run` a <ide> container gives the new container's `/etc/hosts` an extra entry <del> named `ALIAS` that points to the IP address of the container named <del> `CONTAINER_NAME`. This lets processes inside the new container <add> named `ALIAS` that points to the IP address of the container identified by <add> `CONTAINER_NAME_or_ID`. This lets processes inside the new container <ide> connect to the hostname `ALIAS` without having to know its IP. The <ide> `--link=` option is discussed in more detail below, in the section <ide> [Communication between containers](#between-containers). Because <ide> If you choose the most secure setting of `--icc=false`, then how can <ide> containers communicate in those cases where you *want* them to provide <ide> each other services? <ide> <del>The answer is the `--link=CONTAINER_NAME:ALIAS` option, which was <add>The answer is the `--link=CONTAINER_NAME_or_ID:ALIAS` option, which was <ide> mentioned in the previous section because of its effect upon name <ide> services. If the Docker daemon is running with both `--icc=false` and <ide> `--iptables=true` then, when it sees `docker run` invoked with the <ide><path>docs/sources/reference/commandline/cli.md <ide> Creates a new container. <ide> --ipc="" Default is to create a private IPC namespace (POSIX SysV IPC) for the container <ide> 'container:<name|id>': reuses another container shared memory, semaphores and message queues <ide> 'host': use the host shared memory,semaphores and message queues inside the container. Note: the host mode gives the container full access to local shared memory and is therefore considered insecure. <del> --link=[] Add link to another container in the form of name:alias <add> --link=[] Add link to another container in the form of <name or id>:alias <ide> --lxc-conf=[] (lxc exec-driver only) Add custom lxc options --lxc-conf="lxc.cgroup.cpuset.cpus = 0,1" <ide> -m, --memory="" Memory limit (format: <number><optional unit>, where unit = b, k, m or g) <ide> --mac-address="" Container MAC address (e.g. 92:d0:c6:0a:29:33) <ide><path>docs/sources/reference/run.md <ide> or override the Dockerfile's exposed defaults: <ide> Both hostPort and containerPort can be specified as a range of ports. <ide> When specifying ranges for both, the number of container ports in the range must match the number of host ports in the range. (e.g., `-p 1234-1236:1234-1236/tcp`) <ide> (use 'docker port' to see the actual mapping) <del> --link="" : Add link to another container (name:alias) <add> --link="" : Add link to another container (<name or id>:alias) <ide> <ide> As mentioned previously, `EXPOSE` (and `--expose`) makes ports available <ide> **in** a container for incoming connections. The port number on the <ide> above, or already defined by the developer with a Dockerfile `ENV`: <ide> <ide> Similarly the operator can set the **hostname** with `-h`. <ide> <del>`--link name:alias` also sets environment variables, using the *alias* string to <add>`--link <name or id>:alias` also sets environment variables, using the *alias* string to <ide> define environment variables within the container that give the IP and PORT <ide> information for connecting to the service container. Let's imagine we have a <ide> container running Redis: <ide><path>docs/sources/userguide/dockerlinks.md <ide> Now, create a new `web` container and link it with your `db` container. <ide> This will link the new `web` container with the `db` container you created <ide> earlier. The `--link` flag takes the form: <ide> <del> --link name:alias <add> --link <name or id>:alias <ide> <ide> Where `name` is the name of the container we're linking to and `alias` is an <ide> alias for the link name. You'll see how that alias gets used shortly.
6
Javascript
Javascript
add gettypedarray unittest
ab69febff58bc0c42920eeb0ffa514de759c531d
<ide><path>test/unit/src/utils.tests.js <ide> /* global QUnit */ <ide> <del>import { arrayMin, arrayMax } from '../../../src/utils'; <add>import { arrayMin, arrayMax, getTypedArray } from '../../../src/utils'; <ide> <ide> QUnit.module( 'utils', () => { <ide> <ide> QUnit.module( 'utils', () => { <ide> } ); <ide> <ide> <add> QUnit.test( 'getTypedArray', ( assert ) => { <add> <add> assert.ok( getTypedArray( 'Int8Array', Buffer.from( '', 'utf8' ) ) instanceof Int8Array, 'Int8Array' ); <add> assert.ok( getTypedArray( 'Uint8Array', Buffer.from( '', 'utf8' ) ) instanceof Uint8Array, 'Uint8Array' ); <add> assert.ok( getTypedArray( 'Uint8ClampedArray', Buffer.from( '', 'utf8' ) ) instanceof Uint8ClampedArray, 'Uint8ClampedArray' ); <add> assert.ok( getTypedArray( 'Int16Array', Buffer.from( '', 'utf8' ) ) instanceof Int16Array, 'Int16Array' ); <add> assert.ok( getTypedArray( 'Uint16Array', Buffer.from( '', 'utf8' ) ) instanceof Uint16Array, 'Uint16Array' ); <add> assert.ok( getTypedArray( 'Int32Array', Buffer.from( '', 'utf8' ) ) instanceof Int32Array, 'Int32Array' ); <add> assert.ok( getTypedArray( 'Uint32Array', Buffer.from( '', 'utf8' ) ) instanceof Uint32Array, 'Uint32Array' ); <add> assert.ok( getTypedArray( 'Float32Array', Buffer.from( '', 'utf8' ) ) instanceof Float32Array, 'Float32Array' ); <add> assert.ok( getTypedArray( 'Float64Array', Buffer.from( '', 'utf8' ) ) instanceof Float64Array, 'Float64Array' ); <add> <add> } ); <add> <ide> } );
1
Ruby
Ruby
fix rubocop warnings
16be0f105ed3eef07133cdd09e48e562b85b7697
<ide><path>Library/Homebrew/language/python.rb <ide> def create <ide> # Robustify symlinks to survive python3 patch upgrades <ide> @venv_root.find do |f| <ide> next unless f.symlink? <del> if (rp = f.realpath.to_s).start_with? HOMEBREW_CELLAR <del> python = rp.include?("python3") ? "python3" : "python" <del> new_target = rp.sub %r{#{HOMEBREW_CELLAR}/#{python}/[^/]+}, Formula[python].opt_prefix <del> f.unlink <del> f.make_symlink new_target <del> end <add> next unless (rp = f.realpath.to_s).start_with? HOMEBREW_CELLAR <add> python = rp.include?("python3") ? "python3" : "python" <add> new_target = rp.sub %r{#{HOMEBREW_CELLAR}/#{python}/[^/]+}, Formula[python].opt_prefix <add> f.unlink <add> f.make_symlink new_target <ide> end <ide> end <ide>
1