content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Javascript
Javascript
update booleankeyframetrack inheritance
5bceba4cf6026194f3118962d484d348d3a5f75b
<ide><path>src/animation/tracks/BooleanKeyframeTrack.js <ide> import { InterpolateDiscrete } from '../../constants.js'; <del>import { KeyframeTrackPrototype } from '../KeyframeTrackPrototype.js'; <del>import { KeyframeTrackConstructor } from '../KeyframeTrackConstructor.js'; <add>import { KeyframeTrack } from '../KeyframeTrack.js'; <ide> <ide> /** <ide> * <ide> import { KeyframeTrackConstructor } from '../KeyframeTrackConstructor.js'; <ide> <ide> function BooleanKeyframeTrack( name, times, values ) { <ide> <del> KeyframeTrackConstructor.call( this, name, times, values ); <add> KeyframeTrack.call( this, name, times, values ); <ide> <ide> } <ide> <del>BooleanKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrackPrototype ), { <add>BooleanKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { <ide> <ide> constructor: BooleanKeyframeTrack, <ide>
1
Javascript
Javascript
fix typo in comment
0d468ab200584c3aaa6ef721f51037d37c9fea7b
<ide><path>lib/_http_server.js <ide> function resOnFinish(req, res, socket, state, server) { <ide> <ide> // Make sure the requestTimeout is cleared before finishing. <ide> // This might occur if the application has sent a response <del> // without consuming the request body, which would have alredy <add> // without consuming the request body, which would have already <ide> // cleared the timer. <ide> // clearRequestTimeout can be executed even if the timer is not active, <ide> // so this is safe.
1
Python
Python
remove trailing semicolon
56ce2bfa7c031564f06cad469219dbeb350d7be7
<ide><path>libcloud/compute/drivers/hostvirtual.py <ide> def create_node(self, name, image, size, **kwargs): <ide> >>> from libcloud.compute.base import NodeAuthSSHKey <ide> >>> key = open('/home/user/.ssh/id_rsa.pub').read() <ide> >>> auth = NodeAuthSSHKey(pubkey=key) <del> >>> from libcloud.compute.providers import get_driver; <add> >>> from libcloud.compute.providers import get_driver <ide> >>> driver = get_driver('hostvirtual') <ide> >>> conn = driver('API_KEY') <ide> >>> image = conn.list_images()[1]
1
Javascript
Javascript
close watchers correctly when closing watching
263c5c9f4013ff956b3d4ad1b154a3d3af7e7a6f
<ide><path>lib/Compiler.js <ide> function Watching(compiler, watchOptions, handler) { <ide> this.error = null; <ide> this.stats = null; <ide> this.handler = handler; <add> this.closed = false; <ide> if(typeof watchOptions === "number") { <ide> this.watchOptions = { <ide> aggregateTimeout: watchOptions <ide> Watching.prototype._done = function(err, compilation) { <ide> else <ide> this.compiler.applyPlugins("failed", this.error); <ide> this.handler(this.error, this.stats); <del> if(!this.error) <add> if(!this.error && !this.closed) <ide> this.watch(compilation.fileDependencies, compilation.contextDependencies, compilation.missingDependencies); <ide> }; <ide> <ide> Watching.prototype.watch = function(files, dirs, missing) { <add> this.pausedWatcher = null; <ide> this.watcher = this.compiler.watchFileSystem.watch(files, dirs, missing, this.startTime, this.watchOptions, function(err, filesModified, contextModified, missingModified, fileTimestamps, contextTimestamps) { <add> this.pausedWatcher = this.watcher; <ide> this.watcher = null; <ide> if(err) return this.handler(err); <ide> <ide> Watching.prototype.watch = function(files, dirs, missing) { <ide> <ide> Watching.prototype.invalidate = function() { <ide> if(this.watcher) { <add> this.pausedWatcher = this.watcher; <ide> this.watcher.pause(); <ide> this.watcher = null; <ide> } <ide> Watching.prototype.invalidate = function() { <ide> Watching.prototype.close = function(callback) { <ide> if(callback === undefined) callback = function() {}; <ide> <add> this.closed = true; <ide> if(this.watcher) { <ide> this.watcher.close(); <ide> this.watcher = null; <ide> } <add> if(this.pausedWatcher) { <add> this.pausedWatcher.close(); <add> this.pausedWatcher = null; <add> } <ide> if(this.running) { <ide> this.invalid = true; <ide> this._done = () => { <ide><path>lib/node/NodeWatchFileSystem.js <ide> class NodeWatchFileSystem { <ide> } <ide> return { <ide> close: () => { <del> this.watcher.close(); <add> if(this.watcher) { <add> this.watcher.close(); <add> this.watcher = null; <add> } <ide> }, <ide> pause: () => { <del> this.watcher.pause(); <add> if(this.watcher) { <add> this.watcher.pause(); <add> } <ide> } <ide> }; <ide> } <ide><path>test/WatchDetection.test.js <ide> describe("WatchDetection", () => { <ide> function step4() { <ide> onChange = null; <ide> <del> watcher.close(); <del> <del> done(); <add> watcher.close(() => { <add> setTimeout(done, 1000); <add> }); <ide> } <ide> <ide> function handleError(err) {
3
Python
Python
add create_output option in graph model
425f29038ad13e1f627f75aadb16e44d71a25d1b
<ide><path>keras/layers/containers.py <ide> def add_input(self, name, ndim=2, dtype='float'): <ide> if ndim == 2: <ide> layer.input = T.imatrix() <ide> else: <del> raise Exception('Type "int" can only be used with ndim==2.') <add> raise Exception('Type "int" can only be used with ndim==2 (Embedding).') <ide> layer.input.name = name <ide> self.inputs[name] = layer <ide> self.input_config.append({'name': name, 'ndim': ndim, 'dtype': dtype}) <ide> <del> def add_node(self, layer, name, input=None, inputs=[], merge_mode='concat'): <add> def add_node(self, layer, name, input=None, inputs=[], merge_mode='concat', create_output=False): <ide> if hasattr(layer, 'set_name'): <ide> layer.set_name(name) <ide> if name in self.namespace: <ide> raise Exception('Duplicate node identifier: ' + name) <ide> if input: <ide> if input not in self.namespace: <del> raise Exception('Unknown identifier: ' + input) <add> raise Exception('Unknown node/input identifier: ' + input) <ide> if input in self.nodes: <ide> layer.set_previous(self.nodes[input]) <ide> elif input in self.inputs: <ide> def add_node(self, layer, name, input=None, inputs=[], merge_mode='concat'): <ide> self.constraints += constraints <ide> self.updates += updates <ide> <add> if create_output: <add> self.add_output(name, input=name) <add> <ide> def add_output(self, name, input=None, inputs=[], merge_mode='concat'): <del> if name in self.namespace: <del> raise Exception('Duplicate node identifier: ' + name) <add> if name in self.output_order: <add> raise Exception('Duplicate output identifier: ' + name) <ide> if input: <ide> if input not in self.namespace: <del> raise Exception('Unknown identifier: ' + input) <add> raise Exception('Unknown node/input identifier: ' + input) <ide> if input in self.nodes: <ide> self.outputs[name] = self.nodes[input] <ide> elif input in self.inputs: <ide> def add_output(self, name, input=None, inputs=[], merge_mode='concat'): <ide> to_merge.append(self.nodes[n]) <ide> merge = Merge(to_merge, mode=merge_mode) <ide> self.outputs[name] = merge <del> self.namespace.add(name) <add> <ide> self.output_order.append(name) <ide> self.output_config.append({'name': name, <ide> 'input': input, <ide><path>tests/auto/test_graph_model.py <ide> def test_recursive(self): <ide> pred = seq.predict(X_test) <ide> seq.get_config(verbose=1) <ide> <add> def test_create_output(self): <add> print('test create_output argument') <add> graph = Graph() <add> graph.add_input(name='input1', ndim=2) <add> <add> graph.add_node(Dense(32, 16), name='dense1', input='input1') <add> graph.add_node(Dense(32, 4), name='dense2', input='input1') <add> graph.add_node(Dense(16, 4), name='dense3', input='dense1') <add> graph.add_node(Dense(4, 4), name='output1', inputs=['dense2', 'dense3'], merge_mode='sum', create_output=True) <add> graph.compile('rmsprop', {'output1': 'mse'}) <add> <add> history = graph.fit({'input1': X_train, 'output1': y_train}, nb_epoch=10) <add> out = graph.predict({'input1': X_test}) <add> assert(type(out == dict)) <add> assert(len(out) == 1) <add> loss = graph.test_on_batch({'input1': X_test, 'output1': y_test}) <add> loss = graph.train_on_batch({'input1': X_test, 'output1': y_test}) <add> loss = graph.evaluate({'input1': X_test, 'output1': y_test}) <add> print(loss) <add> assert(loss < 2.5) <add> <ide> <ide> if __name__ == '__main__': <ide> print('Test graph model')
2
Javascript
Javascript
fix sourcemap loading on android
d1e9fc0737fc0987436807d3b9992869f51ce078
<ide><path>Libraries/JavaScriptAppEngine/Initialization/SourceMapsUtils.js <ide> var SourceMapsUtils = { <ide> .then(map => new SourceMapConsumer(map)); <ide> }, <ide> <del> extractSourceMapURL(data: ({url:string, text:string})): ?string { <add> extractSourceMapURL(data: ({url?:string, text?:string, fullSourceMappingURL?:string})): ?string { <ide> const url = data.url; <ide> const text = data.text; <add> const fullSourceMappingURL = data.fullSourceMappingURL; <add> if (fullSourceMappingURL) { <add> return fullSourceMappingURL; <add> } <ide> var mapURL = SourceMapURL.getFrom(text); <ide> if (!mapURL) { <ide> return null; <ide> } <add> if (!url) { <add> return null; <add> } <ide> var baseURLs = url.match(/(.+:\/\/.*?)\//); <ide> if (!baseURLs || baseURLs.length < 2) { <ide> return null;
1
Go
Go
add debugs for key change events in networkdb
929921a640bc2dc2e8534a95b72cd3342d484188
<ide><path>libnetwork/networkdb/cluster.go <ide> package networkdb <ide> import ( <ide> "bytes" <ide> "crypto/rand" <add> "encoding/hex" <ide> "fmt" <ide> "math/big" <ide> rnd "math/rand" <ide> func (l *logWriter) Write(p []byte) (int, error) { <ide> <ide> // SetKey adds a new key to the key ring <ide> func (nDB *NetworkDB) SetKey(key []byte) { <add> logrus.Debugf("Adding key %s", hex.EncodeToString(key)[0:5]) <ide> for _, dbKey := range nDB.config.Keys { <ide> if bytes.Equal(key, dbKey) { <ide> return <ide> func (nDB *NetworkDB) SetKey(key []byte) { <ide> // SetPrimaryKey sets the given key as the primary key. This should have <ide> // been added apriori through SetKey <ide> func (nDB *NetworkDB) SetPrimaryKey(key []byte) { <add> logrus.Debugf("Primary Key %s", hex.EncodeToString(key)[0:5]) <ide> for _, dbKey := range nDB.config.Keys { <ide> if bytes.Equal(key, dbKey) { <ide> if nDB.keyring != nil { <ide> func (nDB *NetworkDB) SetPrimaryKey(key []byte) { <ide> // RemoveKey removes a key from the key ring. The key being removed <ide> // can't be the primary key <ide> func (nDB *NetworkDB) RemoveKey(key []byte) { <add> logrus.Debugf("Remove Key %s", hex.EncodeToString(key)[0:5]) <ide> for i, dbKey := range nDB.config.Keys { <ide> if bytes.Equal(key, dbKey) { <ide> nDB.config.Keys = append(nDB.config.Keys[:i], nDB.config.Keys[i+1:]...) <ide> func (nDB *NetworkDB) clusterInit() error { <ide> <ide> var err error <ide> if len(nDB.config.Keys) > 0 { <add> for i, key := range nDB.config.Keys { <add> logrus.Debugf("Encryption key %d: %s", i+1, hex.EncodeToString(key)[0:5]) <add> } <ide> nDB.keyring, err = memberlist.NewKeyring(nDB.config.Keys, nDB.config.Keys[0]) <ide> if err != nil { <ide> return err
1
Javascript
Javascript
fix typo in claim certificate api
95fd287f8bac36e8636d62e53dd6d85fec0178a3
<ide><path>server/boot/certificate.js <ide> export default function certificate(app) { <ide> <ide> function verifyCert(certType, req, res, next) { <ide> const { user } = req; <del> return user.getChallengeMap() <add> return user.getChallengeMap$() <ide> .flatMap(() => certTypeIds[certType]) <ide> .flatMap(challenge => { <ide> const {
1
Python
Python
fix anotehr file
06d674890f7cb4ae72392e7a5266f92837ef024e
<ide><path>research/object_detection/dataset_tools/context_rcnn/generate_embedding_data.py <add># Copyright 2020 The TensorFlow Authors. All Rights Reserved. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add># ============================================================================== <add>r"""A Beam job to generate embedding data for camera trap images. <add> <add>This tool runs inference with an exported Object Detection model in <add>`saved_model` format and produce raw embeddings for camera trap data. These <add>embeddings contain an object-centric feature embedding from Faster R-CNN, the <add>datetime that the image was taken (normalized in a specific way), and the <add>position of the object of interest. By default, only the highest-scoring object <add>embedding is included. <add> <add>Steps to generate a embedding dataset: <add>1. Use object_detection/export_inference_graph.py to get a Faster R-CNN <add> `saved_model` for inference. The input node must accept a tf.Example proto. <add>2. Run this tool with `saved_model` from step 1 and an TFRecord of tf.Example <add> protos containing images for inference. <add> <add>Example Usage: <add>-------------- <add>python tensorflow_models/object_detection/export_inference_graph.py \ <add> --alsologtostderr \ <add> --input_type tf_example \ <add> --pipeline_config_path path/to/faster_rcnn_model.config \ <add> --trained_checkpoint_prefix path/to/model.ckpt \ <add> --output_directory path/to/exported_model_directory \ <add> --additional_output_tensor_names detection_features <add> <add>python generate_embedding_data.py \ <add> --alsologtostderr \ <add> --embedding_input_tfrecord path/to/input_tfrecords* \ <add> --embedding_output_tfrecord path/to/output_tfrecords \ <add> --embedding_model_dir path/to/exported_model_directory/saved_model <add>""" <add> <add>from __future__ import absolute_import <add>from __future__ import division <add>from __future__ import print_function <add> <add>import argparse <add>import datetime <add>import os <add>import threading <add> <add>import numpy as np <add>import six <add>import tensorflow.compat.v1 as tf <add> <add>try: <add> import apache_beam as beam # pylint:disable=g-import-not-at-top <add>except ModuleNotFoundError: <add> pass <add> <add> <add>class GenerateEmbeddingDataFn(beam.DoFn): <add> """Generates embedding data for camera trap images. <add> <add> This Beam DoFn performs inference with an object detection `saved_model` and <add> produces contextual embedding vectors. <add> """ <add> session_lock = threading.Lock() <add> <add> def __init__(self, model_dir, top_k_embedding_count, <add> bottom_k_embedding_count): <add> """Initialization function. <add> <add> Args: <add> model_dir: A directory containing saved model. <add> top_k_embedding_count: the number of high-confidence embeddings to store <add> bottom_k_embedding_count: the number of low-confidence embeddings to store <add> """ <add> self._model_dir = model_dir <add> self._session = None <add> self._num_examples_processed = beam.metrics.Metrics.counter( <add> 'embedding_data_generation', 'num_tf_examples_processed') <add> self._top_k_embedding_count = top_k_embedding_count <add> self._bottom_k_embedding_count = bottom_k_embedding_count <add> <add> def start_bundle(self): <add> self._load_inference_model() <add> <add> def _load_inference_model(self): <add> # Because initialization of the tf.Session is expensive we share <add> # one instance across all threads in the worker. This is possible since <add> # tf.Session.run() is thread safe. <add> with self.session_lock: <add> if self._session is None: <add> graph = tf.Graph() <add> self._session = tf.Session(graph=graph) <add> with graph.as_default(): <add> meta_graph = tf.saved_model.loader.load( <add> self._session, [tf.saved_model.tag_constants.SERVING], <add> self._model_dir) <add> signature = meta_graph.signature_def['serving_default'] <add> input_tensor_name = signature.inputs['input_tensor'].name <add> detection_features_name = signature.outputs['detection_features'].name <add> detection_boxes_name = signature.outputs['detection_boxes'].name <add> num_detections_name = signature.outputs['num_detections'].name <add> self._input = graph.get_tensor_by_name(input_tensor_name) <add> self._embedding_node = graph.get_tensor_by_name(detection_features_name) <add> self._box_node = graph.get_tensor_by_name(detection_boxes_name) <add> self._scores_node = graph.get_tensor_by_name( <add> signature.outputs['detection_scores'].name) <add> self._num_detections = graph.get_tensor_by_name(num_detections_name) <add> tf.logging.info(signature.outputs['detection_features'].name) <add> tf.logging.info(signature.outputs['detection_boxes'].name) <add> tf.logging.info(signature.outputs['num_detections'].name) <add> <add> def process(self, tfrecord_entry): <add> return self._run_inference_and_generate_embedding(tfrecord_entry) <add> <add> def _run_inference_and_generate_embedding(self, tfrecord_entry): <add> input_example = tf.train.Example.FromString(tfrecord_entry) <add> # Convert date_captured datetime string to unix time integer and store <add> <add> def get_date_captured(example): <add> date_captured = datetime.datetime.strptime( <add> six.ensure_str( <add> example.features.feature[ <add> 'image/date_captured'].bytes_list.value[0]), <add> '%Y-%m-%d %H:%M:%S') <add> return date_captured <add> <add> try: <add> date_captured = get_date_captured(input_example) <add> except Exception: # pylint: disable=broad-except <add> # we require date_captured to be available for all images <add> return [] <add> <add> def embed_date_captured(date_captured): <add> """Encodes the datetime of the image.""" <add> embedded_date_captured = [] <add> month_max = 12.0 <add> day_max = 31.0 <add> hour_max = 24.0 <add> minute_max = 60.0 <add> min_year = 1990.0 <add> max_year = 2030.0 <add> <add> year = (date_captured.year-min_year)/float(max_year-min_year) <add> embedded_date_captured.append(year) <add> <add> month = (date_captured.month-1)/month_max <add> embedded_date_captured.append(month) <add> <add> day = (date_captured.day-1)/day_max <add> embedded_date_captured.append(day) <add> <add> hour = date_captured.hour/hour_max <add> embedded_date_captured.append(hour) <add> <add> minute = date_captured.minute/minute_max <add> embedded_date_captured.append(minute) <add> <add> return np.asarray(embedded_date_captured) <add> <add> def embed_position_and_size(box): <add> """Encodes the bounding box of the object of interest.""" <add> ymin = box[0] <add> xmin = box[1] <add> ymax = box[2] <add> xmax = box[3] <add> w = xmax - xmin <add> h = ymax - ymin <add> x = xmin + w / 2.0 <add> y = ymin + h / 2.0 <add> return np.asarray([x, y, w, h]) <add> <add> unix_time = ( <add> (date_captured - datetime.datetime.fromtimestamp(0)).total_seconds()) <add> <add> example = tf.train.Example() <add> example.features.feature['image/unix_time'].float_list.value.extend( <add> [unix_time]) <add> <add> (detection_features, detection_boxes, num_detections, <add> detection_scores) = self._session.run( <add> [ <add> self._embedding_node, self._box_node, self._num_detections[0], <add> self._scores_node <add> ], <add> feed_dict={self._input: [tfrecord_entry]}) <add> <add> num_detections = int(num_detections) <add> embed_all = [] <add> score_all = [] <add> <add> detection_features = np.asarray(detection_features) <add> <add> def get_bb_embedding(detection_features, detection_boxes, detection_scores, <add> index): <add> embedding = detection_features[0][index] <add> pooled_embedding = np.mean(np.mean(embedding, axis=1), axis=0) <add> <add> box = detection_boxes[0][index] <add> position_embedding = embed_position_and_size(box) <add> <add> score = detection_scores[0][index] <add> return np.concatenate((pooled_embedding, position_embedding)), score <add> <add> temporal_embedding = embed_date_captured(date_captured) <add> <add> embedding_count = 0 <add> for index in range(min(num_detections, self._top_k_embedding_count)): <add> bb_embedding, score = get_bb_embedding( <add> detection_features, detection_boxes, detection_scores, index) <add> embed_all.extend(bb_embedding) <add> embed_all.extend(temporal_embedding) <add> score_all.append(score) <add> embedding_count += 1 <add> <add> for index in range( <add> max(0, num_detections - 1), <add> max(-1, num_detections - 1 - self._bottom_k_embedding_count), -1): <add> bb_embedding, score = get_bb_embedding( <add> detection_features, detection_boxes, detection_scores, index) <add> embed_all.extend(bb_embedding) <add> embed_all.extend(temporal_embedding) <add> score_all.append(score) <add> embedding_count += 1 <add> <add> if embedding_count == 0: <add> bb_embedding, score = get_bb_embedding( <add> detection_features, detection_boxes, detection_scores, 0) <add> embed_all.extend(bb_embedding) <add> embed_all.extend(temporal_embedding) <add> score_all.append(score) <add> <add> # Takes max in case embedding_count is 0. <add> embedding_length = len(embed_all) // max(1, embedding_count) <add> <add> embed_all = np.asarray(embed_all) <add> <add> example.features.feature['image/embedding'].float_list.value.extend( <add> embed_all) <add> example.features.feature['image/embedding_score'].float_list.value.extend( <add> score_all) <add> example.features.feature['image/embedding_length'].int64_list.value.append( <add> embedding_length) <add> example.features.feature['image/embedding_count'].int64_list.value.append( <add> embedding_count) <add> <add> # Add other essential example attributes <add> example.features.feature['image/encoded'].bytes_list.value.extend( <add> input_example.features.feature['image/encoded'].bytes_list.value) <add> example.features.feature['image/height'].int64_list.value.extend( <add> input_example.features.feature['image/height'].int64_list.value) <add> example.features.feature['image/width'].int64_list.value.extend( <add> input_example.features.feature['image/width'].int64_list.value) <add> example.features.feature['image/source_id'].bytes_list.value.extend( <add> input_example.features.feature['image/source_id'].bytes_list.value) <add> example.features.feature['image/location'].bytes_list.value.extend( <add> input_example.features.feature['image/location'].bytes_list.value) <add> <add> example.features.feature['image/date_captured'].bytes_list.value.extend( <add> input_example.features.feature['image/date_captured'].bytes_list.value) <add> <add> example.features.feature['image/class/text'].bytes_list.value.extend( <add> input_example.features.feature['image/class/text'].bytes_list.value) <add> example.features.feature['image/class/label'].int64_list.value.extend( <add> input_example.features.feature['image/class/label'].int64_list.value) <add> <add> example.features.feature['image/seq_id'].bytes_list.value.extend( <add> input_example.features.feature['image/seq_id'].bytes_list.value) <add> example.features.feature['image/seq_num_frames'].int64_list.value.extend( <add> input_example.features.feature['image/seq_num_frames'].int64_list.value) <add> example.features.feature['image/seq_frame_num'].int64_list.value.extend( <add> input_example.features.feature['image/seq_frame_num'].int64_list.value) <add> <add> example.features.feature['image/object/bbox/ymax'].float_list.value.extend( <add> input_example.features.feature[ <add> 'image/object/bbox/ymax'].float_list.value) <add> example.features.feature['image/object/bbox/ymin'].float_list.value.extend( <add> input_example.features.feature[ <add> 'image/object/bbox/ymin'].float_list.value) <add> example.features.feature['image/object/bbox/xmax'].float_list.value.extend( <add> input_example.features.feature[ <add> 'image/object/bbox/xmax'].float_list.value) <add> example.features.feature['image/object/bbox/xmin'].float_list.value.extend( <add> input_example.features.feature[ <add> 'image/object/bbox/xmin'].float_list.value) <add> example.features.feature[ <add> 'image/object/class/score'].float_list.value.extend( <add> input_example.features.feature[ <add> 'image/object/class/score'].float_list.value) <add> example.features.feature[ <add> 'image/object/class/label'].int64_list.value.extend( <add> input_example.features.feature[ <add> 'image/object/class/label'].int64_list.value) <add> example.features.feature[ <add> 'image/object/class/text'].bytes_list.value.extend( <add> input_example.features.feature[ <add> 'image/object/class/text'].bytes_list.value) <add> <add> self._num_examples_processed.inc(1) <add> return [example] <add> <add> <add>def construct_pipeline(pipeline, input_tfrecord, output_tfrecord, model_dir, <add> top_k_embedding_count, bottom_k_embedding_count, <add> num_shards): <add> """Returns a beam pipeline to run object detection inference. <add> <add> Args: <add> pipeline: Initialized beam pipeline. <add> input_tfrecord: An TFRecord of tf.train.Example protos containing images. <add> output_tfrecord: An TFRecord of tf.train.Example protos that contain images <add> in the input TFRecord and the detections from the model. <add> model_dir: Path to `saved_model` to use for inference. <add> top_k_embedding_count: The number of high-confidence embeddings to store. <add> bottom_k_embedding_count: The number of low-confidence embeddings to store. <add> num_shards: The number of output shards. <add> """ <add> input_collection = ( <add> pipeline | 'ReadInputTFRecord' >> beam.io.tfrecordio.ReadFromTFRecord( <add> input_tfrecord, <add> coder=beam.coders.BytesCoder())) <add> output_collection = input_collection | 'ExtractEmbedding' >> beam.ParDo( <add> GenerateEmbeddingDataFn(model_dir, top_k_embedding_count, <add> bottom_k_embedding_count)) <add> output_collection = output_collection | 'Reshuffle' >> beam.Reshuffle() <add> _ = output_collection | 'WritetoDisk' >> beam.io.tfrecordio.WriteToTFRecord( <add> output_tfrecord, <add> num_shards=num_shards, <add> coder=beam.coders.ProtoCoder(tf.train.Example)) <add> <add> <add>def parse_args(argv): <add> """Command-line argument parser. <add> <add> Args: <add> argv: command line arguments <add> Returns: <add> beam_args: Arguments for the beam pipeline. <add> pipeline_args: Arguments for the pipeline options, such as runner type. <add> """ <add> parser = argparse.ArgumentParser() <add> parser.add_argument( <add> '--embedding_input_tfrecord', <add> dest='embedding_input_tfrecord', <add> required=True, <add> help='TFRecord containing images in tf.Example format for object ' <add> 'detection.') <add> parser.add_argument( <add> '--embedding_output_tfrecord', <add> dest='embedding_output_tfrecord', <add> required=True, <add> help='TFRecord containing embeddings in tf.Example format.') <add> parser.add_argument( <add> '--embedding_model_dir', <add> dest='embedding_model_dir', <add> required=True, <add> help='Path to directory containing an object detection SavedModel with' <add> 'detection_box_classifier_features in the output.') <add> parser.add_argument( <add> '--top_k_embedding_count', <add> dest='top_k_embedding_count', <add> default=1, <add> help='The number of top k embeddings to add to the memory bank.') <add> parser.add_argument( <add> '--bottom_k_embedding_count', <add> dest='bottom_k_embedding_count', <add> default=0, <add> help='The number of bottom k embeddings to add to the memory bank.') <add> parser.add_argument( <add> '--num_shards', <add> dest='num_shards', <add> default=0, <add> help='Number of output shards.') <add> beam_args, pipeline_args = parser.parse_known_args(argv) <add> return beam_args, pipeline_args <add> <add> <add>def main(argv=None, save_main_session=True): <add> """Runs the Beam pipeline that performs inference. <add> <add> Args: <add> argv: Command line arguments. <add> save_main_session: Whether to save the main session. <add> """ <add> args, pipeline_args = parse_args(argv) <add> <add> pipeline_options = beam.options.pipeline_options.PipelineOptions( <add> pipeline_args) <add> pipeline_options.view_as( <add> beam.options.pipeline_options.SetupOptions).save_main_session = ( <add> save_main_session) <add> <add> dirname = os.path.dirname(args.embedding_output_tfrecord) <add> tf.io.gfile.makedirs(dirname) <add> <add> p = beam.Pipeline(options=pipeline_options) <add> <add> construct_pipeline( <add> p, <add> args.embedding_input_tfrecord, <add> args.embedding_output_tfrecord, <add> args.embedding_model_dir, <add> args.top_k_embedding_count, <add> args.bottom_k_embedding_count, <add> args.num_shards) <add> <add> p.run() <add> <add> <add>if __name__ == '__main__': <add> main() <add>
1
Python
Python
modify benchmarks for radix sort
01eebb134411b8a48aa33ea0c5c6b1757abe60db
<ide><path>benchmarks/benchmarks/bench_function_base.py <ide> def time_select_larger(self): <ide> np.select(self.cond_large, ([self.d, self.e] * 10)) <ide> <ide> <add>def memoize(f): <add> _memoized = {} <add> def wrapped(*args): <add> if args not in _memoized: <add> _memoized[args] = f(*args) <add> <add> return _memoized[args].copy() <add> <add> return f <add> <add> <ide> class SortGenerator(object): <ide> # The size of the unsorted area in the "random unsorted area" <ide> # benchmarks <ide> class SortGenerator(object): <ide> BUBBLE_SIZE = 100 <ide> <ide> @staticmethod <add> @memoize <ide> def random(size, dtype): <ide> """ <ide> Returns a randomly-shuffled array. <ide> def random(size, dtype): <ide> return arr <ide> <ide> @staticmethod <add> @memoize <ide> def ordered(size, dtype): <ide> """ <ide> Returns an ordered array. <ide> """ <ide> return np.arange(size, dtype=dtype) <ide> <ide> @staticmethod <add> @memoize <ide> def reversed(size, dtype): <ide> """ <ide> Returns an array that's in descending order. <ide> """ <ide> return np.arange(size-1, -1, -1, dtype=dtype) <ide> <ide> @staticmethod <add> @memoize <ide> def uniform(size, dtype): <ide> """ <ide> Returns an array that has the same value everywhere. <ide> """ <ide> return np.ones(size, dtype=dtype) <ide> <ide> @staticmethod <add> @memoize <ide> def swapped_pair(size, dtype, swap_frac): <ide> """ <ide> Returns an ordered array, but one that has ``swap_frac * size`` <ide> def swapped_pair(size, dtype, swap_frac): <ide> return a <ide> <ide> @staticmethod <add> @memoize <ide> def sorted_block(size, dtype, block_size): <ide> """ <ide> Returns an array with blocks that are all sorted. <ide> def sorted_block(size, dtype, block_size): <ide> return np.array(b) <ide> <ide> @classmethod <add> @memoize <ide> def random_unsorted_area(cls, size, dtype, frac, area_size=None): <ide> """ <ide> This type of array has random unsorted areas such that they <ide> def random_unsorted_area(cls, size, dtype, frac, area_size=None): <ide> return a <ide> <ide> @classmethod <add> @memoize <ide> def random_bubble(cls, size, dtype, bubble_num, bubble_size=None): <ide> """ <ide> This type of array has ``bubble_num`` random unsorted areas. <ide> class Sort(Benchmark): <ide> # In NumPy 1.17 and newer, 'merge' can be one of several <ide> # stable sorts, it isn't necessarily merge sort. <ide> ['quick', 'merge', 'heap'], <del> ['float64', 'int64', 'uint64'], <add> ['float64', 'int64', 'int16'], <ide> [ <ide> ('random',), <ide> ('ordered',), <ide> class Sort(Benchmark): <ide> ('sorted_block', 10), <ide> ('sorted_block', 100), <ide> ('sorted_block', 1000), <del> ('swapped_pair', 0.01), <del> ('swapped_pair', 0.1), <del> ('swapped_pair', 0.5), <del> ('random_unsorted_area', 0.5), <del> ('random_unsorted_area', 0.1), <del> ('random_unsorted_area', 0.01), <del> ('random_bubble', 1), <del> ('random_bubble', 5), <del> ('random_bubble', 10), <add> # ('swapped_pair', 0.01), <add> # ('swapped_pair', 0.1), <add> # ('swapped_pair', 0.5), <add> # ('random_unsorted_area', 0.5), <add> # ('random_unsorted_area', 0.1), <add> # ('random_unsorted_area', 0.01), <add> # ('random_bubble', 1), <add> # ('random_bubble', 5), <add> # ('random_bubble', 10), <ide> ], <ide> ] <ide> param_names = ['kind', 'dtype', 'array_type'] <ide> def setup(self, kind, dtype, array_type): <ide> array_class = array_type[0] <ide> self.arr = getattr(SortGenerator, array_class)(self.ARRAY_SIZE, dtype, *array_type[1:]) <ide> <del> def time_sort_inplace(self, kind, dtype, array_type): <del> self.arr.sort(kind=kind) <del> <ide> def time_sort(self, kind, dtype, array_type): <add> # Using np.sort(...) instead of arr.sort(...) because it makes a copy. <add> # This is important because the data is prepared once per benchmark, but <add> # used across multiple runs. <ide> np.sort(self.arr, kind=kind) <ide> <ide> def time_argsort(self, kind, dtype, array_type):
1
Go
Go
add info for driver
cfd188e9251f5047e4fd677fe8f2921ae28b8bcc
<ide><path>execdriver/namespaces/driver.go <ide> func init() { <ide> } <ide> <ide> type driver struct { <add> root string <ide> } <ide> <del>func NewDriver() (*driver, error) { <del> return &driver{}, nil <add>type info struct { <add> ID string <add> driver *driver <add>} <add> <add>func (i *info) IsRunning() bool { <add> p := filepath.Join(i.driver.root, "containers", i.ID, "rootfs", ".nspid") <add> if _, err := os.Stat(p); err == nil { <add> return true <add> } <add> return false <add>} <add> <add>func NewDriver(root string) (*driver, error) { <add> return &driver{ <add> root: root, <add> }, nil <ide> } <ide> <ide> func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (int, error) { <ide> func (d *driver) Restore(c *execdriver.Command) error { <ide> } <ide> <ide> func (d *driver) Info(id string) execdriver.Info { <del> return nil <add> return &info{ <add> ID: id, <add> driver: d, <add> } <ide> } <ide> <ide> func (d *driver) Name() string { <ide><path>integration/container_test.go <ide> func TestEnv(t *testing.T) { <ide> goodEnv := []string{ <ide> "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", <ide> "HOME=/", <del> "container=lxc", <add> "container=docker", <ide> "HOSTNAME=" + utils.TruncateID(container.ID), <ide> "FALSE=true", <ide> "TRUE=false", <ide><path>runtime.go <ide> func NewRuntimeFromDirectory(config *DaemonConfig, eng *engine.Engine) (*Runtime <ide> <ide> sysInfo := sysinfo.New(false) <ide> <del> ed, err := namespaces.NewDriver() <add> ed, err := namespaces.NewDriver(config.Root) <ide> if err != nil { <ide> return nil, err <ide> }
3
Javascript
Javascript
improve assertion messages
8e814fcf3aa82ddf796a4714c43bed26381e6883
<ide><path>test/parallel/test-domain-safe-exit.js <ide> // USE OR OTHER DEALINGS IN THE SOFTWARE. <ide> <ide> 'use strict'; <add>require('../common'); <ide> // Make sure the domain stack doesn't get clobbered by un-matched .exit() <ide> <del>require('../common'); <ide> const assert = require('assert'); <ide> const domain = require('domain'); <add>const util = require('util'); <ide> <ide> const a = domain.create(); <ide> const b = domain.create(); <ide> <ide> a.enter(); // push <ide> b.enter(); // push <del>assert.deepStrictEqual(domain._stack, [a, b], 'b not pushed'); <add>assert.deepStrictEqual(domain._stack, [a, b], 'Unexpected stack shape ' + <add> `(domain._stack = ${util.inspect(domain._stack)})`); <ide> <ide> domain.create().exit(); // no-op <del>assert.deepStrictEqual(domain._stack, [a, b], 'stack mangled!'); <add>assert.deepStrictEqual(domain._stack, [a, b], 'Unexpected stack shape ' + <add> `(domain._stack = ${util.inspect(domain._stack)})`);
1
Python
Python
increase test coverages by factorizing cntk pads
25a8973dfce5251c0bd527ffa16ce17174b94218
<ide><path>keras/backend/cntk_backend.py <ide> def function(inputs, outputs, updates=[], **kwargs): <ide> def temporal_padding(x, padding=(1, 1)): <ide> assert len(padding) == 2 <ide> num_dynamic_axis = _get_dynamic_axis_num(x) <del> base_shape = x.shape <del> if num_dynamic_axis > 0: <del> assert len(base_shape) == 2 <del> if hasattr(C, 'pad'): <del> x = C.pad(x, pattern=[padding, (0, 0)]) <del> else: <del> x = _padding(x, padding, 0) <del> else: <del> assert len(base_shape) == 3 <del> if hasattr(C, 'pad'): <del> x = C.pad(x, pattern=[(0, 0), padding, (0, 0)]) <del> else: <del> x = _padding(x, padding, 1) <del> return x <add> assert len(x.shape) == 3 - (1 if num_dynamic_axis > 0 else 0) <add> return pad(x, [padding], 'channels_last', num_dynamic_axis) <ide> <ide> <ide> def _padding(x, pattern, axis): <ide> def _padding(x, pattern, axis): <ide> return x <ide> <ide> <add>def pad(x, pad_info, data_format, num_dynamic_axis): <add> if hasattr(C, 'pad'): <add> pattern = [list(p) for p in pad_info] <add> if data_format == 'channels_first': <add> pattern = [[0, 0]] + pattern <add> else: <add> pattern = pattern + [[0, 0]] <add> if num_dynamic_axis == 0: <add> pattern = [[0, 0]] + pattern <add> return C.pad(x, pattern=pattern) <add> else: <add> for (a, p) in enumerate(pad_info): <add> x = _padding(x, p, <add> a + (1 if num_dynamic_axis == 0 else 0) + <add> (1 if data_format == 'channels_first' else 0)) <add> return x <add> <add> <ide> def spatial_2d_padding(x, padding=((1, 1), (1, 1)), data_format=None): <ide> assert len(padding) == 2 <ide> assert len(padding[0]) == 2 <ide> def spatial_2d_padding(x, padding=((1, 1), (1, 1)), data_format=None): <ide> raise ValueError('Unknown data_format ' + str(data_format)) <ide> <ide> num_dynamic_axis = _get_dynamic_axis_num(x) <del> base_shape = x.shape <del> if data_format == 'channels_first': <del> if num_dynamic_axis > 0: <del> assert len(base_shape) == 3 <del> if hasattr(C, 'pad'): <del> x = C.pad(x, pattern=[[0, 0], list(padding[0]), list(padding[1])]) <del> else: <del> x = _padding(x, padding[0], 1) <del> x = _padding(x, padding[1], 2) <del> else: <del> assert len(base_shape) == 4 <del> if hasattr(C, 'pad'): <del> x = C.pad(x, pattern=[[0, 0], [0, 0], list(padding[0]), list(padding[1])]) <del> else: <del> x = _padding(x, padding[0], 2) <del> x = _padding(x, padding[1], 3) <del> else: <del> if num_dynamic_axis > 0: <del> assert len(base_shape) == 3 <del> if hasattr(C, 'pad'): <del> x = C.pad(x, pattern=[list(padding[0]), list(padding[1]), [0, 0]]) <del> else: <del> x = _padding(x, padding[0], 0) <del> x = _padding(x, padding[1], 1) <del> else: <del> assert len(base_shape) == 4 <del> if hasattr(C, 'pad'): <del> x = C.pad(x, pattern=[[0, 0], list(padding[0]), list(padding[1]), [0, 0]]) <del> else: <del> x = _padding(x, padding[0], 1) <del> x = _padding(x, padding[1], 2) <del> return x <add> assert len(x.shape) == 4 - (1 if num_dynamic_axis > 0 else 0) <add> return pad(x, padding, data_format, num_dynamic_axis) <ide> <ide> <ide> def spatial_3d_padding(x, padding=((1, 1), (1, 1), (1, 1)), data_format=None): <ide> def spatial_3d_padding(x, padding=((1, 1), (1, 1), (1, 1)), data_format=None): <ide> raise ValueError('Unknown data_format ' + str(data_format)) <ide> <ide> num_dynamic_axis = _get_dynamic_axis_num(x) <del> base_shape = x.shape <del> if data_format == 'channels_first': <del> if num_dynamic_axis > 0: <del> assert len(base_shape) == 4 <del> if hasattr(C, 'pad'): <del> x = C.pad(x, pattern=[[0, 0], list(padding[0]), list(padding[1]), list(padding[2])]) <del> else: <del> x = _padding(x, padding[0], 1) <del> x = _padding(x, padding[1], 2) <del> x = _padding(x, padding[2], 3) <del> else: <del> assert len(base_shape) == 5 <del> if hasattr(C, 'pad'): <del> x = C.pad(x, pattern=[[0, 0], [0, 0], list(padding[0]), list(padding[1]), list(padding[2])]) <del> else: <del> x = _padding(x, padding[0], 2) <del> x = _padding(x, padding[1], 3) <del> x = _padding(x, padding[2], 4) <del> else: <del> if num_dynamic_axis > 0: <del> assert len(base_shape) == 4 <del> if hasattr(C, 'pad'): <del> x = C.pad(x, pattern=[list(padding[0]), list(padding[1]), list(padding[2]), [0, 0]]) <del> else: <del> x = _padding(x, padding[0], 0) <del> x = _padding(x, padding[1], 1) <del> x = _padding(x, padding[2], 2) <del> else: <del> assert len(base_shape) == 5 <del> if hasattr(C, 'pad'): <del> x = C.pad(x, pattern=[[0, 0], list(padding[0]), list(padding[1]), list(padding[2]), [0, 0]]) <del> else: <del> x = _padding(x, padding[0], 1) <del> x = _padding(x, padding[1], 2) <del> x = _padding(x, padding[2], 3) <del> return x <add> assert len(x.shape) == 5 - (1 if num_dynamic_axis > 0 else 0) <add> return pad(x, padding, data_format, num_dynamic_axis) <ide> <ide> <ide> def one_hot(indices, num_classes):
1
Python
Python
add function to resolve model names and link them
aedefef49dddae29ba9775f389ec7150749ac85f
<ide><path>spacy/__init__.py <ide> import json <ide> from pathlib import Path <ide> from .util import set_lang_class, get_lang_class, parse_package_meta <add>from .deprecated import resolve_model_name <ide> <ide> from . import en <ide> from . import de <ide> <ide> def load(name, **overrides): <ide> data_path = overrides.get('path', util.get_data_path()) <del> meta = parse_package_meta(data_path, name) <add> model_name = resolve_model_name(name) <add> meta = parse_package_meta(data_path, model_name) <ide> lang = meta['lang'] if meta and 'lang' in meta else 'en' <ide> cls = get_lang_class(lang) <ide> overrides['meta'] = meta <del> overrides['path'] = Path(data_path / name) <add> overrides['path'] = Path(data_path / model_name) <ide> return cls(**overrides) <ide> <ide> <ide><path>spacy/deprecated.py <ide> from . import about <ide> from . import util <ide> from .download import download <add>from .link import link <ide> <ide> <ide> try: <ide> def fix_glove_vectors_loading(overrides): <ide> return overrides <ide> <ide> <add>def resolve_model_name(name): <add> """If spaCy is loaded with 'en' or 'de', check if symlink already exists. If <add> not, user have upgraded from older version and have old models installed. <add> Check if old model directory exists and if so, return that instead and create <add> shortcut link. <add> """ <add> <add> if name == 'en' or name == 'de': <add> versions = ['1.0.0', '1.1.0'] <add> data_path = Path(util.get_data_path()) <add> model_path = data_path / name <add> v_model_paths = [data_path / Path(name + '-' + v) for v in versions] <add> if not model_path.exists(): <add> for v_path in v_model_paths: <add> if v_path.exists(): <add> link(v_path, name) <add> return name <add> return name <add> <add> <ide> class ModelDownload(): <ide> """Replace download modules within en and de with deprecation warning and <ide> download default language model (using shortcut). Use classmethods to allow
2
Javascript
Javascript
add test for top-level _document error
a0e3198aa0442fc6bfb8fe3eb01ad32e729be606
<ide><path>test/acceptance/ReactRefreshLogBox.dev.test.js <ide> test('_app top level error shows logbox', async () => { <ide> expect(await session.hasRedbox()).toBe(false) <ide> await cleanup() <ide> }) <add> <add>test('_document top level error shows logbox', async () => { <add> const [session, cleanup] = await sandbox( <add> undefined, <add> new Map([ <add> [ <add> 'pages/_document.js', <add> ` <add> import Document, { Html, Head, Main, NextScript } from 'next/document' <add> <add> throw new Error("test"); <add> <add> class MyDocument extends Document { <add> static async getInitialProps(ctx) { <add> const initialProps = await Document.getInitialProps(ctx) <add> return { ...initialProps } <add> } <add> <add> render() { <add> return ( <add> <Html> <add> <Head /> <add> <body> <add> <Main /> <add> <NextScript /> <add> </body> <add> </Html> <add> ) <add> } <add> } <add> <add> export default MyDocument <add> `, <add> ], <add> ]) <add> ) <add> expect(await session.hasRedbox(true)).toBe(true) <add> expect(await session.getRedboxSource()).toMatchInlineSnapshot(` <add> "pages/_document.js (4:16) @ eval <add> <add> 2 | import Document, { Html, Head, Main, NextScript } from 'next/document' <add> 3 | <add> > 4 | throw new Error(\\"test\\"); <add> | ^ <add> 5 | <add> 6 | class MyDocument extends Document { <add> 7 | static async getInitialProps(ctx) {" <add>`) <add> <add> await session.patch( <add> 'pages/_document.js', <add> ` <add> import Document, { Html, Head, Main, NextScript } from 'next/document' <add> <add> class MyDocument extends Document { <add> static async getInitialProps(ctx) { <add> const initialProps = await Document.getInitialProps(ctx) <add> return { ...initialProps } <add> } <add> <add> render() { <add> return ( <add> <Html> <add> <Head /> <add> <body> <add> <Main /> <add> <NextScript /> <add> </body> <add> </Html> <add> ) <add> } <add> } <add> <add> export default MyDocument <add> ` <add> ) <add> expect(await session.hasRedbox()).toBe(false) <add> await cleanup() <add>})
1
Ruby
Ruby
upgrade virtualenv to 16.6.2
ba9dde9a4e384cb590718331d74e18da5e78786e
<ide><path>Library/Homebrew/language/python_virtualenv_constants.rb <ide> # frozen_string_literal: true <ide> <ide> PYTHON_VIRTUALENV_URL = <del> "https://files.pythonhosted.org/packages/37/27" \ <del> "/706af3ee62032933a3217454609c50a5325a6bd9c2c2f495b58c456ba286" \ <del> "/virtualenv-16.6.1.tar.gz" <add> "https://files.pythonhosted.org/packages/97/f4" \ <add> "/64c1853c3b35c1cfa57f3485b49c8c684f9dcaba4e24c56717b83fc66e90" \ <add> "/virtualenv-16.6.2.tar.gz" <ide> PYTHON_VIRTUALENV_SHA256 = <del> "b7335cddd9260a3dd214b73a2521ffc09647bde3e9457fcca31dc3be3999d04a" <add> "861bbce3a418110346c70f5c7a696fdcf23a261424e1d28aa4f9362fc2ccbc19"
1
Python
Python
add test for the nditer debug_print
d7c8f3dfab63852870d94c43b7b6d667700710a8
<ide><path>numpy/core/tests/test_nditer.py <ide> import sys <ide> import pytest <ide> <add>import subprocess, textwrap, re <add> <ide> import numpy as np <ide> import numpy.core._multiarray_tests as _multiarray_tests <ide> from numpy import array, arange, nditer, all <ide> def test_partial_iteration_error(in_dtype, buf_dtype): <ide> it.iternext() <ide> <ide> assert count == sys.getrefcount(value) <add> <add> <add>def test_debug_print(): <add> """ <add> Matches the expected output of a debug print with the actual output. <add> Note that the iterator dump should not be considered stable API, <add> this test is mainly to ensure the print does not crash. <add> <add> Currently uses a subprocess to avoid dealing with the C level `printf`s. <add> """ <add> # the expected output with all addresses and sizes stripped (they vary <add> # and/or are platform dependend). <add> expected = textwrap.dedent(""" <add> ------ BEGIN ITERATOR DUMP ------ <add> | Iterator Address: <add> | ItFlags: BUFFER REDUCE REUSE_REDUCE_LOOPS <add> | NDim: 2 <add> | NOp: 2 <add> | IterSize: 50 <add> | IterStart: 0 <add> | IterEnd: 50 <add> | IterIndex: 0 <add> | Iterator SizeOf: <add> | BufferData SizeOf: <add> | AxisData SizeOf: <add> | <add> | Perm: 0 1 <add> | DTypes: <add> | DTypes: dtype('float64') dtype('int32') <add> | InitDataPtrs: <add> | BaseOffsets: 0 0 <add> | Operands: <add> | Operand DTypes: dtype('int64') dtype('float64') <add> | OpItFlags: <add> | Flags[0]: READ CAST ALIGNED <add> | Flags[1]: READ WRITE CAST ALIGNED REDUCE <add> | <add> | BufferData: <add> | BufferSize: 50 <add> | Size: 5 <add> | BufIterEnd: 5 <add> | REDUCE Pos: 0 <add> | REDUCE OuterSize: 10 <add> | REDUCE OuterDim: 1 <add> | Strides: 8 4 <add> | Ptrs: <add> | REDUCE Outer Strides: 40 0 <add> | REDUCE Outer Ptrs: <add> | ReadTransferFn: <add> | ReadTransferData: (nil) (nil) <add> | WriteTransferFn: (nil) <add> | WriteTransferData: (nil) (nil) <add> | Buffers: <add> | <add> | AxisData[0]: <add> | Shape: 5 <add> | Index: 0 <add> | Strides: 16 8 <add> | Ptrs: <add> | AxisData[1]: <add> | Shape: 10 <add> | Index: 0 <add> | Strides: 80 0 <add> | Ptrs: <add> ------- END ITERATOR DUMP ------- <add> """).strip() <add> <add> code = textwrap.dedent(""" <add> import numpy as np <add> arr1 = np.arange(100, dtype=np.int64).reshape(10, 10)[:, ::2] <add> arr2 = np.arange(5.) <add> it = np.nditer((arr1, arr2), op_dtypes=["d", "i4"], casting="unsafe", <add> flags=["reduce_ok", "buffered"], <add> op_flags=[["readonly"], ["readwrite"]]) <add> it.debug_print() <add> """) <add> res = subprocess.check_output([sys.executable, "-c", code], text=True) <add> res = res.strip() <add> <add> for res_line, expected_line in zip(res.splitlines(), expected.splitlines()): <add> # The actual output may have additional pointers listed that are <add> # stripped from the example output: <add> assert res_line.startswith(expected_line)
1
Go
Go
fix a misused network object name
f041953d04bffa2be05466173f02dd016c68286d
<ide><path>integration-cli/docker_cli_network_unix_test.go <ide> func (s *DockerNetworkSuite) TestDockerNetworkInspectCustomSpecified(c *check.C) <ide> c.Assert(nr.IPAM.Config[0].Gateway, checker.Equals, "172.28.5.254") <ide> c.Assert(nr.Internal, checker.False) <ide> dockerCmd(c, "network", "rm", "br0") <del> assertNwNotAvailable(c, "test01") <add> assertNwNotAvailable(c, "br0") <ide> } <ide> <ide> func (s *DockerNetworkSuite) TestDockerNetworkIPAMInvalidCombinations(c *check.C) {
1
Python
Python
add reboot_node to vps.net
95ba6a7f537889c8e25a1d33b44f9b4c3f548470
<ide><path>libcloud/drivers/vpsnet.py <ide> def create_node(self, name, image, size, **kwargs): <ide> node = self._to_node(res.object['virtual_machine']) <ide> return node <ide> <add> def reboot_node(self, node): <add> res = self.connection.request('/virtual_machines/%s/%s.%s' % <add> (node.id, 'reboot', API_VERSION), <add> method="POST") <add> node = self._to_node(res.object['virtual_machine']) <add> return node <add> <add> <ide> def destroy_node(self, node): <del> res = self.connection.request('/virtual_machines/%s.%s' % (node.id,API_VERSION), <add> res = self.connection.request('/virtual_machines/%s.%s' % (node.id, API_VERSION), <ide> method='DELETE') <ide> return res.status == 200 <ide> <ide><path>test/test_vpsnet.py <ide> def test_list_nodes(self): <ide> self.assertEqual(node.id, '1384') <ide> self.assertEqual(node.state, NodeState.RUNNING) <ide> <add> def test_reboot_node(self): <add> VPSNetMockHttp.type = 'virtual_machines' <add> node = self.driver.list_nodes()[0] <add> <add> VPSNetMockHttp.type = 'reboot' <add> node = self.driver.reboot_node(node) <add> self.assertEqual(node.id, '1384') <add> <ide> def test_destroy_node(self): <ide> VPSNetMockHttp.type = 'delete' <ide> node = Node('2222', None, None, None, None, self.driver) <ide> def _virtual_machines_2222_api10json_delete_fail(self, method, url, body, header <ide> def _virtual_machines_2222_api10json_delete(self, method, url, body, headers): <ide> return (httplib.OK, '', {}, httplib.responses[httplib.OK]) <ide> <add> def _virtual_machines_1384_reboot_api10json_reboot(self, method, url, body, headers): <add> body = """{ <add> "virtual_machine": <add> { <add> "running": true, <add> "updated_at": "2009-05-15T06:55:02-04:00", <add> "power_action_pending": false, <add> "system_template_id": 41, <add> "id": 1384, <add> "cloud_id": 3, <add> "domain_name": "demodomain.com", <add> "hostname": "web01", <add> "consumer_id": 0, <add> "backups_enabled": false, <add> "password": "a8hjsjnbs91", <add> "label": "foo", <add> "slices_count": null, <add> "created_at": "2009-04-16T08:17:39-04:00" <add> } <add> }""" <add> return (httplib.OK, body, {}, httplib.responses[httplib.OK]) <add> <ide> def _virtual_machines_api10json_create(self, method, url, body, headers): <ide> body = """{ <ide> "virtual_machine":
2
Ruby
Ruby
remove unnecessary parameter from method
bd9c436d50c71eef58b3f9ba511e701cf27b377c
<ide><path>Library/Homebrew/livecheck/livecheck.rb <ide> def status_hash(package_or_resource, status_str, messages = nil, full_name: fals <ide> end <ide> <ide> # Formats and prints the livecheck result for a formula/cask/resource. <del> sig { params(info: Hash, verbose: T::Boolean, ambiguous_cask: T::Boolean, resource: T::Boolean).void } <del> def print_latest_version(info, verbose: false, ambiguous_cask: false, resource: false) <del> package_or_resource_s = resource ? " " : "" <add> sig { params(info: Hash, verbose: T::Boolean, ambiguous_cask: T::Boolean).void } <add> def print_latest_version(info, verbose: false, ambiguous_cask: false) <add> package_or_resource_s = info[:resource].present? ? " " : "" <ide> package_or_resource_s += "#{Tty.blue}#{info[:formula] || info[:cask] || info[:resource]}#{Tty.reset}" <ide> package_or_resource_s += " (cask)" if ambiguous_cask <ide> package_or_resource_s += " (guessed)" if verbose && !info[:meta][:livecheckable] <ide> def print_resources_info(info, verbose: false) <ide> if r_info[:status] && r_info[:messages] <ide> SkipConditions.print_skip_information(r_info) <ide> else <del> print_latest_version( <del> r_info, <del> verbose: verbose, <del> resource: true, <del> ) <add> print_latest_version(r_info, verbose: verbose) <ide> end <ide> end <ide> end
1
Text
Text
simplify governance info in readme intro
eddfa2c52ee91e657c1a3e42815e6dff960a7fe3
<ide><path>README.md <ide> Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. For <ide> more information on using Node.js, see the [Node.js Website][]. <ide> <del>Node.js contributions, policies, and releases are managed under an <del>[open governance model](./GOVERNANCE.md). The [Node.js Foundation][] provides <del>support for the project. <add>The Node.js project uses an [open governance model](./GOVERNANCE.md). The <add>[Node.js Foundation][] provides support for the project. <ide> <ide> **This project is bound by a [Code of Conduct][].** <ide>
1
PHP
PHP
use string template
19903b0cbfd616e7de095cc6fe0f2d41506f6719
<ide><path>src/View/Helper/FormHelper.php <ide> public function secure($fields = array()) { <ide> $out .= $this->hidden('_Token.unlocked', array( <ide> 'value' => urlencode($unlocked), <ide> )); <del> return $this->Html->useTag('hiddenblock', $out); <add> return $this->formatTemplate('hiddenblock', ['content' => $out]); <ide> } <ide> <ide> /** <ide> public function postLink($title, $url = null, $options = array(), $confirmMessag <ide> } <ide> <ide> $formName = str_replace('.', '', uniqid('post_', true)); <del> $formUrl = $this->url($url); <ide> $formOptions = array( <add> 'action' => $this->url($url), <ide> 'name' => $formName, <ide> 'id' => $formName, <ide> 'style' => 'display:none;', <ide> public function postLink($title, $url = null, $options = array(), $confirmMessag <ide> unset($options['target']); <ide> } <ide> <del> $out = $this->Html->useTag('form', $formUrl, $formOptions); <del> $out .= $this->Html->useTag('hidden', '_method', array( <del> 'value' => $requestMethod <del> )); <add> $out = $this->formatTemplate('formstart', [ <add> 'attrs' => $this->_templater->formatAttributes($formOptions) <add> ]); <add> $out .= $this->hidden('_method', ['value' => $requestMethod]); <ide> $out .= $this->_csrfField(); <ide> <ide> $fields = array(); <ide> public function postLink($title, $url = null, $options = array(), $confirmMessag <ide> unset($options['data']); <ide> } <ide> $out .= $this->secure($fields); <del> $out .= $this->Html->useTag('formend'); <add> $out .= $this->formatTemplate('formend', []); <ide> <ide> if ($options['block']) { <ide> $this->_View->append($options['block'], $out);
1
Java
Java
add responseentity.of(optional) variant
432cdd7802b9d1109eb02925d45782b6c99b9e01
<ide><path>spring-web/src/main/java/org/springframework/http/ResponseEntity.java <ide> import java.net.URI; <ide> import java.util.Arrays; <ide> import java.util.LinkedHashSet; <add>import java.util.Optional; <ide> import java.util.Set; <ide> <ide> import org.springframework.lang.Nullable; <ide> public static BodyBuilder status(int status) { <ide> return new DefaultBuilder(status); <ide> } <ide> <add> /** <add> * A shortcut for creating a {@code ResponseEntity} with the given body <add> * and the {@linkplain HttpStatus#OK OK} status, or an empty body and a <add> * {@linkplain HttpStatus#NOT_FOUND NOT FOUND} status in case of a <add> * {@linkplain Optional#empty()} parameter. <add> * @return the created {@code ResponseEntity} <add> * @since 5.1 <add> */ <add> public static <T> ResponseEntity<T> of(Optional<T> body) { <add> return body.map(ResponseEntity::ok).orElse(notFound().build()); <add> } <add> <ide> /** <ide> * Create a builder with the status set to {@linkplain HttpStatus#OK OK}. <ide> * @return the created builder <ide><path>spring-web/src/test/java/org/springframework/http/ResponseEntityTests.java <ide> /* <del> * Copyright 2002-2016 the original author or authors. <add> * Copyright 2002-2018 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> import java.net.URI; <ide> import java.net.URISyntaxException; <ide> import java.util.List; <add>import java.util.Optional; <ide> import java.util.concurrent.TimeUnit; <ide> <ide> import org.hamcrest.Matchers; <ide> public void okEntity() { <ide> assertEquals(entity, responseEntity.getBody()); <ide> } <ide> <add> @Test <add> public void ofOptional() { <add> Integer entity = 42; <add> ResponseEntity<Integer> responseEntity = ResponseEntity.of(Optional.of(entity)); <add> <add> assertNotNull(responseEntity); <add> assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); <add> assertEquals(entity, responseEntity.getBody()); <add> } <add> <add> @Test <add> public void ofEmptyOptional() { <add> ResponseEntity<Integer> responseEntity = ResponseEntity.of(Optional.empty()); <add> <add> assertNotNull(responseEntity); <add> assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); <add> assertNull(responseEntity.getBody()); <add> } <add> <ide> @Test <ide> public void createdLocation() throws URISyntaxException { <ide> URI location = new URI("location");
2
PHP
PHP
fix duplicate logging definition
4e4ac0b8e2153bef704528f3f2eb06665fbb88e8
<ide><path>src/TestSuite/Fixture/PHPUnitExtension.php <ide> public function executeBeforeFirstTest(): void <ide> $enableLogging = in_array('--debug', $_SERVER['argv'] ?? [], true); <ide> if ($enableLogging) { <ide> $helper->enableQueryLogging(); <add> Log::drop('queries'); <ide> Log::setConfig('queries', [ <ide> 'className' => 'Console', <ide> 'stream' => 'php://stderr',
1
Go
Go
update plugingetter import path in docker/docker
a98be0344b24d71235c17a87ff425f3d602e48e8
<ide><path>daemon/daemon.go <ide> import ( <ide> "github.com/docker/docker/pkg/fileutils" <ide> "github.com/docker/docker/pkg/graphdb" <ide> "github.com/docker/docker/pkg/idtools" <add> "github.com/docker/docker/pkg/plugingetter" <ide> "github.com/docker/docker/pkg/progress" <ide> "github.com/docker/docker/pkg/registrar" <ide> "github.com/docker/docker/pkg/signal" <ide> "github.com/docker/docker/pkg/streamformatter" <ide> "github.com/docker/docker/pkg/sysinfo" <ide> "github.com/docker/docker/pkg/system" <ide> "github.com/docker/docker/pkg/truncindex" <del> plugingetter "github.com/docker/docker/plugin/getter" <ide> pluginstore "github.com/docker/docker/plugin/store" <ide> "github.com/docker/docker/reference" <ide> "github.com/docker/docker/registry" <ide><path>daemon/graphdriver/driver.go <ide> import ( <ide> <ide> "github.com/docker/docker/pkg/archive" <ide> "github.com/docker/docker/pkg/idtools" <del> "github.com/docker/docker/plugin/getter" <add> "github.com/docker/docker/pkg/plugingetter" <ide> ) <ide> <ide> // FsMagic unsigned id of the filesystem in use. <ide> func Register(name string, initFunc InitFunc) error { <ide> } <ide> <ide> // GetDriver initializes and returns the registered driver <del>func GetDriver(name, home string, options []string, uidMaps, gidMaps []idtools.IDMap, plugingetter getter.PluginGetter) (Driver, error) { <add>func GetDriver(name, home string, options []string, uidMaps, gidMaps []idtools.IDMap, pg plugingetter.PluginGetter) (Driver, error) { <ide> if initFunc, exists := drivers[name]; exists { <ide> return initFunc(filepath.Join(home, name), options, uidMaps, gidMaps) <ide> } <del> if pluginDriver, err := lookupPlugin(name, home, options, plugingetter); err == nil { <add> if pluginDriver, err := lookupPlugin(name, home, options, pg); err == nil { <ide> return pluginDriver, nil <ide> } <ide> logrus.Errorf("Failed to GetDriver graph %s %s", name, home) <ide> func getBuiltinDriver(name, home string, options []string, uidMaps, gidMaps []id <ide> } <ide> <ide> // New creates the driver and initializes it at the specified root. <del>func New(root string, name string, options []string, uidMaps, gidMaps []idtools.IDMap, plugingetter getter.PluginGetter) (Driver, error) { <add>func New(root string, name string, options []string, uidMaps, gidMaps []idtools.IDMap, pg plugingetter.PluginGetter) (Driver, error) { <ide> if name != "" { <ide> logrus.Debugf("[graphdriver] trying provided driver: %s", name) // so the logs show specified driver <del> return GetDriver(name, root, options, uidMaps, gidMaps, plugingetter) <add> return GetDriver(name, root, options, uidMaps, gidMaps, pg) <ide> } <ide> <ide> // Guess for prior driver <ide><path>daemon/graphdriver/plugin.go <ide> import ( <ide> "fmt" <ide> "io" <ide> <del> "github.com/docker/docker/plugin/getter" <add> "github.com/docker/docker/pkg/plugingetter" <ide> ) <ide> <ide> type pluginClient interface { <ide> type pluginClient interface { <ide> SendFile(string, io.Reader, interface{}) error <ide> } <ide> <del>func lookupPlugin(name, home string, opts []string, pluginGetter getter.PluginGetter) (Driver, error) { <del> pl, err := pluginGetter.Get(name, "GraphDriver", getter.LOOKUP) <add>func lookupPlugin(name, home string, opts []string, pg plugingetter.PluginGetter) (Driver, error) { <add> pl, err := pg.Get(name, "GraphDriver", plugingetter.LOOKUP) <ide> if err != nil { <ide> return nil, fmt.Errorf("Error looking up graphdriver plugin %s: %v", name, err) <ide> } <ide><path>daemon/graphdriver/plugin_unsupported.go <ide> <ide> package graphdriver <ide> <del>import "github.com/docker/docker/plugin/getter" <add>import "github.com/docker/docker/pkg/plugingetter" <ide> <del>func lookupPlugin(name, home string, opts []string, plugingetter getter.PluginGetter) (Driver, error) { <add>func lookupPlugin(name, home string, opts []string, pg plugingetter.PluginGetter) (Driver, error) { <ide> return nil, ErrNotSupported <ide> } <ide><path>layer/layer_store.go <ide> import ( <ide> "github.com/docker/docker/daemon/graphdriver" <ide> "github.com/docker/docker/pkg/archive" <ide> "github.com/docker/docker/pkg/idtools" <add> "github.com/docker/docker/pkg/plugingetter" <ide> "github.com/docker/docker/pkg/stringid" <del> "github.com/docker/docker/plugin/getter" <ide> "github.com/vbatts/tar-split/tar/asm" <ide> "github.com/vbatts/tar-split/tar/storage" <ide> ) <ide> type StoreOptions struct { <ide> GraphDriverOptions []string <ide> UIDMaps []idtools.IDMap <ide> GIDMaps []idtools.IDMap <del> PluginGetter getter.PluginGetter <add> PluginGetter plugingetter.PluginGetter <ide> } <ide> <ide> // NewStoreFromOptions creates a new Store instance <ide><path>plugin/getter/interface.go <del>package getter <del> <del>import "github.com/docker/docker/pkg/plugins" <del> <del>const ( <del> // LOOKUP doesn't update RefCount <del> LOOKUP = 0 <del> // CREATE increments RefCount <del> CREATE = 1 <del> // REMOVE decrements RefCount <del> REMOVE = -1 <del>) <del> <del>// CompatPlugin is a abstraction to handle both v2(new) and v1(legacy) plugins. <del>type CompatPlugin interface { <del> Client() *plugins.Client <del> Name() string <del> IsV1() bool <del>} <del> <del>// PluginGetter is the interface implemented by Store <del>type PluginGetter interface { <del> Get(name, capability string, mode int) (CompatPlugin, error) <del> GetAllByCap(capability string) ([]CompatPlugin, error) <del> Handle(capability string, callback func(string, *plugins.Client)) <del>} <ide><path>plugin/store/store.go <ide> package store <ide> <ide> import ( <add> "github.com/docker/docker/pkg/plugingetter" <ide> "github.com/docker/docker/pkg/plugins" <del> "github.com/docker/docker/plugin/getter" <ide> ) <ide> <ide> // GetAllByCap returns a list of plugins matching the given capability. <del>func (ps Store) GetAllByCap(capability string) ([]getter.CompatPlugin, error) { <add>func (ps Store) GetAllByCap(capability string) ([]plugingetter.CompatPlugin, error) { <ide> pl, err := plugins.GetAll(capability) <ide> if err != nil { <ide> return nil, err <ide> } <del> result := make([]getter.CompatPlugin, len(pl)) <add> result := make([]plugingetter.CompatPlugin, len(pl)) <ide> for i, p := range pl { <ide> result[i] = p <ide> } <ide> return result, nil <ide> } <ide> <ide> // Get returns a plugin matching the given name and capability. <del>func (ps Store) Get(name, capability string, _ int) (getter.CompatPlugin, error) { <add>func (ps Store) Get(name, capability string, _ int) (plugingetter.CompatPlugin, error) { <ide> return plugins.Get(name, capability) <ide> } <ide> <ide><path>plugin/store/store_experimental.go <ide> import ( <ide> <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/pkg/ioutils" <add> "github.com/docker/docker/pkg/plugingetter" <ide> "github.com/docker/docker/pkg/plugins" <del> "github.com/docker/docker/plugin/getter" <ide> "github.com/docker/docker/plugin/v2" <ide> "github.com/docker/docker/reference" <ide> ) <ide> func (ps *Store) getByCap(name string, capability string) (*v2.Plugin, error) { <ide> return p.FilterByCap(capability) <ide> } <ide> <del>func (ps *Store) getAllByCap(capability string) []getter.CompatPlugin { <add>func (ps *Store) getAllByCap(capability string) []plugingetter.CompatPlugin { <ide> ps.RLock() <ide> defer ps.RUnlock() <ide> <del> result := make([]getter.CompatPlugin, 0, 1) <add> result := make([]plugingetter.CompatPlugin, 0, 1) <ide> for _, p := range ps.plugins { <ide> if _, err := p.FilterByCap(capability); err == nil { <ide> result = append(result, p) <ide> func (ps *Store) updatePluginDB() error { <ide> } <ide> <ide> // Get returns a plugin matching the given name and capability. <del>func (ps *Store) Get(name, capability string, mode int) (getter.CompatPlugin, error) { <add>func (ps *Store) Get(name, capability string, mode int) (plugingetter.CompatPlugin, error) { <ide> var ( <ide> p *v2.Plugin <ide> err error <ide> func (ps *Store) Get(name, capability string, mode int) (getter.CompatPlugin, er <ide> } <ide> <ide> // GetAllByCap returns a list of plugins matching the given capability. <del>func (ps *Store) GetAllByCap(capability string) ([]getter.CompatPlugin, error) { <del> result := make([]getter.CompatPlugin, 0, 1) <add>func (ps *Store) GetAllByCap(capability string) ([]plugingetter.CompatPlugin, error) { <add> result := make([]plugingetter.CompatPlugin, 0, 1) <ide> <ide> /* Daemon start always calls plugin.Init thereby initializing a store. <ide> * So store on experimental builds can never be nil, even while <ide><path>volume/drivers/extpoint.go <ide> import ( <ide> "sync" <ide> <ide> "github.com/docker/docker/pkg/locker" <del> "github.com/docker/docker/plugin/getter" <add> getter "github.com/docker/docker/pkg/plugingetter" <ide> "github.com/docker/docker/volume" <ide> ) <ide>
9
Java
Java
improve concurrentlrucache performance
713a112812fd9ca1e6b64f3f8105374743d677bc
<ide><path>spring-core/src/main/java/org/springframework/util/MimeTypeUtils.java <ide> import java.util.Random; <ide> import java.util.concurrent.ConcurrentHashMap; <ide> import java.util.concurrent.ConcurrentLinkedQueue; <add>import java.util.concurrent.locks.Lock; <ide> import java.util.concurrent.locks.ReadWriteLock; <ide> import java.util.concurrent.locks.ReentrantReadWriteLock; <ide> import java.util.function.Function; <ide> public static String generateMultipartBoundaryString() { <ide> <ide> private final ConcurrentHashMap<K, V> cache = new ConcurrentHashMap<>(); <ide> <del> private final ReadWriteLock lock = new ReentrantReadWriteLock(); <add> private final Lock readLock; <add> <add> private final Lock writeLock; <ide> <ide> private final Function<K, V> generator; <ide> <add> private volatile int size = 0; <add> <ide> public ConcurrentLruCache(int maxSize, Function<K, V> generator) { <ide> Assert.isTrue(maxSize > 0, "LRU max size should be positive"); <ide> Assert.notNull(generator, "Generator function should not be null"); <ide> this.maxSize = maxSize; <ide> this.generator = generator; <add> <add> ReadWriteLock lock = new ReentrantReadWriteLock(); <add> this.readLock = lock.readLock(); <add> this.writeLock = lock.writeLock(); <ide> } <ide> <ide> public V get(K key) { <del> this.lock.readLock().lock(); <del> try { <del> if (this.queue.size() < this.maxSize / 2) { <del> V cached = this.cache.get(key); <del> if (cached != null) { <del> return cached; <del> } <add> V cached; <add> <add> if ((cached = this.cache.get(key)) != null) { <add> if (this.size < this.maxSize / 2) { <add> return cached; <ide> } <del> else if (this.queue.remove(key)) { <add> <add> try { <add> this.readLock.lock(); <ide> this.queue.add(key); <del> return this.cache.get(key); <add> this.queue.remove(key); <add> return cached; <add> } <add> finally { <add> this.readLock.unlock(); <ide> } <ide> } <del> finally { <del> this.lock.readLock().unlock(); <del> } <del> this.lock.writeLock().lock(); <add> <add> this.writeLock.lock(); <ide> try { <ide> // retrying in case of concurrent reads on the same key <del> if (this.queue.remove(key)) { <add> if ((cached = this.cache.get(key)) != null) { <ide> this.queue.add(key); <del> return this.cache.get(key); <add> this.queue.remove(key); <add> return cached; <ide> } <del> if (this.queue.size() == this.maxSize) { <add> <add> // Generate value first, to prevent size inconsistency <add> V value = this.generator.apply(key); <add> <add> int cacheSize = this.size; <add> if (cacheSize == this.maxSize) { <ide> K leastUsed = this.queue.poll(); <ide> if (leastUsed != null) { <ide> this.cache.remove(leastUsed); <add> cacheSize--; <ide> } <ide> } <del> V value = this.generator.apply(key); <add> <ide> this.queue.add(key); <ide> this.cache.put(key, value); <add> this.size = cacheSize + 1; <add> <ide> return value; <ide> } <ide> finally { <del> this.lock.writeLock().unlock(); <add> this.writeLock.unlock(); <ide> } <ide> } <ide> }
1
Python
Python
add right test
311dc9f71c72d4460b194d17734c3d80830c2798
<ide><path>research/object_detection/meta_architectures/context_rcnn_lib.py <ide> def compute_box_context_attention(box_features, context_features, <ide> output_features = output_features[:, :, tf.newaxis, tf.newaxis, :] <ide> <ide> return output_features <del> <ide>\ No newline at end of file
1
Javascript
Javascript
simplify the cmap format 6 conversion - fix #449
6329f89982ba7d9e9c80a30fdfb55f57c5054d03
<ide><path>fonts.js <ide> var Font = (function Font() { <ide> var entryCount = int16(font.getBytes(2)); <ide> <ide> var glyphs = []; <del> var min = 0xffff, max = 0; <del> for (var j = 0; j < entryCount; j++) { <del> var charcode = int16(font.getBytes(2)); <del> if (!charcode) <del> continue; <del> glyphs.push(charcode); <del> <del> if (charcode < min) <del> min = charcode; <del> if (charcode > max) <del> max = charcode; <del> } <del> <del> // Since Format 6 is a dense array, check for gaps <del> for (var j = min; j < max; j++) { <del> if (glyphs.indexOf(j) == -1) <del> glyphs.push(j); <del> } <del> <del> for (var j = 0; j < glyphs.length; j++) <del> glyphs[j] = { unicode: glyphs[j] + firstCode }; <del> <del> var ranges = getRanges(glyphs); <del> assert(ranges.length == 1, 'Got ' + ranges.length + <del> ' ranges in a dense array'); <del> <del> var denseRange = ranges[0]; <del> var start = denseRange[0]; <del> var end = denseRange[1]; <del> var index = firstCode; <del> for (var j = start; j <= end; j++) { <del> var code = glyphs[j - start]; <del> var mapping = encoding[index] || {}; <del> mapping.unicode = code.unicode; <del> encoding[index++] = mapping; <add> var ids = []; <add> for (var j = 0; j < firstCode + entryCount; j++) { <add> var code = (j >= firstCode) ? int16(font.getBytes(2)) : j; <add> glyphs.push({ unicode: j + kCmapGlyphOffset }); <add> ids.push(code); <add> <add> var mapping = encoding[j] || {}; <add> mapping.unicode = glyphs[j].unicode; <add> encoding[j] = mapping; <ide> } <del> return cmap.data = createCMapTable(glyphs); <add> return cmap.data = createCMapTable(glyphs, ids); <ide> } <ide> } <ide> return cmap.data;
1
Javascript
Javascript
replace space with \b in regex
ea77b33a526763675713dbc23cbd7fa98f733f27
<ide><path>tools/doc/html.js <ide> const BSD_ONLY_SYSCALLS = new Set(['lchmod']); <ide> // '<a href="http://man7.org/linux/man-pages/man2/open.2.html">open(2)</a>' <ide> function linkManPages(text) { <ide> return text.replace( <del> / ([a-z.]+)\((\d)([a-z]?)\)/gm, <add> /\b([a-z.]+)\((\d)([a-z]?)\)/gm, <ide> (match, name, number, optionalCharacter) => { <ide> // name consists of lowercase letters, number is a single digit <ide> const displayAs = `${name}(${number}${optionalCharacter})`;
1
Javascript
Javascript
remove unused variables on async hook test
056e68749cc60156f51811d5026ec98e68ebb257
<ide><path>test/parallel/test-async-hooks-enable-recursive.js <ide> const nestedHook = async_hooks.createHook({ <ide> }); <ide> <ide> async_hooks.createHook({ <del> init: common.mustCall((id, type) => { <add> init: common.mustCall(() => { <ide> nestedHook.enable(); <ide> }, 2) <ide> }).enable();
1
Ruby
Ruby
add chop removed in 89bcca5
531d14d0da70ae2bac2a5d58acaa6165039557e2
<ide><path>activerecord/test/cases/fixtures_test.rb <ide> def test_bulk_insert_multiple_table_with_a_multi_statement_query <ide> <ide> create_fixtures("bulbs", "authors", "computers") <ide> <del> expected_sql = <<~EOS <add> expected_sql = <<~EOS.chop <ide> INSERT INTO #{ActiveRecord::Base.connection.quote_table_name("bulbs")} .* <ide> INSERT INTO #{ActiveRecord::Base.connection.quote_table_name("authors")} .* <ide> INSERT INTO #{ActiveRecord::Base.connection.quote_table_name("computers")} .*
1
Ruby
Ruby
keep the socket reference after close
4d01cd1545a00ed6f96d6cb658a590afd36e1871
<ide><path>actioncable/test/client_test.rb <ide> def with_puma_server(rack_app = ActionCable.server, port = 3099) <ide> yield port <ide> <ide> ensure <del> server.stop(true) <del> t.join <add> server.stop(true) if server <add> t.join if t <ide> end <ide> <ide> def start_event_machine <ide> def initialize(em_controller, port) <ide> end <ide> <ide> @ws.on(:close) do |event| <del> @ws = nil <ide> em_controller.stop_event_machine <ide> @closed.set <ide> end
1
Ruby
Ruby
add to_i method
74433968f61bd6098fed0ecd663bccbd0d69bd35
<ide><path>Library/Homebrew/version/null.rb <ide> def to_f <ide> Float::NAN <ide> end <ide> <add> def to_i <add> 0 <add> end <add> <ide> def to_s <ide> "" <ide> end
1
Javascript
Javascript
prefix public path in importscripts
eb63cb78b6b0db89bcd32bf0d9484641ce7a7f2b
<ide><path>lib/runtime/AutoPublicPathRuntimeModule.js <ide> class AutoPublicPathRuntimeModule extends RuntimeModule { <ide> } <ide> ); <ide> const undoPath = getUndoPath(chunkName, false); <add> <ide> return Template.asString([ <ide> "var scriptUrl;", <ide> scriptType === "module" <ide><path>lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js <ide> class ImportScriptsChunkLoadingRuntimeModule extends RuntimeModule { <ide> ? "if(true) { // all chunks have JS" <ide> : `if(${hasJsMatcher("chunkId")}) {`, <ide> Template.indent( <del> `importScripts(${JSON.stringify(rootOutputDir)} + ${ <del> RuntimeGlobals.getChunkScriptFilename <del> }(chunkId));` <add> `importScripts(${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId));` <ide> ), <ide> "}" <ide> ]), <ide> class ImportScriptsChunkLoadingRuntimeModule extends RuntimeModule { <ide> "success = true;" <ide> ])};`, <ide> "// start update chunk loading", <del> `importScripts(${JSON.stringify(rootOutputDir)} + ${ <del> RuntimeGlobals.getChunkUpdateScriptFilename <del> }(chunkId));`, <add> `importScripts(${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId));`, <ide> 'if(!success) throw new Error("Loading update chunk failed for unknown reason");' <ide> ]), <ide> "}", <ide><path>test/ConfigTestCases.template.js <ide> const describeCases = config => { <ide> options <ide> ), <ide> importScripts: url => { <del> _require(path.dirname(p), options, `./${url}`); <add> expect(url).toMatch( <add> /^https:\/\/test\.cases\/path\// <add> ); <add> _require( <add> outputDirectory, <add> options, <add> `.${url.slice("https://test.cases/path".length)}` <add> ); <ide> }, <ide> module: m, <ide> exports: m.exports, <ide><path>test/HotTestCases.template.js <ide> const describeCases = config => { <ide> } <ide> }, <ide> importScripts: url => { <del> _require("./" + url); <add> expect(url).toMatch(/^https:\/\/test\.cases\/path\//); <add> _require(urlToRelativePath(url)); <ide> }, <ide> document: { <ide> createElement(type) { <ide><path>test/helpers/createFakeWorker.js <ide> const path = require("path"); <ide> const fs = require("fs"); <ide> global.self = global; <ide> self.URL = URL; <add>self.location = new URL(${JSON.stringify(url.toString())}); <ide> const urlToPath = url => { <ide> if(url.startsWith("https://test.cases/path/")) url = url.slice(24); <ide> return path.resolve(${JSON.stringify(outputDirectory)}, \`./\${url}\`);
5
Text
Text
explain async action creators
c86ba09c16af391deb169b1229eaeff09cd261b1
<ide><path>docs/recipes/ReducingBoilerplate.md <ide> dispatch({ <ide> <ide> you might write an action creator in a separate file, and import it from your component: <ide> <del>#### `ActionCreators.js` <add>#### `actionCreators.js` <ide> <ide> ```js <ide> export function addTodo(text) { <ide> export function addTodo(text) { <ide> #### `AddTodo.js` <ide> <ide> ```js <del>import { addTodo } from './ActionCreators'; <add>import { addTodo } from './actionCreators'; <ide> <ide> // somewhere in an event handler <ide> dispatch(addTodo('Use Redux')) <ide> See [redux-action-utils](https://github.com/insin/redux-action-utils) and [redux <ide> Note that such utilities add magic to your code. <ide> Are magic and indirection really worth extra few lines? <ide> <add>## Async Action Creators <add> <add>[Middleware](../Glossary.html#middleware) lets you inject a custom logic that interprets every action object before it is dispatched. Async actions are the most common use case for middleware. <add> <add>Without any middleware, [`dispatch`](../api/Store.md#dispatch) only accepts a plain object, so we have to perform AJAX calls inside our components: <add> <add>#### `actionCreators.js` <add> <add>```js <add>export function loadPostsSuccess(userId, response) { <add> return { <add> type: 'LOAD_POSTS_SUCCESS', <add> userId, <add> response <add> }; <add>} <add> <add>export function loadPostsFailure(userId, error) { <add> return { <add> type: 'LOAD_POSTS_FAILURE', <add> userId, <add> error <add> }; <add>} <add> <add>export function loadPostsRequest(userId) { <add> return { <add> type: 'LOAD_POSTS_REQUEST', <add> userId <add> }; <add>} <add>``` <add> <add>#### `UserInfo.js` <add> <add>```js <add>import { Component } from 'react'; <add>import { connect } from 'react-redux'; <add>import { loadPostsRequest, loadPostsSuccess, loadPostsFailure } from './actionCreators'; <add> <add>class Posts extends Component { <add> loadData(userId) { <add> // Injected into props by React Redux `connect()` call: <add> let { dispatch, posts } = this.props; <add> <add> if (posts[userId]) { <add> // There is cached data! Don't do anything. <add> return; <add> } <add> <add> // Reducer can react to this action by setting <add> // `isFetching` and thus letting us show a spinner. <add> dispatch(loadPostsRequest(userId)); <add> <add> // Reducer can react to these actions by filling the `users`. <add> fetch(`http://myapi.com/users/${userId}/posts`).then( <add> response => dispatch(loadPostsSuccess(userId, response)), <add> error => dispatch(loadPostsFailure(userId, error)) <add> ); <add> } <add> <add> componentDidMount() { <add> this.loadData(this.props.userId); <add> } <add> <add> componentWillReceiveProps(nextProps) { <add> if (nextProps.userId !== this.props.userId) { <add> this.loadData(nextProps.userId); <add> } <add> } <add> <add> render() { <add> if (this.props.isLoading) { <add> return <p>Loading...</p>; <add> } <add> <add> let posts = this.props.posts.map(post => <add> <Post post={post} key={post.id} /> <add> ); <add> <add> return <div>{posts}</div>; <add> } <add>} <add> <add>export default connect(state => ({ <add> posts: state.posts <add>}))(Posts); <add>``` <add> <add>However, this quickly gets repetitive because different components request data from the same API endpoints. Moreover, we want to reuse some of this logic (e.g. early exit when there is cached data available) from many components. <add> <add>**Middleware lets us write more expressive, potentially async action creators.** It lets us dispatch something other than plain objects, and interprets the values. For example, middleware can “catch” dispatched Promises and turn them into a pair of request and success/failure actions. <add> <add>The simplest example of middleware is [redux-thunk](https://github.com/gaearon/redux-thunk). It lets you write action creators as “thunks”, that is, functions returning functions. This inverts the control: you will get `dispatch` as an argument, so you can write an action creator that dispatches many times. <add> <add>Consider the code above rewritten with [redux-thunk](https://github.com/gaearon/redux-thunk): <add> <add>#### `actionCreators.js` <add> <add>```js <add>export function loadPosts(userId) { <add> // Interpreted by the thunk middleware: <add> return function (dispatch, getState) { <add> let { posts } = getState(); <add> if (posts[userId]) { <add> // There is cached data! Don't do anything. <add> return; <add> } <add> <add> dispatch({ <add> type: 'LOAD_POSTS_REQUEST', <add> userId <add> }); <add> <add> // Dispatch vanilla actions asynchronously <add> fetch(`http://myapi.com/users/${userId}/posts`).then( <add> response => dispatch({ <add> type: 'LOAD_POSTS_SUCCESS', <add> userId, <add> respone <add> }), <add> error => dispatch({ <add> type: 'LOAD_POSTS_FAILURE', <add> userId, <add> error <add> }) <add> ); <add> } <add>} <add>``` <add> <add>#### `UserInfo.js` <add> <add>```js <add>import { Component } from 'react'; <add>import { connect } from 'react-redux'; <add>import { loadPosts } from './actionCreators'; <add> <add>class Posts extends Component { <add> componentDidMount() { <add> this.props.dispatch(loadPosts(this.props.userId)); <add> } <add> <add> componentWillReceiveProps(nextProps) { <add> if (nextProps.userId !== this.props.userId) { <add> this.props.dispatch(loadPosts(nextProps.userId)); <add> } <add> } <add> <add> render() { <add> if (this.props.isLoading) { <add> return <p>Loading...</p>; <add> } <add> <add> let posts = this.props.posts.map(post => <add> <Post post={post} key={post.id} /> <add> ); <add> <add> return <div>{posts}</div>; <add> } <add>} <add> <add>export default connect(state => ({ <add> posts: state.posts <add>}))(Posts); <add>``` <add> <add>This is much less typing! If you’d like, you can still have “vanilla” action creators like `loadPostsSuccess` which you’d use from a “smart” `loadPosts` action creator. <add> <add>**Finally, you can write your own middleware.** Let’s say you want to generalize the pattern above and describe your async action creators like this instead: <add> <add>```js <add>export function loadPosts(userId) { <add> return { <add> // Types of actions to emit before and after <add> types: ['LOAD_POSTS_REQUEST', 'LOAD_POSTS_SUCCESS', 'LOAD_POSTS_FAILURE'], <add> // Check the cache (optional): <add> shouldCallAPI: (state) => !state.users[userId], <add> // Perform the fetching: <add> callAPI: () => fetch(`http://myapi.com/users/${userId}/posts`), <add> // Arguments to inject in begin/end actions <add> payload: { userId } <add> }; <add>} <add>``` <add> <add>The middleware that interprets such actions could look like this: <add> <add>```js <add>function callAPIMiddleware({ dispatch, getState }) { <add> return function (next) { <add> return function (action) { <add> const { <add> types, <add> callAPI, <add> shouldCallAPI = () => true, <add> payload = {} <add> } = action; <add> <add> if (!types) { <add> // Normal action: pass it on <add> return next(action); <add> } <add> <add> if ( <add> !Array.isArray(types) || <add> types.length !== 3 || <add> !types.every(type => typeof type === 'string') <add> ) { <add> throw new Error('Expected an array of three string types.'); <add> } <add> <add> if (typeof fetch !== 'function') { <add> throw new Error('Expected fetch to be a function.'); <add> } <add> <add> if (!shouldCallAPI(getState())) { <add> return; <add> } <add> <add> const [requestType, successType, failureType] = types; <add> <add> dispatch(Object.assign({}, payload, { <add> type: requestType <add> })); <add> <add> return callAPI().then( <add> response => dispatch(Object.assign({}, payload, { <add> type: successType <add> })), <add> error => dispatch(Object.assign({}, payload, { <add> type: failureType <add> })) <add> ); <add> }; <add> }; <add>} <add>``` <add> <add>After passing it once to [`applyMiddleware(...middlewares)`](../api/applyMiddleware.md), you can write all your API-calling action creators the same way: <add> <add>```js <add>export function loadPosts(userId) { <add> return { <add> types: ['LOAD_POSTS_REQUEST', 'LOAD_POSTS_SUCCESS', 'LOAD_POSTS_FAILURE'], <add> shouldCallAPI: (state) => !state.users[userId], <add> callAPI: () => fetch(`http://myapi.com/users/${userId}/posts`), <add> payload: { userId } <add> }; <add>} <add> <add>export function loadComments(postId) { <add> return { <add> types: ['LOAD_COMMENTS_REQUEST', 'LOAD_COMMENTS_SUCCESS', 'LOAD_COMMENTS_FAILURE'], <add> shouldCallAPI: (state) => !state.posts[postId], <add> callAPI: () => fetch(`http://myapi.com/posts/${postId}/comments`), <add> payload: { postId } <add> }; <add>} <add> <add>export function addComment(postId, message) { <add> return { <add> types: ['ADD_COMMENT_REQUEST', 'ADD_COMMENT_SUCCESS', 'ADD_COMMENT_FAILURE'], <add> callAPI: () => fetch(`http://myapi.com/posts/${postId}/comments`, { <add> method: 'post', <add> headers: { <add> 'Accept': 'application/json', <add> 'Content-Type': 'application/json' <add> }, <add> body: JSON.stringify({ message }) <add> }), <add> payload: { postId, message } <add> }; <add>} <add>``` <add> <ide> ## Reducers <ide> <ide> Redux reduces the boilerplate of Flux stores considerably by describing the update logic as a function. A function is simpler than an object, and much simpler than a class.
1
Javascript
Javascript
add index to core
087ba88da6d76f9aea00608923eac8ba1e6679f5
<ide><path>src/core/index.js <add>export {default as _adapters} from './core.adapters'; <add>export {default as Animation} from './core.animation'; <add>export {default as Animations} from './core.animations'; <add>export {default as Animator} from './core.animator'; <add>export {default as Chart} from './core.controller'; <add>export {default as DatasetController} from './core.datasetController'; <add>export {default as Defaults} from './core.defaults'; <add>export {default as Element} from './core.element'; <add>export {default as Interaction} from './core.interaction'; <add>export {default as Layouts} from './core.layouts'; <add>export {default as Plugins} from './core.plugins'; <add>export {default as Scale} from './core.scale'; <add>export {default as ScaleService} from './core.scaleService'; <add>export {default as Ticks} from './core.ticks';
1
Ruby
Ruby
add more tests to new api
b30eb39ff072ce95ccd5ce94ae08d116c23fd260
<ide><path>actionmailer/lib/action_mailer/base.rb <ide> class Base < AbstractController::Base <ide> @@deliveries = [] <ide> cattr_accessor :deliveries <ide> <del> @@default_charset = "utf-8" <del> cattr_accessor :default_charset <add> extlib_inheritable_accessor :default_charset <add> self.default_charset = "utf-8" <ide> <del> @@default_content_type = "text/plain" <del> cattr_accessor :default_content_type <add> extlib_inheritable_accessor :default_content_type <add> self.default_content_type = "text/plain" <ide> <del> @@default_mime_version = "1.0" <del> cattr_accessor :default_mime_version <add> extlib_inheritable_accessor :default_mime_version <add> self.default_mime_version = "1.0" <ide> <ide> # This specifies the order that the parts of a multipart email will be. Usually you put <ide> # text/plain at the top so someone without a MIME capable email reader can read the plain <ide> # text of your email first. <ide> # <ide> # Any content type that is not listed here will be inserted in the order you add them to <ide> # the email after the content types you list here. <del> @@default_implicit_parts_order = [ "text/plain", "text/enriched", "text/html" ] <del> cattr_accessor :default_implicit_parts_order <add> extlib_inheritable_accessor :default_implicit_parts_order <add> self.default_implicit_parts_order = [ "text/plain", "text/enriched", "text/html" ] <ide> <ide> # Expose the internal Mail message <ide> attr_reader :message <ide> <del> # Pass calls to headers and attachment to the Mail#Message instance <del> delegate :headers, :attachments, :to => :@message <add> def headers(args=nil) <add> if args <add> ActiveSupport::Deprecation.warn "headers(Hash) is deprecated, please do headers[key] = value instead", caller <add> @headers = args <add> else <add> @message <add> end <add> end <add> <add> def attachments <add> @message.attachments <add> end <ide> <ide> class << self <ide> <ide> def mail(headers = {}) <ide> <ide> m = @message <ide> <del> m.content_type ||= headers[:content_type] || @@default_content_type <del> m.charset ||= headers[:charset] || @@default_charset <del> m.mime_version ||= headers[:mime_version] || @@default_mime_version <add> m.content_type ||= headers[:content_type] || self.class.default_content_type <add> m.charset ||= headers[:charset] || self.class.default_charset <add> m.mime_version ||= headers[:mime_version] || self.class.default_mime_version <ide> <ide> m.subject = quote_if_necessary(headers[:subject], m.charset) if headers[:subject] <ide> m.to = quote_address_if_necessary(headers[:to], m.charset) if headers[:to] <ide> def mail(headers = {}) <ide> m.reply_to = quote_address_if_necessary(headers[:reply_to], m.charset) if headers[:reply_to] <ide> m.date = headers[:date] if headers[:date] <ide> <del> m.body.set_sort_order(headers[:parts_order] || @@default_implicit_parts_order) <add> m.body.set_sort_order(headers[:parts_order] || self.class.default_implicit_parts_order) <ide> <ide> # # Set the subject if not set yet <ide> # @subject ||= I18n.t(:subject, :scope => [:actionmailer, mailer_name, method_name], <ide><path>actionmailer/lib/action_mailer/deprecated_api.rb <ide> def create_mail #:nodoc: <ide> m.mime_version = mime_version unless mime_version.nil? <ide> m.date = sent_on.to_time rescue sent_on if sent_on <ide> <del> headers.each { |k, v| m[k] = v } <add> @headers.each { |k, v| m[k] = v } <ide> <ide> real_content_type, ctype_attrs = parse_content_type <ide> main_type, sub_type = split_content_type(real_content_type) <ide><path>actionmailer/test/base_test.rb <ide> # mail.deliver <ide> # <ide> # Notifier.welcome(user).deliver # => creates and sends the Mail in one step <del>class BaseTest < Test::Unit::TestCase <del> <add>class BaseTest < ActiveSupport::TestCase <add> DEFAULT_HEADERS = { <add> :to => '[email protected]', <add> :from => '[email protected]', <add> :subject => 'The first email on new API!' <add> } <add> <ide> class TestMailer < ActionMailer::Base <del> <ide> def welcome(hash = {}) <del> hash = {:to => '[email protected]', :from => '[email protected]', <del> :subject => 'The first email on new API!'}.merge!(hash) <del> mail(hash) <add> headers['X-SPAM'] = "Not SPAM" <add> mail(DEFAULT_HEADERS.merge(hash)) <ide> end <del> <del> def invoice(hash = {}) <add> <add> def attachment_with_content <ide> attachments['invoice.pdf'] = 'This is test File content' <del> hash = {:to => '[email protected]', :from => '[email protected]', <del> :subject => 'Your invoice is attached'}.merge!(hash) <del> mail(hash) <add> mail(DEFAULT_HEADERS) <add> end <add> <add> def attachment_with_hash <add> attachments['invoice.jpg'] = { :content => "you smiling", :mime_type => "image/x-jpg", <add> :transfer_encoding => "base64" } <add> mail(DEFAULT_HEADERS) <ide> end <del> <ide> end <ide> <del> def test_the_method_call_to_mail_does_not_raise_error <add> test "method call to mail does not raise error" do <ide> assert_nothing_raised { TestMailer.deliver_welcome } <ide> end <ide> <del> def test_should_set_the_headers_of_the_mail_message <add> test "mail() should set the headers of the mail message" do <ide> email = TestMailer.deliver_welcome <ide> assert_equal(email.to, ['[email protected]']) <ide> assert_equal(email.from, ['[email protected]']) <ide> assert_equal(email.subject, 'The first email on new API!') <ide> end <del> <del> def test_should_allow_all_headers_set <add> <add> test "mail() with bcc, cc, content_type, charset, mime_version, reply_to and date" do <ide> @time = Time.now <ide> email = TestMailer.deliver_welcome(:bcc => '[email protected]', <ide> :cc => '[email protected]', <ide> def test_should_allow_all_headers_set <ide> assert_equal(email.date, @time) <ide> end <ide> <del># def test_should_allow_custom_headers_to_be_set <del># email = TestMailer.deliver_welcome <del># assert_equal("Not SPAM", email['X-SPAM']) <del># end <del> <del> def test_should_allow_you_to_send_an_attachment <del> assert_nothing_raised { TestMailer.deliver_invoice } <add> test "custom headers" do <add> email = TestMailer.deliver_welcome <add> assert_equal("Not SPAM", email['X-SPAM'].decoded) <ide> end <ide> <del> def test_should_allow_you_to_send_an_attachment <del> email = TestMailer.deliver_invoice <add> test "attachment with content" do <add> email = TestMailer.deliver_attachment_with_content <ide> assert_equal(1, email.attachments.length) <add> assert_equal('invoice.pdf', email.attachments[0].filename) <add> assert_equal('This is test File content', email.attachments['invoice.pdf'].decoded) <ide> end <ide> <del> def test_should_allow_you_to_send_an_attachment <del> email = TestMailer.deliver_invoice <add> test "attachment gets content type from filename" do <add> email = TestMailer.deliver_attachment_with_content <ide> assert_equal('invoice.pdf', email.attachments[0].filename) <ide> end <ide> <del> def test_should_allow_you_to_send_an_attachment <del> email = TestMailer.deliver_invoice <del> assert_equal('This is test File content', email.attachments['invoice.pdf'].decoded) <add> test "attachment with hash" do <add> email = TestMailer.deliver_attachment_with_hash <add> assert_equal(1, email.attachments.length) <add> assert_equal('invoice.jpg', email.attachments[0].filename) <add> assert_equal("\312\213\254\232)b", email.attachments['invoice.jpg'].decoded) <add> end <add> <add> test "uses default charset from class" do <add> swap TestMailer, :default_charset => "US-ASCII" do <add> email = TestMailer.deliver_welcome <add> assert_equal("US-ASCII", email.charset) <add> <add> email = TestMailer.deliver_welcome(:charset => "iso-8559-1") <add> assert_equal("iso-8559-1", email.charset) <add> end <ide> end <ide> <del> def test_should_use_class_defaults <del> <add> test "uses default content type from class" do <add> swap TestMailer, :default_content_type => "text/html" do <add> email = TestMailer.deliver_welcome <add> assert_equal("text/html", email.mime_type) <add> <add> email = TestMailer.deliver_welcome(:content_type => "application/xml") <add> assert_equal("application/xml", email.mime_type) <add> end <add> end <add> <add> test "uses default mime version from class" do <add> swap TestMailer, :default_mime_version => "2.0" do <add> email = TestMailer.deliver_welcome <add> assert_equal("2.0", email.mime_version) <add> <add> email = TestMailer.deliver_welcome(:mime_version => "1.0") <add> assert_equal("1.0", email.mime_version) <add> end <ide> end <ide> <ide> # def test_that_class_defaults_are_set_on_instantiation <ide> def test_should_use_class_defaults <ide> # def test_should_set_the_subject_from_i18n <ide> # pending <ide> # end <del> <add> <add> protected <add> <add> # Execute the block setting the given values and restoring old values after <add> # the block is executed. <add> def swap(object, new_values) <add> old_values = {} <add> new_values.each do |key, value| <add> old_values[key] = object.send key <add> object.send :"#{key}=", value <add> end <add> yield <add> ensure <add> old_values.each do |key, value| <add> object.send :"#{key}=", value <add> end <add> end <add> <ide> end <ide>\ No newline at end of file
3
Ruby
Ruby
fix regular expression
33c3faa1252f2391ec456fa922ea2bf654f341b6
<ide><path>Library/Homebrew/requirements/java_requirement.rb <ide> def oracle_java_os <ide> end <ide> <ide> def satisfies_version(java) <del> java_version_s = system_command(java, args: ["-version"], print_stderr: false).stderr[/\d+.\d/] <add> java_version_s = system_command(java, args: ["-version"], print_stderr: false).stderr[/\d+\.\d/] <ide> return false unless java_version_s <ide> <ide> java_version = Version.create(java_version_s)
1
Javascript
Javascript
remove ascii art
24df55bd00d5af34e87afab0551cb21f56c30acb
<ide><path>src/geo/projection.js <ide> function d3_geo_projectionMutator(projectAt) { <ide> } <ide> <ide> // TODO automate wrapping. <del> projection.point = function(coordinates, c) { context = c; clip.point(coordinates, resample); context = null; }; <del> projection.line = function(coordinates, c) { context = c; clip.line(coordinates, resample); context = null; }; <add> projection.point = function(coordinates, c) { context = c; clip.point(coordinates, resample); context = null; }; <add> projection.line = function(coordinates, c) { context = c; clip.line(coordinates, resample); context = null; }; <ide> projection.polygon = function(coordinates, c) { context = c; clip.polygon(coordinates, resample); context = null; }; <del> projection.sphere = function( c) { context = c; clip.sphere( resample); context = null; }; <add> projection.sphere = function(c) { context = c; clip.sphere(resample); context = null; }; <ide> <ide> projection.clipAngle = function(_) { <ide> if (!arguments.length) return clipAngle;
1
Ruby
Ruby
simplify available check
2776f08fa095b95dafbc9af5f80188f3f063e001
<ide><path>Library/Homebrew/gpg.rb <ide> def self.gpg2 <ide> GPG_EXECUTABLE = gpg2 || gpg <ide> <ide> def self.available? <del> File.exist?(GPG_EXECUTABLE.to_s) && File.executable?(GPG_EXECUTABLE.to_s) <add> File.executable?(GPG_EXECUTABLE.to_s) <ide> end <ide> <ide> def self.create_test_key(path)
1
PHP
PHP
add test for find() and array conditions
0ff9545e5adab509153551596a0be81a6a1493bd
<ide><path>lib/Cake/Test/Case/Model/ModelReadTest.php <ide> public function testFindAll() { <ide> } <ide> } <ide> <add>/** <add> * Test that find() with array conditions works when there is only one element. <add> * <add> * @return void <add> */ <add> public function testFindAllArrayConditions() { <add> $this->loadFixtures('User'); <add> $TestModel = new User(); <add> $TestModel->cacheQueries = false; <add> <add> $result = $TestModel->find('all', array( <add> 'conditions' => array('User.id' => array(3)), <add> )); <add> $expected = array( <add> array( <add> 'User' => array( <add> 'id' => '3', <add> 'user' => 'larry', <add> 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', <add> 'created' => '2007-03-17 01:20:23', <add> 'updated' => '2007-03-17 01:22:31' <add> )) <add> ); <add> $this->assertEquals($expected, $result); <add> <add> $result = $TestModel->find('all', array( <add> 'conditions' => array('User.user' => array('larry')), <add> )); <add> $this->assertEquals($expected, $result); <add> } <add> <ide> /** <ide> * test find('list') method <ide> * <ide> * @return void <ide> */ <del> public function testGenerateFindList() { <add> public function testFindList() { <ide> $this->loadFixtures('Article', 'Apple', 'Post', 'Author', 'User', 'Comment'); <ide> <ide> $TestModel = new Article(); <ide> public function testGenerateFindList() { <ide> $this->assertEquals($expected, $result); <ide> } <ide> <add>/** <add> * Test that find(list) works with array conditions that have only one element. <add> * <add> * @return void <add> */ <add> public function testFindListArrayCondition() { <add> $this->loadFixtures('User'); <add> $TestModel = new User(); <add> $TestModel->cacheQueries = false; <add> <add> $result = $TestModel->find('list', array( <add> 'fields' => array('id', 'user'), <add> 'conditions' => array('User.id' => array(3)), <add> )); <add> $expected = array( <add> 3 => 'larry' <add> ); <add> $this->assertEquals($expected, $result); <add> <add> $result = $TestModel->find('list', array( <add> 'fields' => array('id', 'user'), <add> 'conditions' => array('User.user' => array('larry')), <add> )); <add> $this->assertEquals($expected, $result); <add> } <add> <ide> /** <ide> * testFindField method <ide> *
1
Python
Python
add cudnn gru and lstm layers.
b3370c0da4430367761e6762e85de7ab4962ff62
<ide><path>keras/layers/__init__.py <ide> from .pooling import * <ide> from .local import * <ide> from .recurrent import * <add>from .cudnn_recurrent import * <ide> from .normalization import * <ide> from .embeddings import * <ide> from .noise import * <ide><path>keras/layers/cudnn_recurrent.py <add>from .. import backend as K <add>from .. import initializers <add>from .. import regularizers <add>from .. import constraints <add>from .recurrent import RNN <add>from ..layers import InputSpec <add> <add>from collections import namedtuple <add> <add> <add>class _CuDNNRNN(RNN): <add> """Private base class for CuDNNGRU and CuDNNLSTM. <add> <add> # Arguments <add> return_sequences: Boolean. Whether to return the last output. <add> in the output sequence, or the full sequence. <add> return_state: Boolean. Whether to return the last state <add> in addition to the output. <add> stateful: Boolean (default False). If True, the last state <add> for each sample at index i in a batch will be used as initial <add> state for the sample of index i in the following batch. <add> """ <add> <add> def __init__(self, <add> return_sequences=False, <add> return_state=False, <add> stateful=False, <add> **kwargs): <add> if K.backend() != 'tensorflow': <add> raise RuntimeError('CuDNN RNNs are only available ' <add> 'with the TensorFlow backend.') <add> super(RNN, self).__init__(**kwargs) <add> self.return_sequences = return_sequences <add> self.return_state = return_state <add> self.stateful = stateful <add> self.supports_masking = False <add> self.input_spec = [InputSpec(ndim=3)] <add> if hasattr(self.cell.state_size, '__len__'): <add> self.state_spec = [InputSpec(shape=(None, dim)) <add> for dim in self.cell.state_size] <add> else: <add> self.state_spec = InputSpec(shape=(None, self.cell.state_size)) <add> self._states = None <add> <add> def _canonical_to_params(self, weights, biases): <add> import tensorflow as tf <add> weights = [tf.reshape(x, (-1,)) for x in weights] <add> biases = [tf.reshape(x, (-1,)) for x in biases] <add> return tf.concat(weights + biases, 0) <add> <add> def call(self, inputs, mask=None, training=None, initial_state=None): <add> if isinstance(mask, list): <add> mask = mask[0] <add> if mask is not None: <add> raise ValueError('Masking is not supported for CuDNN RNNs.') <add> <add> # input shape: `(samples, time (padded with zeros), input_dim)` <add> # note that the .build() method of subclasses MUST define <add> # self.input_spec and self.state_spec with complete input shapes. <add> if isinstance(inputs, list): <add> initial_state = inputs[1:] <add> inputs = inputs[0] <add> elif initial_state is not None: <add> pass <add> elif self.stateful: <add> initial_state = self.states <add> else: <add> initial_state = self.get_initial_state(inputs) <add> <add> if len(initial_state) != len(self.states): <add> raise ValueError('Layer has ' + str(len(self.states)) + <add> ' states but was passed ' + <add> str(len(initial_state)) + <add> ' initial states.') <add> <add> output, states = self._process_batch(inputs, initial_state) <add> <add> if self.stateful: <add> updates = [] <add> for i in range(len(states)): <add> updates.append((self.states[i], states[i])) <add> self.add_update(updates, inputs) <add> <add> if self.return_state: <add> return [output] + states <add> else: <add> return output <add> <add> def get_config(self): <add> config = {'return_sequences': self.return_sequences, <add> 'return_state': self.return_state, <add> 'stateful': self.stateful} <add> base_config = super(RNN, self).get_config() <add> return dict(list(base_config.items()) + list(config.items())) <add> <add> @classmethod <add> def from_config(cls, config): <add> return cls(**config) <add> <add> @property <add> def trainable_weights(self): <add> if self.trainable and self.built: <add> return [self.kernel, self.recurrent_kernel, self.bias] <add> return [] <add> <add> @property <add> def non_trainable_weights(self): <add> if not self.trainable and self.built: <add> return [self.kernel, self.recurrent_kernel, self.bias] <add> return [] <add> <add> @property <add> def losses(self): <add> return super(RNN, self).losses <add> <add> def get_losses_for(self, inputs=None): <add> return super(RNN, self).get_losses_for(inputs=inputs) <add> <add> <add>class CuDNNGRU(_CuDNNRNN): <add> """Fast GRU implementation backed by CuDNN. <add> <add> Can only be run on GPU. <add> <add> # Arguments <add> units: Positive integer, dimensionality of the output space. <add> kernel_initializer: Initializer for the `kernel` weights matrix, <add> used for the linear transformation of the inputs. <add> (see [initializers](../initializers.md)). <add> recurrent_initializer: Initializer for the `recurrent_kernel` <add> weights matrix, <add> used for the linear transformation of the recurrent state. <add> (see [initializers](../initializers.md)). <add> bias_initializer: Initializer for the bias vector <add> (see [initializers](../initializers.md)). <add> kernel_regularizer: Regularizer function applied to <add> the `kernel` weights matrix <add> (see [regularizer](../regularizers.md)). <add> recurrent_regularizer: Regularizer function applied to <add> the `recurrent_kernel` weights matrix <add> (see [regularizer](../regularizers.md)). <add> bias_regularizer: Regularizer function applied to the bias vector <add> (see [regularizer](../regularizers.md)). <add> activity_regularizer: Regularizer function applied to <add> the output of the layer (its "activation"). <add> (see [regularizer](../regularizers.md)). <add> kernel_constraint: Constraint function applied to <add> the `kernel` weights matrix <add> (see [constraints](../constraints.md)). <add> recurrent_constraint: Constraint function applied to <add> the `recurrent_kernel` weights matrix <add> (see [constraints](../constraints.md)). <add> bias_constraint: Constraint function applied to the bias vector <add> (see [constraints](../constraints.md)). <add> return_sequences: Boolean. Whether to return the last output. <add> in the output sequence, or the full sequence. <add> return_state: Boolean. Whether to return the last state <add> in addition to the output. <add> stateful: Boolean (default False). If True, the last state <add> for each sample at index i in a batch will be used as initial <add> state for the sample of index i in the following batch. <add> """ <add> <add> def __init__(self, units, <add> kernel_initializer='glorot_uniform', <add> recurrent_initializer='orthogonal', <add> bias_initializer='zeros', <add> kernel_regularizer=None, <add> recurrent_regularizer=None, <add> bias_regularizer=None, <add> activity_regularizer=None, <add> kernel_constraint=None, <add> recurrent_constraint=None, <add> bias_constraint=None, <add> return_sequences=False, <add> return_state=False, <add> stateful=False, <add> **kwargs): <add> self.units = units <add> super(CuDNNGRU, self).__init__( <add> return_sequences=return_sequences, <add> return_state=return_state, <add> stateful=stateful, <add> **kwargs) <add> <add> self.kernel_initializer = initializers.get(kernel_initializer) <add> self.recurrent_initializer = initializers.get(recurrent_initializer) <add> self.bias_initializer = initializers.get(bias_initializer) <add> <add> self.kernel_regularizer = regularizers.get(kernel_regularizer) <add> self.recurrent_regularizer = regularizers.get(recurrent_regularizer) <add> self.bias_regularizer = regularizers.get(bias_regularizer) <add> self.activity_regularizer = regularizers.get(activity_regularizer) <add> <add> self.kernel_constraint = constraints.get(kernel_constraint) <add> self.recurrent_constraint = constraints.get(recurrent_constraint) <add> self.bias_constraint = constraints.get(bias_constraint) <add> <add> @property <add> def cell(self): <add> Cell = namedtuple('cell', 'state_size') <add> cell = Cell(state_size=self.units) <add> return cell <add> <add> def build(self, input_shape): <add> super(CuDNNGRU, self).build(input_shape) <add> if isinstance(input_shape, list): <add> input_shape = input_shape[0] <add> input_dim = input_shape[-1] <add> <add> from tensorflow.contrib.cudnn_rnn.python.ops import cudnn_rnn_ops <add> self._cudnn_gru = cudnn_rnn_ops.CudnnGRU( <add> num_layers=1, <add> num_units=self.units, <add> input_size=input_dim, <add> input_mode='linear_input') <add> <add> self.kernel = self.add_weight(shape=(input_dim, self.units * 3), <add> name='kernel', <add> initializer=self.kernel_initializer, <add> regularizer=self.kernel_regularizer, <add> constraint=self.kernel_constraint) <add> self.recurrent_kernel = self.add_weight( <add> shape=(self.units, self.units * 3), <add> name='recurrent_kernel', <add> initializer=self.recurrent_initializer, <add> regularizer=self.recurrent_regularizer, <add> constraint=self.recurrent_constraint) <add> <add> self.bias = self.add_weight(shape=(self.units * 6,), <add> name='bias', <add> initializer=self.bias_initializer, <add> regularizer=self.bias_regularizer, <add> constraint=self.bias_constraint) <add> <add> self.kernel_z = self.kernel[:, :self.units] <add> self.recurrent_kernel_z = self.recurrent_kernel[:, :self.units] <add> self.kernel_r = self.kernel[:, self.units: self.units * 2] <add> self.recurrent_kernel_r = self.recurrent_kernel[:, <add> self.units: <add> self.units * 2] <add> self.kernel_h = self.kernel[:, self.units * 2:] <add> self.recurrent_kernel_h = self.recurrent_kernel[:, self.units * 2:] <add> <add> self.bias_z_i = self.bias[:self.units] <add> self.bias_r_i = self.bias[self.units: self.units * 2] <add> self.bias_h_i = self.bias[self.units * 2: self.units * 3] <add> self.bias_z = self.bias[self.units * 3: self.units * 4] <add> self.bias_r = self.bias[self.units * 4: self.units * 5] <add> self.bias_h = self.bias[self.units * 5:] <add> <add> self.built = True <add> <add> def _process_batch(self, inputs, initial_state): <add> import tensorflow as tf <add> inputs = tf.transpose(inputs, (1, 0, 2)) <add> input_h = initial_state[0] <add> input_h = tf.expand_dims(input_h, axis=0) <add> <add> params = self._canonical_to_params( <add> weights=[ <add> self.kernel_r, <add> self.kernel_z, <add> self.kernel_h, <add> self.recurrent_kernel_r, <add> self.recurrent_kernel_z, <add> self.recurrent_kernel_h, <add> ], <add> biases=[ <add> self.bias_r_i, <add> self.bias_z_i, <add> self.bias_h_i, <add> self.bias_r, <add> self.bias_z, <add> self.bias_h, <add> ], <add> ) <add> outputs, h = self._cudnn_gru( <add> inputs, <add> input_h=input_h, <add> params=params, <add> is_training=True) <add> <add> if self.stateful or self.return_state: <add> h = h[0] <add> if self.return_sequences: <add> output = tf.transpose(outputs, (1, 0, 2)) <add> else: <add> output = outputs[-1] <add> return output, [h] <add> <add> def get_config(self): <add> config = { <add> 'units': self.units, <add> 'kernel_initializer': initializers.serialize(self.kernel_initializer), <add> 'recurrent_initializer': initializers.serialize(self.recurrent_initializer), <add> 'bias_initializer': initializers.serialize(self.bias_initializer), <add> 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer), <add> 'recurrent_regularizer': regularizers.serialize(self.recurrent_regularizer), <add> 'bias_regularizer': regularizers.serialize(self.bias_regularizer), <add> 'activity_regularizer': regularizers.serialize(self.activity_regularizer), <add> 'kernel_constraint': constraints.serialize(self.kernel_constraint), <add> 'recurrent_constraint': constraints.serialize(self.recurrent_constraint), <add> 'bias_constraint': constraints.serialize(self.bias_constraint)} <add> base_config = super(CuDNNGRU, self).get_config() <add> return dict(list(base_config.items()) + list(config.items())) <add> <add> <add>class CuDNNLSTM(_CuDNNRNN): <add> """Fast LSTM implementation backed by CuDNN. <add> <add> Can only be run on GPU. <add> <add> # Arguments <add> units: Positive integer, dimensionality of the output space. <add> kernel_initializer: Initializer for the `kernel` weights matrix, <add> used for the linear transformation of the inputs. <add> (see [initializers](../initializers.md)). <add> unit_forget_bias: Boolean. <add> If True, add 1 to the bias of the forget gate at initialization. <add> Setting it to true will also force `bias_initializer="zeros"`. <add> This is recommended in [Jozefowicz et al.](http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf) <add> recurrent_initializer: Initializer for the `recurrent_kernel` <add> weights matrix, <add> used for the linear transformation of the recurrent state. <add> (see [initializers](../initializers.md)). <add> bias_initializer: Initializer for the bias vector <add> (see [initializers](../initializers.md)). <add> kernel_regularizer: Regularizer function applied to <add> the `kernel` weights matrix <add> (see [regularizer](../regularizers.md)). <add> recurrent_regularizer: Regularizer function applied to <add> the `recurrent_kernel` weights matrix <add> (see [regularizer](../regularizers.md)). <add> bias_regularizer: Regularizer function applied to the bias vector <add> (see [regularizer](../regularizers.md)). <add> activity_regularizer: Regularizer function applied to <add> the output of the layer (its "activation"). <add> (see [regularizer](../regularizers.md)). <add> kernel_constraint: Constraint function applied to <add> the `kernel` weights matrix <add> (see [constraints](../constraints.md)). <add> recurrent_constraint: Constraint function applied to <add> the `recurrent_kernel` weights matrix <add> (see [constraints](../constraints.md)). <add> bias_constraint: Constraint function applied to the bias vector <add> (see [constraints](../constraints.md)). <add> return_sequences: Boolean. Whether to return the last output. <add> in the output sequence, or the full sequence. <add> return_state: Boolean. Whether to return the last state <add> in addition to the output. <add> stateful: Boolean (default False). If True, the last state <add> for each sample at index i in a batch will be used as initial <add> state for the sample of index i in the following batch. <add> """ <add> def __init__(self, units, <add> kernel_initializer='glorot_uniform', <add> recurrent_initializer='orthogonal', <add> bias_initializer='zeros', <add> unit_forget_bias=True, <add> kernel_regularizer=None, <add> recurrent_regularizer=None, <add> bias_regularizer=None, <add> activity_regularizer=None, <add> kernel_constraint=None, <add> recurrent_constraint=None, <add> bias_constraint=None, <add> return_sequences=False, <add> return_state=False, <add> stateful=False, <add> **kwargs): <add> self.units = units <add> super(CuDNNLSTM, self).__init__( <add> return_sequences=return_sequences, <add> return_state=return_state, <add> stateful=stateful, <add> **kwargs) <add> <add> self.kernel_initializer = initializers.get(kernel_initializer) <add> self.recurrent_initializer = initializers.get(recurrent_initializer) <add> self.bias_initializer = initializers.get(bias_initializer) <add> self.unit_forget_bias = unit_forget_bias <add> <add> self.kernel_regularizer = regularizers.get(kernel_regularizer) <add> self.recurrent_regularizer = regularizers.get(recurrent_regularizer) <add> self.bias_regularizer = regularizers.get(bias_regularizer) <add> self.activity_regularizer = regularizers.get(activity_regularizer) <add> <add> self.kernel_constraint = constraints.get(kernel_constraint) <add> self.recurrent_constraint = constraints.get(recurrent_constraint) <add> self.bias_constraint = constraints.get(bias_constraint) <add> <add> @property <add> def cell(self): <add> Cell = namedtuple('cell', 'state_size') <add> cell = Cell(state_size=(self.units, self.units)) <add> return cell <add> <add> def build(self, input_shape): <add> super(CuDNNLSTM, self).build(input_shape) <add> if isinstance(input_shape, list): <add> input_shape = input_shape[0] <add> input_dim = input_shape[-1] <add> <add> from tensorflow.contrib.cudnn_rnn.python.ops import cudnn_rnn_ops <add> self._cudnn_lstm = cudnn_rnn_ops.CudnnLSTM( <add> num_layers=1, <add> num_units=self.units, <add> input_size=input_dim, <add> input_mode='linear_input') <add> <add> self.kernel = self.add_weight(shape=(input_dim, self.units * 4), <add> name='kernel', <add> initializer=self.kernel_initializer, <add> regularizer=self.kernel_regularizer, <add> constraint=self.kernel_constraint) <add> self.recurrent_kernel = self.add_weight( <add> shape=(self.units, self.units * 4), <add> name='recurrent_kernel', <add> initializer=self.recurrent_initializer, <add> regularizer=self.recurrent_regularizer, <add> constraint=self.recurrent_constraint) <add> <add> if self.unit_forget_bias: <add> def bias_initializer(shape, *args, **kwargs): <add> return K.concatenate([ <add> self.bias_initializer((self.units * 5,), *args, **kwargs), <add> initializers.Ones()((self.units,), *args, **kwargs), <add> self.bias_initializer((self.units * 2,), *args, **kwargs), <add> ]) <add> else: <add> bias_initializer = self.bias_initializer <add> self.bias = self.add_weight(shape=(self.units * 8,), <add> name='bias', <add> initializer=bias_initializer, <add> regularizer=self.bias_regularizer, <add> constraint=self.bias_constraint) <add> <add> self.kernel_i = self.kernel[:, :self.units] <add> self.kernel_f = self.kernel[:, self.units: self.units * 2] <add> self.kernel_c = self.kernel[:, self.units * 2: self.units * 3] <add> self.kernel_o = self.kernel[:, self.units * 3:] <add> <add> self.recurrent_kernel_i = self.recurrent_kernel[:, :self.units] <add> self.recurrent_kernel_f = self.recurrent_kernel[:, self.units: self.units * 2] <add> self.recurrent_kernel_c = self.recurrent_kernel[:, self.units * 2: self.units * 3] <add> self.recurrent_kernel_o = self.recurrent_kernel[:, self.units * 3:] <add> <add> self.bias_i_i = self.bias[:self.units] <add> self.bias_f_i = self.bias[self.units: self.units * 2] <add> self.bias_c_i = self.bias[self.units * 2: self.units * 3] <add> self.bias_o_i = self.bias[self.units * 3: self.units * 4] <add> self.bias_i = self.bias[self.units * 4: self.units * 5] <add> self.bias_f = self.bias[self.units * 5: self.units * 6] <add> self.bias_c = self.bias[self.units * 6: self.units * 7] <add> self.bias_o = self.bias[self.units * 7:] <add> <add> self.built = True <add> <add> def _process_batch(self, inputs, initial_state): <add> import tensorflow as tf <add> inputs = tf.transpose(inputs, (1, 0, 2)) <add> input_h = initial_state[0] <add> input_c = initial_state[1] <add> input_h = tf.expand_dims(input_h, axis=0) <add> input_c = tf.expand_dims(input_c, axis=0) <add> <add> params = self._canonical_to_params( <add> weights=[ <add> self.kernel_i, <add> self.kernel_f, <add> self.kernel_c, <add> self.kernel_o, <add> self.recurrent_kernel_i, <add> self.recurrent_kernel_f, <add> self.recurrent_kernel_c, <add> self.recurrent_kernel_o, <add> ], <add> biases=[ <add> self.bias_i_i, <add> self.bias_f_i, <add> self.bias_c_i, <add> self.bias_o_i, <add> self.bias_i, <add> self.bias_f, <add> self.bias_c, <add> self.bias_o, <add> ], <add> ) <add> outputs, h, c = self._cudnn_lstm( <add> inputs, <add> input_h=input_h, <add> input_c=input_c, <add> params=params, <add> is_training=True) <add> <add> if self.stateful or self.return_state: <add> h = h[0] <add> c = c[0] <add> if self.return_sequences: <add> output = tf.transpose(outputs, (1, 0, 2)) <add> else: <add> output = outputs[-1] <add> return output, [h, c] <add> <add> def get_config(self): <add> config = { <add> 'units': self.units, <add> 'kernel_initializer': initializers.serialize(self.kernel_initializer), <add> 'recurrent_initializer': initializers.serialize(self.recurrent_initializer), <add> 'bias_initializer': initializers.serialize(self.bias_initializer), <add> 'unit_forget_bias': self.unit_forget_bias, <add> 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer), <add> 'recurrent_regularizer': regularizers.serialize(self.recurrent_regularizer), <add> 'bias_regularizer': regularizers.serialize(self.bias_regularizer), <add> 'activity_regularizer': regularizers.serialize(self.activity_regularizer), <add> 'kernel_constraint': constraints.serialize(self.kernel_constraint), <add> 'recurrent_constraint': constraints.serialize(self.recurrent_constraint), <add> 'bias_constraint': constraints.serialize(self.bias_constraint)} <add> base_config = super(CuDNNLSTM, self).get_config() <add> return dict(list(base_config.items()) + list(config.items())) <ide><path>tests/keras/layers/cudnn_recurrent_test.py <add>import pytest <add>import numpy as np <add>from numpy.testing import assert_allclose <add>import keras <add>from keras.utils.test_utils import layer_test <add>from keras.utils.test_utils import keras_test <add>import time <add> <add> <add>@keras_test <add>@pytest.mark.skipif((keras.backend.backend() != 'tensorflow'), <add> reason='Requires TensorFlow backend') <add>@pytest.mark.skipif(not keras.backend.tensorflow_backend._get_available_gpus(), <add> reason='Requires GPU') <add>def test_cudnn_rnn_canonical_to_params_lstm(): <add> units = 1 <add> input_size = 1 <add> layer = keras.layers.CuDNNLSTM(units) <add> layer.build((None, None, input_size)) <add> <add> params = layer._canonical_to_params( <add> weights=[ <add> layer.kernel_i, <add> layer.kernel_f, <add> layer.kernel_c, <add> layer.kernel_o, <add> layer.recurrent_kernel_i, <add> layer.recurrent_kernel_f, <add> layer.recurrent_kernel_c, <add> layer.recurrent_kernel_o, <add> ], <add> biases=[ <add> layer.bias_i_i, <add> layer.bias_f_i, <add> layer.bias_c_i, <add> layer.bias_o_i, <add> layer.bias_i, <add> layer.bias_f, <add> layer.bias_c, <add> layer.bias_o, <add> ], <add> ) <add> ref_params = layer._cudnn_lstm.canonical_to_params( <add> weights=[ <add> layer.kernel_i, <add> layer.kernel_f, <add> layer.kernel_c, <add> layer.kernel_o, <add> layer.recurrent_kernel_i, <add> layer.recurrent_kernel_f, <add> layer.recurrent_kernel_c, <add> layer.recurrent_kernel_o, <add> ], <add> biases=[ <add> layer.bias_i_i, <add> layer.bias_f_i, <add> layer.bias_c_i, <add> layer.bias_o_i, <add> layer.bias_i, <add> layer.bias_f, <add> layer.bias_c, <add> layer.bias_o, <add> ], <add> ) <add> ref_params_value = keras.backend.get_value(ref_params) <add> params_value = keras.backend.get_value(params) <add> diff = np.mean(ref_params_value - params_value) <add> assert diff < 1e-8 <add> <add> <add>@keras_test <add>@pytest.mark.skipif((keras.backend.backend() != 'tensorflow'), <add> reason='Requires TensorFlow backend') <add>@pytest.mark.skipif(not keras.backend.tensorflow_backend._get_available_gpus(), <add> reason='Requires GPU') <add>def test_cudnn_rnn_canonical_to_params_gru(): <add> units = 7 <add> input_size = 9 <add> layer = keras.layers.CuDNNGRU(units) <add> layer.build((None, None, input_size)) <add> <add> ref_params = layer._cudnn_gru.canonical_to_params( <add> weights=[ <add> layer.kernel_r, <add> layer.kernel_z, <add> layer.kernel_h, <add> layer.recurrent_kernel_r, <add> layer.recurrent_kernel_z, <add> layer.recurrent_kernel_h, <add> ], <add> biases=[ <add> layer.bias_r_i, <add> layer.bias_z_i, <add> layer.bias_h_i, <add> layer.bias_r, <add> layer.bias_z, <add> layer.bias_h, <add> ], <add> ) <add> params = layer._canonical_to_params( <add> weights=[ <add> layer.kernel_r, <add> layer.kernel_z, <add> layer.kernel_h, <add> layer.recurrent_kernel_r, <add> layer.recurrent_kernel_z, <add> layer.recurrent_kernel_h, <add> ], <add> biases=[ <add> layer.bias_r_i, <add> layer.bias_z_i, <add> layer.bias_h_i, <add> layer.bias_r, <add> layer.bias_z, <add> layer.bias_h, <add> ], <add> ) <add> ref_params_value = keras.backend.get_value(ref_params) <add> params_value = keras.backend.get_value(params) <add> diff = np.mean(ref_params_value - params_value) <add> assert diff < 1e-8 <add> <add> <add>@keras_test <add>@pytest.mark.skipif((keras.backend.backend() != 'tensorflow'), <add> reason='Requires TensorFlow backend') <add>@pytest.mark.skipif(not keras.backend.tensorflow_backend._get_available_gpus(), <add> reason='Requires GPU') <add>def test_cudnn_rnn_timing(): <add> input_size = 1000 <add> timesteps = 60 <add> units = 256 <add> num_samples = 10000 <add> <add> times = [] <add> for rnn_type in ['lstm', 'gru']: <add> for use_cudnn in [True, False]: <add> start_time = time.time() <add> inputs = keras.layers.Input(shape=(None, input_size)) <add> if use_cudnn: <add> if rnn_type == 'lstm': <add> layer = keras.layers.CuDNNLSTM(units) <add> else: <add> layer = keras.layers.CuDNNGRU(units) <add> else: <add> if rnn_type == 'lstm': <add> layer = keras.layers.LSTM(units) <add> else: <add> layer = keras.layers.GRU(units) <add> outputs = layer(inputs) <add> <add> model = keras.models.Model(inputs, outputs) <add> model.compile('sgd', 'mse') <add> <add> x = np.random.random((num_samples, timesteps, input_size)) <add> y = np.random.random((num_samples, units)) <add> model.fit(x, y, epochs=4, batch_size=32) <add> <add> times.append(time.time() - start_time) <add> <add> speedup = times[1] / times[0] <add> print(rnn_type, 'speedup', speedup) <add> assert speedup > 3 <add> keras.backend.clear_session() <add> <add> <add>@keras_test <add>@pytest.mark.skipif((keras.backend.backend() != 'tensorflow'), <add> reason='Requires TensorFlow backend') <add>@pytest.mark.skipif(not keras.backend.tensorflow_backend._get_available_gpus(), <add> reason='Requires GPU') <add>def test_cudnn_rnn_basics(): <add> input_size = 10 <add> timesteps = 6 <add> units = 2 <add> num_samples = 32 <add> for layer_class in [keras.layers.CuDNNGRU, keras.layers.CuDNNLSTM]: <add> for return_sequences in [True, False]: <add> with keras.utils.CustomObjectScope( <add> {'keras.layers.CuDNNGRU': keras.layers.CuDNNGRU, <add> 'keras.layers.CuDNNLSTM': keras.layers.CuDNNLSTM}): <add> layer_test( <add> layer_class, <add> kwargs={'units': units, <add> 'return_sequences': return_sequences}, <add> input_shape=(num_samples, timesteps, input_size)) <add> <add> <add>@keras_test <add>@pytest.mark.skipif((keras.backend.backend() != 'tensorflow'), <add> reason='Requires TensorFlow backend') <add>@pytest.mark.skipif(not keras.backend.tensorflow_backend._get_available_gpus(), <add> reason='Requires GPU') <add>def test_trainability(): <add> input_size = 10 <add> units = 2 <add> for layer_class in [keras.layers.CuDNNGRU, keras.layers.CuDNNLSTM]: <add> layer = layer_class(units) <add> layer.build((None, None, input_size)) <add> assert len(layer.weights) == 3 <add> assert len(layer.trainable_weights) == 3 <add> assert len(layer.non_trainable_weights) == 0 <add> layer.trainable = False <add> assert len(layer.weights) == 3 <add> assert len(layer.non_trainable_weights) == 3 <add> assert len(layer.trainable_weights) == 0 <add> layer.trainable = True <add> assert len(layer.weights) == 3 <add> assert len(layer.trainable_weights) == 3 <add> assert len(layer.non_trainable_weights) == 0 <add> <add> <add>@keras_test <add>@pytest.mark.skipif((keras.backend.backend() != 'tensorflow'), <add> reason='Requires TensorFlow backend') <add>@pytest.mark.skipif(not keras.backend.tensorflow_backend._get_available_gpus(), <add> reason='Requires GPU') <add>def test_regularizer(): <add> input_size = 10 <add> timesteps = 6 <add> units = 2 <add> num_samples = 32 <add> for layer_class in [keras.layers.CuDNNGRU, keras.layers.CuDNNLSTM]: <add> layer = layer_class(units, return_sequences=False, <add> input_shape=(timesteps, input_size), <add> kernel_regularizer=keras.regularizers.l1(0.01), <add> recurrent_regularizer=keras.regularizers.l1(0.01), <add> bias_regularizer='l2') <add> layer.build((None, None, input_size)) <add> assert len(layer.losses) == 3 <add> <add> layer = layer_class(units, return_sequences=False, <add> input_shape=(timesteps, input_size), <add> activity_regularizer='l2') <add> assert layer.activity_regularizer <add> x = keras.backend.variable(np.ones((num_samples, <add> timesteps, <add> input_size))) <add> layer(x) <add> assert len(layer.get_losses_for(x)) == 1 <add> <add> <add>@keras_test <add>@pytest.mark.skipif((keras.backend.backend() != 'tensorflow'), <add> reason='Requires TensorFlow backend') <add>@pytest.mark.skipif(not keras.backend.tensorflow_backend._get_available_gpus(), <add> reason='Requires GPU') <add>def test_return_state(): <add> input_size = 10 <add> timesteps = 6 <add> units = 2 <add> num_samples = 32 <add> <add> for layer_class in [keras.layers.CuDNNGRU, keras.layers.CuDNNLSTM]: <add> num_states = 2 if layer_class is keras.layers.CuDNNLSTM else 1 <add> <add> inputs = keras.Input(batch_shape=(num_samples, timesteps, input_size)) <add> layer = layer_class(units, return_state=True, stateful=True) <add> outputs = layer(inputs) <add> output, state = outputs[0], outputs[1:] <add> assert len(state) == num_states <add> model = keras.models.Model(inputs, state[0]) <add> <add> inputs = np.random.random((num_samples, timesteps, input_size)) <add> state = model.predict(inputs) <add> np.testing.assert_allclose( <add> keras.backend.eval(layer.states[0]), state, atol=1e-4) <add> <add> <add>@keras_test <add>@pytest.mark.skipif((keras.backend.backend() != 'tensorflow'), <add> reason='Requires TensorFlow backend') <add>@pytest.mark.skipif(not keras.backend.tensorflow_backend._get_available_gpus(), <add> reason='Requires GPU') <add>def test_specify_initial_state_keras_tensor(): <add> input_size = 10 <add> timesteps = 6 <add> units = 2 <add> num_samples = 32 <add> for layer_class in [keras.layers.CuDNNGRU, keras.layers.CuDNNLSTM]: <add> num_states = 2 if layer_class is keras.layers.CuDNNLSTM else 1 <add> <add> inputs = keras.Input((timesteps, input_size)) <add> initial_state = [keras.Input((units,)) for _ in range(num_states)] <add> layer = layer_class(units) <add> if len(initial_state) == 1: <add> output = layer(inputs, initial_state=initial_state[0]) <add> else: <add> output = layer(inputs, initial_state=initial_state) <add> assert initial_state[0] in layer.inbound_nodes[0].input_tensors <add> <add> model = keras.models.Model([inputs] + initial_state, output) <add> model.compile(loss='categorical_crossentropy', optimizer='adam') <add> <add> inputs = np.random.random((num_samples, timesteps, input_size)) <add> initial_state = [np.random.random((num_samples, units)) <add> for _ in range(num_states)] <add> targets = np.random.random((num_samples, units)) <add> model.fit([inputs] + initial_state, targets) <add> <add> <add>@keras_test <add>@pytest.mark.skipif((keras.backend.backend() != 'tensorflow'), <add> reason='Requires TensorFlow backend') <add>@pytest.mark.skipif(not keras.backend.tensorflow_backend._get_available_gpus(), <add> reason='Requires GPU') <add>def test_statefulness(): <add> input_size = 10 <add> timesteps = 6 <add> units = 2 <add> num_samples = 32 <add> <add> for layer_class in [keras.layers.CuDNNGRU, keras.layers.CuDNNLSTM]: <add> model = keras.models.Sequential() <add> model.add(keras.layers.Embedding(10, input_size, <add> input_length=timesteps, <add> batch_input_shape=(num_samples, <add> timesteps))) <add> layer = layer_class(units, <add> return_sequences=False, <add> stateful=True, <add> weights=None) <add> model.add(layer) <add> model.compile(optimizer='sgd', loss='mse') <add> out1 = model.predict(np.ones((num_samples, timesteps))) <add> assert(out1.shape == (num_samples, units)) <add> <add> # train once so that the states change <add> model.train_on_batch(np.ones((num_samples, timesteps)), <add> np.ones((num_samples, units))) <add> out2 = model.predict(np.ones((num_samples, timesteps))) <add> <add> # if the state is not reset, output should be different <add> assert(out1.max() != out2.max()) <add> <add> # check that output changes after states are reset <add> # (even though the model itself didn't change) <add> layer.reset_states() <add> out3 = model.predict(np.ones((num_samples, timesteps))) <add> assert(out2.max() != out3.max()) <add> <add> # check that container-level reset_states() works <add> model.reset_states() <add> out4 = model.predict(np.ones((num_samples, timesteps))) <add> assert_allclose(out3, out4, atol=1e-5) <add> <add> # check that the call to `predict` updated the states <add> out5 = model.predict(np.ones((num_samples, timesteps))) <add> assert(out4.max() != out5.max()) <add> <add> <add>if __name__ == '__main__': <add> pytest.main([__file__]) <ide><path>tests/keras/layers/wrappers_test.py <ide> def test_TimeDistributed(): <ide> <ide> <ide> @keras_test <add>@pytest.mark.skipif((K.backend() == 'cntk'), <add> reason='Flaky with CNTK backend') <ide> def test_TimeDistributed_learning_phase(): <ide> # test layers that need learning_phase to be set <ide> np.random.seed(1234)
4
PHP
PHP
present tense and fix tests
58278256e853de199d35c0a087a724fd52b5cd35
<ide><path>src/TestSuite/Constraint/Response/CookieEquals.php <ide> public function matches($other) <ide> */ <ide> public function toString() <ide> { <del> return sprintf('was in cookie \'%s\'', $this->cookieName); <add> return sprintf('is in cookie \'%s\'', $this->cookieName); <ide> } <ide> } <ide><path>src/TestSuite/Constraint/Response/CookieNotSet.php <ide> public function matches($other) <ide> */ <ide> public function toString() <ide> { <del> return 'cookie was not set'; <add> return 'cookie is not set'; <ide> } <ide> } <ide><path>src/TestSuite/Constraint/Response/CookieSet.php <ide> public function matches($other) <ide> */ <ide> public function toString() <ide> { <del> return 'cookie was set'; <add> return 'cookie is set'; <ide> } <ide> } <ide><path>src/TestSuite/Constraint/Session/FlashParamEquals.php <ide> public function matches($other) <ide> public function toString() <ide> { <ide> if ($this->at !== null) { <del> return sprintf('was in \'%s\' %s #%d', $this->key, $this->param, $this->at); <add> return sprintf('is in \'%s\' %s #%d', $this->key, $this->param, $this->at); <ide> } <ide> <del> return sprintf('was in \'%s\' %s', $this->key, $this->param); <add> return sprintf('is in \'%s\' %s', $this->key, $this->param); <ide> } <ide> } <ide><path>tests/TestCase/TestSuite/IntegrationTestTraitTest.php <ide> public function testAssertCookieNotSet() <ide> public function testCookieNotSetFailure() <ide> { <ide> $this->expectException(AssertionFailedError::class); <del> $this->expectExceptionMessage('Failed asserting that \'remember_me\' cookie was not set'); <add> $this->expectExceptionMessage('Failed asserting that \'remember_me\' cookie is not set'); <ide> $this->post('/posts/index'); <ide> $this->assertCookieNotSet('remember_me'); <ide> } <ide> public function assertionFailureMessagesProvider() <ide> $templateDir = TEST_APP . 'TestApp' . DS . 'Template' . DS; <ide> <ide> return [ <del> 'assertContentType' => ['assertContentType', 'Failed asserting that \'test\' was set as the Content-Type (`text/html`).', '/posts/index', 'test'], <add> 'assertContentType' => ['assertContentType', 'Failed asserting that \'test\' is set as the Content-Type (`text/html`).', '/posts/index', 'test'], <ide> 'assertContentTypeVerbose' => ['assertContentType', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', 'test'], <del> 'assertCookie' => ['assertCookie', 'Failed asserting that \'test\' was in cookie \'remember_me\'.', '/posts/index', 'test', 'remember_me'], <add> 'assertCookie' => ['assertCookie', 'Failed asserting that \'test\' is in cookie \'remember_me\'.', '/posts/index', 'test', 'remember_me'], <ide> 'assertCookieVerbose' => ['assertCookie', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', 'test', 'remember_me'], <ide> 'assertCookieEncrypted' => ['assertCookieEncrypted', 'Failed asserting that \'test\' was encrypted in cookie \'NameOfCookie\'.', '/cookie_component_test/set_cookie', 'test', 'NameOfCookie'], <ide> 'assertCookieEncryptedVerbose' => ['assertCookieEncrypted', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', 'test', 'NameOfCookie'], <del> 'assertCookieNotSet' => ['assertCookieNotSet', 'Failed asserting that \'remember_me\' cookie was not set.', '/posts/index', 'remember_me'], <add> 'assertCookieNotSet' => ['assertCookieNotSet', 'Failed asserting that \'remember_me\' cookie is not set.', '/posts/index', 'remember_me'], <ide> 'assertFileResponse' => ['assertFileResponse', 'Failed asserting that \'test\' file was sent.', '/posts/file', 'test'], <ide> 'assertFileResponseVerbose' => ['assertFileResponse', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', 'test'], <ide> 'assertHeader' => ['assertHeader', 'Failed asserting that \'test\' equals content in header \'X-Cake\' (`custom header`).', '/posts/header', 'X-Cake', 'test'], <ide> public function assertionFailureMessagesProvider() <ide> 'assertSession' => ['assertSession', 'Failed asserting that \'test\' is in session path \'Missing.path\'.', '/posts/index', 'test', 'Missing.path'], <ide> 'assertTemplate' => ['assertTemplate', 'Failed asserting that \'custom_template\' equals template file `' . $templateDir . 'Posts' . DS . 'index.ctp`.', '/posts/index', 'custom_template'], <ide> 'assertTemplateVerbose' => ['assertTemplate', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', 'custom_template'], <del> 'assertFlashMessage' => ['assertFlashMessage', 'Failed asserting that \'missing\' was in \'flash\' message.', '/posts/index', 'missing'], <del> 'assertFlashMessageWithKey' => ['assertFlashMessage', 'Failed asserting that \'missing\' was in \'auth\' message.', '/posts/index', 'missing', 'auth'], <del> 'assertFlashMessageAt' => ['assertFlashMessageAt', 'Failed asserting that \'missing\' was in \'flash\' message #0.', '/posts/index', 0, 'missing'], <del> 'assertFlashMessageAtWithKey' => ['assertFlashMessageAt', 'Failed asserting that \'missing\' was in \'auth\' message #0.', '/posts/index', 0, 'missing', 'auth'], <del> 'assertFlashElement' => ['assertFlashElement', 'Failed asserting that \'missing\' was in \'flash\' element.', '/posts/index', 'missing'], <del> 'assertFlashElementWithKey' => ['assertFlashElement', 'Failed asserting that \'missing\' was in \'auth\' element.', '/posts/index', 'missing', 'auth'], <del> 'assertFlashElementAt' => ['assertFlashElementAt', 'Failed asserting that \'missing\' was in \'flash\' element #0.', '/posts/index', 0, 'missing'], <del> 'assertFlashElementAtWithKey' => ['assertFlashElementAt', 'Failed asserting that \'missing\' was in \'auth\' element #0.', '/posts/index', 0, 'missing', 'auth'], <add> 'assertFlashMessage' => ['assertFlashMessage', 'Failed asserting that \'missing\' is in \'flash\' message.', '/posts/index', 'missing'], <add> 'assertFlashMessageWithKey' => ['assertFlashMessage', 'Failed asserting that \'missing\' is in \'auth\' message.', '/posts/index', 'missing', 'auth'], <add> 'assertFlashMessageAt' => ['assertFlashMessageAt', 'Failed asserting that \'missing\' is in \'flash\' message #0.', '/posts/index', 0, 'missing'], <add> 'assertFlashMessageAtWithKey' => ['assertFlashMessageAt', 'Failed asserting that \'missing\' is in \'auth\' message #0.', '/posts/index', 0, 'missing', 'auth'], <add> 'assertFlashElement' => ['assertFlashElement', 'Failed asserting that \'missing\' is in \'flash\' element.', '/posts/index', 'missing'], <add> 'assertFlashElementWithKey' => ['assertFlashElement', 'Failed asserting that \'missing\' is in \'auth\' element.', '/posts/index', 'missing', 'auth'], <add> 'assertFlashElementAt' => ['assertFlashElementAt', 'Failed asserting that \'missing\' is in \'flash\' element #0.', '/posts/index', 0, 'missing'], <add> 'assertFlashElementAtWithKey' => ['assertFlashElementAt', 'Failed asserting that \'missing\' is in \'auth\' element #0.', '/posts/index', 0, 'missing', 'auth'], <ide> ]; <ide> } <ide>
5
Javascript
Javascript
make timezone optional
9473780e77a960ba27644ca76c2413924cc8972e
<ide><path>src/ng/filter/filters.js <ide> dateFilter.$inject = ['$locale']; <ide> function dateFilter($locale) { <ide> <ide> <del> var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/; <add> var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; <ide> function jsonStringToDate(string){ <ide> var match; <ide> if (match = string.match(R_ISO8601_STR)) { <ide><path>test/ng/filter/filtersSpec.js <ide> describe('filters', function() { <ide> <ide> expect(date('20030910T033203-0930', format)).toEqual('2003-09 03'); <ide> <add> //no timezone <add> expect(date('2003-09-10T13:02:03.000', format)).toEqual('2003-09 03'); <add> <ide> //no millis <ide> expect(date('2003-09-10T13:02:03Z', format)).toEqual('2003-09 03'); <ide>
2
Javascript
Javascript
fix some warnings
99705440a085de64c57155e00ea4f3361dec9879
<ide><path>Libraries/AppRegistry/AppRegistry.js <ide> if (__DEV__) { <ide> } <ide> <ide> var runnables = {}; <add>var runCount = 1; <ide> <ide> type ComponentProvider = () => ReactClass<any>; <ide> <ide> var AppRegistry = { <ide> ', performance optimizations are ' + (__DEV__ ? 'OFF' : 'ON'); <ide> console.log(msg); <ide> BugReporting.init(); <del> BugReporting.addSource('AppRegistry.runApplication', () => msg); <add> BugReporting.addSource('AppRegistry.runApplication' + runCount++, () => msg); <ide> invariant( <ide> runnables[appKey] && runnables[appKey].run, <ide> 'Application ' + appKey + ' has not been registered. This ' + <ide><path>Libraries/Components/Touchable/Touchable.js <ide> var Touchable = { <ide> ); <ide> } <ide> }; <del>if (Touchable.TOUCH_TARGET_DEBUG) { <del> console.warn('Touchable.TOUCH_TARGET_DEBUG is enabled'); <del>} <ide> <ide> module.exports = Touchable;
2
Javascript
Javascript
remove var in libraries/component
a06c0da828f42b804b526a5de35b94b5b4468c1c
<ide><path>Libraries/Components/RefreshControl/RefreshControl.js <ide> const nullthrows = require('nullthrows'); <ide> import type {ColorValue} from 'StyleSheetTypes'; <ide> import type {ViewProps} from 'ViewPropTypes'; <ide> <add>let RefreshLayoutConsts; <ide> if (Platform.OS === 'android') { <ide> const AndroidSwipeRefreshLayout = require('UIManager').getViewManagerConfig( <ide> 'AndroidSwipeRefreshLayout', <ide> ); <del> var RefreshLayoutConsts = AndroidSwipeRefreshLayout <add> RefreshLayoutConsts = AndroidSwipeRefreshLayout <ide> ? AndroidSwipeRefreshLayout.Constants <ide> : {SIZE: {}}; <ide> } else { <del> var RefreshLayoutConsts = {SIZE: {}}; <add> RefreshLayoutConsts = {SIZE: {}}; <ide> } <ide> type NativeRefreshControlType = Class<NativeComponent<RefreshControlProps>>; <ide> <ide><path>Libraries/Components/TabBarIOS/TabBarItemIOS.ios.js <ide> class TabBarItemIOS extends React.Component<Props, State> { <ide> showedDeprecationWarning = true; <ide> } <ide> } <del> <add> <ide> render() { <ide> const {style, children, ...props} = this.props; <ide> <ide> // if the tab has already been shown once, always continue to show it so we <ide> // preserve state between tab transitions <add> let tabContents; <ide> if (this.state.hasBeenSelected) { <del> var tabContents = ( <add> tabContents = ( <ide> <StaticContainer shouldUpdate={this.props.selected}> <ide> {children} <ide> </StaticContainer> <ide> ); <ide> } else { <del> var tabContents = <View />; <add> tabContents = <View />; <ide> } <ide> <ide> return (
2
Python
Python
fix a typo in the example
3a8d7ff5f047c7b3476b8dcffa0e6850e952a645
<ide><path>docs/examples/http_proxy/set_http_proxy_method.py <ide> <ide> cls = get_driver(Provider.RACKSPACE) <ide> driver = cls('username', 'api key', region='ord') <del>driver.set_http_proxy(proxy_url=PROXY_URL) <add>driver.connection.set_http_proxy(proxy_url=PROXY_URL) <ide> <ide> pprint(driver.list_nodes())
1
Python
Python
correct io counter and max cpu/mem
6f62a9f2e8418fb4e7c224942843d5fcab87882f
<ide><path>glances/processes.py <ide> def update(self): <ide> self.processcount['pid_max'] = self.pid_max <ide> <ide> # Compute the maximum value for keys in self._max_values_list <del> # Reset the max dict <del> self.reset_max_values() <add> # # Reset the max dict <add> # self.reset_max_values() <ide> # Compute max <ide> for k in self._max_values_list: <ide> self.set_max_values(k, max(i[k] for i in self.processlist))
1
Javascript
Javascript
add polygon tag to transform
42444f6bb9a001096cfd95306a1e720eb1ed537e
<ide><path>vendor/fbtransform/transforms/xjs.js <ide> var knownTags = { <ide> p: true, <ide> param: true, <ide> path: true, <add> polygon: true, <ide> polyline: true, <ide> pre: true, <ide> progress: true,
1
Go
Go
optimize the unit test for restartmanager
0a0bbab81d30a22e1c60e17c57be09df1541ee9c
<ide><path>restartmanager/restartmanager.go <ide> type restartManager struct { <ide> canceled bool <ide> } <ide> <del>// New returns a new restartmanager based on a policy. <add>// New returns a new restartManager based on a policy. <ide> func New(policy container.RestartPolicy, restartCount int) RestartManager { <ide> return &restartManager{policy: policy, restartCount: restartCount, cancel: make(chan struct{})} <ide> } <ide> func (rm *restartManager) ShouldRestart(exitCode uint32, hasBeenManuallyStopped <ide> } <ide> <ide> if rm.active { <del> return false, nil, fmt.Errorf("invalid call on active restartmanager") <add> return false, nil, fmt.Errorf("invalid call on an active restart manager") <ide> } <ide> // if the container ran for more than 10s, regardless of status and policy reset the <ide> // the timeout back to the default. <ide><path>restartmanager/restartmanager_test.go <ide> import ( <ide> <ide> func TestRestartManagerTimeout(t *testing.T) { <ide> rm := New(container.RestartPolicy{Name: "always"}, 0).(*restartManager) <del> should, _, err := rm.ShouldRestart(0, false, 1*time.Second) <add> var duration = time.Duration(1 * time.Second) <add> should, _, err := rm.ShouldRestart(0, false, duration) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> if !should { <ide> t.Fatal("container should be restarted") <ide> } <del> if rm.timeout != 100*time.Millisecond { <del> t.Fatalf("restart manager should have a timeout of 100ms but has %s", rm.timeout) <add> if rm.timeout != defaultTimeout { <add> t.Fatalf("restart manager should have a timeout of 100 ms but has %s", rm.timeout) <ide> } <ide> } <ide> <ide> func TestRestartManagerTimeoutReset(t *testing.T) { <ide> rm := New(container.RestartPolicy{Name: "always"}, 0).(*restartManager) <ide> rm.timeout = 5 * time.Second <del> _, _, err := rm.ShouldRestart(0, false, 10*time.Second) <add> var duration = time.Duration(10 * time.Second) <add> _, _, err := rm.ShouldRestart(0, false, duration) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <del> if rm.timeout != 100*time.Millisecond { <del> t.Fatalf("restart manager should have a timeout of 100ms but has %s", rm.timeout) <add> if rm.timeout != defaultTimeout { <add> t.Fatalf("restart manager should have a timeout of 100 ms but has %s", rm.timeout) <ide> } <ide> }
2
Javascript
Javascript
remove unneeded code
01fb5c7006d1e2c6896d9cb80e664ecee0a1f675
<ide><path>lib/dependencies/URLDependency.js <ide> URLDependency.Template = class URLDependencyTemplate extends ModuleDependency.Te <ide> chunkGraph, <ide> moduleGraph, <ide> runtimeRequirements, <del> runtimeTemplate, <del> runtime <add> runtimeTemplate <ide> } = templateContext; <ide> const dep = /** @type {URLDependency} */ (dependency); <ide> <del> const connection = moduleGraph.getConnection(dep); <del> if (connection && !connection.isActive(runtime)) return; <del> <ide> runtimeRequirements.add(RuntimeGlobals.baseURI); <ide> runtimeRequirements.add(RuntimeGlobals.require); <ide>
1
Ruby
Ruby
remove useless conditional
f597dc5cf6a0a513e89144dd302e7e3cbac22a5d
<ide><path>actionpack/lib/action_dispatch/http/response.rb <ide> def to_ary <ide> end <ide> <ide> def rack_response(status, header) <del> header[SET_COOKIE] = header[SET_COOKIE].join("\n") if header[SET_COOKIE].respond_to?(:join) <del> <ide> if NO_CONTENT_CODES.include?(@status) <ide> header.delete CONTENT_TYPE <ide> header.delete 'Content-Length'
1
Javascript
Javascript
pass testid down in modal
5050e7eaa17cb417baf7c20eb5c4406cce6790a5
<ide><path>Libraries/Modal/Modal.js <ide> class Modal extends React.Component<Props> { <ide> // $FlowFixMe[method-unbinding] added when improving typing for this parameters <ide> onStartShouldSetResponder={this._shouldSetResponder} <ide> supportedOrientations={this.props.supportedOrientations} <del> onOrientationChange={this.props.onOrientationChange}> <add> onOrientationChange={this.props.onOrientationChange} <add> testID={this.props.testID}> <ide> <VirtualizedListContextResetter> <ide> <ScrollView.Context.Provider value={null}> <ide> <View
1
Ruby
Ruby
support more methods
675264a4493586794c942acf3d9db896fd9453f2
<ide><path>activestorage/app/models/active_storage/attachment.rb <ide> class ActiveStorage::Attachment < ActiveStorage::Record <ide> after_create_commit :mirror_blob_later, :analyze_blob_later <ide> after_destroy_commit :purge_dependent_blob_later <ide> <del> scope :with_all_variant_records, -> { includes(blob: :variant_records) } <add> scope :with_all_variant_records, -> { includes(blob: { variant_records: { image_attachment: :blob } }) } <ide> <ide> # Synchronously deletes the attachment and {purges the blob}[rdoc-ref:ActiveStorage::Blob#purge]. <ide> def purge <ide><path>activestorage/lib/active_storage/attached/model.rb <ide> def deprecate(action) <ide> <ide> scope :"with_attached_#{name}", -> { <ide> if ActiveStorage.track_variants <del> includes("#{name}_attachments": { blob: :variant_records }) <add> includes("#{name}_attachments": { blob: { variant_records: { image_attachment: :blob } } }) <ide> else <ide> includes("#{name}_attachments": :blob) <ide> end <ide><path>activestorage/test/models/variant_with_record_test.rb <ide> class ActiveStorage::VariantWithRecordTest < ActiveSupport::TestCase <ide> assert_equal "local_public", variant.image.blob.service_name <ide> end <ide> <del> test "eager loading is supported" do <add> test "eager loading" do <ide> user = User.create!(name: "Josh") <ide> <ide> blob1 = directly_upload_file_blob(filename: "racecar.jpg") <ide> class ActiveStorage::VariantWithRecordTest < ActiveSupport::TestCase <ide> user.reload <ide> <ide> assert_no_difference -> { ActiveStorage::VariantRecord.count } do <del> assert_queries(5) do <del> # 5 queries: <add> assert_queries(9) do <add> # 9 queries: <ide> # attachments (vlogs) x 1 <ide> # blob x 2 <del> # variant record x 2 <del> user.vlogs.map do |vlog| <del> vlog.representation(resize_to_limit: [100, 100]).processed <add> # variant record x 1 per blob <add> # attachment x 1 per variant record <add> # variant record x 1 per variant record attachment <add> user.vlogs.each do |vlog| <add> rep = vlog.representation(resize_to_limit: [100, 100]) <add> rep.processed <add> rep.key <add> rep.url <ide> end <ide> end <ide> end <ide> <ide> user.reload <ide> <ide> assert_no_difference -> { ActiveStorage::VariantRecord.count } do <del> assert_queries(3) do <del> # 3 queries: <add> assert_queries(7) do <add> # 7 queries: <ide> # attachments (vlogs) x 1 <ide> # blob x 1 <ide> # variant record x 1 <del> user.vlogs.includes(blob: :variant_records).map do |vlog| <del> vlog.representation(resize_to_limit: [100, 100]).processed <add> # attachment -> blob x 1 per variant record (so 2) <add> user.vlogs.includes(blob: :variant_records).each do |vlog| <add> rep = vlog.representation(resize_to_limit: [100, 100]) <add> rep.processed <add> rep.key <add> rep.url <ide> end <ide> end <ide> end <ide> <ide> user.reload <ide> <ide> assert_no_difference -> { ActiveStorage::VariantRecord.count } do <del> assert_queries(3) do <del> # 3 queries: <add> assert_queries(5) do <add> # 5 queries: <ide> # attachments (vlogs) x 1 <del> # blob x 1 <del> # variant record x 1 <del> user.vlogs.with_all_variant_records.map do |vlog| <del> vlog.representation(resize_to_limit: [100, 100]).processed <add> # blobs for the vlogs x 1 <add> # variant records for the blobs x 1 <add> # attachments for the variant records x 1 <add> # blobs for the attachments for the variant records x 1 <add> user.vlogs.includes(blob: { variant_records: { image_attachment: :blob } }).each do |vlog| <add> rep = vlog.representation(resize_to_limit: [100, 100]) <add> rep.processed <add> rep.key <add> rep.url <ide> end <ide> end <ide> end <ide> <ide> user.reload <ide> <ide> assert_no_difference -> { ActiveStorage::VariantRecord.count } do <del> assert_queries(4) do <del> # 4 queries: <add> assert_queries(5) do <add> # 5 queries: <add> # attachments (vlogs) x 1 <add> # blobs for the vlogs x 1 <add> # variant records for the blobs x 1 <add> # attachments for the variant records x 1 <add> # blobs for the attachments for the variant records x 1 <add> user.vlogs.with_all_variant_records.each do |vlog| <add> rep = vlog.representation(resize_to_limit: [100, 100]) <add> rep.processed <add> rep.key <add> rep.url <add> end <add> end <add> end <add> <add> user.reload <add> <add> assert_no_difference -> { ActiveStorage::VariantRecord.count } do <add> assert_queries(6) do <add> # 6 queries: <ide> # user x 1 <ide> # attachments (vlogs) x 1 <del> # blob x 1 <del> # variant record x 1 <del> User.where(id: user.id).with_attached_vlogs.map do |u| <add> # blobs for the vlogs x 1 <add> # variant records for the blobs x 1 <add> # attachments for the variant records x 1 <add> # blobs for the attachments for the variant records x 1 <add> User.where(id: user.id).with_attached_vlogs.each do |u| <ide> u.vlogs.map do |vlog| <del> vlog.representation(resize_to_limit: [100, 100]).processed <add> rep = vlog.representation(resize_to_limit: [100, 100]) <add> rep.processed <add> rep.key <add> rep.url <ide> end <ide> end <ide> end <ide> end <add> <add> user.reload <add> <add> assert_difference -> { ActiveStorage::VariantRecord.count }, +2 do <add> # More queries here because we are creating a different variant. <add> # The second time we load this variant, we are back down to just 3 queries. <add> <add> assert_queries(9, matcher: /SELECT/) do <add> # 9 queries: <add> # attachments (vlogs) initial load x 1 <add> # blob x 1 (gets both records) <add> # variant record x 1 (gets both records) <add> # 2x get blob, attachment, variant records again, this happens when loading the new blob inside `VariantWithRecord#key` <add> user.vlogs.with_all_variant_records.each do |vlog| <add> rep = vlog.representation(resize_to_limit: [200, 200]) <add> rep.processed <add> rep.key <add> rep.url <add> end <add> end <add> <add> user.reload <add> <add> assert_queries(5) do <add> user.vlogs.with_all_variant_records.each do |vlog| <add> rep = vlog.representation(resize_to_limit: [200, 200]) <add> rep.processed <add> rep.key <add> rep.url <add> end <add> end <add> end <ide> end <ide> end <ide><path>activestorage/test/test_helper.rb <ide> class ActiveSupport::TestCase <ide> ActiveStorage::Current.reset <ide> end <ide> <del> def assert_queries(expected_count) <add> def assert_queries(expected_count, matcher: nil) <ide> ActiveRecord::Base.connection.materialize_transactions <ide> <ide> queries = [] <ide> ActiveSupport::Notifications.subscribe("sql.active_record") do |*, payload| <del> queries << payload[:sql] unless %w[ SCHEMA TRANSACTION ].include?(payload[:name]) <add> queries << payload[:sql] if %w[ SCHEMA TRANSACTION ].exclude?(payload[:name]) && (matcher.nil? || payload[:sql].match(matcher)) <ide> end <ide> <ide> yield.tap do <del> assert_equal expected_count, queries.size, "#{queries.size} instead of #{expected_count} queries were executed. #{queries.inspect}" <add> assert_equal expected_count, queries.size, "#{queries.size} instead of #{expected_count} queries were executed. Queries: #{queries.join("\n\n")}" <ide> end <ide> end <ide>
4
Java
Java
support multi sources for images
65f4988ddf480a78667a1856b728174c9ac2fb9f
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/RCTImageView.java <ide> <ide> import com.facebook.csslayout.Spacing; <ide> import com.facebook.drawee.drawable.ScalingUtils.ScaleType; <add>import com.facebook.react.bridge.ReadableArray; <ide> import com.facebook.react.uimanager.PixelUtil; <ide> import com.facebook.react.uimanager.annotations.ReactProp; <ide> import com.facebook.react.uimanager.ViewProps; <ide> public void setShouldNotifyLoadEvents(boolean shouldNotifyLoadEvents) { <ide> } <ide> <ide> @ReactProp(name = "src") <del> public void setSource(@Nullable String source) { <add> public void setSource(@Nullable ReadableArray sources) { <add> final String source = <add> (sources == null || sources.size() == 0) ? null : sources.getMap(0).getString("uri"); <ide> getMutableDrawImage().setImageRequest( <ide> ImageRequestHelper.createImageRequest(getThemedContext(), source)); <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/RCTTextInlineImage.java <ide> import android.text.SpannableStringBuilder; <ide> import android.text.Spanned; <ide> <add>import com.facebook.react.bridge.ReadableArray; <ide> import com.facebook.react.uimanager.annotations.ReactProp; <ide> <ide> /** <ide> protected void performCollectAttachDetachListeners(StateBuilder stateBuilder) { <ide> } <ide> <ide> @ReactProp(name = "src") <del> public void setSource(@Nullable String source) { <add> public void setSource(@Nullable ReadableArray sources) { <add> final String source = <add> (sources == null || sources.size() == 0) ? null : sources.getMap(0).getString("uri"); <ide> getMutableSpan().setImageRequest( <ide> ImageRequestHelper.createImageRequest(getThemedContext(), source)); <ide> }
2
Javascript
Javascript
delay listen emit
d64e070e26cc3545367ef38098a0fe963be0ea8d
<ide><path>lib/net_uv.js <ide> function listenip(self, ip, port) { <ide> self.emit('error', errnoException(errno, 'listen')); <ide> } else { <ide> self._handle.listen(self._backlog || 128); <del> self.emit('listening'); <add> process.nextTick(function() { <add> self.emit('listening'); <add> }); <ide> } <ide> } <ide> <ide> Server.prototype.listen = function() { <ide> // Don't bind(). OS will assign a port with INADDR_ANY. <ide> // The port can be found with server.address() <ide> this._handle.listen(self._backlog || 128); <del> this.emit('listening'); <add> process.nextTick(function() { <add> self.emit('listening'); <add> }); <ide> <ide> } else if (typeof arguments[1] == 'undefined') { <ide> // The first argument is the port, no IP given.
1
Text
Text
specify width and height for image(remote source)
6b2a49e73e52bf40ab82f792e7748aa36847c17f
<ide><path>docs/Props.md <ide> class Bananas extends Component { <ide> uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg' <ide> }; <ide> return ( <del> <Image source={pic} /> <add> <Image source={pic} style={{width: 193, height: 110}}/> <ide> ); <ide> } <ide> }
1
Javascript
Javascript
convert code samples to js
08ca84e58732e10bece209dd2d677d33b18838d7
<ide><path>src/text-editor.js <ide> const DEFAULT_NON_WORD_CHARACTERS = "/\\()\"':,.;<>~!@#$%^&*|+=[]{}`?-…" <ide> // then be called with all current editor instances and also when any editor is <ide> // created in the future. <ide> // <del>// ```coffee <del>// atom.workspace.observeTextEditors (editor) -> <add>// ```js <add>// atom.workspace.observeTextEditors(editor => { <ide> // editor.insertText('Hello World') <add>// }) <ide> // ``` <ide> // <ide> // ## Buffer vs. Screen Coordinates <ide> class TextEditor { <ide> // <ide> // ## Examples <ide> // <del> // ```coffee <del> // editor.clipBufferPosition([-1, -1]) # -> `[0, 0]` <add> // ```js <add> // editor.clipBufferPosition([-1, -1]) // -> `[0, 0]` <ide> // <del> // # When the line at buffer row 2 is 10 characters long <del> // editor.clipBufferPosition([2, Infinity]) # -> `[2, 10]` <add> // // When the line at buffer row 2 is 10 characters long <add> // editor.clipBufferPosition([2, Infinity]) // -> `[2, 10]` <ide> // ``` <ide> // <ide> // * `bufferPosition` The {Point} representing the position to clip. <ide> class TextEditor { <ide> // <ide> // ## Examples <ide> // <del> // ```coffee <del> // editor.clipScreenPosition([-1, -1]) # -> `[0, 0]` <add> // ```js <add> // editor.clipScreenPosition([-1, -1]) // -> `[0, 0]` <ide> // <del> // # When the line at screen row 2 is 10 characters long <del> // editor.clipScreenPosition([2, Infinity]) # -> `[2, 10]` <add> // // When the line at screen row 2 is 10 characters long <add> // editor.clipScreenPosition([2, Infinity]) // -> `[2, 10]` <ide> // ``` <ide> // <ide> // * `screenPosition` The {Point} representing the position to clip.
1
Python
Python
adjust assertraisesregex argument
78688e7bc057ecb8a9ddcfdfbe157737aadf81a2
<ide><path>keras/layers/normalization/batch_normalization_test.py <ide> def test_basic_batchnorm_v2_input_shape_and_virtual_batch_size(self): <ide> norm = batch_normalization.BatchNormalization(virtual_batch_size=8) <ide> _ = norm(np.ones((1, 28, 28))) <ide> <del> with self.assertRaisesRegex(Exception, "requested shape requires"): <add> with self.assertRaisesRegex(Exception, "Reshape"): <ide> norm = batch_normalization.BatchNormalization(virtual_batch_size=8) <ide> _ = norm(np.ones((1, 28, 28)), training=True) <ide>
1
PHP
PHP
change default job attempts from unlimited to 1
a37d88a3a3c193882f29aab88b33accbd995c749
<ide><path>src/Illuminate/Queue/Console/ListenCommand.php <ide> class ListenCommand extends Command <ide> {--queue= : The queue to listen on} <ide> {--sleep=3 : Number of seconds to sleep when no job is available} <ide> {--timeout=60 : The number of seconds a child process can run} <del> {--tries=0 : Number of times to attempt a job before logging it failed}'; <add> {--tries=1 : Number of times to attempt a job before logging it failed}'; <ide> <ide> /** <ide> * The console command description. <ide><path>src/Illuminate/Queue/Console/WorkCommand.php <ide> class WorkCommand extends Command <ide> {--memory=128 : The memory limit in megabytes} <ide> {--sleep=3 : Number of seconds to sleep when no job is available} <ide> {--timeout=60 : The number of seconds a child process can run} <del> {--tries=0 : Number of times to attempt a job before logging it failed}'; <add> {--tries=1 : Number of times to attempt a job before logging it failed}'; <ide> <ide> /** <ide> * The console command description. <ide><path>src/Illuminate/Queue/ListenerOptions.php <ide> class ListenerOptions extends WorkerOptions <ide> * @param bool $force <ide> * @return void <ide> */ <del> public function __construct($environment = null, $delay = 0, $memory = 128, $timeout = 60, $sleep = 3, $maxTries = 0, $force = false) <add> public function __construct($environment = null, $delay = 0, $memory = 128, $timeout = 60, $sleep = 3, $maxTries = 1, $force = false) <ide> { <ide> $this->environment = $environment; <ide> <ide><path>src/Illuminate/Queue/WorkerOptions.php <ide> class WorkerOptions <ide> * @param bool $stopWhenEmpty <ide> * @return void <ide> */ <del> public function __construct($delay = 0, $memory = 128, $timeout = 60, $sleep = 3, $maxTries = 0, $force = false, $stopWhenEmpty = false) <add> public function __construct($delay = 0, $memory = 128, $timeout = 60, $sleep = 3, $maxTries = 1, $force = false, $stopWhenEmpty = false) <ide> { <ide> $this->delay = $delay; <ide> $this->sleep = $sleep; <ide><path>tests/Queue/QueueListenerTest.php <ide> public function testMakeProcessCorrectlyFormatsCommandLine() <ide> $this->assertInstanceOf(Process::class, $process); <ide> $this->assertEquals(__DIR__, $process->getWorkingDirectory()); <ide> $this->assertEquals(3, $process->getTimeout()); <del> $this->assertEquals($escape.PHP_BINARY.$escape." {$escape}artisan{$escape} {$escape}queue:work{$escape} {$escape}connection{$escape} {$escape}--once{$escape} {$escape}--queue=queue{$escape} {$escape}--delay=1{$escape} {$escape}--memory=2{$escape} {$escape}--sleep=3{$escape} {$escape}--tries=0{$escape}", $process->getCommandLine()); <add> $this->assertEquals($escape.PHP_BINARY.$escape." {$escape}artisan{$escape} {$escape}queue:work{$escape} {$escape}connection{$escape} {$escape}--once{$escape} {$escape}--queue=queue{$escape} {$escape}--delay=1{$escape} {$escape}--memory=2{$escape} {$escape}--sleep=3{$escape} {$escape}--tries=1{$escape}", $process->getCommandLine()); <ide> } <ide> <ide> public function testMakeProcessCorrectlyFormatsCommandLineWithAnEnvironmentSpecified() <ide> public function testMakeProcessCorrectlyFormatsCommandLineWithAnEnvironmentSpeci <ide> $this->assertInstanceOf(Process::class, $process); <ide> $this->assertEquals(__DIR__, $process->getWorkingDirectory()); <ide> $this->assertEquals(3, $process->getTimeout()); <del> $this->assertEquals($escape.PHP_BINARY.$escape." {$escape}artisan{$escape} {$escape}queue:work{$escape} {$escape}connection{$escape} {$escape}--once{$escape} {$escape}--queue=queue{$escape} {$escape}--delay=1{$escape} {$escape}--memory=2{$escape} {$escape}--sleep=3{$escape} {$escape}--tries=0{$escape} {$escape}--env=test{$escape}", $process->getCommandLine()); <add> $this->assertEquals($escape.PHP_BINARY.$escape." {$escape}artisan{$escape} {$escape}queue:work{$escape} {$escape}connection{$escape} {$escape}--once{$escape} {$escape}--queue=queue{$escape} {$escape}--delay=1{$escape} {$escape}--memory=2{$escape} {$escape}--sleep=3{$escape} {$escape}--tries=1{$escape} {$escape}--env=test{$escape}", $process->getCommandLine()); <ide> } <ide> <ide> public function testMakeProcessCorrectlyFormatsCommandLineWhenTheConnectionIsNotSpecified() <ide> public function testMakeProcessCorrectlyFormatsCommandLineWhenTheConnectionIsNot <ide> $this->assertInstanceOf(Process::class, $process); <ide> $this->assertEquals(__DIR__, $process->getWorkingDirectory()); <ide> $this->assertEquals(3, $process->getTimeout()); <del> $this->assertEquals($escape.PHP_BINARY.$escape." {$escape}artisan{$escape} {$escape}queue:work{$escape} {$escape}--once{$escape} {$escape}--queue=queue{$escape} {$escape}--delay=1{$escape} {$escape}--memory=2{$escape} {$escape}--sleep=3{$escape} {$escape}--tries=0{$escape} {$escape}--env=test{$escape}", $process->getCommandLine()); <add> $this->assertEquals($escape.PHP_BINARY.$escape." {$escape}artisan{$escape} {$escape}queue:work{$escape} {$escape}--once{$escape} {$escape}--queue=queue{$escape} {$escape}--delay=1{$escape} {$escape}--memory=2{$escape} {$escape}--sleep=3{$escape} {$escape}--tries=1{$escape} {$escape}--env=test{$escape}", $process->getCommandLine()); <ide> } <ide> }
5
Ruby
Ruby
indicate action that failed in yamlcolumn
1c1aba775826589b5038959120ea57e050e38123
<ide><path>activerecord/lib/active_record/coders/yaml_column.rb <ide> def initialize(attr_name, object_class = Object) <ide> def dump(obj) <ide> return if obj.nil? <ide> <del> assert_valid_value(obj) <add> assert_valid_value(obj, action: "dump") <ide> YAML.dump obj <ide> end <ide> <ide> def load(yaml) <ide> return yaml unless yaml.is_a?(String) && /^---/.match?(yaml) <ide> obj = YAML.load(yaml) <ide> <del> assert_valid_value(obj) <add> assert_valid_value(obj, action: "load") <ide> obj ||= object_class.new if object_class != Object <ide> <ide> obj <ide> end <ide> <del> def assert_valid_value(obj) <add> def assert_valid_value(obj, action:) <ide> unless obj.nil? || obj.is_a?(object_class) <ide> raise SerializationTypeMismatch, <del> "Attribute `#{@attr_name}` was supposed to be a #{object_class}, but was a #{obj.class}. -- #{obj.inspect}" <add> "can't #{action} `#{@attr_name}`: was supposed to be a #{object_class}, but was a #{obj.class}. -- #{obj.inspect}" <ide> end <ide> end <ide> <ide><path>activerecord/lib/active_record/type/serialized.rb <ide> def accessor <ide> <ide> def assert_valid_value(value) <ide> if coder.respond_to?(:assert_valid_value) <del> coder.assert_valid_value(value) <add> coder.assert_valid_value(value, action: "serialize") <ide> end <ide> end <ide> <ide><path>activerecord/test/cases/coders/yaml_column_test.rb <ide> def test_initialize_takes_class <ide> end <ide> <ide> def test_type_mismatch_on_different_classes_on_dump <del> coder = YAMLColumn.new("attr_name", Array) <add> coder = YAMLColumn.new("tags", Array) <ide> error = assert_raises(SerializationTypeMismatch) do <ide> coder.dump("a") <ide> end <del> assert_equal %{Attribute `attr_name` was supposed to be a Array, but was a String. -- "a"}, error.to_s <add> assert_equal %{can't dump `tags`: was supposed to be a Array, but was a String. -- "a"}, error.to_s <ide> end <ide> <ide> def test_type_mismatch_on_different_classes <del> coder = YAMLColumn.new("attr_name", Array) <add> coder = YAMLColumn.new("tags", Array) <ide> error = assert_raises(SerializationTypeMismatch) do <ide> coder.load "--- foo" <ide> end <del> assert_equal %{Attribute `attr_name` was supposed to be a Array, but was a String. -- "foo"}, error.to_s <add> assert_equal %{can't load `tags`: was supposed to be a Array, but was a String. -- "foo"}, error.to_s <ide> end <ide> <ide> def test_nil_is_ok <ide><path>activerecord/test/cases/serialized_attribute_test.rb <ide> def test_unexpected_serialized_type <ide> error = assert_raise(ActiveRecord::SerializationTypeMismatch) do <ide> topic.content <ide> end <del> expected = "Attribute `content` was supposed to be a Array, but was a Hash. -- {:zomg=>true}" <add> expected = "can't load `content`: was supposed to be a Array, but was a Hash. -- {:zomg=>true}" <ide> assert_equal expected, error.to_s <ide> end <ide>
4
Mixed
Javascript
add missing deprecation code
b3f35e2c70c7d1e3ee7b4c3fd74672adceb16c52
<ide><path>doc/api/deprecations.md <ide> Previously, `index.js` and extension searching lookups would apply to <ide> With this deprecation, all ES module main entry point resolutions require <ide> an explicit [`"exports"` or `"main"` entry][] with the exact file extension. <ide> <del>### DEP0XXX: Extension PerformanceEntry properties <add>### DEP0152: Extension PerformanceEntry properties <ide> <!-- YAML <ide> changes: <ide> - version: REPLACEME <ide><path>lib/internal/perf/observe.js <ide> function observerCallback(name, type, startTime, duration, details) { <ide> enumerable: true, <ide> get: deprecate(() => { <ide> return entry[kDeprecatedFields].get(key); <del> }, kDeprecationMessage, 'DEP0XXX'), <add> }, kDeprecationMessage, 'DEP0152'), <ide> set: deprecate((value) => { <ide> entry[kDeprecatedFields].set(key, value); <del> }, kDeprecationMessage, 'DEP0XXX'), <add> }, kDeprecationMessage, 'DEP0152'), <ide> }; <ide> } <ide> ObjectDefineProperties(entry, props);
2
Javascript
Javascript
expose xhr instance
ab361ac169bc39524e2b5d9fa1be64a93fef0546
<ide><path>lib/adapters/http.js <ide> module.exports = function httpAdapter(resolve, reject, config) { <ide> status: res.statusCode, <ide> statusText: res.statusMessage, <ide> headers: res.headers, <del> config: config <add> config: config, <add> request: req <ide> }; <ide> <ide> // Resolve or reject the Promise based on the status <ide><path>lib/adapters/xhr.js <ide> module.exports = function xhrAdapter(resolve, reject, config) { <ide> status: request.status === 1223 ? 204 : request.status, <ide> statusText: request.status === 1223 ? 'No Content' : request.statusText, <ide> headers: responseHeaders, <del> config: config <add> config: config, <add> request: request <ide> }; <ide> <ide> // Resolve or reject the Promise based on the status
2
Python
Python
replace assigment with augmented assignment
7c206a82a6f074abcc4898a005ecd2c84a920054
<ide><path>airflow/providers/amazon/aws/hooks/datasync.py <ide> def wait_for_task_execution(self, task_execution_arn, max_iterations=2 * 180): <ide> ) <ide> status = task_execution["Status"] <ide> self.log.info("status=%s", status) <del> iterations = iterations - 1 <add> iterations -= 1 <ide> if status in self.TASK_EXECUTION_FAILURE_STATES: <ide> break <ide> if status in self.TASK_EXECUTION_SUCCESS_STATES: <ide><path>airflow/providers/amazon/aws/hooks/logs.py <ide> def get_log_events(self, log_group, log_stream_name, start_time=0, skip=0, start <ide> events = events[skip:] <ide> skip = 0 <ide> else: <del> skip = skip - event_count <add> skip -= event_count <ide> events = [] <ide> <ide> yield from events <ide><path>airflow/providers/amazon/aws/hooks/sagemaker.py <ide> def check_status(self, job_name, key, <ide> <ide> while running: <ide> time.sleep(check_interval) <del> sec = sec + check_interval <add> sec += check_interval <ide> <ide> try: <ide> response = describe_function(job_name) <ide> def check_training_status_with_log(self, job_name, non_terminal_states, failed_s <ide> <ide> while True: <ide> time.sleep(check_interval) <del> sec = sec + check_interval <add> sec += check_interval <ide> <ide> state, last_description, last_describe_job_call = \ <ide> self.describe_training_job_with_log(job_name, positions, stream_names, <ide><path>airflow/providers/apache/druid/hooks/druid.py <ide> def submit_indexing_job(self, json_index_spec: Dict[str, Any]) -> None: <ide> <ide> time.sleep(self.timeout) <ide> <del> sec = sec + self.timeout <add> sec += self.timeout <ide> <ide> status = req_status.json()['status']['status'] <ide> if status == 'RUNNING': <ide><path>airflow/providers/apache/hive/hooks/hive.py <ide> def run_cli(self, <ide> <ide> with TemporaryDirectory(prefix='airflow_hiveop_') as tmp_dir: <ide> with NamedTemporaryFile(dir=tmp_dir) as f: <del> hql = hql + '\n' <add> hql += '\n' <ide> f.write(hql.encode('UTF-8')) <ide> f.flush() <ide> hive_cmd = self._prepare_cli_cmd() <ide><path>airflow/providers/apache/spark/hooks/spark_submit.py <ide> def _start_driver_status_tracking(self) -> None: <ide> <ide> if returncode: <ide> if missed_job_status_reports < max_missed_job_status_reports: <del> missed_job_status_reports = missed_job_status_reports + 1 <add> missed_job_status_reports += 1 <ide> else: <ide> raise AirflowException( <ide> "Failed to poll for the driver status {} times: returncode = {}" <ide><path>airflow/providers/cncf/kubernetes/operators/kubernetes_pod.py <ide> def handle_pod_overlap(self, labels, try_numbers_match, launcher, pod_list): <ide> log_line = "found a running pod with labels {} but a different try_number.".format(labels) <ide> <ide> if self.reattach_on_restart: <del> log_line = log_line + " Will attach to this pod and monitor instead of starting new one" <add> log_line += " Will attach to this pod and monitor instead of starting new one" <ide> self.log.info(log_line) <ide> final_state, result = self.monitor_launched_pod(launcher, pod_list.items[0]) <ide> else: <del> log_line = log_line + "creating pod with labels {} and launcher {}".format(labels, launcher) <add> log_line += "creating pod with labels {} and launcher {}".format(labels, launcher) <ide> self.log.info(log_line) <ide> final_state, _, result = self.create_new_pod_for_operator(labels, launcher) <ide> return final_state, result <ide><path>airflow/providers/google/cloud/hooks/bigquery.py <ide> def run_grant_dataset_view_access( <ide> 'Granting table %s:%s.%s authorized view access to %s:%s dataset.', <ide> view_project, view_dataset, view_table, project_id, source_dataset <ide> ) <del> dataset.access_entries = dataset.access_entries + [view_access] <add> dataset.access_entries += [view_access] <ide> dataset = self.update_dataset( <ide> fields=["access"], <ide> dataset_resource=dataset.to_api_repr(), <ide> def cancel_job( <ide> <ide> job_complete = False <ide> while polling_attempts < max_polling_attempts and not job_complete: <del> polling_attempts = polling_attempts + 1 <add> polling_attempts += 1 <ide> job_complete = self.poll_job_complete(job_id) <ide> if job_complete: <ide> self.log.info('Job successfully canceled: %s, %s', project_id, job_id) <ide><path>airflow/providers/jenkins/example_dags/example_jenkins_job_trigger.py <ide> def grab_artifact_from_jenkins(**context): <ide> # The JenkinsJobTriggerOperator store the job url in the xcom variable corresponding to the task <ide> # You can then use it to access things or to get the job number <ide> # This url looks like : http://jenkins_url/job/job_name/job_number/ <del> url = url + "artifact/myartifact.xml" # Or any other artifact name <add> url += "artifact/myartifact.xml" # Or any other artifact name <ide> request = Request(url) <ide> response = jenkins_server.jenkins_open(request) <ide> return response # We store the artifact content in a xcom variable for later use <ide><path>airflow/providers/jenkins/operators/jenkins_job_trigger.py <ide> def poll_job_in_queue(self, location: str, jenkins_server: Jenkins) -> int: <ide> :return: The build_number corresponding to the triggered job <ide> """ <ide> try_count = 0 <del> location = location + '/api/json' <add> location += '/api/json' <ide> # TODO Use get_queue_info instead <ide> # once it will be available in python-jenkins (v > 0.4.15) <ide> self.log.info('Polling jenkins queue at the url %s', location) <ide><path>airflow/providers/oracle/transfers/oracle_to_oracle.py <ide> def _execute(self, src_hook, dest_hook, context): <ide> rows_total = 0 <ide> rows = cursor.fetchmany(self.rows_chunk) <ide> while len(rows) > 0: <del> rows_total = rows_total + len(rows) <add> rows_total += len(rows) <ide> dest_hook.bulk_insert_rows(self.destination_table, rows, <ide> target_fields=target_fields, <ide> commit_every=self.rows_chunk) <ide><path>airflow/providers/singularity/operators/singularity.py <ide> def execute(self, context): <ide> <ide> # Prepare list of binds <ide> for bind in self.volumes: <del> self.options = self.options + ['--bind', bind] <add> self.options += ['--bind', bind] <ide> <ide> # Does the user want a custom working directory? <ide> if self.working_dir is not None: <del> self.options = self.options + ['--workdir', self.working_dir] <add> self.options += ['--workdir', self.working_dir] <ide> <ide> # Export environment before instance is run <ide> for enkey, envar in self.environment.items():
12
Text
Text
add text "advanced android development"
4446ed1099613d960db2c9ba84d22fd5e8a0332c
<ide><path>client/src/pages/guide/english/android-development/core-components/index.md <ide> A _broadcast receiver_ is another component without user interface (except an op <ide> ## [Content providers](https://developer.android.com/guide/topics/providers/content-providers) <ide> A _content provider_ is a component used to manage a set of app data to share with other applications. Each item saved in the content provider is identified by a URI scheme. <ide> <del>For detailed information about the topic, see the official [Android fundamentals](https://developer.android.com/guide/components/fundamentals) documentation <ide>\ No newline at end of file <add>For detailed information about the topic, see the official [Android fundamentals](https://developer.android.com/guide/components/fundamentals) documentation. <add> <add>## Advanced Android Development <add>To learn advanced Android programming concepts, see Google's [Advanced Android Development](https://developers.google.com/training/courses/android-advanced) course.
1
Ruby
Ruby
require different core extensions correctly
1a4d8736ce7294d2ecfc46172cc8de3b4591ac23
<ide><path>activesupport/lib/active_support/i18n.rb <add>require 'active_support/core_ext/hash/deep_merge' <add>require 'active_support/core_ext/hash/except' <add>require 'active_support/core_ext/hash/slice' <ide> begin <del> require 'active_support/core_ext/hash/deep_merge' <del> require 'active_support/core_ext/hash/except' <del> require 'active_support/core_ext/hash/slice' <ide> require 'i18n' <del> require 'active_support/lazy_load_hooks' <ide> rescue LoadError => e <ide> $stderr.puts "The i18n gem is not available. Please add it to your Gemfile and run bundle install" <ide> raise e <ide> end <add>require 'active_support/lazy_load_hooks' <ide> <ide> ActiveSupport.run_load_hooks(:i18n) <ide> I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml"
1
Javascript
Javascript
fix uniforms to support fog
d9fa714202b9f9c687ffe848751e1565790adb56
<ide><path>examples/js/loaders/LDrawLoader.js <ide> THREE.LDrawLoader = ( function () { <ide> edgeMaterial.userData.conditionalEdgeMaterial = new THREE.ShaderMaterial( { <ide> vertexShader: conditionalLineVertShader, <ide> fragmentShader: conditionalLineFragShader, <del> uniforms: { <del> diffuse: { <del> value: new THREE.Color( edgeColour ) <del> }, <del> opacity: { <del> value: alpha <add> uniforms: THREE.UniformsUtils.merge( [ <add> THREE.UniformsLib.fog, <add> { <add> diffuse: { <add> value: new THREE.Color( edgeColour ) <add> }, <add> opacity: { <add> value: alpha <add> } <ide> } <del> }, <add> ] ), <add> fog: true, <ide> transparent: isTransparent, <ide> depthWrite: ! isTransparent <ide> } );
1
PHP
PHP
remove insert and update methods from eloquent
21efdbf69b031935f812076f106d7aff5c3b7aaf
<ide><path>system/db/eloquent.php <ide> public function save() <ide> $this->timestamp(); <ide> } <ide> <del> $result = ($this->exists) ? $this->update() : $this->insert(); <add> if ($this->exists) <add> { <add> $result = $this->query->where('id', '=', $this->attributes['id'])->update($this->dirty) == 1; <add> } <add> else <add> { <add> $this->attributes['id'] = $this->query->insert_get_id($this->attributes); <add> <add> $result = $this->exists = is_numeric($this->id); <add> } <ide> <ide> $this->dirty = array(); <ide> <ide> return $result; <ide> } <ide> <del> /** <del> * Update an existing model in the database. <del> * <del> * @return bool <del> */ <del> private function update() <del> { <del> return $this->query->where('id', '=', $this->attributes['id'])->update($this->dirty) == 1; <del> } <del> <del> /** <del> * Insert a new model into the database. <del> * <del> * @return bool <del> */ <del> private function insert() <del> { <del> $this->attributes['id'] = $this->query->insert_get_id($this->attributes); <del> <del> return $this->exists = is_numeric($this->id); <del> } <del> <ide> /** <ide> * Delete a model from the database. <ide> * <ide> public function delete($id = null) <ide> return Query::table(static::table(get_class($this)))->delete($this->id); <ide> } <ide> <del> return 0; <add> return $this->query->delete(); <ide> } <ide> <ide> /**
1
Javascript
Javascript
get new infra in place
235193ef315cf2351e942da277b3d3ace245a400
<ide><path>packages/ember-runtime/tests/mixins/array_test.js <ide> const TestArray = EmberObject.extend(EmberArray, { <ide> <ide> ArrayTests.extend({ <ide> <del> name: 'Basic Mutable Array', <add> name: 'Basic Ember Array', <ide> <ide> newObject(ary) { <ide> ary = ary ? ary.slice() : this.newFixture(3); <ide><path>packages/ember-runtime/tests/suites/array.js <ide> const ArrayTests = Suite.extend({ <ide> observerClass: ArrayTestsObserverClass <ide> }); <ide> <del>import anyTests from './array/any'; <add>// import './array/any'; <ide> import compactTests from './array/compact'; <ide> import everyTests from './array/every'; <ide> import filterTests from './array/filter'; <ide> import uniqByTests from './array/uniqBy'; <ide> import uniqTests from './array/uniq'; <ide> import withoutTests from './array/without'; <ide> <del>ArrayTests.importModuleTests(anyTests); <add>// ArrayTests.importModuleTests(anyTests); <ide> ArrayTests.importModuleTests(compactTests); <ide> ArrayTests.importModuleTests(everyTests); <ide> ArrayTests.importModuleTests(filterTests); <ide><path>packages/ember-runtime/tests/suites/array/any.js <del>import { SuiteModuleBuilder } from '../suite'; <add>// import { SuiteModuleBuilder } from '../suite'; <ide> import { A as emberA } from '../../../mixins/array'; <add>import { get } from 'ember-metal'; <add>import { AbstractTestCase, moduleFor } from 'internal-test-helpers'; <add>import { generateGuid } from 'ember-utils'; <add>import ArrayProxy from '../../../system/array_proxy'; <ide> <del>const suite = SuiteModuleBuilder.create(); <add>// const suite = SuiteModuleBuilder.create(); <ide> <ide> // .......................................................... <ide> // any() <ide> // <ide> <del>suite.module('any'); <del> <del>suite.test('any should should invoke callback on each item as long as you return false', function(assert) { <del> let obj = this.newObject(); <del> let ary = this.toArray(obj); <del> let found = []; <del> let result; <del> <del> result = obj.any(function(i) { <del> found.push(i); <del> return false; <del> }); <del> assert.equal(result, false, 'return value of obj.any'); <del> assert.deepEqual(found, ary, 'items passed during any() should match'); <del>}); <del> <del>suite.test('any should stop invoking when you return true', function(assert) { <del> let obj = this.newObject(); <del> let ary = this.toArray(obj); <del> let cnt = ary.length - 2; <del> let exp = cnt; <del> let found = []; <del> let result; <del> <del> result = obj.any(function(i) { <del> found.push(i); <del> return --cnt <= 0; <del> }); <del> assert.equal(result, true, 'return value of obj.any'); <del> assert.equal(found.length, exp, 'should invoke proper number of times'); <del> assert.deepEqual(found, ary.slice(0, -2), 'items passed during any() should match'); <del>}); <del> <del>suite.test('any should return true if any object matches the callback', function(assert) { <del> let obj = emberA([0, 1, 2]); <del> let result; <del> <del> result = obj.any(i => !!i); <del> assert.equal(result, true, 'return value of obj.any'); <del>}); <del> <del>suite.test('any should return false if no object matches the callback', function(assert) { <del> let obj = emberA([0, null, false]); <del> let result; <del> <del> result = obj.any(i => !!i); <del> assert.equal(result, false, 'return value of obj.any'); <del>}); <del> <del>suite.test('any should produce correct results even if the matching element is undefined', function(assert) { <del> let obj = emberA([undefined]); <del> let result; <del> <del> result = obj.any(() => true); <del> assert.equal(result, true, 'return value of obj.any'); <del>}); <del> <del>export default suite; <add>// class AbstractArrayHelpers { <add>// newObject() { <add>// throw new Error('Must implement'); <add>// } <add> <add>// toArray() { <add>// throw new Error('Must implement'); <add>// } <add>// } <add> <add>// class AbstractArrayTests extends AbstractTestCase { <add>// constructor(ArrayHelpers) { <add>// super(); <add>// this.ArrayHelpers = ArrayHelpers; <add>// } <add> <add>// newObject() { <add>// return new this.ArrayHelpers().newObject(...arguments); <add>// } <add> <add>// toArray() { <add>// return new this.ArrayHelpers().toArray(...arguments); <add>// } <add>// } <add> <add>class NativeArrayHelpers { <add> newObject(ary) { <add> return emberA(ary ? ary.slice() : this.newFixture(3)); <add> } <add> <add> newFixture(cnt) { <add> let ret = []; <add> while (--cnt >= 0) { <add> ret.push(generateGuid()); <add> } <add> <add> return ret; <add> } <add> <add> mutate(obj) { <add> obj.pushObject(obj.length + 1); <add> } <add> <add> toArray(obj) { <add> return obj.slice(); <add> } <add>} <add> <add>class AbstractArrayHelper { <add> newFixture(cnt) { <add> let ret = []; <add> while (--cnt >= 0) { <add> ret.push(generateGuid()); <add> } <add> <add> return ret; <add> } <add>} <add> <add>class ArrayProxyHelpers extends AbstractArrayHelper { <add> newObject(ary) { <add> let ret = ary ? ary.slice() : this.newFixture(3); <add> return ArrayProxy.create({ content: emberA(ret) }); <add> } <add> <add> mutate(obj) { <add> obj.pushObject(get(obj, 'length') + 1); <add> } <add> <add> toArray(obj) { <add> return obj.toArray ? obj.toArray() : obj.slice(); <add> } <add>} <add> <add>// class ArrayProxyTests extends AbstractArrayTests { <add>// newObject(ary) { <add>// let ret = ary ? ary.slice() : this.newFixture(3); <add>// return ArrayProxy.create({ content: emberA(ret) }); <add>// } <add> <add>// mutate(obj) { <add>// obj.pushObject(get(obj, 'length') + 1); <add>// } <add> <add>// toArray(obj) { <add>// return obj.toArray ? obj.toArray() : obj.slice(); <add>// } <add>// } <add> <add> <add>// function f(K, S) { <add>// return class K extends S { <add> <add>// }; <add>// } <add> <add>// moduleFor('any', f(class { <add>// d() { <add>// this.newObject(); <add>// } <add>// }, ArrayProxyTests)); <add> <add>class AnyTests extends AbstractTestCase { <add> '@test any should should invoke callback on each item as long as you return false'() { <add> let obj = this.newObject(); <add> let ary = this.toArray(obj); <add> let found = []; <add> let result; <add> <add> result = obj.any(function(i) { <add> found.push(i); <add> return false; <add> }); <add> <add> this.assert.equal(result, false, 'return value of obj.any'); <add> this.assert.deepEqual(found, ary, 'items passed during any() should match'); <add> } <add> <add> '@test any should stop invoking when you return true'() { <add> let obj = this.newObject(); <add> let ary = this.toArray(obj); <add> let cnt = ary.length - 2; <add> let exp = cnt; <add> let found = []; <add> let result; <add> <add> result = obj.any(function(i) { <add> found.push(i); <add> return --cnt <= 0; <add> }); <add> this.assert.equal(result, true, 'return value of obj.any'); <add> this.assert.equal(found.length, exp, 'should invoke proper number of times'); <add> this.assert.deepEqual(found, ary.slice(0, -2), 'items passed during any() should match'); <add> } <add> <add> '@test any should return true if any object matches the callback'() { <add> let obj = emberA([0, 1, 2]); <add> let result; <add> <add> result = obj.any(i => !!i); <add> this.assert.equal(result, true, 'return value of obj.any'); <add> } <add> <add> '@test any should produce correct results even if the matching element is undefined'(assert) { <add> let obj = emberA([undefined]); <add> let result; <add> <add> result = obj.any(() => true); <add> assert.equal(result, true, 'return value of obj.any'); <add> } <add>} <add> <add>moduleFor('[NEW] NativeArray: any', AnyTests, NativeArrayHelpers); <add>moduleFor('[NEW] ArrayProxy: any', AnyTests, ArrayProxyHelpers); <ide>\ No newline at end of file <ide><path>packages/internal-test-helpers/lib/apply-mixins.js <ide> export default function applyMixins(TestClass, ...mixins) { <ide> generator.cases.forEach((value, idx) => { <ide> assign(mixin, generator.generate(value, idx)); <ide> }); <add> <add> assign(TestClass.prototype, mixin); <add> } else if (typeof mixinOrGenerator === 'function') { <add> mixin = new mixinOrGenerator(); <add> assign(TestClass.prototype, mixin.__proto__); <ide> } else { <ide> mixin = mixinOrGenerator; <add> assign(TestClass.prototype, mixin); <ide> } <ide> <del> assign(TestClass.prototype, mixin); <add> <ide> }); <ide> <ide> return TestClass; <ide><path>packages/internal-test-helpers/lib/module-for.js <ide> export default function moduleFor(description, TestClass, ...mixins) { <ide> } <ide> }); <ide> <del> applyMixins(TestClass, mixins); <add> if (mixins.length > 0) { <add> applyMixins(TestClass, ...mixins); <add> } <ide> <ide> let proto = TestClass.prototype; <ide>
5
Text
Text
fix typo in overview doc for react-devtools
6508ab3be8a4a79d18e46fac7318454307a51170
<ide><path>packages/react-devtools/OVERVIEW.md <ide> It consists of: <ide> <ide> 1. the total length of next items that belong to string table <ide> 2. for each string in a table: <del> 1. encoded size <del> 2. a list of its UTF encoded codepoints <add> * encoded size <add> * a list of its UTF encoded codepoints <ide> <ide> For example, for `Foo` and `Bar` we would see: <ide>
1
Text
Text
add elements.arc.angle in documentation
6e69a38305e532a36b8d8b1ed58a9c3655c58192
<ide><path>docs/configuration/elements.md <ide> Global arc options: `Chart.defaults.global.elements.arc`. <ide> <ide> | Name | Type | Default | Description <ide> | ---- | ---- | ------- | ----------- <add>| `angle` - for polar only | `number` | `circumference / (arc count)` | Arc angle to cover. <ide> | `backgroundColor` | `Color` | `'rgba(0, 0, 0, 0.1)'` | Arc fill color. <ide> | `borderAlign` | `string` | `'center'` | Arc stroke alignment. <ide> | `borderColor` | `Color` | `'#fff'` | Arc stroke color.
1
PHP
PHP
add tests for phperror and file headers
2e0682f865aeed35df904f7ae813e2dafc4e0622
<ide><path>src/Error/ErrorRendererInterface.php <ide> <?php <ide> declare(strict_types=1); <ide> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 4.4.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <ide> namespace Cake\Error; <ide> <ide> /** <ide><path>src/Error/PhpError.php <ide> <?php <ide> declare(strict_types=1); <ide> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 4.4.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <ide> namespace Cake\Error; <ide> <ide> /** <ide> class PhpError <ide> */ <ide> private $trace; <ide> <add> /** <add> * @var array<int, string> <add> */ <add> private $levelMap = [ <add> E_PARSE => 'error', <add> E_ERROR => 'error', <add> E_CORE_ERROR => 'error', <add> E_COMPILE_ERROR => 'error', <add> E_USER_ERROR => 'error', <add> E_WARNING => 'warning', <add> E_USER_WARNING => 'warning', <add> E_COMPILE_WARNING => 'warning', <add> E_RECOVERABLE_ERROR => 'warning', <add> E_NOTICE => 'notice', <add> E_USER_NOTICE => 'notice', <add> E_STRICT => 'strict', <add> E_DEPRECATED => 'deprecated', <add> E_USER_DEPRECATED => 'deprecated', <add> ]; <add> <add> /** <add> * @var array<string, int> <add> */ <add> private $logMap = [ <add> 'error' => LOG_ERR, <add> 'warning' => LOG_WARNING, <add> 'notice' => LOG_NOTICE, <add> 'strict' => LOG_NOTICE, <add> 'deprecated' => LOG_NOTICE, <add> ]; <add> <ide> /** <ide> * Constructor <ide> * <del> * @param int $level The PHP error constant <add> * @param int $code The PHP error code constant <ide> * @param string $message The error message. <ide> * @param string|null $file The filename of the error. <ide> * @param int|null $line The line number for the error. <ide> * @param array $trace The backtrace for the error. <ide> */ <ide> public function __construct( <del> int $level, <add> int $code, <ide> string $message, <ide> ?string $file = null, <ide> ?int $line = null, <ide> array $trace = [], <ide> ) { <del> $this->level = $level; <add> $this->code = $code; <ide> $this->message = $message; <ide> $this->file = $file; <ide> $this->line = $line; <ide> public function __construct( <ide> * <ide> * @return string <ide> */ <del> public function getLevel(): int <add> public function getCode(): int <add> { <add> return $this->code; <add> } <add> <add> /** <add> * Get the mapped LOG_ constant. <add> * <add> * @return int <add> */ <add> public function getLogLevel(): int <add> { <add> $label = $this->getLabel(); <add> <add> return $this->logMap[$label] ?? 'error'; <add> } <add> <add> /** <add> * Get the error code label <add> * <add> * @return string <add> */ <add> public function getLabel(): string <ide> { <del> return $this->level; <add> return $this->levelMap[$this->code] ?? 'error'; <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Error/PhpErrorTest.php <add><?php <add>declare(strict_types=1); <add> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 4.4.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Test\TestCase\Error; <add> <add>use Cake\Error\PhpError; <add>use Cake\TestSuite\TestCase; <add> <add>class PhpErrorTest extends TestCase <add>{ <add> public function testBasicGetters() <add> { <add> $error = new PhpError(E_ERROR, 'something bad'); <add> $this->assertEquals(E_ERROR, $error->getCode()); <add> $this->assertEquals('something bad', $error->getMessage()); <add> $this->assertNull($error->getFile()); <add> $this->assertNull($error->getLine()); <add> $this->assertEquals([], $error->getTrace()); <add> $this->assertEquals('', $error->getTraceAsString()); <add> } <add> <add> public static function errorCodeProvider(): array <add> { <add> // [php error code, label, log-level] <add> return [ <add> [E_ERROR, 'error', LOG_ERR], <add> [E_WARNING, 'warning', LOG_WARNING], <add> [E_NOTICE, 'notice', LOG_NOTICE], <add> [E_STRICT, 'strict', LOG_NOTICE], <add> [E_STRICT, 'strict', LOG_NOTICE], <add> [E_USER_DEPRECATED, 'deprecated', LOG_NOTICE], <add> ]; <add> } <add> <add> /** <add> * @dataProvider errorCodeProvider <add> */ <add> public function testMappings($phpCode, $label, $logLevel) <add> { <add> $error = new PhpError($phpCode, 'something bad'); <add> $this->assertEquals($phpCode, $error->getCode()); <add> $this->assertEquals($label, $error->getLabel()); <add> $this->assertEquals($logLevel, $error->getLogLevel()); <add> } <add> <add> public function testGetTraceAsString() <add> { <add> $trace = [ <add> ['file' => 'a.php', 'line' => 10, 'reference' => 'TestObject::a()'], <add> ['file' => 'b.php', 'line' => 5, 'reference' => '[main]'], <add> ]; <add> $error = new PhpError(E_ERROR, 'something bad', __FILE__, __LINE__, $trace); <add> $this->assertEquals($trace, $error->getTrace()); <add> $expected = [ <add> 'TestObject::a() a.php, line 10', <add> '[main] b.php, line 5', <add> ]; <add> $this->assertEquals(implode("\n", $expected), $error->getTraceAsString()); <add> $this->assertEquals('error', $error->getLabel()); <add> } <add>}
3
Javascript
Javascript
remove unused trailing function arguments
bf2b5e1d5c239a1b4ea812051ec82101e1ce4347
<ide><path>tools/doc/html.js <ide> function altDocs(filename) { <ide> const host = 'https://nodejs.org'; <ide> const href = (v) => `${host}/docs/latest-v${v.num}/api/${filename}.html`; <ide> <del> function li(v, i) { <add> function li(v) { <ide> let html = `<li><a href="${href(v)}">${v.num}`; <ide> <ide> if (v.lts) <ide><path>tools/eslint-rules/crypto-check.js <ide> module.exports = function(context) { <ide> } <ide> } <ide> <del> function reportIfMissingCheck(node) { <add> function reportIfMissingCheck() { <ide> if (hasSkipCall) { <ide> return; <ide> } <ide><path>tools/eslint-rules/inspector-check.js <ide> module.exports = function(context) { <ide> } <ide> } <ide> <del> function reportIfMissing(context, node) { <add> function reportIfMissing(context) { <ide> if (!hasInspectorCheck) { <ide> missingCheckNodes.forEach((node) => { <ide> context.report(node, msg);
3
Javascript
Javascript
remove @providesmodule in www shims
3e9515eedebe0c19f047391605c5b3c71d13fbc2
<ide><path>scripts/rollup/shims/facebook-www/EventPluginHub.js <ide> * <ide> * This source code is licensed under the MIT license found in the <ide> * LICENSE file in the root directory of this source tree. <del> * <del> * @providesModule EventPluginHub <ide> */ <ide> <ide> 'use strict'; <ide><path>scripts/rollup/shims/facebook-www/ReactBrowserEventEmitter.js <ide> * <ide> * This source code is licensed under the MIT license found in the <ide> * LICENSE file in the root directory of this source tree. <del> * <del> * @providesModule ReactBrowserEventEmitter <ide> */ <ide> <ide> 'use strict'; <ide><path>scripts/rollup/shims/facebook-www/ReactDOMComponentTree.js <ide> * <ide> * This source code is licensed under the MIT license found in the <ide> * LICENSE file in the root directory of this source tree. <del> * <del> * @providesModule ReactDOMComponentTree <ide> */ <ide> <ide> 'use strict'; <ide><path>scripts/rollup/shims/facebook-www/ReactInstanceMap.js <ide> * <ide> * This source code is licensed under the MIT license found in the <ide> * LICENSE file in the root directory of this source tree. <del> * <del> * @providesModule ReactInstanceMap <ide> */ <ide> <ide> 'use strict'; <ide><path>scripts/rollup/shims/facebook-www/TapEventPlugin.js <ide> * <ide> * This source code is licensed under the MIT license found in the <ide> * LICENSE file in the root directory of this source tree. <del> * <del> * @providesModule TapEventPlugin <ide> */ <ide> <ide> 'use strict'; <ide><path>scripts/rollup/shims/facebook-www/findDOMNode.js <ide> * <ide> * This source code is licensed under the MIT license found in the <ide> * LICENSE file in the root directory of this source tree. <del> * <del> * @providesModule findDOMNode <ide> */ <ide> <ide> 'use strict'; <ide><path>scripts/rollup/shims/facebook-www/renderSubtreeIntoContainer.js <ide> * <ide> * This source code is licensed under the MIT license found in the <ide> * LICENSE file in the root directory of this source tree. <del> * <del> * @providesModule renderSubtreeIntoContainer <ide> */ <ide> <ide> 'use strict';
7
Go
Go
add test for ingress removal on service removal
805b6a7f749a6c7cbb237e21ee7260d536621808
<ide><path>integration/network/service_test.go <ide> func TestServiceWithPredefinedNetwork(t *testing.T) { <ide> if runtime.GOARCH == "arm64" || runtime.GOARCH == "arm" { <ide> config.Timeout = 50 * time.Second <ide> config.Delay = 100 * time.Millisecond <add> } else { <add> config.Timeout = 30 * time.Second <add> config.Delay = 100 * time.Millisecond <add> } <add> } <add> <add> serviceID := serviceResp.ID <add> poll.WaitOn(t, serviceRunningCount(client, serviceID, instances), pollSettings) <add> <add> _, _, err = client.ServiceInspectWithRaw(context.Background(), serviceID, types.ServiceInspectOptions{}) <add> require.NoError(t, err) <add> <add> err = client.ServiceRemove(context.Background(), serviceID) <add> require.NoError(t, err) <add> <add> poll.WaitOn(t, serviceIsRemoved(client, serviceID), pollSettings) <add> poll.WaitOn(t, noTasks(client), pollSettings) <add> <add>} <add> <add>const ingressNet = "ingress" <add> <add>func TestServiceWithIngressNetwork(t *testing.T) { <add> defer setupTest(t)() <add> d := newSwarm(t) <add> defer d.Stop(t) <add> <add> client, err := client.NewClientWithOpts(client.WithHost((d.Sock()))) <add> require.NoError(t, err) <add> <add> pollSettings := func(config *poll.Settings) { <add> if runtime.GOARCH == "arm64" || runtime.GOARCH == "arm" { <add> config.Timeout = 50 * time.Second <add> config.Delay = 100 * time.Millisecond <add> } else { <add> config.Timeout = 30 * time.Second <add> config.Delay = 100 * time.Millisecond <ide> } <ide> } <ide> <add> poll.WaitOn(t, swarmIngressReady(client), pollSettings) <add> <add> var instances uint64 = 1 <add> serviceName := "TestIngressService" <add> serviceSpec := swarmServiceSpec(serviceName, instances) <add> serviceSpec.TaskTemplate.Networks = append(serviceSpec.TaskTemplate.Networks, swarm.NetworkAttachmentConfig{Target: ingressNet}) <add> serviceSpec.EndpointSpec = &swarm.EndpointSpec{ <add> Ports: []swarm.PortConfig{ <add> { <add> Protocol: swarm.PortConfigProtocolTCP, <add> TargetPort: 80, <add> PublishMode: swarm.PortConfigPublishModeIngress, <add> }, <add> }, <add> } <add> <add> serviceResp, err := client.ServiceCreate(context.Background(), serviceSpec, types.ServiceCreateOptions{ <add> QueryRegistry: false, <add> }) <add> require.NoError(t, err) <add> <ide> serviceID := serviceResp.ID <ide> poll.WaitOn(t, serviceRunningCount(client, serviceID, instances), pollSettings) <ide> <ide> func TestServiceWithPredefinedNetwork(t *testing.T) { <ide> poll.WaitOn(t, serviceIsRemoved(client, serviceID), pollSettings) <ide> poll.WaitOn(t, noTasks(client), pollSettings) <ide> <add> // Ensure that "ingress" is not removed or corrupted <add> time.Sleep(10 * time.Second) <add> netInfo, err := client.NetworkInspect(context.Background(), ingressNet, types.NetworkInspectOptions{ <add> Verbose: true, <add> Scope: "swarm", <add> }) <add> require.NoError(t, err, "Ingress network was removed after removing service!") <add> require.NotZero(t, len(netInfo.Containers), "No load balancing endpoints in ingress network") <add> require.NotZero(t, len(netInfo.Peers), "No peers (including self) in ingress network") <add> _, ok := netInfo.Containers["ingress-sbox"] <add> require.True(t, ok, "ingress-sbox not present in ingress network") <ide> } <ide> <ide> func serviceRunningCount(client client.ServiceAPIClient, serviceID string, instances uint64) func(log poll.LogT) poll.Result { <ide> func serviceRunningCount(client client.ServiceAPIClient, serviceID string, insta <ide> return poll.Success() <ide> } <ide> } <add> <add>func swarmIngressReady(client client.NetworkAPIClient) func(log poll.LogT) poll.Result { <add> return func(log poll.LogT) poll.Result { <add> netInfo, err := client.NetworkInspect(context.Background(), ingressNet, types.NetworkInspectOptions{ <add> Verbose: true, <add> Scope: "swarm", <add> }) <add> if err != nil { <add> return poll.Error(err) <add> } <add> np := len(netInfo.Peers) <add> nc := len(netInfo.Containers) <add> if np == 0 || nc == 0 { <add> return poll.Continue("ingress not ready: %d peers and %d containers", nc, np) <add> } <add> _, ok := netInfo.Containers["ingress-sbox"] <add> if !ok { <add> return poll.Continue("ingress not ready: does not contain the ingress-sbox") <add> } <add> return poll.Success() <add> } <add>}
1
Javascript
Javascript
replace input[select] with option for clarity
ce20dd06fe196bdcc0d1b0c9d2d271f90aea21fc
<ide><path>src/ng/directive/input.js <ide> var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/; <ide> * @name ngValue <ide> * <ide> * @description <del> * Binds the given expression to the value of `input[select]` or `input[radio]`, so <del> * that when the element is selected, the `ngModel` of that element is set to the <del> * bound value. <add> * Binds the given expression to the value of `option` or `input[radio]`, so <add> * that when the element is selected, the `ngModel` of that element is set to <add> * the bound value. <ide> * <ide> * `ngValue` is useful when dynamically generating lists of radio buttons using `ng-repeat`, as <ide> * shown below.
1
Java
Java
add contains form data requestmatcher
de0a0437397124083eeea9fb46c8bf3cc5a70763
<ide><path>spring-test/src/main/java/org/springframework/test/web/client/match/ContentRequestMatchers.java <ide> <ide> package org.springframework.test.web.client.match; <ide> <del>import java.io.ByteArrayInputStream; <ide> import java.io.IOException; <del>import java.io.InputStream; <ide> import java.util.List; <ide> import java.util.Map; <ide> <ide> import org.w3c.dom.Node; <ide> <ide> import org.springframework.core.io.Resource; <del>import org.springframework.http.HttpHeaders; <del>import org.springframework.http.HttpInputMessage; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.http.client.ClientHttpRequest; <ide> import org.springframework.http.converter.FormHttpMessageConverter; <add>import org.springframework.mock.http.MockHttpInputMessage; <ide> import org.springframework.mock.http.client.MockClientHttpRequest; <ide> import org.springframework.mock.web.MockHttpServletRequest; <ide> import org.springframework.test.util.JsonExpectationsHelper; <ide> public RequestMatcher bytes(byte[] expectedContent) { <ide> * Parse the body as form data and compare to the given {@code MultiValueMap}. <ide> * @since 4.3 <ide> */ <del> public RequestMatcher formData(MultiValueMap<String, String> expectedContent) { <add> public RequestMatcher formData(MultiValueMap<String, String> expected) { <add> return formData(expected, true); <add> } <add> <add> /** <add> * Variant of {@link #formData(MultiValueMap)} that matches the given subset <add> * of expected form parameters. <add> * @since 5.3 <add> */ <add> public RequestMatcher formDataContains(Map<String, String> expected) { <add> MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>(expected.size()); <add> expected.forEach(multiValueMap::add); <add> return formData(multiValueMap, false); <add> } <add> <add> private RequestMatcher formData(MultiValueMap<String, String> expectedMap, boolean containsExactly) { <ide> return request -> { <del> HttpInputMessage inputMessage = new HttpInputMessage() { <del> @Override <del> public InputStream getBody() throws IOException { <del> MockClientHttpRequest mockRequest = (MockClientHttpRequest) request; <del> return new ByteArrayInputStream(mockRequest.getBodyAsBytes()); <del> } <del> @Override <del> public HttpHeaders getHeaders() { <del> return request.getHeaders(); <add> MockClientHttpRequest mockRequest = (MockClientHttpRequest) request; <add> MockHttpInputMessage message = new MockHttpInputMessage(mockRequest.getBodyAsBytes()); <add> message.getHeaders().putAll(mockRequest.getHeaders()); <add> MultiValueMap<String, String> actualMap = new FormHttpMessageConverter().read(null, message); <add> if (containsExactly) { <add> assertEquals("Form data", expectedMap, actualMap); <add> } <add> else { <add> assertTrue("Form data " + actualMap, expectedMap.size() <= actualMap.size()); <add> for (Map.Entry<String, ? extends List<?>> entry : expectedMap.entrySet()) { <add> String name = entry.getKey(); <add> List<?> values = entry.getValue(); <add> assertTrue("No form parameter '" + name + "'", actualMap.get(name) != null); <add> assertTrue("Parameter value count " + values.size(), values.size() <= actualMap.get(name).size()); <add> for (int i = 0; i < values.size(); i++) { <add> assertEquals("Form parameter", values.get(i), actualMap.get(name).get(i)); <add> } <ide> } <del> }; <del> FormHttpMessageConverter converter = new FormHttpMessageConverter(); <del> assertEquals("Request content", expectedContent, converter.read(null, inputMessage)); <add> } <ide> }; <ide> } <ide> <ide> public RequestMatcher multipartDataContains(Map<String, ?> expectedMap) { <ide> } <ide> <ide> @SuppressWarnings("ConstantConditions") <del> private RequestMatcher multipartData(MultiValueMap<String, ?> expectedMap, boolean assertSize) { <add> private RequestMatcher multipartData(MultiValueMap<String, ?> expectedMap, boolean containsExactly) { <ide> return request -> { <ide> MultiValueMap<String, ?> actualMap = MultipartHelper.parse(request); <del> if (assertSize) { <add> if (containsExactly) { <ide> assertEquals("Multipart request content: " + actualMap, expectedMap.size(), actualMap.size()); <ide> } <ide> for (Map.Entry<String, ? extends List<?>> entry : expectedMap.entrySet()) { <ide> String name = entry.getKey(); <ide> List<?> values = entry.getValue(); <ide> assertTrue("No Multipart '" + name + "'", actualMap.get(name) != null); <del> assertTrue("Multipart value count " + values.size(), assertSize ? <add> assertTrue("Multipart value count " + values.size(), containsExactly ? <ide> values.size() == actualMap.get(name).size() : <ide> values.size() <= actualMap.get(name).size()); <ide> for (int i = 0; i < values.size(); i++) { <ide> else if (expected instanceof String) { <ide> assertEquals("Multipart content", expected, (String) actual); <ide> } <ide> else { <del> throw new IllegalArgumentException( <del> "Unexpected multipart value type: " + expected.getClass()); <add> throw new IllegalArgumentException("Unexpected multipart value: " + expected.getClass()); <ide> } <ide> } <ide> } <ide><path>spring-test/src/test/java/org/springframework/test/web/client/match/ContentRequestMatchersTests.java <ide> package org.springframework.test.web.client.match; <ide> <ide> import java.nio.charset.StandardCharsets; <add>import java.util.Collections; <ide> <ide> import org.junit.jupiter.api.BeforeEach; <ide> import org.junit.jupiter.api.Test; <ide> public void testFormData() throws Exception { <ide> MockRestRequestMatchers.content().formData(map).match(this.request); <ide> } <ide> <add> @Test <add> public void testFormDataContains() throws Exception { <add> String contentType = "application/x-www-form-urlencoded;charset=UTF-8"; <add> String body = "name+1=value+1&name+2=value+A&name+2=value+B&name+3"; <add> <add> this.request.getHeaders().setContentType(MediaType.parseMediaType(contentType)); <add> this.request.getBody().write(body.getBytes(StandardCharsets.UTF_8)); <add> <add> MockRestRequestMatchers.content() <add> .formDataContains(Collections.singletonMap("name 1", "value 1")) <add> .match(this.request); <add> } <add> <ide> @Test <ide> public void testXml() throws Exception { <ide> String content = "<foo><bar>baz</bar><bar>bazz</bar></foo>";
2
PHP
PHP
apply fixes from styleci
20d9fffe5ea845db6336d089a4d6e5b6c85a9d9c
<ide><path>src/Illuminate/Support/Pluralizer.php <ide> <ide> namespace Illuminate\Support; <ide> <del>use Doctrine\Inflector\InflectorFactory; <ide> use Doctrine\Inflector\Inflector; <del>use Doctrine\Inflector\RulesetInflector; <add>use Doctrine\Inflector\InflectorFactory; <ide> <ide> class Pluralizer <ide> {
1
Python
Python
correct a bug on the sensor plugin
e1801def7d255bd7732501f60079a9847ad55b7a
<ide><path>glances/plugins/glances_alert.py <ide> """Alert plugin.""" <ide> <ide> # Import system lib <add>import types <ide> from datetime import datetime <ide> <ide> # Import Glances libs <ide> def msg_curse(self, args=None): <ide> msg = str(alert[3]) <ide> ret.append(self.curse_add_line(msg, decoration=alert[2])) <ide> # Min / Mean / Max <del> if alert[6] == alert[4]: <add> if self.approx_equal(alert[6], alert[4], tolerance=0.1): <ide> msg = ' ({0:.1f})'.format(alert[5]) <ide> else: <ide> msg = _(" (Min:{0:.1f} Mean:{1:.1f} Max:{2:.1f})").format(alert[6], alert[5], alert[4]) <ide> def msg_curse(self, args=None): <ide> # ret.append(self.curse_add_line(msg)) <ide> <ide> return ret <add> <add> def approx_equal(self, a, b, tolerance=0.0): <add> """ <add> Compare a with b using the tolerance (if numerical) <add> """ <add> numericalType = [types.IntType, types.FloatType, types.LongType] <add> if type(a) in numericalType and type(b) in numericalType: <add> return abs(a-b) <= max(abs(a), abs(b)) * tolerance <add> else: <add> return a == b <ide><path>glances/plugins/glances_batpercent.py <ide> def __init__(self): <ide> def update(self): <ide> """Update the stats.""" <ide> if self.initok: <del> reply = self.bat.update() <del> if reply is not None: <del> self.bat_list = [] <del> new_item = {'label': _("Battery (%)"), <del> 'value': self.getcapacitypercent()} <del> self.bat_list.append(new_item) <add> self.bat_list = [{'label': _("Battery (%)"), 'value': self.getcapacitypercent()}] <ide> else: <ide> self.bat_list = [] <ide> <ide> def getcapacitypercent(self): <ide> if not self.initok or self.bat.stat == []: <ide> return [] <ide> <del> # Init the bsum (sum of percent) and bcpt (number of batteries) <add> # Init the bsum (sum of percent) <ide> # and Loop over batteries (yes a computer could have more than 1 battery) <ide> bsum = 0 <del> for bcpt in range(len(self.bat.stat)): <add> for b in self.bat.stat: <ide> try: <del> bsum = bsum + int(self.bat.stat[bcpt].capacity) <add> bsum = bsum + int(b.capacity) <ide> except ValueError: <ide> return [] <del> bcpt = bcpt + 1 <ide> <ide> # Return the global percent <del> return int(bsum / bcpt) <add> return int(bsum / len(self.bat.stat))
2
PHP
PHP
fix command bug
1973197d53c9daaf65c54c4c872669e787a408d3
<ide><path>src/Illuminate/Database/Seeder.php <ide> public function call($class) <ide> { <ide> $this->resolve($class)->run(); <ide> <del> $this->command->getOutput()->writeln("<info>Seeded:</info> $class"); <add> if ($this->command) <add> { <add> $this->command->getOutput()->writeln("<info>Seeded:</info> $class"); <add> } <ide> } <ide> <ide> /**
1
Ruby
Ruby
fix configurable cristalization and tests
d677097eb6d49f75ef41dae2ee832d5e0a1d177d
<ide><path>activesupport/lib/active_support/configurable.rb <ide> module Configurable <ide> <ide> class Configuration < ActiveSupport::InheritableOptions <ide> def compile_methods! <del> self.class.compile_methods!(keys.reject {|key| respond_to?(key)}) <add> self.class.compile_methods!(keys) <ide> end <ide> <ide> # compiles reader methods so we don't have to go through method_missing <ide> def self.compile_methods!(keys) <del> keys.each do |key| <add> keys.reject { |m| method_defined?(m) }.each do |key| <ide> class_eval <<-RUBY, __FILE__, __LINE__ + 1 <ide> def #{key}; _get(#{key.inspect}); end <ide> RUBY <ide><path>activesupport/test/configurable_test.rb <ide> class Child < Parent <ide> child = Class.new(parent) <ide> <ide> parent.config.bar = :foo <del> assert !parent.config.respond_to?(:bar) <del> assert !child.config.respond_to?(:bar) <del> assert !child.new.config.respond_to?(:bar) <add> assert_method_not_defined parent.config, :bar <add> assert_method_not_defined child.config, :bar <add> assert_method_not_defined child.new.config, :bar <ide> <ide> parent.config.compile_methods! <ide> assert_equal :foo, parent.config.bar <ide> assert_equal :foo, child.new.config.bar <ide> <del> assert_respond_to parent.config, :bar <del> assert_respond_to child.config, :bar <del> assert_respond_to child.new.config, :bar <add> assert_method_defined parent.config, :bar <add> assert_method_defined child.config, :bar <add> assert_method_defined child.new.config, :bar <add> end <add> <add> def assert_method_defined(object, method) <add> methods = object.public_methods.map(&:to_s) <add> assert methods.include?(method.to_s), "Expected #{methods.inspect} to include #{method.to_s.inspect}" <add> end <add> <add> def assert_method_not_defined(object, method) <add> methods = object.public_methods.map(&:to_s) <add> assert !methods.include?(method.to_s), "Expected #{methods.inspect} to not include #{method.to_s.inspect}" <ide> end <ide> end
2
Text
Text
fix a missed bullet
446ddf7b06739a50c0766032b6bb893313884397
<ide><path>README.md <ide> tests for CakePHP by doing the following: <ide> * [#cakephp](http://webchat.freenode.net/?channels=#cakephp) on irc.freenode.net - Come chat with us, we have cake. <ide> * [Forum](http://discourse.cakephp.org/) - Offical CakePHP forum. <ide> * [GitHub Issues](https://github.com/cakephp/cakephp/issues) - Got issues? Please tell us! <del> <del>[Roadmaps](https://github.com/cakephp/cakephp/wiki#roadmaps) - Want to contribute? Get involved! <add>* [Roadmaps](https://github.com/cakephp/cakephp/wiki#roadmaps) - Want to contribute? Get involved! <ide> <ide> ## Contributing <ide>
1
Python
Python
fix py2/3 issue
5551052840833ef9a5c2f1f679dd390e0a035a0d
<ide><path>spacy/en/download.py <ide> def main(data_size='all', force=False): <ide> print("Model already installed. Please run 'python -m " <ide> "spacy.en.download --force' to reinstall.", file=sys.stderr) <ide> sys.exit(1) <del> except PackageNotFoundException, CompatiblePackageNotFoundException: <add> except (PackageNotFoundException, CompatiblePackageNotFoundException): <ide> pass <ide> <ide> package = sputnik.install(about.__name__, about.__version__, about.__default_model__) <ide> <ide> try: <ide> sputnik.package(about.__name__, about.__version__, about.__default_model__) <del> except PackageNotFoundException, CompatiblePackageNotFoundException: <add> except (PackageNotFoundException, CompatiblePackageNotFoundException): <ide> print("Model failed to install. Please run 'python -m " <ide> "spacy.en.download --force'.", file=sys.stderr) <ide> sys.exit(1)
1
Javascript
Javascript
allow form label and name to differ
c4240cdf2f11d4d7f7164f3cb9c16d32b9ca0eb8
<ide><path>client/src/components/formHelpers/Form.js <ide> import { <ide> const propTypes = { <ide> buttonText: PropTypes.string, <ide> enableSubmit: PropTypes.bool, <del> formFields: PropTypes.arrayOf(PropTypes.string).isRequired, <add> formFields: PropTypes.arrayOf( <add> PropTypes.shape({ name: PropTypes.string, label: PropTypes.string }) <add> .isRequired <add> ).isRequired, <ide> hideButton: PropTypes.bool, <ide> id: PropTypes.string.isRequired, <ide> initialValues: PropTypes.object, <ide> function DynamicForm({ <ide> onSubmit={handleSubmit} <ide> style={{ width: '100%' }} <ide> > <del> <FormFields fields={formFields} options={options} /> <add> <FormFields formFields={formFields} options={options} /> <ide> <BlockSaveWrapper> <ide> {hideButton ? null : ( <ide> <BlockSaveButton disabled={(pristine && !enableSubmit) || error}> <ide><path>client/src/components/formHelpers/Form.test.js <ide> import Form from './Form'; <ide> <ide> const defaultTestProps = { <ide> buttonText: 'Submit', <del> formFields: ['name', 'website'], <add> formFields: [ <add> { name: 'name', label: 'name Label' }, <add> { name: 'website', label: 'WebSite label' } <add> ], <ide> id: 'my-test-form', <ide> options: { <ide> types: { <ide> const defaultTestProps = { <ide> test('should render', () => { <ide> const { getByLabelText, getByText } = render(<Form {...defaultTestProps} />); <ide> <del> const nameInput = getByLabelText(/name/i); <add> const nameInput = getByLabelText(/name Label/); <ide> expect(nameInput).not.toBeRequired(); <ide> expect(nameInput).toHaveAttribute('type', 'text'); <ide> <del> const websiteInput = getByLabelText(/website/i); <add> const websiteInput = getByLabelText(/WebSite label/); <ide> expect(websiteInput).toBeRequired(); <ide> expect(websiteInput).toHaveAttribute('type', 'url'); <ide> <ide> test('should render with default values', () => { <ide> /> <ide> ); <ide> <del> const nameInput = getByLabelText(/name/i); <add> const nameInput = getByLabelText(/name Label/); <ide> expect(nameInput).toHaveValue(nameValue); <ide> <del> const websiteInput = getByLabelText(/website/i); <add> const websiteInput = getByLabelText(/WebSite label/); <ide> expect(websiteInput).toHaveValue(websiteValue); <ide> <ide> const button = getByText(/submit/i); <ide> test('should submit', () => { <ide> <ide> const { getByLabelText, getByText } = render(<Form {...props} />); <ide> <del> const websiteInput = getByLabelText(/website/i); <add> const websiteInput = getByLabelText(/WebSite label/); <ide> fireEvent.change(websiteInput, { target: { value: websiteValue } }); <ide> expect(websiteInput).toHaveValue(websiteValue); <ide> <ide><path>client/src/components/formHelpers/FormFields.js <ide> import React from 'react'; <del>import { kebabCase, startCase } from 'lodash'; <add>import { kebabCase } from 'lodash'; <ide> import PropTypes from 'prop-types'; <ide> import { <ide> Alert, <ide> import { <ide> import { Field } from 'react-final-form'; <ide> <ide> const propTypes = { <del> fields: PropTypes.arrayOf(PropTypes.string.isRequired).isRequired, <add> formFields: PropTypes.arrayOf( <add> PropTypes.shape({ name: PropTypes.string, label: PropTypes.string }) <add> .isRequired <add> ).isRequired, <ide> options: PropTypes.shape({ <ide> ignored: PropTypes.arrayOf(PropTypes.string), <ide> placeholders: PropTypes.objectOf(PropTypes.string), <ide> const propTypes = { <ide> }; <ide> <ide> function FormFields(props) { <del> const { fields, options = {} } = props; <add> const { formFields, options = {} } = props; <ide> const { <ide> ignored = [], <ide> placeholders = {}, <ide> required = [], <ide> types = {} <ide> } = options; <add> <ide> return ( <ide> <div> <del> {fields <del> .filter(field => !ignored.includes(field)) <del> .map(name => ( <del> <Field key={`${name}-field`} name={name}> <add> {formFields <add> .filter(formField => !ignored.includes(formField.name)) <add> .map(({ name, label }) => ( <add> <Field key={`${kebabCase(name)}-field`} name={name}> <ide> {({ input: { value, onChange }, meta: { pristine, error } }) => { <ide> const key = kebabCase(name); <ide> const type = name in types ? types[name] : 'text'; <ide> function FormFields(props) { <ide> <Col key={key} xs={12}> <ide> <FormGroup> <ide> {type === 'hidden' ? null : ( <del> <ControlLabel htmlFor={key}> <del> {startCase(name)} <del> </ControlLabel> <add> <ControlLabel htmlFor={key}>{label}</ControlLabel> <ide> )} <ide> <FormControl <ide> componentClass={type === 'textarea' ? type : 'input'} <ide><path>client/src/components/formHelpers/index.js <ide> export { default as FormFields } from './FormFields.js'; <ide> const normalizeOptions = { <ide> stripWWW: false <ide> }; <del> <ide> // callIfDefined(fn: (Any) => Any) => (value: Any) => Any <ide> export function callIfDefined(fn) { <ide> return value => (value ? fn(value) : value); <ide> export function formatUrlValues(values, options) { <ide> return { ...result, [key]: value }; <ide> }, {}); <ide> } <del> <ide> // formatUrl(url: String) => String <ide> export function formatUrl(url) { <ide> if (typeof url === 'string' && url.length > 4 && url.indexOf('.') !== -1) { <ide> export function formatUrl(url) { <ide> } <ide> return url; <ide> } <del> <ide> export function isValidURL(data) { <ide> /* eslint-disable camelcase */ <ide> return isURL(data, { require_protocol: true }); <ide> /* eslint-enable camelcase */ <ide> } <del> <ide> export function makeOptional(validator) { <ide> return val => (val ? validator(val) : true); <ide> } <del> <ide> export function makeRequired(validator) { <ide> return val => (val ? validator(val) : false); <ide> } <del> <ide> export function createFormValidator(fieldValidators) { <ide> const fieldKeys = Object.keys(fieldValidators); <ide> return values => <ide> export function createFormValidator(fieldValidators) { <ide> .filter(Boolean) <ide> .reduce((errors, error) => ({ ...errors, ...error }), {}); <ide> } <del> <ide> export function getValidationState(field) { <ide> if (field.pristine) { <ide> return null; <ide><path>client/src/components/settings/Certification.js <ide> export class CertificationSettings extends Component { <ide> { types: {} } <ide> ); <ide> <add> const formFields = challengeTitles.map(title => ({ <add> name: title, <add> label: title <add> })); <add> <ide> const fullForm = filledforms === challengeTitles.length; <ide> <ide> const createClickHandler = certLocation => e => { <ide> export class CertificationSettings extends Component { <ide> <Form <ide> buttonText={fullForm ? 'Claim Certification' : 'Save Progress'} <ide> enableSubmit={fullForm} <del> formFields={challengeTitles} <add> formFields={formFields} <ide> hideButton={isCertClaimed} <ide> id={superBlock} <ide> initialValues={{ <ide><path>client/src/templates/Challenges/projects/SolutionForm.js <ide> const propTypes = { <ide> }; <ide> <ide> // back end challenges and front end projects use a single form field <del>const solutionField = ['solution']; <del>const backEndProjectFields = ['solution', 'githubLink']; <add>const solutionField = [{ name: 'solution', label: 'Solution Link' }]; <add>const backEndProjectFields = [ <add> { name: 'solution', label: 'Solution Link' }, <add> { name: 'githubLink', label: 'GitHub Link' } <add>]; <ide> <ide> const options = { <ide> types: {
6
Ruby
Ruby
introduce ignore_errors parameter
49285fb88c2b0845d9d4847b89e32ac9b54206e9
<ide><path>Library/Homebrew/formulary.rb <ide> def self.clear_cache <ide> super <ide> end <ide> <del> def self.load_formula(name, path, contents, namespace, flags:) <add> def self.load_formula(name, path, contents, namespace, flags:, ignore_errors:) <ide> raise "Formula loading disabled by HOMEBREW_DISABLE_LOAD_FORMULA!" if Homebrew::EnvConfig.disable_load_formula? <ide> <ide> require "formula" <add> require "ignorable" <ide> <ide> mod = Module.new <ide> remove_const(namespace) if const_defined?(namespace) <ide> const_set(namespace, mod) <ide> <del> begin <add> eval_formula = lambda do <ide> # Set `BUILD_FLAGS` in the formula's namespace so we can <ide> # access them from within the formula's class scope. <ide> mod.const_set(:BUILD_FLAGS, flags) <ide> mod.module_eval(contents, path) <ide> rescue NameError, ArgumentError, ScriptError, MethodDeprecatedError, MacOSVersionError => e <del> remove_const(namespace) <del> raise FormulaUnreadableError.new(name, e) <add> if e.is_a?(Ignorable::ExceptionMixin) <add> e.ignore <add> else <add> remove_const(namespace) <add> raise FormulaUnreadableError.new(name, e) <add> end <ide> end <add> if ignore_errors <add> Ignorable.hook_raise(&eval_formula) <add> else <add> eval_formula.call <add> end <add> <ide> class_name = class_s(name) <ide> <ide> begin <ide> def self.load_formula(name, path, contents, namespace, flags:) <ide> end <ide> end <ide> <del> def self.load_formula_from_path(name, path, flags:) <add> def self.load_formula_from_path(name, path, flags:, ignore_errors:) <ide> contents = path.open("r") { |f| ensure_utf8_encoding(f).read } <ide> namespace = "FormulaNamespace#{Digest::MD5.hexdigest(path.to_s)}" <del> klass = load_formula(name, path, contents, namespace, flags: flags) <add> klass = load_formula(name, path, contents, namespace, flags: flags, ignore_errors: ignore_errors) <ide> cache[path] = klass <ide> end <ide> <ide> def initialize(name, path) <ide> # Gets the formula instance. <ide> # `alias_path` can be overridden here in case an alias was used to refer to <ide> # a formula that was loaded in another way. <del> def get_formula(spec, alias_path: nil, force_bottle: false, flags: []) <add> def get_formula(spec, alias_path: nil, force_bottle: false, flags: [], ignore_errors: false) <ide> alias_path ||= self.alias_path <del> klass(flags: flags).new(name, path, spec, alias_path: alias_path, force_bottle: force_bottle) <add> klass(flags: flags, ignore_errors: ignore_errors) <add> .new(name, path, spec, alias_path: alias_path, force_bottle: force_bottle) <ide> end <ide> <del> def klass(flags:) <del> load_file(flags: flags) unless Formulary.formula_class_defined?(path) <add> def klass(flags:, ignore_errors:) <add> load_file(flags: flags, ignore_errors: ignore_errors) unless Formulary.formula_class_defined?(path) <ide> Formulary.formula_class_get(path) <ide> end <ide> <ide> private <ide> <del> def load_file(flags:) <add> def load_file(flags:, ignore_errors:) <ide> $stderr.puts "#{$PROGRAM_NAME} (#{self.class.name}): loading #{path}" if debug? <ide> raise FormulaUnavailableError, name unless path.file? <ide> <del> Formulary.load_formula_from_path(name, path, flags: flags) <add> Formulary.load_formula_from_path(name, path, flags: flags, ignore_errors: ignore_errors) <ide> end <ide> end <ide> <ide> def initialize(bottle_name) <ide> super name, Formulary.path(full_name) <ide> end <ide> <del> def get_formula(spec, force_bottle: false, flags: [], **) <add> def get_formula(spec, force_bottle: false, flags: [], ignore_errors: false, **) <ide> formula = begin <ide> contents = Utils::Bottles.formula_contents @bottle_filename, name: name <del> Formulary.from_contents(name, path, contents, spec, force_bottle: force_bottle, flags: flags) <add> Formulary.from_contents(name, path, contents, spec, force_bottle: force_bottle, <add> flags: flags, ignore_errors: ignore_errors) <ide> rescue FormulaUnreadableError => e <ide> opoo <<~EOS <ide> Unreadable formula in #{@bottle_filename}: <ide> def initialize(url) <ide> super formula, HOMEBREW_CACHE_FORMULA/File.basename(uri.path) <ide> end <ide> <del> def load_file(flags:) <add> def load_file(flags:, ignore_errors:) <ide> if %r{githubusercontent.com/[\w-]+/[\w-]+/[a-f0-9]{40}(?:/Formula)?/(?<formula_name>[\w+-.@]+).rb} =~ url <ide> raise UsageError, "Installation of #{formula_name} from a GitHub commit URL is unsupported! " \ <ide> "`brew extract #{formula_name}` to a stable tap on GitHub instead." <ide> def formula_name_path(tapped_name, warn: true) <ide> [name, path] <ide> end <ide> <del> def get_formula(spec, alias_path: nil, force_bottle: false, flags: []) <add> def get_formula(spec, alias_path: nil, force_bottle: false, flags: [], ignore_errors: false) <ide> super <ide> rescue FormulaUnreadableError => e <ide> raise TapFormulaUnreadableError.new(tap, name, e.formula_error), "", e.backtrace <ide> def get_formula(spec, alias_path: nil, force_bottle: false, flags: []) <ide> raise TapFormulaUnavailableError.new(tap, name), "", e.backtrace <ide> end <ide> <del> def load_file(flags:) <add> def load_file(flags:, ignore_errors:) <ide> super <ide> rescue MethodDeprecatedError => e <ide> e.issues_url = tap.issues_url || tap.to_s <ide> def initialize(name, path, contents) <ide> super name, path <ide> end <ide> <del> def klass(flags:) <add> def klass(flags:, ignore_errors:) <ide> $stderr.puts "#{$PROGRAM_NAME} (#{self.class.name}): loading #{path}" if debug? <ide> namespace = "FormulaNamespace#{Digest::MD5.hexdigest(contents.to_s)}" <del> Formulary.load_formula(name, path, contents, namespace, flags: flags) <add> Formulary.load_formula(name, path, contents, namespace, flags: flags, ignore_errors: ignore_errors) <ide> end <ide> end <ide> <ide> def klass(flags:) <ide> # * a formula pathname <ide> # * a formula URL <ide> # * a local bottle reference <del> def self.factory(ref, spec = :stable, alias_path: nil, from: nil, force_bottle: false, flags: []) <add> def self.factory( <add> ref, spec = :stable, alias_path: nil, from: nil, <add> force_bottle: false, flags: [], ignore_errors: false <add> ) <ide> raise ArgumentError, "Formulae must have a ref!" unless ref <ide> <ide> cache_key = "#{ref}-#{spec}-#{alias_path}-#{from}" <ide> def self.factory(ref, spec = :stable, alias_path: nil, from: nil, force_bottle: <ide> end <ide> <ide> formula = loader_for(ref, from: from).get_formula(spec, alias_path: alias_path, <del> force_bottle: force_bottle, flags: flags) <add> force_bottle: force_bottle, flags: flags, <add> ignore_errors: ignore_errors) <ide> if factory_cached? <ide> cache[:formulary_factory] ||= {} <ide> cache[:formulary_factory][cache_key] ||= formula <ide> def self.from_keg(keg, spec = nil, alias_path: nil, force_bottle: false, flags: <ide> end <ide> <ide> # Return a {Formula} instance directly from contents. <del> def self.from_contents(name, path, contents, spec = :stable, alias_path: nil, force_bottle: false, flags: []) <add> def self.from_contents( <add> name, path, contents, spec = :stable, alias_path: nil, <add> force_bottle: false, flags: [], ignore_errors: false <add> ) <ide> FormulaContentsLoader.new(name, path, contents) <del> .get_formula(spec, alias_path: alias_path, force_bottle: force_bottle, flags: flags) <add> .get_formula(spec, alias_path: alias_path, force_bottle: force_bottle, <add> flags: flags, ignore_errors: ignore_errors) <ide> end <ide> <ide> def self.to_rack(ref)
1
Javascript
Javascript
fix invalid prop usage in rntesterexamplelist
da057749f8be59516b7dcb5cb3a7bdb67c3d990c
<ide><path>RNTester/js/components/RNTesterExampleList.js <ide> class RNTesterExampleList extends React.Component<Props, $FlowFixMeState> { <ide> automaticallyAdjustContentInsets={false} <ide> keyboardDismissMode="on-drag" <ide> renderSectionHeader={renderSectionHeader} <del> backgroundColor={Platform.select({ <del> ios: 'transparent', <del> default: undefined, <del> })} <ide> /> <ide> )} <ide> />
1
Ruby
Ruby
update depends_on_java to suggest temurin
8c22e009acaafa7de7c2c8ee298229efd21f2503
<ide><path>Library/Homebrew/cask/dsl/caveats.rb <ide> def eval_caveats(&block) <ide> if java_version == :any <ide> <<~EOS <ide> #{@cask} requires Java. You can install the latest version with: <del> brew install --cask adoptopenjdk <add> brew install --cask temurin <ide> EOS <ide> elsif java_version.include?("+") <ide> <<~EOS <ide> #{@cask} requires Java #{java_version}. You can install the latest version with: <del> brew install --cask adoptopenjdk <add> brew install --cask temurin <ide> EOS <ide> else <ide> <<~EOS <ide> #{@cask} requires Java #{java_version}. You can install it with: <del> brew install --cask homebrew/cask-versions/adoptopenjdk#{java_version} <add> brew install --cask homebrew/cask-versions/temurin#{java_version} <ide> EOS <ide> end <ide> end
1
Ruby
Ruby
verbose => false as in new thor version
b4ef958de6b16294094de28d00ba25fe2f48accc
<ide><path>railties/lib/generators/actions.rb <ide> module Actions <ide> # <ide> # apply "recipes/jquery.rb" <ide> # <del> def apply(path, log_status=true) <add> def apply(path) <ide> path = find_in_source_paths(path) unless path =~ /^http\:\/\// <ide> <del> log :apply, path, log_status <add> log :apply, path <add> shell.padding += 1 <ide> instance_eval(open(path).read) <del> log :applied, path, log_status <add> shell.padding -= 1 <ide> end <ide> <ide> # Install a plugin. You must provide either a Subversion url or Git url. <ide> def plugin(name, options) <ide> <ide> if options[:git] && options[:submodule] <ide> in_root do <del> run "git submodule add #{options[:git]} vendor/plugins/#{name}", false <add> run "git submodule add #{options[:git]} vendor/plugins/#{name}", :verbose => false <ide> end <ide> elsif options[:git] || options[:svn] <ide> in_root do <del> run_ruby_script "script/plugin install #{options[:svn] || options[:git]}", false <add> run_ruby_script "script/plugin install #{options[:svn] || options[:git]}", :verbose => false <ide> end <ide> else <ide> log "! no git or svn provided for #{name}. Skipping..." <ide> def plugin(name, options) <ide> # gem "rspec", :env => :test <ide> # gem "technoweenie-restful-authentication", :lib => "restful-authentication", :source => "http://gems.github.com/" <ide> # <del> def gem(name, options = {}) <add> def gem(name, options={}) <ide> log :gem, name <ide> env = options.delete(:env) <ide> <ide> def environment(data=nil, options={}, &block) <ide> <ide> in_root do <ide> if options[:env].nil? <del> inject_into_file 'config/environment.rb', "\n #{data}", { :after => sentinel }, false <add> inject_into_file 'config/environment.rb', "\n #{data}", :after => sentinel, :verbose => false <ide> else <ide> Array.wrap(options[:env]).each do|env| <del> append_file "config/environments/#{env}.rb", "\n#{data}", false <add> append_file "config/environments/#{env}.rb", "\n#{data}", :verbose => false <ide> end <ide> end <ide> end <ide> def environment(data=nil, options={}, &block) <ide> # git :add => "this.file that.rb" <ide> # git :add => "onefile.rb", :rm => "badfile.cxx" <ide> # <del> def git(command = {}) <add> def git(command={}) <ide> in_root do <ide> if command.is_a?(Symbol) <ide> run "git #{command}" <ide> def git(command = {}) <ide> # <ide> def vendor(filename, data=nil, &block) <ide> log :vendor, filename <del> create_file("vendor/#{filename}", data, false, &block) <add> create_file("vendor/#{filename}", data, :verbose => false, &block) <ide> end <ide> <ide> # Create a new file in the lib/ directory. Code can be specified <ide> def vendor(filename, data=nil, &block) <ide> # <ide> def lib(filename, data=nil, &block) <ide> log :lib, filename <del> create_file("lib/#{filename}", data, false, &block) <add> create_file("lib/#{filename}", data, :verbose => false, &block) <ide> end <ide> <ide> # Create a new Rakefile with the provided code (either in a block or a string). <ide> def lib(filename, data=nil, &block) <ide> # <ide> def rakefile(filename, data=nil, &block) <ide> log :rakefile, filename <del> create_file("lib/tasks/#{filename}", data, false, &block) <add> create_file("lib/tasks/#{filename}", data, :verbose => false, &block) <ide> end <ide> <ide> # Create a new initializer with the provided code (either in a block or a string). <ide> def rakefile(filename, data=nil, &block) <ide> # <ide> def initializer(filename, data=nil, &block) <ide> log :initializer, filename <del> create_file("config/initializers/#{filename}", data, false, &block) <add> create_file("config/initializers/#{filename}", data, :verbose => false, &block) <ide> end <ide> <ide> # Generate something using a generator from Rails or a plugin. <ide> def generate(what, *args) <ide> log :generate, what <ide> argument = args.map {|arg| arg.to_s }.flatten.join(" ") <ide> <del> in_root { run_ruby_script("script/generate #{what} #{argument}", false) } <add> in_root { run_ruby_script("script/generate #{what} #{argument}", :verbose => false) } <ide> end <ide> <ide> # Runs the supplied rake task <ide> def rake(command, options={}) <ide> log :rake, command <ide> env = options[:env] || 'development' <ide> sudo = options[:sudo] && RUBY_PLATFORM !~ /mswin|mingw/ ? 'sudo ' : '' <del> in_root { run("#{sudo}#{extify(:rake)} #{command} RAILS_ENV=#{env}", false) } <add> in_root { run("#{sudo}#{extify(:rake)} #{command} RAILS_ENV=#{env}", :verbose => false) } <ide> end <ide> <ide> # Just run the capify command in root <ide> def rake(command, options={}) <ide> # <ide> def capify! <ide> log :capify, "" <del> in_root { run("#{extify(:capify)} .", false) } <add> in_root { run("#{extify(:capify)} .", :verbose => false) } <ide> end <ide> <ide> # Add Rails to /vendor/rails <ide> def capify! <ide> # <ide> def freeze!(args = {}) <ide> log :vendor, "rails" <del> in_root { run("#{extify(:rake)} rails:freeze:edge", false) } <add> in_root { run("#{extify(:rake)} rails:freeze:edge", :verbose => false) } <ide> end <ide> <ide> # Make an entry in Rails routing file conifg/routes.rb <ide> def route(routing_code) <ide> sentinel = "ActionController::Routing::Routes.draw do |map|" <ide> <ide> in_root do <del> inject_into_file 'config/routes.rb', "\n #{routing_code}\n", { :after => sentinel }, false <add> inject_into_file 'config/routes.rb', "\n #{routing_code}\n", { :after => sentinel, :verbose => false } <ide> end <ide> end <ide> <ide><path>railties/lib/generators/migration.rb <ide> def self.included(base) #:nodoc: <ide> # <ide> # migration_template "migration.rb", "db/migrate/add_foo_to_bar.rb" <ide> # <del> def migration_template(source, destination=nil, log_status=true) <add> def migration_template(source, destination=nil, config={}) <ide> destination = File.expand_path(destination || source, self.destination_root) <ide> <ide> migration_dir = File.dirname(destination) <ide> def migration_template(source, destination=nil, log_status=true) <ide> destination = File.join(migration_dir, "#{@migration_number}_#{@migration_file_name}.rb") <ide> end <ide> <del> template(source, destination, log_status) <add> template(source, destination, config) <ide> end <ide> <ide> protected <ide><path>railties/lib/generators/rails/app/app_generator.rb <ide> def create_log_files <ide> inside "log" do <ide> %w( server production development test ).each do |file| <ide> create_file "#{file}.log" <del> chmod "#{file}.log", 0666, false <add> chmod "#{file}.log", 0666, :verbose => false <ide> end <ide> end <ide> end <ide> <ide> def create_public_files <del> directory "public", "public", false # Non-recursive. Do small steps, so anyone can overwrite it. <add> directory "public", "public", :recursive => false # Do small steps, so anyone can overwrite it. <ide> end <ide> <ide> def create_dispatch_files <ide> return unless options[:with_dispatchers] <ide> copy_file "dispatchers/config.ru", "config.ru" <ide> <ide> template "dispatchers/dispatch.rb", "public/dispatch.rb" <del> chmod "public/dispatch.rb", 0755, false <add> chmod "public/dispatch.rb", 0755, :verbose => false <ide> <ide> template "dispatchers/dispatch.rb", "public/dispatch.cgi" <del> chmod "public/dispatch.cgi", 0755, false <add> chmod "public/dispatch.cgi", 0755, :verbose => false <ide> <ide> template "dispatchers/dispatch.fcgi", "public/dispatch.fcgi" <del> chmod "public/dispatch.fcgi", 0755, false <add> chmod "public/dispatch.fcgi", 0755, :verbose => false <ide> end <ide> <ide> def create_public_image_files <ide> def create_prototype_files <ide> <ide> def create_script_files <ide> directory "script" <del> chmod "script", 0755, false <add> chmod "script", 0755, :verbose => false <ide> end <ide> <ide> def create_test_files <ide><path>railties/lib/generators/rails/plugin/plugin_generator.rb <ide> class PluginGenerator < NamedBase <ide> check_class_collision <ide> <ide> def create_root_files <del> directory '.', plugin_dir, false # non-recursive <add> directory '.', plugin_dir, :recursive => false <ide> end <ide> <ide> def create_lib_files <del> directory 'lib', plugin_dir('lib'), false # non-recursive <add> directory 'lib', plugin_dir('lib'), :recursive => false <ide> end <ide> <ide> def create_tasks_files <ide><path>railties/lib/vendor/thor-0.11.1/lib/thor/actions.rb <ide> def inside(dir='', &block) <ide> <ide> # Same as inside, but log status and use padding. <ide> # <del> def inside_with_padding(dir='', log_status=true, &block) <del> say_status :inside, dir, log_status <add> def inside_with_padding(dir='', config={}, &block) <add> say_status :inside, dir, config.fetch(:verbose, true) <ide> shell.padding += 1 <ide> inside(dir, &block) <ide> shell.padding -= 1 <ide> def in_root <ide> # ==== Parameters <ide> # mode<Integer>:: the file mode <ide> # path<String>:: the name of the file to change mode <del> # log_status<Boolean>:: if false, does not log the status. True by default. <del> # If a symbol is given, uses it as the output color. <add> # config<Hash>:: give :verbose => false to not log the status. <ide> # <ide> # ==== Example <ide> # <ide> # chmod "script/*", 0755 <ide> # <del> def chmod(path, mode, log_status=true) <add> def chmod(path, mode, config={}) <ide> return unless behavior == :invoke <ide> path = File.expand_path(path, destination_root) <del> say_status :chmod, relative_to_original_destination_root(path), log_status <add> say_status :chmod, relative_to_original_destination_root(path), config.fetch(:verbose, true) <ide> FileUtils.chmod_R(mode, path) unless options[:pretend] <ide> end <ide> <ide> # Executes a command. <ide> # <ide> # ==== Parameters <ide> # command<String>:: the command to be executed. <del> # log_status<Boolean>:: if false, does not log the status. True by default. <del> # If a symbol is given, uses it as the output color. <add> # config<Hash>:: give :verbose => false to not log the status. <ide> # <ide> # ==== Example <ide> # <ide> # inside('vendor') do <ide> # run('ln -s ~/edge rails') <ide> # end <ide> # <del> def run(command, log_status=true) <add> def run(command, config={}) <ide> return unless behavior == :invoke <del> say_status :run, "\"#{command}\" from #{relative_to_original_destination_root(destination_root, false)}", log_status <add> description = "#{command.inspect} from #{relative_to_original_destination_root(destination_root, false)}" <add> say_status :run, description, config.fetch(:verbose, true) <ide> `#{command}` unless options[:pretend] <ide> end <ide> <ide> # Executes a ruby script (taking into account WIN32 platform quirks). <ide> # <ide> # ==== Parameters <ide> # command<String>:: the command to be executed. <del> # log_status<Boolean>:: if false, does not log the status. True by default. <del> # If a symbol is given, uses it as the output color. <add> # config<Hash>:: give :verbose => false to not log the status. <ide> # <del> def run_ruby_script(command, log_status=true) <add> def run_ruby_script(command, config={}) <ide> return unless behavior == :invoke <del> say_status File.basename(Thor::Util.ruby_command), command, log_status <add> say_status File.basename(Thor::Util.ruby_command), command, config.fetch(:verbose, true) <ide> `#{Thor::Util.ruby_command} #{command}` unless options[:pretend] <ide> end <ide> <ide> def run_ruby_script(command, log_status=true) <ide> # ==== Parameters <ide> # task<String>:: the task to be invoked <ide> # args<Array>:: arguments to the task <del> # options<Hash>:: a hash with options used on invocation <del> # log_status<Boolean>:: if false, does not log the status. True by default. <del> # If a symbol is given, uses it as the output color. <add> # options<Hash>:: give :verbose => false to not log the status. Other options <add> # are given as parameter to Thor. <ide> # <ide> # ==== Examples <ide> # <ide> def run_ruby_script(command, log_status=true) <ide> # #=> thor list --all --substring=rails <ide> # <ide> def thor(task, *args) <del> log_status = args.last.is_a?(Symbol) || [true, false].include?(args.last) ? args.pop : true <del> options = args.last.is_a?(Hash) ? args.pop : {} <add> config = args.last.is_a?(Hash) ? args.pop : {} <add> verbose = config.key?(:verbose) ? config.delete(:verbose) : true <ide> <ide> args.unshift task <del> args.push Thor::Options.to_switches(options) <add> args.push Thor::Options.to_switches(config) <ide> command = args.join(' ').strip <ide> <del> say_status :thor, command, log_status <del> run "thor #{command}", false <add> say_status :thor, command, verbose <add> run "thor #{command}", :verbose => false <ide> end <ide> <ide> # Removes a file at the given location. <ide> # <ide> # ==== Parameters <ide> # path<String>:: path of the file to be changed <del> # log_status<Boolean>:: if false, does not log the status. True by default. <del> # If a symbol is given, uses it as the output color. <add> # config<Hash>:: give :verbose => false to not log the status. <ide> # <ide> # ==== Example <ide> # <ide> # remove_file 'README' <ide> # remove_file 'app/controllers/application_controller.rb' <ide> # <del> def remove_file(path, log_status=true) <add> def remove_file(path, config={}) <ide> return unless behavior == :invoke <ide> path = File.expand_path(path, destination_root) <del> color = log_status.is_a?(Symbol) ? log_status : :red <ide> <del> say_status :remove, relative_to_original_destination_root(path), log_status <add> say_status :remove, relative_to_original_destination_root(path), config.fetch(:verbose, true) <ide> ::FileUtils.rm_rf(path) if !options[:pretend] && File.exists?(path) <ide> end <ide> <ide> def remove_file(path, log_status=true) <ide> # path<String>:: path of the file to be changed <ide> # flag<Regexp|String>:: the regexp or string to be replaced <ide> # replacement<String>:: the replacement, can be also given as a block <del> # log_status<Boolean>:: if false, does not log the status. True by default. <del> # If a symbol is given, uses it as the output color. <add> # config<Hash>:: give :verbose => false to not log the status. <ide> # <ide> # ==== Example <ide> # <ide> def remove_file(path, log_status=true) <ide> # <ide> def gsub_file(path, flag, *args, &block) <ide> return unless behavior == :invoke <del> log_status = args.last.is_a?(Symbol) || [ true, false ].include?(args.last) ? args.pop : true <add> config = args.last.is_a?(Hash) ? args.pop : {} <ide> <ide> path = File.expand_path(path, destination_root) <del> say_status :gsub, relative_to_original_destination_root(path), log_status <add> say_status :gsub, relative_to_original_destination_root(path), config.fetch(:verbose, true) <ide> <ide> unless options[:pretend] <ide> content = File.read(path) <ide> def gsub_file(path, flag, *args, &block) <ide> # ==== Parameters <ide> # path<String>:: path of the file to be changed <ide> # data<String>:: the data to append to the file, can be also given as a block. <del> # log_status<Boolean>:: if false, does not log the status. True by default. <del> # If a symbol is given, uses it as the output color. <add> # config<Hash>:: give :verbose => false to not log the status. <ide> # <ide> # ==== Example <ide> # <ide> # append_file 'config/environments/test.rb', 'config.gem "rspec"' <ide> # <del> def append_file(path, data=nil, log_status=true, &block) <add> def append_file(path, data=nil, config={}, &block) <ide> return unless behavior == :invoke <ide> path = File.expand_path(path, destination_root) <del> say_status :append, relative_to_original_destination_root(path), log_status <add> say_status :append, relative_to_original_destination_root(path), config.fetch(:verbose, true) <ide> File.open(path, 'ab') { |file| file.write(data || block.call) } unless options[:pretend] <ide> end <ide> <ide> def append_file(path, data=nil, log_status=true, &block) <ide> # ==== Parameters <ide> # path<String>:: path of the file to be changed <ide> # data<String>:: the data to prepend to the file, can be also given as a block. <del> # log_status<Boolean>:: if false, does not log the status. True by default. <del> # If a symbol is given, uses it as the output color. <add> # config<Hash>:: give :verbose => false to not log the status. <ide> # <ide> # ==== Example <ide> # <ide> # prepend_file 'config/environments/test.rb', 'config.gem "rspec"' <ide> # <del> def prepend_file(path, data=nil, log_status=true, &block) <add> def prepend_file(path, data=nil, config={}, &block) <ide> return unless behavior == :invoke <ide> path = File.expand_path(path, destination_root) <del> say_status :prepend, relative_to_original_destination_root(path), log_status <add> say_status :prepend, relative_to_original_destination_root(path), config.fetch(:verbose, true) <ide> <ide> unless options[:pretend] <ide> content = data || block.call <ide><path>railties/lib/vendor/thor-0.11.1/lib/thor/actions/copy_file.rb <ide> module Actions <ide> # the destination is not given it's assumed to be equal to the source. <ide> # <ide> # ==== Parameters <del> # source<String>:: the relative path to the source root <del> # destination<String>:: the relative path to the destination root <del> # log_status<Boolean>:: if false, does not log the status. True by default. <add> # source<String>:: the relative path to the source root. <add> # destination<String>:: the relative path to the destination root. <add> # config<Hash>:: give :verbose => false to not log the status. <ide> # <ide> # ==== Examples <ide> # <ide> # copy_file "README", "doc/README" <ide> # <ide> # copy_file "doc/README" <ide> # <del> def copy_file(source, destination=nil, log_status=true) <del> action CopyFile.new(self, source, destination || source, log_status) <add> def copy_file(source, destination=nil, config={}) <add> action CopyFile.new(self, source, destination || source, config) <ide> end <ide> <ide> class CopyFile < Templater #:nodoc: <ide><path>railties/lib/vendor/thor-0.11.1/lib/thor/actions/create_file.rb <ide> module Actions <ide> # ==== Parameters <ide> # destination<String>:: the relative path to the destination root. <ide> # data<String|NilClass>:: the data to append to the file. <del> # log_status<Boolean>:: if false, does not log the status. True by default. <add> # config<Hash>:: give :verbose => false to not log the status. <ide> # <ide> # ==== Examples <ide> # <ide> module Actions <ide> # <ide> # create_file "config/apach.conf", "your apache config" <ide> # <del> def create_file(destination, data=nil, log_status=true, &block) <del> action CreateFile.new(self, destination, block || data.to_s, log_status) <add> def create_file(destination, data=nil, config={}, &block) <add> action CreateFile.new(self, destination, block || data.to_s, config) <ide> end <ide> alias :add_file :create_file <ide> <ide> def create_file(destination, data=nil, log_status=true, &block) <ide> class CreateFile < Templater #:nodoc: <ide> attr_reader :data <ide> <del> def initialize(base, destination, data, log_status) <del> super(base, nil, destination, log_status) <add> def initialize(base, destination, data, config={}) <add> super(base, nil, destination, config) <ide> @data = data <ide> end <ide> <ide><path>railties/lib/vendor/thor-0.11.1/lib/thor/actions/directory.rb <ide> module Actions <ide> # blog.rb <ide> # <ide> # ==== Parameters <del> # source<String>:: the relative path to the source root <del> # destination<String>:: the relative path to the destination root <del> # recursive<Boolean>:: if the directory must be copied recursively, true by default <del> # log_status<Boolean>:: if false, does not log the status. True by default. <add> # source<String>:: the relative path to the source root. <add> # destination<String>:: the relative path to the destination root. <add> # config<Hash>:: give :verbose => false to not log the status. <add> # If :recursive => false, does not look for paths recursively. <ide> # <ide> # ==== Examples <ide> # <ide> # directory "doc" <del> # directory "doc", "docs", false <add> # directory "doc", "docs", :recursive => false <ide> # <del> def directory(source, destination=nil, recursive=true, log_status=true) <del> action Directory.new(self, source, destination || source, recursive, log_status) <add> def directory(source, destination=nil, config={}) <add> action Directory.new(self, source, destination || source, config) <ide> end <ide> <ide> class Directory < Templater #:nodoc: <del> attr_reader :recursive <del> <del> def initialize(base, source, destination=nil, recursive=true, log_status=true) <del> @recursive = recursive <del> super(base, source, destination, log_status) <add> def initialize(base, source, destination=nil, config={}) <add> super(base, source, destination, { :recursive => true }.merge(config)) <ide> end <ide> <ide> def invoke! <del> base.empty_directory given_destination, @log_status <add> base.empty_directory given_destination, config <ide> execute! <ide> end <ide> <ide> def revoke! <ide> protected <ide> <ide> def execute! <del> lookup = recursive ? File.join(source, '**') : source <add> lookup = config[:recursive] ? File.join(source, '**') : source <ide> lookup = File.join(lookup, '{*,.[a-z]*}') <ide> <ide> Dir[lookup].each do |file_source| <ide> def execute! <ide> <ide> case file_source <ide> when /\.empty_directory$/ <del> base.empty_directory(File.dirname(file_destination), @log_status) <add> base.empty_directory(File.dirname(file_destination), config) <ide> when /\.tt$/ <del> base.template(file_source, file_destination[0..-4], @log_status) <add> base.template(file_source, file_destination[0..-4], config) <ide> else <del> base.copy_file(file_source, file_destination, @log_status) <add> base.copy_file(file_source, file_destination, config) <ide> end <ide> end <ide> end <ide><path>railties/lib/vendor/thor-0.11.1/lib/thor/actions/empty_directory.rb <ide> module Actions <ide> # Creates an empty directory. <ide> # <ide> # ==== Parameters <del> # destination<String>:: the relative path to the destination root <del> # log_status<Boolean>:: if false, does not log the status. True by default. <add> # destination<String>:: the relative path to the destination root. <add> # config<Hash>:: give :verbose => false to not log the status. <ide> # <ide> # ==== Examples <ide> # <ide> # empty_directory "doc" <ide> # <del> def empty_directory(destination, log_status=true) <del> action EmptyDirectory.new(self, nil, destination, log_status) <add> def empty_directory(destination, config={}) <add> action EmptyDirectory.new(self, nil, destination, config) <ide> end <ide> <ide> class EmptyDirectory < Templater #:nodoc: <ide> <ide> def invoke! <del> invoke_with_options!(base.options) do <add> invoke_with_options!(base.options.merge(config)) do <ide> ::FileUtils.mkdir_p(destination) <ide> end <ide> end <ide><path>railties/lib/vendor/thor-0.11.1/lib/thor/actions/get.rb <ide> module Actions <ide> # the url is yielded and used as location. <ide> # <ide> # ==== Parameters <del> # source<String>:: the address of the given content <del> # destination<String>:: the relative path to the destination root <del> # log_status<Boolean>:: if false, does not log the status. True by default. <add> # source<String>:: the address of the given content. <add> # destination<String>:: the relative path to the destination root. <add> # config<Hash>:: give :verbose => false to not log the status. <ide> # <ide> # ==== Examples <ide> # <ide> module Actions <ide> # content.split("\n").first <ide> # end <ide> # <del> def get(source, destination=nil, log_status=true, &block) <del> action Get.new(self, source, block || destination, log_status) <add> def get(source, destination=nil, config={}, &block) <add> action Get.new(self, source, block || destination, config) <ide> end <ide> <ide> class Get < Templater #:nodoc: <ide><path>railties/lib/vendor/thor-0.11.1/lib/thor/actions/inject_into_file.rb <ide> module Actions <ide> # ==== Parameters <ide> # destination<String>:: Relative path to the destination root <ide> # data<String>:: Data to add to the file. Can be given as a block. <del> # flag<String>:: Flag of where to add the changes. <del> # log_status<Boolean>:: If false, does not log the status. True by default. <del> # If a symbol is given, uses it as the output color. <add> # config<Hash>:: give :verbose => false to not log the status and the flag <add> # for injection (:after or :before). <ide> # <ide> # ==== Examples <ide> # <ide> module Actions <ide> # <ide> def inject_into_file(destination, *args, &block) <ide> if block_given? <del> data, flag = block, args.shift <add> data, config = block, args.shift <ide> else <del> data, flag = args.shift, args.shift <add> data, config = args.shift, args.shift <ide> end <ide> <ide> log_status = args.empty? || args.pop <del> action InjectIntoFile.new(self, destination, data, flag, log_status) <add> action InjectIntoFile.new(self, destination, data, config) <ide> end <ide> <ide> class InjectIntoFile #:nodoc: <del> attr_reader :base, :destination, :relative_destination, :flag, :replacement <add> attr_reader :base, :destination, :relative_destination, :flag, :replacement, :config <ide> <del> def initialize(base, destination, data, flag, log_status=true) <del> @base, @log_status = base, log_status <del> behavior, @flag = flag.keys.first, flag.values.first <add> def initialize(base, destination, data, config) <add> @base, @config = base, { :verbose => true }.merge(config) <ide> <ide> self.destination = destination <ide> data = data.call if data.is_a?(Proc) <ide> <del> @replacement = if behavior == :after <add> @replacement = if @config.key?(:after) <add> @flag = @config.delete(:after) <ide> @flag + data <ide> else <add> @flag = @config.delete(:before) <ide> data + @flag <ide> end <ide> end <ide> def destination=(destination) <ide> # Shortcut to say_status shell method. <ide> # <ide> def say_status(status) <del> base.shell.say_status status, relative_destination, @log_status <add> base.shell.say_status status, relative_destination, config[:verbose] <ide> end <ide> <ide> # Adds the content to the file. <ide><path>railties/lib/vendor/thor-0.11.1/lib/thor/actions/template.rb <ide> module Actions <ide> # to be equal to the source removing .tt from the filename. <ide> # <ide> # ==== Parameters <del> # source<String>:: the relative path to the source root <del> # destination<String>:: the relative path to the destination root <del> # log_status<Boolean>:: if false, does not log the status. True by default. <add> # source<String>:: the relative path to the source root. <add> # destination<String>:: the relative path to the destination root. <add> # config<Hash>:: give :verbose => false to not log the status. <ide> # <ide> # ==== Examples <ide> # <ide> # template "README", "doc/README" <ide> # <ide> # template "doc/README" <ide> # <del> def template(source, destination=nil, log_status=true) <add> def template(source, destination=nil, config={}) <ide> destination ||= source.gsub(/.tt$/, '') <del> action Template.new(self, source, destination, log_status) <add> action Template.new(self, source, destination, config) <ide> end <ide> <ide> class Template < Templater #:nodoc: <ide><path>railties/lib/vendor/thor-0.11.1/lib/thor/actions/templater.rb <ide> module Actions <ide> # by Jonas Nicklas and Michael S. Klishin under MIT LICENSE. <ide> # <ide> class Templater #:nodoc: <del> attr_reader :base, :source, :destination, :given_destination, :relative_destination <add> attr_reader :base, :source, :destination, :given_destination, :relative_destination, :config <ide> <ide> # Initializes given the source and destination. <ide> # <ide> # ==== Parameters <ide> # base<Thor::Base>:: A Thor::Base instance <ide> # source<String>:: Relative path to the source of this file <ide> # destination<String>:: Relative path to the destination of this file <del> # log_status<Boolean>:: If false, does not log the status. True by default. <del> # Templater log status does not accept color. <add> # config<Hash>:: give :verbose => false to not log the status. <ide> # <del> def initialize(base, source, destination, log_status=true) <del> @base, @log_status = base, log_status <add> def initialize(base, source, destination, config={}) <add> @base, @config = base, { :verbose => true }.merge(config) <ide> self.source = source <ide> self.destination = destination <ide> end <ide> def identical? <ide> # but you can modify in the subclass. <ide> # <ide> def invoke! <del> invoke_with_options!(base.options) do <add> invoke_with_options!(base.options.merge(config)) do <ide> ::FileUtils.mkdir_p(::File.dirname(destination)) <ide> ::File.open(destination, 'w'){ |f| f.write render } <ide> end <ide> def force_on_collision? <ide> # Shortcut to say_status shell method. <ide> # <ide> def say_status(status, color) <del> base.shell.say_status status, relative_destination, color if @log_status <add> base.shell.say_status status, relative_destination, color if config[:verbose] <ide> end <ide> <ide> end <ide><path>railties/test/generators/actions_test.rb <ide> def test_apply_loads_and_evaluates_a_template <ide> assert_equal generator.instance_variable_get("@foo"), "FOO" <ide> end <ide> <add> def test_apply_uses_padding_in_the_applied_template <add> template = <<-TEMPLATE <add> say_status :cool, :padding <add> TEMPLATE <add> template.instance_eval "def read; self; end" <add> <add> generator.expects(:open).with("http://gist.github.com/103208.txt").returns(template) <add> content = action(:apply, "http://gist.github.com/103208.txt") <add> assert_match /cool padding/, content <add> end <add> <ide> def test_create_file_should_write_data_to_file_path <ide> action :create_file, 'lib/test_file.rb', 'heres test data' <ide> assert_file 'lib/test_file.rb', 'heres test data' <ide> def test_create_file_should_write_block_contents_to_file_path <ide> end <ide> <ide> def test_plugin_with_git_option_should_run_plugin_install <del> generator.expects(:run_ruby_script).once.with("script/plugin install #{@git_plugin_uri}", false) <add> generator.expects(:run_ruby_script).once.with("script/plugin install #{@git_plugin_uri}", :verbose => false) <ide> action :plugin, 'restful-authentication', :git => @git_plugin_uri <ide> end <ide> <ide> def test_plugin_with_svn_option_should_run_plugin_install <del> generator.expects(:run_ruby_script).once.with("script/plugin install #{@svn_plugin_uri}", false) <add> generator.expects(:run_ruby_script).once.with("script/plugin install #{@svn_plugin_uri}", :verbose => false) <ide> action :plugin, 'restful-authentication', :svn => @svn_plugin_uri <ide> end <ide> <ide> def test_plugin_with_git_option_and_submodule_should_use_git_scm <del> generator.expects(:run).with("git submodule add #{@git_plugin_uri} vendor/plugins/rest_auth", false) <add> generator.expects(:run).with("git submodule add #{@git_plugin_uri} vendor/plugins/rest_auth", :verbose => false) <ide> action :plugin, 'rest_auth', :git => @git_plugin_uri, :submodule => true <ide> end <ide> <ide> def test_initializer_should_write_date_to_file_in_config_initializers <ide> end <ide> <ide> def test_generate_should_run_script_generate_with_argument_and_options <del> generator.expects(:run_ruby_script).once.with('script/generate model MyModel', false) <add> generator.expects(:run_ruby_script).once.with('script/generate model MyModel', :verbose => false) <ide> action :generate, 'model', 'MyModel' <ide> end <ide> <ide> def test_rake_should_run_rake_command_with_development_env <del> generator.expects(:run).once.with('rake log:clear RAILS_ENV=development', false) <add> generator.expects(:run).once.with('rake log:clear RAILS_ENV=development', :verbose => false) <ide> action :rake, 'log:clear' <ide> end <ide> <ide> def test_rake_with_env_option_should_run_rake_command_in_env <del> generator.expects(:run).once.with('rake log:clear RAILS_ENV=production', false) <add> generator.expects(:run).once.with('rake log:clear RAILS_ENV=production', :verbose => false) <ide> action :rake, 'log:clear', :env => 'production' <ide> end <ide> <ide> def test_rake_with_sudo_option_should_run_rake_command_with_sudo <del> generator.expects(:run).once.with('sudo rake log:clear RAILS_ENV=development', false) <add> generator.expects(:run).once.with('sudo rake log:clear RAILS_ENV=development', :verbose => false) <ide> action :rake, 'log:clear', :sudo => true <ide> end <ide> <ide> def test_capify_should_run_the_capify_command <del> generator.expects(:run).once.with('capify .', false) <add> generator.expects(:run).once.with('capify .', :verbose => false) <ide> action :capify! <ide> end <ide> <ide> def test_freeze_should_freeze_rails_edge <del> generator.expects(:run).once.with('rake rails:freeze:edge', false) <add> generator.expects(:run).once.with('rake rails:freeze:edge', :verbose => false) <ide> action :freeze! <ide> end <ide> <ide><path>railties/test/generators/app_generator_test.rb <ide> def test_shebang_when_is_the_same_as_default_use_env <ide> end <ide> <ide> def test_rails_is_frozen <del> generator(:freeze => true, :database => "sqlite3").expects(:run).with("rake rails:freeze:edge", false) <add> generator(:freeze => true, :database => "sqlite3").expects(:run). <add> with("rake rails:freeze:edge", :verbose => false) <ide> silence(:stdout){ generator.invoke } <ide> assert_file 'config/environment.rb', /# RAILS_GEM_VERSION/ <ide> end <ide><path>railties/test/generators/generators_test_helper.rb <ide> require 'generators' <ide> <ide> CURRENT_PATH = File.expand_path(Dir.pwd) <add>Rails::Generators.no_color! <ide> <ide> class GeneratorsTestCase < Test::Unit::TestCase <ide> include FileUtils <ide><path>railties/test/generators/scaffold_generator_test.rb <ide> def test_scaffold_on_revoke <ide> assert_file "public/stylesheets/scaffold.css" <ide> end <ide> <del> def test_invoke_output <del> output = run_generator <del> assert_match /invoke.{4} active_record/, output <del> assert_match /create.{4} app\/models\/product_line\.rb/, output <del> end <del> <ide> protected <ide> <ide> def run_generator(config={})
17
Javascript
Javascript
make test context an es6 module
f3ef620c6876ad13188f5c95f65b010952d219ea
<ide><path>karma.conf.js <ide> module.exports = function(karma) { <ide> plugins: [ <ide> resolve(), <ide> babel({exclude: 'node_modules/**'}), // use babel since we have ES proposal features <del> commonjs() <add> commonjs({exclude: ['src/**', 'test/**']}) <ide> ], <ide> output: { <ide> name: 'test', <ide><path>test/context.js <ide> // Code from https://stackoverflow.com/questions/4406864/html-canvas-unit-testing <del>var Context = function() { <add>const Context = function() { <ide> this._calls = []; // names/args of recorded calls <ide> this._initMethods(); <ide> <ide> Context.prototype.resetCalls = function() { <ide> this._calls = []; <ide> }; <ide> <del>module.exports = Context; <add>export default Context;
2
PHP
PHP
add regression test for
9b0c1fc5606ca53116ea2913b5e629c6e7f13d49
<ide><path>tests/TestCase/ORM/QueryRegressionTest.php <ide> public function testDotNotationNotOverride() <ide> <ide> $this->assertEquals([['name' => 'nate', 'tag' => 'tag1']], $results); <ide> } <add> <add> /** <add> * Test expression based ordering with unions. <add> * <add> * @return void <add> */ <add> public function testComplexOrderWithUnion() <add> { <add> $table = TableRegistry::get('Comments'); <add> $query = $table->find(); <add> $inner = $table->find()->where(['id >' => 3]); <add> $inner2 = $table->find()->where(['id <' => 3]); <add> <add> $order = $query->func()->concat(['inside__comment' => 'literal', 'test']); <add> <add> $query->select(['inside__comment' => 'Comments__comment']) <add> ->from(['inside' => $inner->unionAll($inner2)]) <add> ->orderAsc($order); <add> <add> $results = $query->toArray(); <add> $this->assertCount(5, $results); <add> } <ide> }
1
Text
Text
replace uses of `you` and other style nits
71f22c842bc3f9e04ebf110461c42b07a304f352
<ide><path>doc/api/addons.md <ide> involving knowledge of several components and APIs : <ide> See [Linking to Node.js' own dependencies][] for additional information. <ide> <ide> All of the following examples are available for [download][] and may <del>be used as a starting-point for your own Addon. <add>be used as the starting-point for an Addon. <ide> <ide> ## Hello world <ide> <ide> Addon module name is `addon`. <ide> <ide> Once the source code has been written, it must be compiled into the binary <ide> `addon.node` file. To do so, create a file called `binding.gyp` in the <del>top-level of the project describing the build configuration of your module <add>top-level of the project describing the build configuration of the module <ide> using a JSON-like format. This file is used by [node-gyp][] -- a tool written <ide> specifically to compile Node.js Addons. <ide> <ide><path>doc/api/child_process.md <ide> The `'error'` event is emitted whenever: <ide> 2. The process could not be killed, or <ide> 3. Sending a message to the child process failed. <ide> <del>Note that the `'exit'` event may or may not fire after an error has occurred. <del>If you are listening to both the `'exit'` and `'error'` events, it is important <add>*Note*: The `'exit'` event may or may not fire after an error has occurred. <add>When listening to both the `'exit'` and `'error'` events, it is important <ide> to guard against accidentally invoking handler functions multiple times. <ide> <ide> See also [`child.kill()`][] and [`child.send()`][]. <ide><path>doc/api/cli.md <ide> Node.js comes with a variety of CLI options. These options expose built-in <ide> debugging, multiple ways to execute scripts, and other helpful runtime options. <ide> <del>To view this documentation as a manual page in your terminal, run `man node`. <add>To view this documentation as a manual page in a terminal, run `man node`. <ide> <ide> <ide> ## Synopsis <ide><path>doc/api/cluster.md <ide> A single instance of Node.js runs in a single thread. To take advantage of <ide> multi-core systems the user will sometimes want to launch a cluster of Node.js <ide> processes to handle the load. <ide> <del>The cluster module allows you to easily create child processes that <del>all share server ports. <add>The cluster module allows easy creation of child processes that all share <add>server ports. <ide> <ide> ```js <ide> const cluster = require('cluster'); <ide> Node.js process and a cluster worker differs: <ide> idea of what the number 7 file descriptor references. <ide> 2. `server.listen(handle)` Listening on handles explicitly will cause <ide> the worker to use the supplied handle, rather than talk to the master <del> process. If the worker already has the handle, then it's presumed <del> that you know what you are doing. <add> process. <ide> 3. `server.listen(0)` Normally, this will cause servers to listen on a <ide> random port. However, in a cluster, each worker will receive the <ide> same "random" port each time they do `listen(0)`. In essence, the <del> port is random the first time, but predictable thereafter. If you <del> want to listen on a unique port, generate a port number based on the <del> cluster worker ID. <add> port is random the first time, but predictable thereafter. To listen <add> on a unique port, generate a port number based on the cluster worker ID. <ide> <del>There is no routing logic in Node.js, or in your program, and no shared <del>state between the workers. Therefore, it is important to design your <del>program such that it does not rely too heavily on in-memory data objects <del>for things like sessions and login. <add>*Note*: Node.js does not provide routing logic. It is, therefore important to <add>design an application such that it does not rely too heavily on in-memory data <add>objects for things like sessions and login. <ide> <ide> Because workers are all separate processes, they can be killed or <del>re-spawned depending on your program's needs, without affecting other <add>re-spawned depending on a program's needs, without affecting other <ide> workers. As long as there are some workers still alive, the server will <ide> continue to accept connections. If no workers are alive, existing connections <del>will be dropped and new connections will be refused. Node.js does not <del>automatically manage the number of workers for you, however. It is your <del>responsibility to manage the worker pool for your application's needs. <add>will be dropped and new connections will be refused. Node.js does not <add>automatically manage the number of workers, however. It is the application's <add>responsibility to manage the worker pool based on its own needs. <ide> <ide> <ide> <ide> added: v0.7.3 <ide> <ide> This event is the same as the one provided by [`child_process.fork()`][]. <ide> <del>In a worker you can also use `process.on('error')`. <add>Within a worker, `process.on('error')` may also be used. <ide> <ide> ### Event: 'exit' <ide> <!-- YAML <ide> added: v0.7.0 <ide> * `message` {Object} <ide> * `handle` {undefined|Object} <ide> <del>Similar to the `cluster.on('message')` event, but specific to this worker. In a <del>worker you can also use `process.on('message')`. <add>Similar to the `cluster.on('message')` event, but specific to this worker. <add> <add>Within a worker, `process.on('message)` may also be used. <ide> <ide> See [`process` event: `'message'`][]. <ide> <ide> added: v6.0.0 <ide> <ide> Set by calling `.kill()` or `.disconnect()`. Until then, it is `undefined`. <ide> <del>The boolean `worker.exitedAfterDisconnect` lets you distinguish between voluntary <del>and accidental exit, the master may choose not to respawn a worker based on <del>this value. <add>The boolean `worker.exitedAfterDisconnect` allows distinguishing between <add>voluntary and accidental exit, the master may choose not to respawn a worker <add>based on this value. <ide> <ide> ```js <ide> cluster.on('exit', (worker, code, signal) => { <ide> cluster.workers <ide> added: v0.11.14 <ide> --> <ide> <del>This function returns `true` if the worker is connected to its master via its IPC <del>channel, `false` otherwise. A worker is connected to its master after it's been <del>created. It is disconnected after the `'disconnect'` event is emitted. <add>This function returns `true` if the worker is connected to its master via its <add>IPC channel, `false` otherwise. A worker is connected to its master after it <add>has been created. It is disconnected after the `'disconnect'` event is emitted. <ide> <ide> ### worker.isDead() <ide> <!-- YAML <ide> An alias to [`worker.exitedAfterDisconnect`][]. <ide> <ide> Set by calling `.kill()` or `.disconnect()`. Until then, it is `undefined`. <ide> <del>The boolean `worker.suicide` lets you distinguish between voluntary <add>The boolean `worker.suicide` is used to distinguish between voluntary <ide> and accidental exit, the master may choose not to respawn a worker based on <ide> this value. <ide> <ide> added: v0.7.0 <ide> * `worker` {cluster.Worker} <ide> <ide> When a new worker is forked the cluster module will emit a `'fork'` event. <del>This can be used to log worker activity, and create your own timeout. <add>This can be used to log worker activity, and create a custom timeout. <ide> <ide> ```js <ide> const timeouts = []; <ide> added: v0.7.0 <ide> * `worker` {cluster.Worker} <ide> * `address` {Object} <ide> <del>After calling `listen()` from a worker, when the `'listening'` event is emitted on <del>the server, a `'listening'` event will also be emitted on `cluster` in the master. <add>After calling `listen()` from a worker, when the `'listening'` event is emitted <add>on the server a `'listening'` event will also be emitted on `cluster` in the <add>master. <ide> <del>The event handler is executed with two arguments, the `worker` contains the worker <del>object and the `address` object contains the following connection properties: <del>`address`, `port` and `addressType`. This is very useful if the worker is listening <del>on more than one address. <add>The event handler is executed with two arguments, the `worker` contains the <add>worker object and the `address` object contains the following connection <add>properties: `address`, `port` and `addressType`. This is very useful if the <add>worker is listening on more than one address. <ide> <ide> ```js <ide> cluster.on('listening', (worker, address) => { <ide> See [child_process event: 'message'][]. <ide> Before Node.js v6.0, this event emitted only the message and the handle, <ide> but not the worker object, contrary to what the documentation stated. <ide> <del>If you need to support older versions and don't need the worker object, <del>you can work around the discrepancy by checking the number of arguments: <add>If support for older versions is required but a worker object is not <add>required, it is possible to work around the discrepancy by checking the <add>number of arguments: <ide> <ide> ```js <ide> cluster.on('message', (worker, message, handle) => { <ide> added: v0.11.2 <ide> <ide> The scheduling policy, either `cluster.SCHED_RR` for round-robin or <ide> `cluster.SCHED_NONE` to leave it to the operating system. This is a <del>global setting and effectively frozen once you spawn the first worker <del>or call `cluster.setupMaster()`, whatever comes first. <add>global setting and effectively frozen once either the first worker is spawned, <add>or `cluster.setupMaster()` is called, whichever comes first. <ide> <ide> `SCHED_RR` is the default on all operating systems except Windows. <ide> Windows will change to `SCHED_RR` once libuv is able to effectively <ide> changes: <ide> After calling `.setupMaster()` (or `.fork()`) this settings object will contain <ide> the settings, including the default values. <ide> <del>This object is not supposed to be changed or set manually, by you. <add>This object is not intended to be changed or set manually. <ide> <ide> ## cluster.setupMaster([settings]) <ide> <!-- YAML <ide> eachWorker((worker) => { <ide> }); <ide> ``` <ide> <del>Should you wish to reference a worker over a communication channel, using <del>the worker's unique id is the easiest way to find the worker. <add>Using the worker's unique id is the easiest way to locate the worker. <ide> <ide> ```js <ide> socket.on('data', (id) => { <ide><path>doc/api/console.md <ide> added: v0.1.104 <ide> * `label` {string} <ide> <ide> Starts a timer that can be used to compute the duration of an operation. Timers <del>are identified by a unique `label`. Use the same `label` when you call <add>are identified by a unique `label`. Use the same `label` when calling <ide> [`console.timeEnd()`][] to stop the timer and output the elapsed time in <ide> milliseconds to `stdout`. Timer durations are accurate to the sub-millisecond. <ide> <ide><path>doc/api/dgram.md <ide> The only way to know for sure that the datagram has been sent is by using a <ide> passed as the first argument to the `callback`. If a `callback` is not given, <ide> the error is emitted as an `'error'` event on the `socket` object. <ide> <del>Offset and length are optional, but if you specify one you would need to <del>specify the other. Also, they are supported only when the first <del>argument is a `Buffer` or `Uint8Array`. <add>Offset and length are optional but both *must* be set if either are used. <add>They are supported only when the first argument is a `Buffer` or `Uint8Array`. <ide> <ide> Example of sending a UDP packet to a random port on `localhost`; <ide> <ide> client.send([buf1, buf2], 41234, (err) => { <ide> }); <ide> ``` <ide> <del>Sending multiple buffers might be faster or slower depending on your <del>application and operating system: benchmark it. Usually it is faster. <add>Sending multiple buffers might be faster or slower depending on the <add>application and operating system. It is important to run benchmarks to <add>determine the optimal strategy on a case-by-case basis. Generally speaking, <add>however, sending multiple buffers is faster. <ide> <ide> **A Note about UDP datagram size** <ide> <ide><path>doc/api/documentation.md <ide> documentation is generated using the `tools/doc/generate.js` program. <ide> The HTML template is located at `doc/template.html`. <ide> <ide> <del>If you find an error in this documentation, please [submit an issue][] <add>If errors are found in this documentation, please [submit an issue][] <ide> or see [the contributing guide][] for directions on how to submit a patch. <ide> <ide> ## Stability Index <ide> <ide> <!--type=misc--> <ide> <del>Throughout the documentation, you will see indications of a section's <del>stability. The Node.js API is still somewhat changing, and as it <del>matures, certain parts are more reliable than others. Some are so <add>Throughout the documentation are indications of a section's <add>stability. The Node.js API is still somewhat changing, and as it <add>matures, certain parts are more reliable than others. Some are so <ide> proven, and so relied upon, that they are unlikely to ever change at <del>all. Others are brand new and experimental, or known to be hazardous <add>all. Others are brand new and experimental, or known to be hazardous <ide> and in the process of being redesigned. <ide> <ide> The stability indices are as follows: <ide><path>doc/api/domain.md <ide> exit immediately with an error code. <ide> <ide> <!-- type=misc --> <ide> <del>Domain error handlers are not a substitute for closing down your <add>Domain error handlers are not a substitute for closing down a <ide> process when an error occurs. <ide> <ide> By the very nature of how [`throw`][] works in JavaScript, there is almost <ide> never any way to safely "pick up where you left off", without leaking <ide> references, or creating some other sort of undefined brittle state. <ide> <ide> The safest way to respond to a thrown error is to shut down the <del>process. Of course, in a normal web server, you might have many <del>connections open, and it is not reasonable to abruptly shut those down <add>process. Of course, in a normal web server, there may be many <add>open connections, and it is not reasonable to abruptly shut those down <ide> because an error was triggered by someone else. <ide> <ide> The better approach is to send an error response to the request that <ide> const cluster = require('cluster'); <ide> const PORT = +process.env.PORT || 1337; <ide> <ide> if (cluster.isMaster) { <del> // In real life, you'd probably use more than just 2 workers, <add> // A more realistic scenario would have more than 2 workers, <ide> // and perhaps not put the master and worker in the same file. <ide> // <del> // You can also of course get a bit fancier about logging, and <del> // implement whatever custom logic you need to prevent DoS <add> // It is also possible to get a bit fancier about logging, and <add> // implement whatever custom logic is needed to prevent DoS <ide> // attacks and other bad behavior. <ide> // <ide> // See the options in the cluster documentation. <ide> if (cluster.isMaster) { <ide> } <ide> <ide> // This part is not important. Just an example routing thing. <del>// You'd put your fancy application logic here. <add>// Put fancy application logic here. <ide> function handleRequest(req, res) { <ide> switch (req.url) { <ide> case '/error': <ide> the active domain at the time of their creation. <ide> <ide> Additionally, callbacks passed to lowlevel event loop requests (such as <ide> to fs.open, or other callback-taking methods) will automatically be <del>bound to the active domain. If they throw, then the domain will catch <add>bound to the active domain. If they throw, then the domain will catch <ide> the error. <ide> <ide> In order to prevent excessive memory usage, Domain objects themselves <ide> are not implicitly added as children of the active domain. If they <ide> were, then it would be too easy to prevent request and response objects <ide> from being properly garbage collected. <ide> <del>If you *want* to nest Domain objects as children of a parent Domain, <del>then you must explicitly add them. <add>To nest Domain objects as children of a parent Domain they must be explicitly <add>added. <ide> <ide> Implicit binding routes thrown errors and `'error'` events to the <ide> Domain's `'error'` event, but does not register the EventEmitter on the <ide><path>doc/api/fs.md <ide> first argument is always reserved for an exception. If the operation was <ide> completed successfully, then the first argument will be `null` or `undefined`. <ide> <ide> When using the synchronous form any exceptions are immediately thrown. <del>You can use try/catch to handle exceptions or allow them to bubble up. <add>Exceptions may be handled using `try`/`catch`, or they may be allowed to <add>bubble up. <ide> <ide> Here is an example of the asynchronous version: <ide> <ide> the entire process until they complete--halting all connections. <ide> The relative path to a filename can be used. Remember, however, that this path <ide> will be relative to `process.cwd()`. <ide> <del>Most fs functions let you omit the callback argument. If you do, a default <del>callback is used that rethrows errors. To get a trace to the original call <del>site, set the `NODE_DEBUG` environment variable: <add>While it is not recommended, most fs functions allow the callback argument to <add>be omitted, in which case a default callback is used that rethrows errors. To <add>get a trace to the original call site, set the `NODE_DEBUG` environment <add>variable: <add> <add>*Note*: Omitting the callback function on asynchronous fs functions is <add>deprecated and may result in an error being thrown in the future. <ide> <ide> ```txt <ide> $ cat script.js <ide> Stats { <ide> ``` <ide> <ide> Please note that `atime`, `mtime`, `birthtime`, and `ctime` are <del>instances of [`Date`][MDN-Date] object and to compare the values of <del>these objects you should use appropriate methods. For most general <del>uses [`getTime()`][MDN-Date-getTime] will return the number of <del>milliseconds elapsed since _1 January 1970 00:00:00 UTC_ and this <del>integer should be sufficient for any comparison, however there are <del>additional methods which can be used for displaying fuzzy information. <del>More details can be found in the [MDN JavaScript Reference][MDN-Date] <del>page. <add>instances of [`Date`][MDN-Date] object and appropriate methods should be used <add>to compare the values of these objects. For most general uses <add>[`getTime()`][MDN-Date-getTime] will return the number of milliseconds elapsed <add>since _1 January 1970 00:00:00 UTC_ and this integer should be sufficient for <add>any comparison, however there are additional methods which can be used for <add>displaying fuzzy information. More details can be found in the <add>[MDN JavaScript Reference][MDN-Date] page. <ide> <ide> ### Stat Time Values <ide> <ide> emitted. Note that `fd` should be blocking; non-blocking `fd`s should be passed <ide> to [`net.Socket`][]. <ide> <ide> If `autoClose` is false, then the file descriptor won't be closed, even if <del>there's an error. It is your responsibility to close it and make sure <del>there's no file descriptor leak. If `autoClose` is set to true (default <add>there's an error. It is the application's responsibility to close it and make <add>sure there's no file descriptor leak. If `autoClose` is set to true (default <ide> behavior), on `error` or `end` the file descriptor will be closed <ide> automatically. <ide> <ide> default mode `w`. The `defaultEncoding` can be any one of those accepted by <ide> If `autoClose` is set to true (default behavior) on `error` or `end` <ide> the file descriptor will be closed automatically. If `autoClose` is false, <ide> then the file descriptor won't be closed, even if there's an error. <del>It is your responsibility to close it and make sure <del>there's no file descriptor leak. <add>It is the application's responsibility to close it and make sure there's no <add>file descriptor leak. <ide> <ide> Like [`ReadStream`][], if `fd` is specified, `WriteStream` will ignore the <ide> `path` argument and will use the specified file descriptor. This means that no <ide> An exception occurs if the file does not exist. <ide> * `'rs+'` - Open file for reading and writing in synchronous mode. Instructs <ide> the operating system to bypass the local file system cache. <ide> <del> This is primarily useful for opening files on NFS mounts as it allows you to <del> skip the potentially stale local cache. It has a very real impact on I/O <del> performance so don't use this flag unless you need it. <add> This is primarily useful for opening files on NFS mounts as it allows skipping <add> the potentially stale local cache. It has a very real impact on I/O <add> performance so using this flag is not recommended unless it is needed. <ide> <ide> Note that this doesn't turn `fs.open()` into a synchronous blocking call. <del> If that's what you want then you should be using `fs.openSync()` <add> If synchronous operation is desired `fs.openSync()` should be used. <ide> <ide> * `'w'` - Open file for writing. <ide> The file is created (if it does not exist) or truncated (if it exists). <ide> added: v0.1.31 <ide> * `listener` {Function} <ide> <ide> Stop watching for changes on `filename`. If `listener` is specified, only that <del>particular listener is removed. Otherwise, *all* listeners are removed and you <del>have effectively stopped watching `filename`. <add>particular listener is removed. Otherwise, *all* listeners are removed, <add>effectively stopping watching of `filename`. <ide> <ide> Calling `fs.unwatchFile()` with a filename that is not being watched is a <ide> no-op, not an error. <ide> directories can be unreliable, and in some cases impossible, on network file <ide> systems (NFS, SMB, etc), or host file systems when using virtualization software <ide> such as Vagrant, Docker, etc. <ide> <del>You can still use `fs.watchFile`, which uses stat polling, but it is slower and <del>less reliable. <add>It is still possible to use `fs.watchFile()`, which uses stat polling, but <add>this method is slower and less reliable. <ide> <ide> #### Inodes <ide> <ide> fs.watchFile('message.text', (curr, prev) => { <ide> <ide> These stat objects are instances of `fs.Stat`. <ide> <del>If you want to be notified when the file was modified, not just accessed, <del>you need to compare `curr.mtime` and `prev.mtime`. <add>To be notified when the file was modified, not just accessed, it is necessary <add>to compare `curr.mtime` and `prev.mtime`. <ide> <ide> _Note: when an `fs.watchFile` operation results in an `ENOENT` error, it will <ide> invoke the listener once, with all the fields zeroed (or, for dates, the Unix <ide><path>doc/api/globals.md <ide> added: v0.1.27 <ide> <ide> * {Object} The global namespace object. <ide> <del>In browsers, the top-level scope is the global scope. That means that in <del>browsers if you're in the global scope `var something` will define a global <del>variable. In Node.js this is different. The top-level scope is not the global <del>scope; `var something` inside an Node.js module will be local to that module. <add>In browsers, the top-level scope is the global scope. This means that <add>within the browser `var something` will define a new global variable. In <add>Node.js this is different. The top-level scope is not the global scope; <add>`var something` inside a Node.js module will be local to that module. <ide> <ide> ## module <ide> <!-- YAML <ide><path>doc/api/modules.md <ide> exports.circumference = (r) => 2 * PI * r; <ide> ``` <ide> <ide> The module `circle.js` has exported the functions `area()` and <del>`circumference()`. To add functions and objects to the root of your module, <del>you can add them to the special `exports` object. <add>`circumference()`. Functions and objects are added to the root of a module <add>by specifying additional properties on the special `exports` object. <ide> <ide> Variables local to the module will be private, because the module is wrapped <ide> in a function by Node.js (see [module wrapper](#modules_the_module_wrapper)). <ide> In this example, the variable `PI` is private to `circle.js`. <ide> <del>If you want the root of your module's export to be a function (such as a <del>constructor) or if you want to export a complete object in one assignment <del>instead of building it one property at a time, assign it to `module.exports` <del>instead of `exports`. <add>The `module.exports` property can be assigned a new value (such as a function <add>or object). <ide> <ide> Below, `bar.js` makes use of the `square` module, which exports a constructor: <ide> <ide> The module system is implemented in the `require('module')` module. <ide> <!-- type=misc --> <ide> <ide> When a file is run directly from Node.js, `require.main` is set to its <del>`module`. That means that you can determine whether a file has been run <del>directly by testing `require.main === module`. <add>`module`. That means that it is possible to determine whether a file has been <add>run directly by testing `require.main === module`. <ide> <ide> For a file `foo.js`, this will be `true` if run via `node foo.js`, but <ide> `false` if run by `require('./foo')`. <ide> Let's say that we wanted to have the folder at <ide> `/usr/lib/node/<some-package>/<some-version>` hold the contents of a <ide> specific version of a package. <ide> <del>Packages can depend on one another. In order to install package `foo`, you <del>may have to install a specific version of package `bar`. The `bar` package <del>may itself have dependencies, and in some cases, these dependencies may even <del>collide or form cycles. <add>Packages can depend on one another. In order to install package `foo`, it <add>may be necessary to install a specific version of package `bar`. The `bar` <add>package may itself have dependencies, and in some cases, these may even collide <add>or form cyclic dependencies. <ide> <ide> Since Node.js looks up the `realpath` of any modules it loads (that is, <ide> resolves symlinks), and then looks for their dependencies in the `node_modules` <ide> executed multiple times. This is an important feature. With it, <ide> "partially done" objects can be returned, thus allowing transitive <ide> dependencies to be loaded even when they would cause cycles. <ide> <del>If you want to have a module execute code multiple times, then export a <del>function, and call that function. <add>To have a module execute code multiple times, export a function, and call <add>that function. <ide> <ide> ### Module Caching Caveats <ide> <ide> a done <ide> in main, a.done=true, b.done=true <ide> ``` <ide> <del>If you have cyclic module dependencies in your program, make sure to <del>plan accordingly. <add>Careful planning is required to allow cyclic module dependencies to work <add>correctly within an application. <ide> <ide> ## File Modules <ide> <ide> this order: <ide> This allows programs to localize their dependencies, so that they do not <ide> clash. <ide> <del>You can require specific files or sub modules distributed with a module by <del>including a path suffix after the module name. For instance <add>It is possible to require specific files or sub modules distributed with a <add>module by including a path suffix after the module name. For instance <ide> `require('example-module/path/to/file')` would resolve `path/to/file` <ide> relative to where `example-module` is located. The suffixed path follows the <ide> same module resolution semantics. <ide> Additionally, Node.js will search in the following locations: <ide> Where `$HOME` is the user's home directory, and `$PREFIX` is Node.js's <ide> configured `node_prefix`. <ide> <del>These are mostly for historic reasons. **You are highly encouraged <del>to place your dependencies locally in `node_modules` folders.** They <del>will be loaded faster, and more reliably. <add>These are mostly for historic reasons. <add> <add>*Note*: It is strongly encouraged to place dependencies in the local <add>`node_modules` folder. These will be loaded faster, and more reliably. <ide> <ide> ## The module wrapper <ide> <ide> wrapper that looks like the following: <ide> <ide> ```js <ide> (function(exports, require, module, __filename, __dirname) { <del>// Your module code actually lives in here <add>// Module code actually lives in here <ide> }); <ide> ``` <ide> <ide> The `module.exports` object is created by the Module system. Sometimes this is <ide> not acceptable; many want their module to be an instance of some class. To do <ide> this, assign the desired export object to `module.exports`. Note that assigning <ide> the desired object to `exports` will simply rebind the local `exports` variable, <del>which is probably not what you want to do. <add>which is probably not what is desired. <ide> <ide> For example suppose we were making a module called `a.js` <ide> <ide> To illustrate the behavior, imagine this hypothetical implementation of <ide> function require(/* ... */) { <ide> const module = { exports: {} }; <ide> ((module, exports) => { <del> // Your module code here. In this example, define a function. <add> // Module code here. In this example, define a function. <ide> function someFunc() {} <ide> exports = someFunc; <ide> // At this point, exports is no longer a shortcut to module.exports, and <ide> added: v0.5.1 <ide> The `module.require` method provides a way to load a module as if <ide> `require()` was called from the original module. <ide> <del>Note that in order to do this, you must get a reference to the `module` <add>*Note*: In order to do this, it is necessary to get a reference to the `module` <ide> object. Since `require()` returns the `module.exports`, and the `module` is <ide> typically *only* available within a specific module's code, it must be <ide> explicitly exported in order to be used. <ide><path>doc/api/net.md <ide> changes: <ide> <ide> Initiate a connection on a given socket. Normally this method is not needed, <ide> the socket should be created and opened with [`net.createConnection()`][]. Use <del>this only if you are implementing a custom Socket. <add>this only when implementing a custom Socket. <ide> <ide> For TCP connections, available `options` are: <ide> <ide> added: v0.9.6 <ide> --> <ide> <ide> The string representation of the local IP address the remote client is <del>connecting on. For example, if you are listening on `'0.0.0.0'` and the <del>client connects on `'192.168.1.1'`, the value would be `'192.168.1.1'`. <add>connecting on. For example, in a server listening on `'0.0.0.0'`, if a client <add>connects on `'192.168.1.1'`, the value of `socket.localAddress` would be <add>`'192.168.1.1'`. <ide> <ide> ### socket.localPort <ide> <!-- YAML <ide><path>doc/api/repl.md <ide> by the `NODE_REPL_HISTORY` variable, as documented in the <ide> <ide> For advanced line-editors, start Node.js with the environmental variable <ide> `NODE_NO_READLINE=1`. This will start the main and debugger REPL in canonical <del>terminal settings which will allow you to use with `rlwrap`. <add>terminal settings, which will allow use with `rlwrap`. <ide> <del>For example, you could add this to your bashrc file: <add>For example, the following can be added to a `.bashrc` file: <ide> <ide> ```text <ide> alias node="env NODE_NO_READLINE=1 rlwrap node"
13
Javascript
Javascript
replace common port with specific number
e0faf8c3e9765afa6180db75c06e39d5b88c0b2b
<ide><path>test/parallel/test-net-connect-options-invalid.js <ide> 'use strict'; <del>const common = require('../common'); <add>require('../common'); <ide> const assert = require('assert'); <ide> const net = require('net'); <ide> <ide> const net = require('net'); <ide> ]; <ide> invalidKeys.forEach((invalidKey) => { <ide> const option = { <del> ...common.localhostIPv4, <add> port: 8080, <ide> [invalidKey]: true <ide> }; <ide> const message = `The property 'options.${invalidKey}' is not supported. Received true`; <ide><path>test/parallel/test-socket-options-invalid.js <ide> 'use strict'; <del>const common = require('../common'); <add>require('../common'); <ide> const assert = require('assert'); <ide> const net = require('net'); <ide> <ide> const net = require('net'); <ide> ]; <ide> invalidKeys.forEach((invalidKey) => { <ide> const option = { <del> ...common.localhostIPv4, <ide> [invalidKey]: true <ide> }; <ide> const message = `The property 'options.${invalidKey}' is not supported. Received true`;
2
Mixed
Go
remove dm.no_warn_on_loop_devices in info warning
2aa01e0fbc76ecb8cf1a1b608e254e6cb8821ff7
<ide><path>api/client/system/info.go <ide> func runInfo(dockerCli *client.DockerCli) error { <ide> <ide> // print a warning if devicemapper is using a loopback file <ide> if pair[0] == "Data loop file" { <del> fmt.Fprintln(dockerCli.Err(), " WARNING: Usage of loopback devices is strongly discouraged for production use. Either use `--storage-opt dm.thinpooldev` or use `--storage-opt dm.no_warn_on_loop_devices=true` to suppress this warning.") <add> fmt.Fprintln(dockerCli.Err(), " WARNING: Usage of loopback devices is strongly discouraged for production use. Use `--storage-opt dm.thinpooldev` to specifies a custom block storage device.") <ide> } <ide> } <ide> <ide><path>docs/userguide/storagedriver/device-mapper-driver.md <ide> Storage Driver: devicemapper <ide> Deferred Deletion Enabled: false <ide> Deferred Deleted Device Count: 0 <ide> Data loop file: /var/lib/docker/devicemapper/devicemapper/data <del> WARNING: Usage of loopback devices is strongly discouraged for production use. Either use `--storage-opt dm.thinpooldev` or use `--storage-opt dm.no_warn_on_loop_devices=true` to suppress this warning. <add> WARNING: Usage of loopback devices is strongly discouraged for production use. Use `--storage-opt dm.thinpooldev` to specifies a custom block storage device. <ide> Metadata loop file: /var/lib/docker/devicemapper/devicemapper/metadata <ide> Library Version: 1.02.90 (2014-09-01) <ide> Logging Driver: json-file
2
Javascript
Javascript
adjust morph usage to be inclusive
a9422f48228f5943886999d5ae3025464c18c409
<ide><path>packages/ember-metal-views/lib/renderer.js <ide> Renderer.prototype.appendAttrTo = <ide> <ide> Renderer.prototype.replaceIn = <ide> function Renderer_replaceIn(view, target) { <del> var morph = this._dom.createMorph(target, null, null); <add> var morph; <add> if (target.firstNode) { <add> morph = this._dom.createMorph(target, target.firstNode, target.lastNode); <add> } else { <add> morph = this._dom.appendMorph(target); <add> } <ide> this.scheduleInsert(view, morph); <ide> }; <ide> <ide><path>packages/ember-metal-views/tests/test_helpers.js <ide> MetalRenderer.prototype.createElement = function (view, contextualElement) { <ide> } <ide> } <ide> if (view.childViews) { <del> view._childViewsMorph = this._dom.createMorph(el, null, null); <add> view._childViewsMorph = this._dom.appendMorph(el); <ide> } else if (view.textContent) { <ide> setElementText(el, view.textContent); <ide> } else if (view.innerHTML) { <ide> this._dom.detectNamespace(el); <del> var nodes = this._dom.parseHTML(view.innerHTML, el); <del> while (nodes[0]) { <del> el.appendChild(nodes[0]); <del> } <add> var frag = this._dom.parseHTML(view.innerHTML, el); <add> el.appendChild(frag); <ide> } <ide> return el; <ide> }; <ide><path>packages/ember-views/lib/system/render_buffer.js <ide> RenderBuffer.prototype = { <ide> if (content.nodeType) { <ide> this._element.appendChild(content); <ide> } else { <del> var nodes; <del> nodes = this.dom.parseHTML(content, contextualElement); <del> while (nodes[0]) { <del> this._element.appendChild(nodes[0]); <del> } <add> var frag = this.dom.parseHTML(content, contextualElement); <add> this._element.appendChild(frag); <ide> } <ide> <ide> // This should only happen with legacy string buffers <ide><path>packages/ember-views/lib/system/utils.js <ide> export function isSimpleClick(event) { <ide> */ <ide> function getViewRange(view) { <ide> var range = document.createRange(); <del> range.setStartAfter(view._morph.start); <del> range.setEndBefore(view._morph.end); <add> range.setStartBefore(view._morph.firstNode); <add> range.setEndAfter(view._morph.lastNode); <ide> return range; <ide> } <ide> <ide><path>packages/ember-views/lib/views/container_view.js <ide> var ContainerView = View.extend(MutableArray, { <ide> var element = buffer.element(); <ide> var dom = buffer.dom; <ide> <del> if (this.tagName === '') { <del> element = dom.createDocumentFragment(); <del> buffer._element = element; <del> this._childViewsMorph = dom.appendMorph(element, this._morph.contextualElement); <del> } else { <del> this._childViewsMorph = dom.createMorph(element, element.lastChild, null); <del> } <add> this._childViewsMorph = dom.appendMorph(element); <ide> <ide> return element; <ide> },
5
Text
Text
clarify behaviour of writefile(fd)
a763de137ceb81a19a2446b0f7286c4a309c27e4
<ide><path>doc/api/fs.md <ide> changes: <ide> * `callback` {Function} <ide> * `err` {Error} <ide> <del>Asynchronously writes data to a file, replacing the file if it already exists. <del>`data` can be a string or a buffer. <add>When `file` is a filename, asynchronously writes data to the file, replacing the <add>file if it already exists. `data` can be a string or a buffer. <add> <add>When `file` is a file descriptor, the behavior is similar to calling <add>`fs.write()` directly (which is recommended). See the notes below on using <add>a file descriptor. <ide> <ide> The `encoding` option is ignored if `data` is a buffer. <ide> <ide> It is unsafe to use `fs.writeFile()` multiple times on the same file without <ide> waiting for the callback. For this scenario, [`fs.createWriteStream()`][] is <ide> recommended. <ide> <del>### File Descriptors <del>1. Any specified file descriptor has to support writing. <del>2. If a file descriptor is specified as the `file`, it will not be closed <del>automatically. <del>3. The writing will begin at the current position. For example, if the string <del>`'Hello'` is written to the file descriptor, and if `', World'` is written with <del>`fs.writeFile()` to the same file descriptor, the contents of the file would <del>become `'Hello, World'`, instead of just `', World'`. <add>### Using `fs.writeFile()` with File Descriptors <add> <add>When `file` is a file descriptor, the behavior is almost identical to directly <add>calling `fs.write()` like: <add>```javascript <add>fs.write(fd, Buffer.from(data, options.encoding), callback); <add>``` <ide> <add>The difference from directly calling `fs.write()` is that under some unusual <add>conditions, `fs.write()` may write only part of the buffer and will need to be <add>retried to write the remaining data, whereas `fs.writeFile()` will retry until <add>the data is entirely written (or an error occurs). <add> <add>Since the implications of this are a common source of confusion, note that in <add>the file descriptor case the file is not replaced! The data is not necessarily <add>written to the beginning of the file, and the file's original data may remain <add>before and/or after the newly written data. <add> <add>For example, if `fs.writeFile()` is called twice in a row, first to write the <add>string `'Hello'`, then to write the string `', World'`, the file would contain <add>`'Hello, World'`, and might contain some of the file's original data (depending <add>on the size of the original file, and the position of the file descriptor). If <add>a file name had been used instead of a descriptor, the file would be guaranteed <add>to contain only `', World'`. <ide> <ide> ## fs.writeFileSync(file, data[, options]) <ide> <!-- YAML
1
Java
Java
remove some superfluous reads before writes.
c9bb518df5991a65c2f97b8ed7ba5458233963ea
<ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundary.java <ide> public void request(long n) { <ide> <ide> @Override <ide> public void cancel() { <del> if (!cancelled) { <del> cancelled = true; <del> } <add> cancelled = true; <ide> } <ide> <ide> void drainLoop() { <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySelector.java <ide> public void request(long n) { <ide> <ide> @Override <ide> public void cancel() { <del> if (!cancelled) { <del> cancelled = true; <del> } <add> cancelled = true; <ide> } <ide> <ide> void dispose() { <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySupplier.java <ide> public void request(long n) { <ide> <ide> @Override <ide> public void cancel() { <del> if (!cancelled) { <del> cancelled = true; <del> } <add> cancelled = true; <ide> } <ide> <ide> void drainLoop() { <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowTimed.java <ide> public void request(long n) { <ide> <ide> @Override <ide> public void cancel() { <del> if (!cancelled) { <del> cancelled = true; <del> } <add> cancelled = true; <ide> } <ide> <ide> @Override <ide> public void request(long n) { <ide> <ide> @Override <ide> public void cancel() { <del> if (!cancelled) { <del> cancelled = true; <del> } <add> cancelled = true; <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/observable/NbpOperatorWindowBoundary.java <ide> public void onComplete() { <ide> <ide> @Override <ide> public void dispose() { <del> if (!cancelled) { <del> cancelled = true; <del> } <add> cancelled = true; <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/observable/NbpOperatorWindowBoundarySelector.java <ide> void error(Throwable t) { <ide> <ide> @Override <ide> public void dispose() { <del> if (!cancelled) { <del> cancelled = true; <del> } <add> cancelled = true; <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/observable/NbpOperatorWindowBoundarySupplier.java <ide> public void onComplete() { <ide> <ide> @Override <ide> public void dispose() { <del> if (!cancelled) { <del> cancelled = true; <del> } <add> cancelled = true; <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/observable/NbpOperatorWindowTimed.java <ide> public void onComplete() { <ide> <ide> @Override <ide> public void dispose() { <del> if (!cancelled) { <del> cancelled = true; <del> } <add> cancelled = true; <ide> } <ide> <ide> @Override <ide> public void onComplete() { <ide> <ide> @Override <ide> public void dispose() { <del> if (!cancelled) { <del> cancelled = true; <del> } <add> cancelled = true; <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableGenerate.java <ide> private void dispose(S s) { <ide> <ide> @Override <ide> public void dispose() { <del> if (!cancelled) { <del> cancelled = true; <del> } <add> cancelled = true; <ide> } <ide> <ide> @Override
9
Text
Text
use a numbered list for maintainers responsibility
cc96d312526dac5eff3e0521b921e08301715ce5
<ide><path>hack/MAINTAINERS.md <ide> speak up! <ide> <ide> It is every maintainer's responsibility to: <ide> <del>* 1) Expose a clear roadmap for improving their component. <del>* 2) Deliver prompt feedback and decisions on pull requests. <del>* 3) Be available to anyone with questions, bug reports, criticism etc. <add>1. Expose a clear roadmap for improving their component. <add>2. Deliver prompt feedback and decisions on pull requests. <add>3. Be available to anyone with questions, bug reports, criticism etc. <ide> on their component. This includes IRC, GitHub requests and the mailing <ide> list. <del>* 4) Make sure their component respects the philosophy, design and <add>4. Make sure their component respects the philosophy, design and <ide> roadmap of the project. <ide> <ide> ## How are decisions made?
1
Python
Python
fix typo in docstring
17e5fb365d7bde8fc795311bb37fe6358e258dc5
<ide><path>flask/app.py <ide> def make_response(self, rv): <ide> :class:`tuple` A tuple in the form ``(response, status, <ide> headers)`` where `response` is any of the <ide> types defined here, `status` is a string <del> or an integer and `headers` is a list of <add> or an integer and `headers` is a list or <ide> a dictionary with header values. <ide> ======================= =========================================== <ide>
1
Javascript
Javascript
parse materialindex when adding groups
206a7d0d4b012be1d79fbccfa38c332279a343c3
<ide><path>src/loaders/BufferGeometryLoader.js <ide> THREE.BufferGeometryLoader.prototype = { <ide> <ide> var group = groups[ i ]; <ide> <del> geometry.addGroup( group.start, group.count ); <add> geometry.addGroup( group.start, group.count, group.materialIndex ); <ide> <ide> } <ide>
1
Ruby
Ruby
return nil for strings with no date information
06a7c2948a8dbf31357b552d468fcf42002736e7
<ide><path>activerecord/lib/active_record/attribute_methods.rb <ide> def define_write_method(attr_name) <ide> def define_write_method_for_time_zone_conversion(attr_name) <ide> method_body = <<-EOV <ide> def #{attr_name}=(time) <del> unless time.blank? || time.acts_like?(:time) <add> unless time.acts_like?(:time) <ide> time = time.is_a?(String) ? Time.zone.parse(time) : time.to_time rescue time <ide> end <ide> time = time.in_time_zone rescue nil if time <ide><path>activesupport/lib/active_support/values/time_zone.rb <ide> def at(secs) <ide> # Time.zone.now # => Fri, 31 Dec 1999 14:00:00 HST -10:00 <ide> # Time.zone.parse('22:30:00') # => Fri, 31 Dec 1999 22:30:00 HST -10:00 <ide> def parse(str, now=now) <add> date_parts = Date._parse(str) <add> return if date_parts.blank? <ide> time = Time.parse(str, now) rescue DateTime.parse(str) <del> if Date._parse(str)[:offset].nil? <add> if date_parts[:offset].nil? <ide> ActiveSupport::TimeWithZone.new(nil, self, time) <ide> else <ide> time.in_time_zone(self) <ide><path>activesupport/test/time_zone_test.rb <ide> def test_parse_far_future_date_with_time_zone_offset_in_string <ide> assert_equal zone, twz.time_zone <ide> end <ide> end <add> <add> def test_parse_returns_nil_when_string_without_date_information_is_passed_in <add> silence_warnings do # silence warnings raised by tzinfo gem <add> zone = TimeZone['Eastern Time (US & Canada)'] <add> assert_nil zone.parse('foobar') <add> assert_nil zone.parse(' ') <add> end <add> end <ide> <ide> uses_mocha 'TestParseWithIncompleteDate' do <ide> def test_parse_with_incomplete_date
3