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 | fix a crash in suspense with finddomnode | 41aa345d2bde261c2fb4a4ef89e379640c88be67 | <ide><path>packages/react-dom/src/__tests__/ReactDOMSuspensePlaceholder-test.js
<ide> describe('ReactDOMSuspensePlaceholder', () => {
<ide> await Lazy;
<ide> expect(log).toEqual(['cDU first', 'cDU second']);
<ide> });
<add>
<add> // Regression test for https://github.com/facebook/react/issues/14188
<add> it('can call findDOMNode() in a suspended component commit phase (#2)', () => {
<add> let suspendOnce = Promise.resolve();
<add> function Suspend() {
<add> if (suspendOnce) {
<add> let promise = suspendOnce;
<add> suspendOnce = null;
<add> throw promise;
<add> }
<add> return null;
<add> }
<add>
<add> const log = [];
<add> class Child extends React.Component {
<add> componentDidMount() {
<add> log.push('cDM');
<add> ReactDOM.findDOMNode(this);
<add> }
<add>
<add> componentDidUpdate() {
<add> log.push('cDU');
<add> ReactDOM.findDOMNode(this);
<add> }
<add>
<add> render() {
<add> return null;
<add> }
<add> }
<add>
<add> function App() {
<add> return (
<add> <Suspense fallback="Loading">
<add> <Suspend />
<add> <Child />
<add> </Suspense>
<add> );
<add> }
<add>
<add> ReactDOM.render(<App />, container);
<add> expect(log).toEqual(['cDM']);
<add> ReactDOM.render(<App />, container);
<add> expect(log).toEqual(['cDM', 'cDU']);
<add> });
<ide> });
<ide><path>packages/react-reconciler/src/ReactFiberTreeReflection.js
<ide> import {
<ide> HostRoot,
<ide> HostPortal,
<ide> HostText,
<add> Fragment,
<add> SuspenseComponent,
<ide> } from 'shared/ReactWorkTags';
<ide> import {NoEffect, Placement} from 'shared/ReactSideEffectTags';
<ide>
<ide> export function findCurrentFiberUsingSlowPath(fiber: Fiber): Fiber | null {
<ide> let parentA = a.return;
<ide> let parentB = parentA ? parentA.alternate : null;
<ide> if (!parentA || !parentB) {
<del> // We're at the root.
<del> break;
<add> // We're either at the root, or we're in a special Fragment
<add> // with no alternate, which is how Suspense (un)hiding works.
<add> let maybeSuspenseFragment = parentA || parentB;
<add> if (maybeSuspenseFragment && maybeSuspenseFragment.tag === Fragment) {
<add> const maybeSuspense = maybeSuspenseFragment.return;
<add> if (
<add> maybeSuspense &&
<add> maybeSuspense.tag === SuspenseComponent &&
<add> // If state isn't null, it timed out and we have two Fragment children.
<add> maybeSuspense.memoizedState !== null
<add> ) {
<add> parentA = maybeSuspense;
<add> parentB = maybeSuspense;
<add> a = maybeSuspenseFragment;
<add> b = maybeSuspenseFragment;
<add> } else {
<add> break;
<add> }
<add> } else {
<add> break;
<add> }
<ide> }
<ide>
<ide> // If both copies of the parent fiber point to the same child, we can | 2 |
PHP | PHP | store the generated key in the .env file only | 41e2080cb2811e9063672248311a66f65e6d899e | <ide><path>src/Illuminate/Foundation/Console/KeyGenerateCommand.php
<ide> public function fire()
<ide> return $this->line('<comment>'.$key.'</comment>');
<ide> }
<ide>
<del> foreach ([base_path('.env'), base_path('.env.example')] as $path)
<add> $path = base_path('.env');
<add>
<add> if (file_exists($path))
<ide> {
<del> if (file_exists($path))
<del> {
<del> file_put_contents($path, str_replace(
<del> $this->laravel['config']['app.key'], $key, file_get_contents($path)
<del> ));
<del> }
<add> file_put_contents($path, str_replace(
<add> $this->laravel['config']['app.key'], $key, file_get_contents($path)
<add> ));
<ide> }
<ide>
<ide> $this->laravel['config']['app.key'] = $key; | 1 |
Ruby | Ruby | introduce minimalistic package for activesupport | 133925804f24d716a3836698dbe5a7d8b30de0b5 | <ide><path>activesupport/lib/active_support/core_ext/string/multibyte.rb
<ide> def is_utf8?
<ide>
<ide> unless '1.8.7 and later'.respond_to?(:chars)
<ide> def chars
<del> ActiveSupport::Deprecation.warn('String#chars has been deprecated in favor of String#mb_chars.', caller)
<add> # FIXME:
<add> # ActiveSupport::Deprecation refers to RAILS_ENV
<add> # and is a show stopper for 3rd party applications
<add> # that only want ActiveSupport
<add> ActiveSupport::Deprecation.warn('String#chars has been deprecated in favor of String#mb_chars.', caller) if defined?(ActiveSupport::Deprecation)
<ide> mb_chars
<ide> end
<ide> end
<ide><path>activesupport/lib/active_support/minimalistic.rb
<add>$LOAD_PATH.unshift File.dirname(__FILE__)
<add>
<add>require "core_ext/blank"
<add># whole object.rb pulls up rare used introspection extensions
<add>require "core_ext/object/metaclass"
<add>require 'core_ext/array'
<add>require 'core_ext/hash'
<add>require 'core_ext/module/attribute_accessors'
<add>require 'multibyte'
<add>require 'core_ext/string/multibyte'
<add>require 'core_ext/string/inflections'
<add>
<add>class String
<add> include ActiveSupport::CoreExtensions::String::Multibyte
<add>end | 2 |
Ruby | Ruby | remove warnings about redefined test methods | 9cf3b1f6719e1fe917f5abe56be6fee157bc3c13 | <ide><path>activesupport/test/inflector_test.rb
<ide> def test_uncountable_word_is_not_greedy
<ide> end
<ide>
<ide> SingularToPlural.each do |singular, plural|
<del> define_method "test_pluralize_#{singular}" do
<add> define_method "test_pluralize_singular_#{singular}" do
<ide> assert_equal(plural, ActiveSupport::Inflector.pluralize(singular))
<ide> assert_equal(plural.capitalize, ActiveSupport::Inflector.pluralize(singular.capitalize))
<ide> end
<ide> end
<ide>
<ide> SingularToPlural.each do |singular, plural|
<del> define_method "test_singularize_#{plural}" do
<add> define_method "test_singularize_plural_#{plural}" do
<ide> assert_equal(singular, ActiveSupport::Inflector.singularize(plural))
<ide> assert_equal(singular.capitalize, ActiveSupport::Inflector.singularize(plural.capitalize))
<ide> end
<ide> end
<del>
<add>
<ide> SingularToPlural.each do |singular, plural|
<del> define_method "test_pluralize_#{plural}" do
<add> define_method "test_pluralize_plural_#{plural}" do
<ide> assert_equal(plural, ActiveSupport::Inflector.pluralize(plural))
<ide> assert_equal(plural.capitalize, ActiveSupport::Inflector.pluralize(plural.capitalize))
<ide> end | 1 |
Ruby | Ruby | fix handling of undefined year in datetimeselector | 8251651a0d759148313cecb2995b69994c896a10 | <ide><path>actionview/lib/action_view/helpers/date_helper.rb
<ide> def select_month
<ide> end
<ide>
<ide> def select_year
<del> if !@datetime || @datetime == 0
<add> if !year || @datetime == 0
<ide> val = "1"
<ide> middle_year = Date.today.year
<ide> else
<ide><path>actionview/test/template/date_helper_test.rb
<ide> def to_param
<ide> "123"
<ide> end
<ide> end
<add>
<add> ComposedDate = Struct.new("ComposedDate", :year, :month, :day)
<ide> end
<ide>
<ide> def assert_distance_of_time_in_words(from, to = nil)
<ide> def test_select_year
<ide> assert_dom_equal expected, select_year(2003, start_year: 2003, end_year: 2005)
<ide> end
<ide>
<add> def test_select_year_with_empty_hash_value_and_no_start_year
<add> expected = +%(<select id="date_year" name="date[year]">\n)
<add> expected << %(<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n)
<add> expected << "</select>\n"
<add>
<add> Date.stub(:current, Date.new(2018, 12, 18)) do
<add> assert_dom_equal expected, select_year({ year: nil, month: 4, day: nil }, { end_year: 2018 })
<add> end
<add> end
<add>
<add> def test_select_year_with_empty_object_value_and_no_start_year
<add> expected = +%(<select id="date_year" name="date[year]">\n)
<add> expected << %(<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n)
<add> expected << "</select>\n"
<add>
<add> Date.stub(:current, Date.new(2018, 12, 18)) do
<add> assert_dom_equal expected, select_year(ComposedDate.new(nil, 4, nil), end_year: 2018)
<add> end
<add> end
<add>
<ide> def test_select_year_with_disabled
<ide> expected = +%(<select id="date_year" name="date[year]" disabled="disabled">\n)
<ide> expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) | 2 |
Python | Python | add useful repr's for finfo, iinfo | 00962c4b845ec461e38850f8ae17253a4eecabf2 | <ide><path>numpy/core/getlimits.py
<ide> def __str__(self):
<ide> ---------------------------------------------------------------------
<ide> ''' % self.__dict__
<ide>
<add> def __repr__(self):
<add> c = self.__class__.__name__
<add> d = self.__dict__.copy()
<add> d['klass'] = c
<add> return ("%(klass)s(resolution=%(resolution)s, min=-%(_str_max)s," \
<add> + " max=%(_str_max)s, dtype=%(dtype)s)") \
<add> % d
<add>
<ide>
<ide> class iinfo(object):
<ide> """
<ide> def __str__(self):
<ide> ---------------------------------------------------------------------
<ide> ''' % {'dtype': self.dtype, 'min': self.min, 'max': self.max}
<ide>
<add> def __repr__(self):
<add> return "%s(min=%s, max=%s, dtype=%s)" % (self.__class__.__name__,
<add> self.min, self.max, self.dtype)
<ide>
<ide> if __name__ == '__main__':
<ide> f = finfo(ntypes.single)
<ide><path>numpy/core/tests/test_getlimits.py
<ide> def test_unsigned_max(self):
<ide> for T in types:
<ide> assert_equal(iinfo(T).max, T(-1))
<ide>
<add>class TestRepr(TestCase):
<add> def test_iinfo_repr(self):
<add> expected = "iinfo(min=-32768, max=32767, dtype=int16)"
<add> assert_equal(repr(np.iinfo(np.int16)), expected)
<add>
<add> def test_finfo_repr(self):
<add> expected = "finfo(resolution=1e-06, min=-3.4028235e+38," + \
<add> " max=3.4028235e+38, dtype=float32)"
<add> assert_equal(repr(np.finfo(np.float32)), expected)
<ide>
<ide> def test_instances():
<ide> iinfo(10) | 2 |
Python | Python | normalize layer imports in examples | 610ccba9f5c030e6106520359c27dc9c226670d7 | <ide><path>examples/addition_rnn.py
<ide> from __future__ import print_function
<ide> from keras.models import Sequential
<ide> from keras.engine.training import slice_X
<del>from keras.layers.core import Activation, TimeDistributedDense, RepeatVector
<del>from keras.layers import recurrent
<add>from keras.layers import Activation, TimeDistributedDense, RepeatVector, recurrent
<ide> import numpy as np
<ide> from six.moves import range
<ide>
<ide><path>examples/antirectifier.py
<ide>
<ide> from __future__ import print_function
<ide> from keras.models import Sequential
<del>from keras.layers.core import Dense, Dropout, Layer, Activation
<add>from keras.layers import Dense, Dropout, Layer, Activation
<ide> from keras.datasets import mnist
<ide> from keras import backend as K
<ide> from keras.utils import np_utils
<ide><path>examples/babi_memnn.py
<ide> from __future__ import print_function
<ide> from keras.models import Sequential
<ide> from keras.layers.embeddings import Embedding
<del>from keras.layers.core import Activation, Dense, Merge, Permute, Dropout
<del>from keras.layers.recurrent import LSTM
<add>from keras.layers import Activation, Dense, Merge, Permute, Dropout
<add>from keras.layers import LSTM
<ide> from keras.utils.data_utils import get_file
<ide> from keras.preprocessing.sequence import pad_sequences
<ide> from functools import reduce
<ide><path>examples/babi_rnn.py
<ide>
<ide> from keras.utils.data_utils import get_file
<ide> from keras.layers.embeddings import Embedding
<del>from keras.layers.core import Dense, Merge, Dropout, RepeatVector
<add>from keras.layers import Dense, Merge, Dropout, RepeatVector
<ide> from keras.layers import recurrent
<ide> from keras.models import Sequential
<ide> from keras.preprocessing.sequence import pad_sequences
<ide><path>examples/cifar10_cnn.py
<ide> from keras.datasets import cifar10
<ide> from keras.preprocessing.image import ImageDataGenerator
<ide> from keras.models import Sequential
<del>from keras.layers.core import Dense, Dropout, Activation, Flatten
<del>from keras.layers.convolutional import Convolution2D, MaxPooling2D
<add>from keras.layers import Dense, Dropout, Activation, Flatten
<add>from keras.layers import Convolution2D, MaxPooling2D
<ide> from keras.optimizers import SGD
<ide> from keras.utils import np_utils
<ide>
<ide><path>examples/deep_dream.py
<ide> import os
<ide>
<ide> from keras.models import Sequential
<del>from keras.layers.convolutional import Convolution2D, ZeroPadding2D, MaxPooling2D
<add>from keras.layers import Convolution2D, ZeroPadding2D, MaxPooling2D
<ide> from keras import backend as K
<ide>
<ide> parser = argparse.ArgumentParser(description='Deep Dreams with Keras.')
<ide><path>examples/imdb_cnn.py
<ide>
<ide> from keras.preprocessing import sequence
<ide> from keras.models import Sequential
<del>from keras.layers.core import Dense, Dropout, Activation, Lambda
<del>from keras.layers.embeddings import Embedding
<del>from keras.layers.convolutional import Convolution1D
<add>from keras.layers import Dense, Dropout, Activation, Lambda
<add>from keras.layers import Embedding
<add>from keras.layers import Convolution1D
<ide> from keras.datasets import imdb
<ide> from keras import backend as K
<ide>
<ide><path>examples/imdb_cnn_lstm.py
<ide>
<ide> from keras.preprocessing import sequence
<ide> from keras.models import Sequential
<del>from keras.layers.core import Dense, Dropout, Activation
<del>from keras.layers.embeddings import Embedding
<del>from keras.layers.recurrent import LSTM, GRU, SimpleRNN
<del>from keras.layers.convolutional import Convolution1D, MaxPooling1D
<add>from keras.layers import Dense, Dropout, Activation
<add>from keras.layers import Embedding
<add>from keras.layers import LSTM, GRU, SimpleRNN
<add>from keras.layers import Convolution1D, MaxPooling1D
<ide> from keras.datasets import imdb
<ide>
<ide>
<ide><path>examples/imdb_lstm.py
<ide> from keras.preprocessing import sequence
<ide> from keras.utils import np_utils
<ide> from keras.models import Sequential
<del>from keras.layers.core import Dense, Dropout, Activation
<del>from keras.layers.embeddings import Embedding
<del>from keras.layers.recurrent import LSTM, SimpleRNN, GRU
<add>from keras.layers import Dense, Dropout, Activation, Embedding
<add>from keras.layers import LSTM, SimpleRNN, GRU
<ide> from keras.datasets import imdb
<ide>
<ide> max_features = 20000
<ide><path>examples/lstm_text_generation.py
<ide>
<ide> from __future__ import print_function
<ide> from keras.models import Sequential
<del>from keras.layers.core import Dense, Activation, Dropout
<del>from keras.layers.recurrent import LSTM
<add>from keras.layers import Dense, Activation, Dropout
<add>from keras.layers import LSTM
<ide> from keras.utils.data_utils import get_file
<ide> import numpy as np
<ide> import random
<ide><path>examples/mnist_cnn.py
<ide>
<ide> from keras.datasets import mnist
<ide> from keras.models import Sequential
<del>from keras.layers.core import Dense, Dropout, Activation, Flatten
<del>from keras.layers.convolutional import Convolution2D, MaxPooling2D
<add>from keras.layers import Dense, Dropout, Activation, Flatten
<add>from keras.layers import Convolution2D, MaxPooling2D
<ide> from keras.utils import np_utils
<ide>
<ide> batch_size = 128
<ide><path>examples/mnist_irnn.py
<ide>
<ide> from keras.datasets import mnist
<ide> from keras.models import Sequential
<del>from keras.layers.core import Dense, Activation
<add>from keras.layers import Dense, Activation
<add>from keras.layers import SimpleRNN
<ide> from keras.initializations import normal, identity
<del>from keras.layers.recurrent import SimpleRNN
<ide> from keras.optimizers import RMSprop
<ide> from keras.utils import np_utils
<ide>
<ide><path>examples/mnist_sklearn_wrapper.py
<ide>
<ide> from keras.datasets import mnist
<ide> from keras.models import Sequential
<del>from keras.layers.core import Dense, Dropout, Activation, Flatten
<del>from keras.layers.convolutional import Convolution2D, MaxPooling2D
<add>from keras.layers import Dense, Dropout, Activation, Flatten
<add>from keras.layers import Convolution2D, MaxPooling2D
<ide> from keras.utils import np_utils
<ide> from keras.wrappers.scikit_learn import KerasClassifier
<ide> from sklearn.grid_search import GridSearchCV
<ide><path>examples/mnist_transfer_cnn.py
<ide>
<ide> from keras.datasets import mnist
<ide> from keras.models import Sequential
<del>from keras.layers.core import Dense, Dropout, Activation, Flatten
<del>from keras.layers.convolutional import Convolution2D, MaxPooling2D
<add>from keras.layers import Dense, Dropout, Activation, Flatten
<add>from keras.layers import Convolution2D, MaxPooling2D
<ide> from keras.utils import np_utils
<ide>
<ide>
<ide><path>examples/neural_style_transfer.py
<ide> import h5py
<ide>
<ide> from keras.models import Sequential
<del>from keras.layers.convolutional import Convolution2D, ZeroPadding2D, MaxPooling2D
<add>from keras.layers import Convolution2D, ZeroPadding2D, MaxPooling2D
<ide> from keras import backend as K
<ide>
<ide> parser = argparse.ArgumentParser(description='Neural style transfer with Keras.')
<ide><path>examples/reuters_mlp.py
<ide>
<ide> from keras.datasets import reuters
<ide> from keras.models import Sequential
<del>from keras.layers.core import Dense, Dropout, Activation
<del>from keras.layers.normalization import BatchNormalization
<add>from keras.layers import Dense, Dropout, Activation
<ide> from keras.utils import np_utils
<ide> from keras.preprocessing.text import Tokenizer
<ide>
<ide><path>examples/stateful_lstm.py
<ide> import numpy as np
<ide> import matplotlib.pyplot as plt
<ide> from keras.models import Sequential
<del>from keras.layers.core import Dense
<del>from keras.layers.recurrent import LSTM
<add>from keras.layers import Dense, LSTM
<ide>
<ide>
<ide> # since we are using stateful rnn tsteps can be set to 1 | 17 |
Javascript | Javascript | add error code for *nix systems | dc0c63e5643639df81e07789fab00bbb8440e240 | <ide><path>lib/FileSystemInfo.js
<ide> class FileSystemInfo {
<ide> const packageJsonPath = join(this.fs, path, "package.json");
<ide> this.fs.readFile(packageJsonPath, (err, content) => {
<ide> if (err) {
<del> if (err.code === "ENOENT") {
<add> if (err.code === "ENOENT" || err.code === "ENOTDIR") {
<add> // no package.json or path is not a directory
<ide> this._managedItems.set(path, null);
<ide> return callback(null, null);
<ide> } | 1 |
Ruby | Ruby | move transaction code to transaction module | 61d12ebb10d9acfffad6ab76a43d3aaedfda5586 | <ide><path>activerecord/lib/active_record/core.rb
<ide> def slice(*methods)
<ide>
<ide> private
<ide>
<del> def set_transaction_state(state) # :nodoc:
<del> @transaction_state = state
<del> end
<del>
<del> def has_transactional_callbacks? # :nodoc:
<del> !_rollback_callbacks.empty? || !_commit_callbacks.empty? || !_before_commit_callbacks.empty?
<del> end
<del>
<del> # Updates the attributes on this particular ActiveRecord object so that
<del> # if it is associated with a transaction, then the state of the AR object
<del> # will be updated to reflect the current state of the transaction
<del> #
<del> # The @transaction_state variable stores the states of the associated
<del> # transaction. This relies on the fact that a transaction can only be in
<del> # one rollback or commit (otherwise a list of states would be required)
<del> # Each AR object inside of a transaction carries that transaction's
<del> # TransactionState.
<del> #
<del> # This method checks to see if the ActiveRecord object's state reflects
<del> # the TransactionState, and rolls back or commits the ActiveRecord object
<del> # as appropriate.
<del> #
<del> # Since ActiveRecord objects can be inside multiple transactions, this
<del> # method recursively goes through the parent of the TransactionState and
<del> # checks if the ActiveRecord object reflects the state of the object.
<del> def sync_with_transaction_state
<del> update_attributes_from_transaction_state(@transaction_state, 0)
<del> end
<del>
<del> def update_attributes_from_transaction_state(transaction_state, depth)
<del> @reflects_state = [false] if depth == 0
<del>
<del> if transaction_state && transaction_state.finalized? && !has_transactional_callbacks?
<del> unless @reflects_state[depth]
<del> restore_transaction_record_state if transaction_state.rolledback?
<del> clear_transaction_record_state
<del> @reflects_state[depth] = true
<del> end
<del> end
<del> end
<del>
<ide> # Under Ruby 1.9, Array#flatten will call #to_ary (recursively) on each of the elements
<ide> # of the array, and then rescues from the possible NoMethodError. If those elements are
<ide> # ActiveRecord::Base's, then this triggers the various method_missing's that we have,
<ide><path>activerecord/lib/active_record/transactions.rb
<ide> def transaction_include_any_action?(actions) #:nodoc:
<ide> end
<ide> end
<ide> end
<add>
<add> def set_transaction_state(state) # :nodoc:
<add> @transaction_state = state
<add> end
<add>
<add> def has_transactional_callbacks? # :nodoc:
<add> !_rollback_callbacks.empty? || !_commit_callbacks.empty? || !_before_commit_callbacks.empty?
<add> end
<add>
<add> # Updates the attributes on this particular ActiveRecord object so that
<add> # if it is associated with a transaction, then the state of the AR object
<add> # will be updated to reflect the current state of the transaction
<add> #
<add> # The @transaction_state variable stores the states of the associated
<add> # transaction. This relies on the fact that a transaction can only be in
<add> # one rollback or commit (otherwise a list of states would be required)
<add> # Each AR object inside of a transaction carries that transaction's
<add> # TransactionState.
<add> #
<add> # This method checks to see if the ActiveRecord object's state reflects
<add> # the TransactionState, and rolls back or commits the ActiveRecord object
<add> # as appropriate.
<add> #
<add> # Since ActiveRecord objects can be inside multiple transactions, this
<add> # method recursively goes through the parent of the TransactionState and
<add> # checks if the ActiveRecord object reflects the state of the object.
<add> def sync_with_transaction_state
<add> update_attributes_from_transaction_state(@transaction_state, 0)
<add> end
<add>
<add> def update_attributes_from_transaction_state(transaction_state, depth)
<add> @reflects_state = [false] if depth == 0
<add>
<add> if transaction_state && transaction_state.finalized? && !has_transactional_callbacks?
<add> unless @reflects_state[depth]
<add> restore_transaction_record_state if transaction_state.rolledback?
<add> clear_transaction_record_state
<add> @reflects_state[depth] = true
<add> end
<add> end
<add> end
<ide> end
<ide> end | 2 |
Ruby | Ruby | ensure log is flushed and tailed on failures | 4598d8874948268e1162c1ef75d0bd565b1e0e64 | <ide><path>actionpack/lib/action_dispatch/middleware/callbacks.rb
<ide> def initialize(app, prepare_each_request = false)
<ide> def call(env)
<ide> run_callbacks(:call) do
<ide> run_callbacks(:prepare) if @prepare_each_request
<del>
<del> ActiveSupport::Notifications.instrument "action_dispatch.callback" do
<del> @app.call(env)
<del> end
<add> @app.call(env)
<ide> end
<add> ensure
<add> ActiveSupport::Notifications.instrument "action_dispatch.callback"
<ide> end
<ide> end
<ide> end
<ide><path>actionpack/test/dispatch/callbacks_test.rb
<ide> def setup
<ide> ActionDispatch::Callbacks.reset_callbacks(:call)
<ide> end
<ide>
<del> def test_prepare_callbacks
<add> def test_prepare_callbacks_with_cache_classes
<ide> a = b = c = nil
<ide> ActionDispatch::Callbacks.to_prepare { |*args| a = b = c = 1 }
<ide> ActionDispatch::Callbacks.to_prepare { |*args| b = c = 2 }
<ide> def test_prepare_callbacks
<ide> assert_nil a || b || c
<ide> end
<ide>
<add> def test_prepare_callbacks_without_cache_classes
<add> a = b = c = nil
<add> ActionDispatch::Callbacks.to_prepare { |*args| a = b = c = 1 }
<add> ActionDispatch::Callbacks.to_prepare { |*args| b = c = 2 }
<add> ActionDispatch::Callbacks.to_prepare { |*args| c = 3 }
<add>
<add> # Ensure to_prepare callbacks are not run when defined
<add> assert_nil a || b || c
<add>
<add> # Run callbacks
<add> dispatch(false)
<add>
<add> assert_equal 1, a
<add> assert_equal 2, b
<add> assert_equal 3, c
<add>
<add> # Make sure they are run again
<add> a = b = c = nil
<add> dispatch(false)
<add> assert_equal 1, a
<add> assert_equal 2, b
<add> assert_equal 3, c
<add> end
<add>
<ide> def test_to_prepare_with_identifier_replaces
<ide> ActionDispatch::Callbacks.to_prepare(:unique_id) { |*args| Foo.a, Foo.b = 1, 1 }
<ide> ActionDispatch::Callbacks.to_prepare(:unique_id) { |*args| Foo.a = 2 }
<ide> def test_should_send_an_instrumentation_callback_for_async_processing
<ide> dispatch
<ide> end
<ide>
<add> def test_should_send_an_instrumentation_callback_for_async_processing_even_on_failure
<add> ActiveSupport::Notifications.notifier.expects(:publish)
<add> assert_raise RuntimeError do
<add> dispatch { |env| raise "OMG" }
<add> end
<add> end
<add>
<ide> private
<ide>
<del> def dispatch(cache_classes = true)
<del> @dispatcher ||= ActionDispatch::Callbacks.new(DummyApp.new, !cache_classes)
<add> def dispatch(cache_classes = true, &block)
<add> @dispatcher ||= ActionDispatch::Callbacks.new(block || DummyApp.new, !cache_classes)
<ide> @dispatcher.call({'rack.input' => StringIO.new('')})
<ide> end
<ide> | 2 |
Text | Text | remove duplication of "the" | c1ae3ded14eb248455a80daac6ca03b8a918413c | <ide><path>docs/tutorials/fundamentals/part-4-store.md
<ide> Now look at the console. You should see `'Hi!'` logged there, in between the oth
<ide>
<ide> 
<ide>
<del>The `sayHiOnDispatch` enhancer wrapped the original `store.dispatch` function with its own specialized version of `dispatch`. When we called `store.dispatch()`, we were actually calling the the wrapper function from `sayHiOnDispatch`, which called the original and then printed 'Hi'.
<add>The `sayHiOnDispatch` enhancer wrapped the original `store.dispatch` function with its own specialized version of `dispatch`. When we called `store.dispatch()`, we were actually calling the wrapper function from `sayHiOnDispatch`, which called the original and then printed 'Hi'.
<ide>
<ide> Now, let's try adding a second enhancer. We can import `includeMeaningOfLife` from that same file... but we have a problem. **`createStore` only accepts one enhancer as its third argument!** How can we pass _two_ enhancers at the same time?
<ide> | 1 |
Javascript | Javascript | add block description to mobile curriculum | 567e99231fbd06be7880a3bc8339d32d9ce6a6b6 | <ide><path>curriculum/getChallenges.js
<ide> async function buildBlocks({ basename: blockName }, curriculum, superBlock) {
<ide> __dirname,
<ide> `./challenges/_meta/${blockName}/meta.json`
<ide> );
<del> let blockMeta;
<del> try {
<del> blockMeta = require(metaPath);
<add>
<add> if (fs.existsSync(metaPath)) {
<add> // try to read the file, if the meta path does not exist it should be a certification.
<add> // As they do not have meta files.
<add>
<add> const blockMeta = JSON.parse(fs.readFileSync(metaPath));
<add>
<ide> const { isUpcomingChange } = blockMeta;
<add>
<ide> if (typeof isUpcomingChange !== 'boolean') {
<ide> throw Error(
<ide> `meta file at ${metaPath} is missing 'isUpcomingChange', it must be 'true' or 'false'`
<ide> async function buildBlocks({ basename: blockName }, curriculum, superBlock) {
<ide> const blockInfo = { meta: blockMeta, challenges: [] };
<ide> curriculum[superBlock].blocks[blockName] = blockInfo;
<ide> }
<del> } catch (e) {
<del> if (e.code !== 'MODULE_NOT_FOUND') {
<del> throw e;
<del> }
<add> } else {
<ide> curriculum['certifications'].blocks[blockName] = { challenges: [] };
<ide> }
<ide> }
<ide><path>tools/scripts/build/build-mobile-curriculum.js
<ide> const path = require('path');
<ide>
<ide> exports.buildMobileCurriculum = function buildMobileCurriculum(json) {
<ide> const mobileStaticPath = path.resolve(__dirname, '../../../client/static');
<add> const blockIntroPath = path.resolve(
<add> __dirname,
<add> '../../../client/i18n/locales/english/intro.json'
<add> );
<ide>
<ide> fs.mkdirSync(`${mobileStaticPath}/mobile`, { recursive: true });
<ide> writeAndParseCurriculumJson(json);
<ide> exports.buildMobileCurriculum = function buildMobileCurriculum(json) {
<ide> key => key !== 'certifications'
<ide> );
<ide>
<del> writeToFile('availableSuperblocks', { superblocks: superBlockKeys });
<add> writeToFile('availableSuperblocks', {
<add> // removing "/" as it will create an extra sub-path when accessed via an endpoint
<add>
<add> superblocks: [
<add> superBlockKeys.map(key => key.replace(/\//, '-')),
<add> getSuperBlockNames(superBlockKeys)
<add> ]
<add> });
<ide>
<ide> for (let i = 0; i < superBlockKeys.length; i++) {
<ide> const superBlock = {};
<ide> exports.buildMobileCurriculum = function buildMobileCurriculum(json) {
<ide>
<ide> for (let j = 0; j < blockNames.length; j++) {
<ide> superBlock[superBlockKeys[i]]['blocks'][blockNames[j]] = {};
<add>
<add> superBlock[superBlockKeys[i]]['blocks'][blockNames[j]]['desc'] =
<add> getBlockDescription(superBlockKeys[i], blockNames[j]);
<add>
<ide> superBlock[superBlockKeys[i]]['blocks'][blockNames[j]]['challenges'] =
<ide> curriculum[superBlockKeys[i]]['blocks'][blockNames[j]]['meta'];
<ide> }
<ide>
<del> writeToFile(superBlockKeys[i], superBlock);
<add> writeToFile(superBlockKeys[i].replace(/\//, '-'), superBlock);
<ide> }
<ide> }
<ide>
<del> function writeToFile(filename, json) {
<del> const fullPath = `${mobileStaticPath}/mobile/${filename}.json`;
<add> function getBlockDescription(superBlockKey, blockKey) {
<add> const intros = JSON.parse(fs.readFileSync(blockIntroPath));
<add>
<add> return intros[superBlockKey]['blocks'][blockKey]['intro'];
<add> }
<add>
<add> function getSuperBlockNames(superBlockKeys) {
<add> const superBlocks = JSON.parse(fs.readFileSync(blockIntroPath));
<add>
<add> return superBlockKeys.map(key => superBlocks[key].title);
<add> }
<add>
<add> function writeToFile(fileName, json) {
<add> const fullPath = `${mobileStaticPath}/mobile/${fileName}.json`;
<ide> fs.mkdirSync(path.dirname(fullPath), { recursive: true });
<ide> fs.writeFileSync(fullPath, JSON.stringify(json, null, 2));
<ide> }
<ide><path>tools/scripts/build/mobile-curriculum.test.js
<add>const path = require('path');
<add>const fs = require('fs');
<add>const { AssertionError } = require('chai');
<add>const { getChallengesForLang } = require('../../../curriculum/getChallenges');
<add>const { buildMobileCurriculum } = require('./build-mobile-curriculum');
<add>const { mobileSchemaValidator } = require('./mobileSchema');
<add>
<add>describe('mobile curriculum build', () => {
<add> const mobileStaticPath = path.resolve(__dirname, '../../../client/static');
<add> const blockIntroPath = path.resolve(
<add> __dirname,
<add> '../../../client/i18n/locales/english/intro.json'
<add> );
<add>
<add> const validateMobileSuperBlock = mobileSchemaValidator();
<add>
<add> let curriculum;
<add>
<add> beforeAll(async () => {
<add> curriculum = await getChallengesForLang('english');
<add> await buildMobileCurriculum(curriculum);
<add> }, 20000);
<add>
<add> test('the mobile curriculum should have a static folder with multiple files', () => {
<add> expect(fs.existsSync(`${mobileStaticPath}/mobile`)).toBe(true);
<add>
<add> expect(fs.readdirSync(`${mobileStaticPath}/mobile`).length).toBeGreaterThan(
<add> 0
<add> );
<add> });
<add>
<add> test('the mobile curriculum should have access to the intro.json file', () => {
<add> expect(fs.existsSync(blockIntroPath)).toBe(true);
<add> });
<add>
<add> test('the files generated should have the correct schema', () => {
<add> const fileArray = fs.readdirSync(`${mobileStaticPath}/mobile`);
<add>
<add> fileArray
<add> .filter(fileInArray => fileInArray !== 'availableSuperblocks.json')
<add> .forEach(fileInArray => {
<add> const fileContent = fs.readFileSync(
<add> `${mobileStaticPath}/mobile/${fileInArray}`
<add> );
<add>
<add> const result = validateMobileSuperBlock(JSON.parse(fileContent));
<add>
<add> if (result.error) {
<add> throw new AssertionError(result.error, `file: ${fileInArray}`);
<add> }
<add> });
<add> });
<add>});
<ide><path>tools/scripts/build/mobileSchema.js
<add>const Joi = require('joi');
<add>
<add>const blockSchema = Joi.object({}).keys({
<add> desc: Joi.array().min(1),
<add> challenges: Joi.object({}).keys({
<add> name: Joi.string(),
<add> isUpcomingChange: Joi.bool(),
<add> usesMultifileEditor: Joi.bool().optional(),
<add> hasEditableBoundaries: Joi.bool().optional(),
<add> isBeta: Joi.bool().optional(),
<add> dashedName: Joi.string(),
<add> order: Joi.number(),
<add> time: Joi.string().allow(''),
<add> template: Joi.string().allow(''),
<add> required: Joi.array(),
<add> superBlock: Joi.string(),
<add> challengeOrder: Joi.array().items(Joi.array().min(1))
<add> })
<add>});
<add>
<add>const subSchema = Joi.object({}).keys({
<add> blocks: Joi.object({}).pattern(Joi.string(), Joi.object().concat(blockSchema))
<add>});
<add>
<add>const schema = Joi.object({}).pattern(
<add> Joi.string(),
<add> Joi.object().concat(subSchema)
<add>);
<add>
<add>exports.mobileSchemaValidator = () => {
<add> return superblock => schema.validate(superblock);
<add>}; | 4 |
Text | Text | add missing word in cluster.workers details | 74867f713a704fe422473e3bba0dae9bc09907e2 | <ide><path>doc/api/cluster.md
<ide> process.
<ide> A worker is removed from `cluster.workers` after the worker has disconnected
<ide> _and_ exited. The order between these two events cannot be determined in
<ide> advance. However, it is guaranteed that the removal from the `cluster.workers`
<del>list happens before last `'disconnect'` or `'exit'` event is emitted.
<add>list happens before the last `'disconnect'` or `'exit'` event is emitted.
<ide>
<ide> ```mjs
<ide> import cluster from 'cluster'; | 1 |
Javascript | Javascript | get more tests with view#remove working | 54ed612c6b214861e480308b4201c1deab04e09e | <ide><path>packages/ember-metal-views/lib/renderer.js
<ide> Renderer.prototype.willRender = function (view) {
<ide>
<ide> Renderer.prototype.remove = function (view, shouldDestroy) {
<ide> this.willDestroyElement(view);
<del> view._transitionTo('destroying', false);
<add>
<add> view._willRemoveElement = true;
<add> run.schedule('render', this, this.renderElementRemoval, view);
<ide> };
<ide>
<add>Renderer.prototype.renderElementRemoval =
<add> function Renderer_renderElementRemoval(view) {
<add> // Use the _willRemoveElement flag to avoid mulitple removal attempts in
<add> // case many have been scheduled. This should be more performant than using
<add> // `scheduleOnce`.
<add> if (view._willRemoveElement) {
<add> view._willRemoveElement = false;
<add>
<add> if (view.lastResult) {
<add> view.renderNode.clear();
<add> }
<add> this.didDestroyElement(view);
<add> }
<add> };
<add>
<ide> Renderer.prototype.willRemoveElement = function (view) {};
<ide>
<ide> Renderer.prototype.willDestroyElement = function (view) {
<ide> Renderer.prototype.willDestroyElement = function (view) {
<ide> view.trigger('willDestroyElement');
<ide> view.trigger('willClearRender');
<ide> }
<add>
<add> view._transitionTo('destroying', false);
<add>
<add> var childViews = view.childViews;
<add> if (childViews) {
<add> for (var i = 0; i < childViews.length; i++) {
<add> this.willDestroyElement(childViews[i]);
<add> }
<add> }
<ide> };
<ide>
<ide> Renderer.prototype.didDestroyElement = function (view) {
<ide> view.element = null;
<del> if (view._transitionTo) {
<add>
<add> // Views that are being destroyed should never go back to the preRender state.
<add> // However if we're just destroying an element on a view (as is the case when
<add> // using View#remove) then the view should go to a preRender state so that
<add> // it can be rendered again later.
<add> if (view._state !== 'destroying') {
<ide> view._transitionTo('preRender');
<ide> }
<add>
<add> var childViews = view.childViews;
<add> if (childViews) {
<add> for (var i = 0; i < childViews.length; i++) {
<add> this.didDestroyElement(childViews[i]);
<add> }
<add> }
<ide> }; // element destroyed so view.destroy shouldn't try to remove it removedFromDOM
<ide>
<ide> export default Renderer;
<ide><path>packages/ember-views/tests/system/event_dispatcher_test.js
<ide> QUnit.test("should not dispatch events to views not inDOM", function() {
<ide>
<ide> var $element = view.$();
<ide>
<del> // TODO change this test not to use private API
<del> // Force into preRender
<del> view.renderer.remove(view, false, true);
<add> run(function() {
<add> // TODO change this test not to use private API
<add> // Force into preRender
<add> view.renderer.remove(view, false, true);
<add> });
<ide>
<ide> $element.trigger('mousedown');
<ide>
<ide><path>packages/ember-views/tests/views/view/append_to_test.js
<ide> QUnit.test("trigger rerender of parent and SimpleBoundView", function () {
<ide> });
<ide> });
<ide>
<del>QUnit.skip("remove removes an element from the DOM", function() {
<add>QUnit.test("remove removes an element from the DOM", function() {
<ide> willDestroyCalled = 0;
<ide>
<ide> view = View.create({
<ide> QUnit.skip("remove removes an element from the DOM", function() {
<ide> equal(willDestroyCalled, 1, "the willDestroyElement hook was called once");
<ide> });
<ide>
<del>QUnit.skip("destroy more forcibly removes the view", function() {
<add>QUnit.test("destroy more forcibly removes the view", function() {
<ide> willDestroyCalled = 0;
<ide>
<ide> view = View.create({
<ide> QUnit.module("EmberView - removing views in a view hierarchy", {
<ide> }
<ide> });
<ide>
<del>QUnit.skip("remove removes child elements from the DOM", function() {
<add>QUnit.test("remove removes child elements from the DOM", function() {
<ide> ok(!get(childView, 'element'), "precond - should not have an element");
<ide>
<ide> run(function() {
<ide> QUnit.skip("remove removes child elements from the DOM", function() {
<ide> equal(willDestroyCalled, 1, "the willDestroyElement hook was called once");
<ide> });
<ide>
<del>QUnit.skip("destroy more forcibly removes child views", function() {
<add>QUnit.test("destroy more forcibly removes child views", function() {
<ide> ok(!get(childView, 'element'), "precond - should not have an element");
<ide>
<ide> run(function() {
<ide><path>packages/ember-views/tests/views/view/remove_test.js
<ide> QUnit.test("does nothing if not in parentView", function() {
<ide> });
<ide>
<ide>
<del>QUnit.skip("the DOM element is gone after doing append and remove in two separate runloops", function() {
<add>QUnit.test("the DOM element is gone after doing append and remove in two separate runloops", function() {
<ide> view = View.create();
<ide> run(function() {
<ide> view.append(); | 4 |
Python | Python | add prefix conversions for strings | a7e4b2326a74067404339b1147c1ff40568ee4c0 | <ide><path>conversions/prefix_conversions_string.py
<add>"""
<add>* Author: Manuel Di Lullo (https://github.com/manueldilullo)
<add>* Description: Convert a number to use the correct SI or Binary unit prefix.
<add>
<add>Inspired by prefix_conversion.py file in this repository by lance-pyles
<add>
<add>URL: https://en.wikipedia.org/wiki/Metric_prefix#List_of_SI_prefixes
<add>URL: https://en.wikipedia.org/wiki/Binary_prefix
<add>"""
<add>
<add>from __future__ import annotations
<add>
<add>from enum import Enum, unique
<add>from typing import Type, TypeVar
<add>
<add># Create a generic variable that can be 'Enum', or any subclass.
<add>T = TypeVar("T", bound="Enum")
<add>
<add>
<add>@unique
<add>class BinaryUnit(Enum):
<add> yotta = 80
<add> zetta = 70
<add> exa = 60
<add> peta = 50
<add> tera = 40
<add> giga = 30
<add> mega = 20
<add> kilo = 10
<add>
<add>
<add>@unique
<add>class SIUnit(Enum):
<add> yotta = 24
<add> zetta = 21
<add> exa = 18
<add> peta = 15
<add> tera = 12
<add> giga = 9
<add> mega = 6
<add> kilo = 3
<add> hecto = 2
<add> deca = 1
<add> deci = -1
<add> centi = -2
<add> milli = -3
<add> micro = -6
<add> nano = -9
<add> pico = -12
<add> femto = -15
<add> atto = -18
<add> zepto = -21
<add> yocto = -24
<add>
<add> @classmethod
<add> def get_positive(cls: Type[T]) -> dict:
<add> """
<add> Returns a dictionary with only the elements of this enum
<add> that has a positive value
<add> >>> from itertools import islice
<add> >>> positive = SIUnit.get_positive()
<add> >>> inc = iter(positive.items())
<add> >>> dict(islice(inc, len(positive) // 2))
<add> {'yotta': 24, 'zetta': 21, 'exa': 18, 'peta': 15, 'tera': 12}
<add> >>> dict(inc)
<add> {'giga': 9, 'mega': 6, 'kilo': 3, 'hecto': 2, 'deca': 1}
<add> """
<add> return {unit.name: unit.value for unit in cls if unit.value > 0}
<add>
<add> @classmethod
<add> def get_negative(cls: Type[T]) -> dict:
<add> """
<add> Returns a dictionary with only the elements of this enum
<add> that has a negative value
<add> @example
<add> >>> from itertools import islice
<add> >>> negative = SIUnit.get_negative()
<add> >>> inc = iter(negative.items())
<add> >>> dict(islice(inc, len(negative) // 2))
<add> {'deci': -1, 'centi': -2, 'milli': -3, 'micro': -6, 'nano': -9}
<add> >>> dict(inc)
<add> {'pico': -12, 'femto': -15, 'atto': -18, 'zepto': -21, 'yocto': -24}
<add> """
<add> return {unit.name: unit.value for unit in cls if unit.value < 0}
<add>
<add>
<add>def add_si_prefix(value: float) -> str:
<add> """
<add> Function that converts a number to his version with SI prefix
<add> @input value (an integer)
<add> @example:
<add> >>> add_si_prefix(10000)
<add> '10.0 kilo'
<add> """
<add> prefixes = SIUnit.get_positive() if value > 0 else SIUnit.get_negative()
<add> for name_prefix, value_prefix in prefixes.items():
<add> numerical_part = value / (10 ** value_prefix)
<add> if numerical_part > 1:
<add> return f"{str(numerical_part)} {name_prefix}"
<add> return str(value)
<add>
<add>
<add>def add_binary_prefix(value: float) -> str:
<add> """
<add> Function that converts a number to his version with Binary prefix
<add> @input value (an integer)
<add> @example:
<add> >>> add_binary_prefix(65536)
<add> '64.0 kilo'
<add> """
<add> for prefix in BinaryUnit:
<add> numerical_part = value / (2 ** prefix.value)
<add> if numerical_part > 1:
<add> return f"{str(numerical_part)} {prefix.name}"
<add> return str(value)
<add>
<add>
<add>if __name__ == "__main__":
<add> import doctest
<add>
<add> doctest.testmod() | 1 |
Ruby | Ruby | avoid lambda scopes when possible | 4e5c2ccc1d97f0c18834f616fc219be6b1531bde | <ide><path>activerecord/lib/active_record/reflection.rb
<ide> def scopes
<ide> end
<ide>
<ide> def source_type_scope
<del> type = foreign_type
<del> source_type = options[:source_type]
<del> lambda { |object| where(type => source_type) }
<add> through_reflection.klass.where(foreign_type => options[:source_type])
<ide> end
<ide>
<ide> def has_scope? | 1 |
Javascript | Javascript | use common.iswindows consistently | d5ab92bcc1f0ddf7ea87a8322824a688dfd43bf5 | <ide><path>test/common.js
<ide> Object.defineProperty(exports, 'opensslCli', {get: function() {
<ide> opensslCli = path.join(path.dirname(process.execPath), 'openssl-cli');
<ide> }
<ide>
<del> if (process.platform === 'win32') opensslCli += '.exe';
<add> if (exports.isWindows) opensslCli += '.exe';
<ide>
<ide> var openssl_cmd = child_process.spawnSync(opensslCli, ['version']);
<ide> if (openssl_cmd.status !== 0 || openssl_cmd.error !== undefined) {
<ide> Object.defineProperty(exports, 'hasCrypto', {get: function() {
<ide> return process.versions.openssl ? true : false;
<ide> }});
<ide>
<del>if (process.platform === 'win32') {
<add>if (exports.isWindows) {
<ide> exports.PIPE = '\\\\.\\pipe\\libuv-test';
<ide> } else {
<ide> exports.PIPE = exports.tmpDir + '/test.sock';
<ide> if (process.env.NODE_COMMON_PIPE) {
<ide> }
<ide> }
<ide>
<del>if (process.platform === 'win32') {
<add>if (exports.isWindows) {
<ide> exports.faketimeCli = false;
<ide> } else {
<ide> exports.faketimeCli = path.join(__dirname, '..', 'tools', 'faketime', 'src',
<ide> exports.indirectInstanceOf = function(obj, cls) {
<ide>
<ide>
<ide> exports.ddCommand = function(filename, kilobytes) {
<del> if (process.platform === 'win32') {
<add> if (exports.isWindows) {
<ide> var p = path.resolve(exports.fixturesDir, 'create-file.js');
<ide> return '"' + process.argv[0] + '" "' + p + '" "' +
<ide> filename + '" ' + (kilobytes * 1024);
<ide> exports.ddCommand = function(filename, kilobytes) {
<ide> exports.spawnCat = function(options) {
<ide> var spawn = require('child_process').spawn;
<ide>
<del> if (process.platform === 'win32') {
<add> if (exports.isWindows) {
<ide> return spawn('more', [], options);
<ide> } else {
<ide> return spawn('cat', [], options);
<ide> exports.spawnCat = function(options) {
<ide> exports.spawnSyncCat = function(options) {
<ide> var spawnSync = require('child_process').spawnSync;
<ide>
<del> if (process.platform === 'win32') {
<add> if (exports.isWindows) {
<ide> return spawnSync('more', [], options);
<ide> } else {
<ide> return spawnSync('cat', [], options);
<ide> exports.spawnSyncCat = function(options) {
<ide> exports.spawnPwd = function(options) {
<ide> var spawn = require('child_process').spawn;
<ide>
<del> if (process.platform === 'win32') {
<add> if (exports.isWindows) {
<ide> return spawn('cmd.exe', ['/c', 'cd'], options);
<ide> } else {
<ide> return spawn('pwd', [], options);
<ide> exports.checkSpawnSyncRet = function(ret) {
<ide> };
<ide>
<ide> var etcServicesFileName = path.join('/etc', 'services');
<del>if (process.platform === 'win32') {
<add>if (exports.isWindows) {
<ide> etcServicesFileName = path.join(process.env.SystemRoot, 'System32', 'drivers',
<ide> 'etc', 'services');
<ide> }
<ide><path>test/parallel/test-c-ares.js
<ide> assert.throws(function() {
<ide> // Windows doesn't usually have an entry for localhost 127.0.0.1 in
<ide> // C:\Windows\System32\drivers\etc\hosts
<ide> // so we disable this test on Windows.
<del>if (process.platform != 'win32') {
<add>if (!common.isWindows) {
<ide> dns.resolve('127.0.0.1', 'PTR', function(error, domains) {
<ide> if (error) throw error;
<ide> assert.ok(Array.isArray(domains));
<ide><path>test/parallel/test-child-process-cwd.js
<ide> function testCwd(options, forCode, forData) {
<ide> }
<ide>
<ide> // Assume these exist, and 'pwd' gives us the right directory back
<del>if (process.platform == 'win32') {
<add>if (common.isWindows) {
<ide> testCwd({cwd: process.env.windir}, 0, process.env.windir);
<ide> testCwd({cwd: 'c:\\'}, 0, 'c:\\');
<ide> } else {
<ide><path>test/parallel/test-child-process-default-options.js
<ide> var assert = require('assert');
<ide>
<ide> var spawn = require('child_process').spawn;
<ide>
<del>var isWindows = process.platform === 'win32';
<del>
<ide> process.env.HELLO = 'WORLD';
<ide>
<del>if (isWindows) {
<add>if (common.isWindows) {
<ide> var child = spawn('cmd.exe', ['/c', 'set'], {});
<ide> } else {
<ide> var child = spawn('/usr/bin/env', [], {});
<ide><path>test/parallel/test-child-process-double-pipe.js
<ide> 'use strict';
<del>var is_windows = process.platform === 'win32';
<del>
<ide> var common = require('../common');
<ide> var assert = require('assert'),
<ide> os = require('os'),
<ide> var assert = require('assert'),
<ide>
<ide> var grep, sed, echo;
<ide>
<del>if (is_windows) {
<add>if (common.isWindows) {
<ide> grep = spawn('grep', ['--binary', 'o']),
<ide> sed = spawn('sed', ['--binary', 's/o/O/']),
<ide> echo = spawn('cmd.exe',
<ide><path>test/parallel/test-child-process-env.js
<ide> var assert = require('assert');
<ide>
<ide> var spawn = require('child_process').spawn;
<ide>
<del>var isWindows = process.platform === 'win32';
<del>
<ide> var env = {
<ide> 'HELLO': 'WORLD'
<ide> };
<ide> env.__proto__ = {
<ide> 'FOO': 'BAR'
<ide> };
<ide>
<del>if (isWindows) {
<add>if (common.isWindows) {
<ide> var child = spawn('cmd.exe', ['/c', 'set'], {env: env});
<ide> } else {
<ide> var child = spawn('/usr/bin/env', [], {env: env});
<ide><path>test/parallel/test-child-process-exec-cwd.js
<ide> 'use strict';
<del>require('../common');
<add>const common = require('../common');
<ide> var assert = require('assert');
<ide> var exec = require('child_process').exec;
<ide>
<ide> var error_count = 0;
<ide>
<ide> var pwdcommand, dir;
<ide>
<del>if (process.platform == 'win32') {
<add>if (common.isWindows) {
<ide> pwdcommand = 'echo %cd%';
<ide> dir = 'c:\\windows';
<ide> } else {
<ide><path>test/parallel/test-child-process-exec-env.js
<ide> function after(err, stdout, stderr) {
<ide> }
<ide> }
<ide>
<del>if (process.platform !== 'win32') {
<add>if (!common.isWindows) {
<ide> child = exec('/usr/bin/env', { env: { 'HELLO': 'WORLD' } }, after);
<ide> } else {
<ide> child = exec('set', { env: { 'HELLO': 'WORLD' } }, after);
<ide><path>test/parallel/test-child-process-exec-error.js
<ide> function test(fun, code) {
<ide> });
<ide> }
<ide>
<del>if (process.platform === 'win32') {
<add>if (common.isWindows) {
<ide> test(child_process.exec, 1); // exit code of cmd.exe
<ide> } else {
<ide> test(child_process.exec, 127); // exit code of /bin/sh
<ide><path>test/parallel/test-child-process-fork-dgram.js
<ide> var fork = require('child_process').fork;
<ide> var assert = require('assert');
<ide> var common = require('../common');
<ide>
<del>if (process.platform === 'win32') {
<add>if (common.isWindows) {
<ide> console.error('Sending dgram sockets to child processes not supported');
<ide> process.exit(0);
<ide> }
<ide><path>test/parallel/test-child-process-kill.js
<ide> var assert = require('assert');
<ide>
<ide> var spawn = require('child_process').spawn;
<ide>
<del>var is_windows = process.platform === 'win32';
<del>
<ide> var exitCode;
<ide> var termSignal;
<ide> var gotStdoutEOF = false;
<ide> var gotStderrEOF = false;
<ide>
<del>var cat = spawn(is_windows ? 'cmd' : 'cat');
<add>var cat = spawn(common.isWindows ? 'cmd' : 'cat');
<ide>
<ide>
<ide> cat.stdout.on('end', function() {
<ide><path>test/parallel/test-child-process-spawn-typeerror.js
<ide> var assert = require('assert');
<ide> var child_process = require('child_process');
<ide> var spawn = child_process.spawn;
<del>var cmd = (process.platform === 'win32') ? 'rundll32' : 'ls';
<add>var cmd = require('../common').isWindows ? 'rundll32' : 'ls';
<ide> var invalidArgsMsg = /Incorrect value of args option/;
<ide> var invalidOptionsMsg = /options argument must be an object/;
<ide>
<ide><path>test/parallel/test-child-process-spawnsync.js
<ide> assert.deepEqual(ret_err.spawnargs, ['bar']);
<ide> var response;
<ide> var cwd;
<ide>
<del> if (process.platform === 'win32') {
<add> if (common.isWindows) {
<ide> cwd = 'c:\\';
<ide> response = spawnSync('cmd.exe', ['/c', 'cd'], {cwd: cwd});
<ide> } else {
<ide><path>test/parallel/test-child-process-stdin.js
<ide> var common = require('../common');
<ide> var assert = require('assert');
<ide>
<ide> var spawn = require('child_process').spawn;
<del>var is_windows = process.platform === 'win32';
<ide>
<del>var cat = spawn(is_windows ? 'more' : 'cat');
<add>var cat = spawn(common.isWindows ? 'more' : 'cat');
<ide> cat.stdin.write('hello');
<ide> cat.stdin.write(' ');
<ide> cat.stdin.write('world');
<ide> cat.on('exit', function(status) {
<ide>
<ide> cat.on('close', function() {
<ide> closed = true;
<del> if (is_windows) {
<add> if (common.isWindows) {
<ide> assert.equal('hello world\r\n', response);
<ide> } else {
<ide> assert.equal('hello world', response);
<ide> cat.on('close', function() {
<ide> process.on('exit', function() {
<ide> assert.equal(0, exitStatus);
<ide> assert(closed);
<del> if (is_windows) {
<add> if (common.isWindows) {
<ide> assert.equal('hello world\r\n', response);
<ide> } else {
<ide> assert.equal('hello world', response);
<ide><path>test/parallel/test-cluster-bind-privileged-port.js
<ide> var assert = require('assert');
<ide> var cluster = require('cluster');
<ide> var net = require('net');
<ide>
<del>if (process.platform === 'win32') {
<add>if (common.isWindows) {
<ide> console.log('1..0 # Skipped: not reliable on Windows.');
<ide> return;
<ide> }
<ide><path>test/parallel/test-cluster-dgram-1.js
<ide> var common = require('../common');
<ide> var dgram = require('dgram');
<ide>
<ide>
<del>if (process.platform === 'win32') {
<add>if (common.isWindows) {
<ide> console.warn('dgram clustering is currently not supported on windows.');
<ide> process.exit(0);
<ide> }
<ide><path>test/parallel/test-cluster-dgram-2.js
<ide> var common = require('../common');
<ide> var dgram = require('dgram');
<ide>
<ide>
<del>if (process.platform === 'win32') {
<add>if (common.isWindows) {
<ide> console.warn('dgram clustering is currently not supported on windows.');
<ide> process.exit(0);
<ide> }
<ide><path>test/parallel/test-cluster-disconnect-unshared-udp.js
<ide> 'use strict';
<del>if (process.platform === 'win32') {
<add>
<add>const common = require('../common');
<add>
<add>if (common.isWindows) {
<ide> console.log('1..0 # Skipped: on windows, because clustered dgram is ENOTSUP');
<ide> return;
<ide> }
<ide><path>test/parallel/test-cluster-http-pipe.js
<ide> 'use strict';
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const cluster = require('cluster');
<add>const http = require('http');
<add>
<ide> // It is not possible to send pipe handles over the IPC pipe on Windows.
<del>if (process.platform === 'win32') {
<add>if (common.isWindows) {
<ide> process.exit(0);
<ide> }
<ide>
<del>var common = require('../common');
<del>var assert = require('assert');
<del>var cluster = require('cluster');
<del>var http = require('http');
<del>
<ide> if (cluster.isMaster) {
<ide> common.refreshTmpDir();
<ide> var ok = false;
<ide><path>test/parallel/test-cluster-shared-handle-bind-privileged-port.js
<ide> var assert = require('assert');
<ide> var cluster = require('cluster');
<ide> var net = require('net');
<ide>
<del>if (process.platform === 'win32') {
<add>if (common.isWindows) {
<ide> console.log('1..0 # Skipped: not reliable on Windows');
<ide> return;
<ide> }
<ide><path>test/parallel/test-cwd-enoent-repl.js
<ide> var fs = require('fs');
<ide> var spawn = require('child_process').spawn;
<ide>
<ide> // Fails with EINVAL on SmartOS, EBUSY on Windows.
<del>if (process.platform === 'sunos' || process.platform === 'win32') {
<add>if (process.platform === 'sunos' || common.isWindows) {
<ide> console.log('1..0 # Skipped: cannot rmdir current working directory');
<ide> return;
<ide> }
<ide><path>test/parallel/test-cwd-enoent.js
<ide> var fs = require('fs');
<ide> var spawn = require('child_process').spawn;
<ide>
<ide> // Fails with EINVAL on SmartOS, EBUSY on Windows.
<del>if (process.platform === 'sunos' || process.platform === 'win32') {
<add>if (process.platform === 'sunos' || common.isWindows) {
<ide> console.log('1..0 # Skipped: cannot rmdir current working directory');
<ide> return;
<ide> }
<ide><path>test/parallel/test-dgram-exclusive-implicit-bind.js
<ide> var dgram = require('dgram');
<ide> // supported while using cluster, though servers still cause the master to error
<ide> // with ENOTSUP.
<ide>
<del>var windows = process.platform === 'win32';
<del>
<ide> if (cluster.isMaster) {
<ide> var pass;
<ide> var messages = 0;
<ide> if (cluster.isMaster) {
<ide> messages++;
<ide> ports[rinfo.port] = true;
<ide>
<del> if (windows && messages === 2) {
<add> if (common.isWindows && messages === 2) {
<ide> assert.equal(Object.keys(ports).length, 2);
<ide> done();
<ide> }
<ide>
<del> if (!windows && messages === 4) {
<add> if (!common.isWindows && messages === 4) {
<ide> assert.equal(Object.keys(ports).length, 3);
<ide> done();
<ide> }
<ide> if (cluster.isMaster) {
<ide> target.on('listening', function() {
<ide> cluster.fork();
<ide> cluster.fork();
<del> if (!windows) {
<add> if (!common.isWindows) {
<ide> cluster.fork({BOUND: 'y'});
<ide> cluster.fork({BOUND: 'y'});
<ide> }
<ide><path>test/parallel/test-fs-access.js
<ide> createFileWithPerms(readWriteFile, 0o666);
<ide> * continuous integration platform to take care of that.
<ide> */
<ide> var hasWriteAccessForReadonlyFile = false;
<del>if (process.platform !== 'win32' && process.getuid() === 0) {
<add>if (!common.isWindows && process.getuid() === 0) {
<ide> hasWriteAccessForReadonlyFile = true;
<ide> try {
<ide> process.setuid('nobody');
<ide><path>test/parallel/test-fs-append-file-sync.js
<ide> var m = 0o600;
<ide> fs.appendFileSync(filename4, num, { mode: m });
<ide>
<ide> // windows permissions aren't unix
<del>if (process.platform !== 'win32') {
<add>if (!common.isWindows) {
<ide> var st = fs.statSync(filename4);
<ide> assert.equal(st.mode & 0o700, m);
<ide> }
<ide><path>test/parallel/test-fs-append-file.js
<ide> fs.appendFile(filename4, n, { mode: m }, function(e) {
<ide> common.error('appended to file4');
<ide>
<ide> // windows permissions aren't unix
<del> if (process.platform !== 'win32') {
<add> if (!common.isWindows) {
<ide> var st = fs.statSync(filename4);
<ide> assert.equal(st.mode & 0o700, m);
<ide> }
<ide><path>test/parallel/test-fs-chmod.js
<ide> var got_error = false;
<ide> var success_count = 0;
<ide> var mode_async;
<ide> var mode_sync;
<del>var is_windows = process.platform === 'win32';
<ide>
<ide> // Need to hijack fs.open/close to make sure that things
<ide> // get closed once they're opened.
<ide> function closeSync() {
<ide>
<ide>
<ide> // On Windows chmod is only able to manipulate read-only bit
<del>if (is_windows) {
<add>if (common.isWindows) {
<ide> mode_async = 0o400; // read-only
<ide> mode_sync = 0o600; // read-write
<ide> } else {
<ide> fs.chmod(file1, mode_async.toString(8), function(err) {
<ide> } else {
<ide> console.log(fs.statSync(file1).mode);
<ide>
<del> if (is_windows) {
<add> if (common.isWindows) {
<ide> assert.ok((fs.statSync(file1).mode & 0o777) & mode_async);
<ide> } else {
<ide> assert.equal(mode_async, fs.statSync(file1).mode & 0o777);
<ide> }
<ide>
<ide> fs.chmodSync(file1, mode_sync);
<del> if (is_windows) {
<add> if (common.isWindows) {
<ide> assert.ok((fs.statSync(file1).mode & 0o777) & mode_sync);
<ide> } else {
<ide> assert.equal(mode_sync, fs.statSync(file1).mode & 0o777);
<ide> fs.open(file2, 'a', function(err, fd) {
<ide> } else {
<ide> console.log(fs.fstatSync(fd).mode);
<ide>
<del> if (is_windows) {
<add> if (common.isWindows) {
<ide> assert.ok((fs.fstatSync(fd).mode & 0o777) & mode_async);
<ide> } else {
<ide> assert.equal(mode_async, fs.fstatSync(fd).mode & 0o777);
<ide> }
<ide>
<ide> fs.fchmodSync(fd, mode_sync);
<del> if (is_windows) {
<add> if (common.isWindows) {
<ide> assert.ok((fs.fstatSync(fd).mode & 0o777) & mode_sync);
<ide> } else {
<ide> assert.equal(mode_sync, fs.fstatSync(fd).mode & 0o777);
<ide><path>test/parallel/test-fs-readfile-pipe-large.js
<ide> var path = require('path');
<ide>
<ide> // simulate `cat readfile.js | node readfile.js`
<ide>
<del>if (process.platform === 'win32') {
<add>if (common.isWindows) {
<ide> console.log('1..0 # Skipped: No /dev/stdin on windows.');
<ide> return;
<ide> }
<ide><path>test/parallel/test-fs-readfile-pipe.js
<ide> var assert = require('assert');
<ide>
<ide> // simulate `cat readfile.js | node readfile.js`
<ide>
<del>if (process.platform === 'win32') {
<add>if (common.isWindows) {
<ide> console.log('1..0 # Skipped: No /dev/stdin on windows.');
<ide> return;
<ide> }
<ide><path>test/parallel/test-fs-readfilesync-pipe-large.js
<ide> var path = require('path');
<ide>
<ide> // simulate `cat readfile.js | node readfile.js`
<ide>
<del>if (process.platform === 'win32') {
<add>if (common.isWindows) {
<ide> console.log('1..0 # Skipped: No /dev/stdin on windows.');
<ide> return;
<ide> }
<ide><path>test/parallel/test-fs-realpath.js
<ide> var fs = require('fs');
<ide> var path = require('path');
<ide> var exec = require('child_process').exec;
<ide> var async_completed = 0, async_expected = 0, unlink = [];
<del>var isWindows = process.platform === 'win32';
<ide> var skipSymlinks = false;
<ide>
<ide> common.refreshTmpDir();
<ide>
<ide> var root = '/';
<del>if (isWindows) {
<add>if (common.isWindows) {
<ide> // something like "C:\\"
<ide> root = process.cwd().substr(0, 3);
<ide>
<ide> function test_relative_input_cwd(callback) {
<ide>
<ide> function test_deep_symlink_mix(callback) {
<ide> console.log('test_deep_symlink_mix');
<del> if (isWindows) {
<add> if (common.isWindows) {
<ide> // This one is a mix of files and directories, and it's quite tricky
<ide> // to get the file/dir links sorted out correctly.
<ide> console.log('1..0 # Skipped: symlink test (no privs)');
<ide> function test_lying_cache_liar(cb) {
<ide> '/a/b' : '/a/b',
<ide> '/a/b/c' : '/a/b',
<ide> '/a/b/d' : '/a/b/d' };
<del> if (isWindows) {
<add> if (common.isWindows) {
<ide> var wc = {};
<ide> Object.keys(cache).forEach(function(k) {
<ide> wc[ path.resolve(k) ] = path.resolve(cache[k]);
<ide><path>test/parallel/test-fs-symlink.js
<ide> var expected_async = 4;
<ide> var linkTime;
<ide> var fileTime;
<ide>
<del>var is_windows = process.platform === 'win32';
<del>
<ide> common.refreshTmpDir();
<ide>
<ide> var runtest = function(skip_symlinks) {
<ide> var runtest = function(skip_symlinks) {
<ide> });
<ide> };
<ide>
<del>if (is_windows) {
<add>if (common.isWindows) {
<ide> // On Windows, creating symlinks requires admin privileges.
<ide> // We'll only try to run symlink test if we have enough privileges.
<ide> exec('whoami /priv', function(err, o) {
<ide><path>test/parallel/test-fs-utimes.js
<ide> var assert = require('assert');
<ide> var util = require('util');
<ide> var fs = require('fs');
<ide>
<del>var is_windows = process.platform === 'win32';
<del>
<ide> var tests_ok = 0;
<ide> var tests_run = 0;
<ide>
<ide> function runTest(atime, mtime, callback) {
<ide> expect_errno('utimes', 'foobarbaz', err, 'ENOENT');
<ide>
<ide> // don't close this fd
<del> if (is_windows) {
<add> if (common.isWindows) {
<ide> fd = fs.openSync(__filename, 'r+');
<ide> } else {
<ide> fd = fs.openSync(__filename, 'r');
<ide><path>test/parallel/test-fs-write-file-sync.js
<ide> var common = require('../common');
<ide> var assert = require('assert');
<ide> var path = require('path');
<ide> var fs = require('fs');
<del>var isWindows = process.platform === 'win32';
<ide> var openCount = 0;
<ide> var mode;
<ide> var content;
<ide> var mask = process.umask(0o000);
<ide>
<ide> // On Windows chmod is only able to manipulate read-only bit. Test if creating
<ide> // the file in read-only mode works.
<del>if (isWindows) {
<add>if (common.isWindows) {
<ide> mode = 0o444;
<ide> } else {
<ide> mode = 0o755;
<ide><path>test/parallel/test-fs-write-file.js
<ide> fs.writeFile(filename3, n, { mode: m }, function(e) {
<ide> if (e) throw e;
<ide>
<ide> // windows permissions aren't unix
<del> if (process.platform !== 'win32') {
<add> if (!common.isWindows) {
<ide> var st = fs.statSync(filename3);
<ide> assert.equal(st.mode & 0o700, m);
<ide> }
<ide><path>test/parallel/test-https-foafssl.js
<ide> server.listen(common.PORT, function() {
<ide> '-key', join(common.fixturesDir, 'foafssl.key')];
<ide>
<ide> // for the performance and stability issue in s_client on Windows
<del> if (process.platform === 'win32')
<add> if (common.isWindows)
<ide> args.push('-no_rand_screen');
<ide>
<ide> var client = spawn(common.opensslCli, args);
<ide><path>test/parallel/test-listen-fd-cluster.js
<ide> var cluster = require('cluster');
<ide>
<ide> console.error('Cluster listen fd test', process.argv.slice(2));
<ide>
<del>if (process.platform === 'win32') {
<add>if (common.isWindows) {
<ide> console.log('1..0 # Skipped: This test is disabled on windows.');
<ide> return;
<ide> }
<ide><path>test/parallel/test-listen-fd-detached-inherit.js
<ide> var net = require('net');
<ide> var PORT = common.PORT;
<ide> var spawn = require('child_process').spawn;
<ide>
<del>if (process.platform === 'win32') {
<add>if (common.isWindows) {
<ide> console.log('1..0 # Skipped: This test is disabled on windows.');
<ide> return;
<ide> }
<ide><path>test/parallel/test-listen-fd-detached.js
<ide> var net = require('net');
<ide> var PORT = common.PORT;
<ide> var spawn = require('child_process').spawn;
<ide>
<del>if (process.platform === 'win32') {
<add>if (common.isWindows) {
<ide> console.log('1..0 # Skipped: This test is disabled on windows.');
<ide> return;
<ide> }
<ide><path>test/parallel/test-listen-fd-server.js
<ide> var net = require('net');
<ide> var PORT = common.PORT;
<ide> var spawn = require('child_process').spawn;
<ide>
<del>if (process.platform === 'win32') {
<add>if (common.isWindows) {
<ide> console.log('1..0 # Skipped: This test is disabled on windows.');
<ide> return;
<ide> }
<ide><path>test/parallel/test-module-globalpaths-nodepath.js
<ide> var assert = require('assert');
<ide>
<ide> var module = require('module');
<ide>
<del>var isWindows = process.platform === 'win32';
<del>
<ide> var partA, partB;
<ide> var partC = '';
<ide>
<del>if (isWindows) {
<add>if (common.isWindows) {
<ide> partA = 'C:\\Users\\Rocko Artischocko\\AppData\\Roaming\\npm';
<ide> partB = 'C:\\Program Files (x86)\\nodejs\\';
<ide> process.env['NODE_PATH'] = partA + ';' + partB + ';' + partC;
<ide><path>test/parallel/test-module-nodemodulepaths.js
<ide> var assert = require('assert');
<ide>
<ide> var module = require('module');
<ide>
<del>var isWindows = process.platform === 'win32';
<del>
<ide> var file, delimiter, paths;
<ide>
<del>if (isWindows) {
<add>if (common.isWindows) {
<ide> file = 'C:\\Users\\Rocko Artischocko\\node_stuff\\foo';
<ide> delimiter = '\\';
<ide> } else {
<ide><path>test/parallel/test-net-pipe-connect-errors.js
<ide> var accessErrorFired = false;
<ide>
<ide> var emptyTxt;
<ide>
<del>if (process.platform === 'win32') {
<add>if (common.isWindows) {
<ide> // on Win, common.PIPE will be a named pipe, so we use an existing empty
<ide> // file instead
<ide> emptyTxt = path.join(common.fixturesDir, 'empty.txt');
<ide> noEntSocketClient.on('error', function(err) {
<ide>
<ide>
<ide> // On Windows or when running as root, a chmod has no effect on named pipes
<del>if (process.platform !== 'win32' && process.getuid() !== 0) {
<add>if (!common.isWindows && process.getuid() !== 0) {
<ide> // Trying to connect to a socket one has no access to should result in EACCES
<ide> var accessServer = net.createServer(function() {
<ide> assert.ok(false);
<ide> if (process.platform !== 'win32' && process.getuid() !== 0) {
<ide> process.on('exit', function() {
<ide> assert.ok(notSocketErrorFired);
<ide> assert.ok(noEntErrorFired);
<del> if (process.platform !== 'win32' && process.getuid() !== 0) {
<add> if (!common.isWindows && process.getuid() !== 0) {
<ide> assert.ok(accessErrorFired);
<ide> }
<ide> });
<ide><path>test/parallel/test-path-makelong.js
<ide> var assert = require('assert');
<ide> var path = require('path');
<ide> var common = require('../common');
<ide>
<del>if (process.platform === 'win32') {
<add>if (common.isWindows) {
<ide> var file = path.join(common.fixturesDir, 'a.js');
<ide> var resolvedFile = path.resolve(file);
<ide>
<ide><path>test/parallel/test-path.js
<ide> var assert = require('assert');
<ide>
<ide> var path = require('path');
<ide>
<del>var isWindows = process.platform === 'win32';
<del>
<ide> var f = __filename;
<ide>
<ide> assert.equal(path.basename(f), 'test-path.js');
<ide> assert.equal(path.posix.basename('basename.ext\\\\'), 'basename.ext\\\\');
<ide>
<ide> // POSIX filenames may include control characters
<ide> // c.f. http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html
<del>if (!isWindows) {
<add>if (!common.isWindows) {
<ide> var controlCharFilename = 'Icon' + String.fromCharCode(13);
<ide> assert.equal(path.basename('/a/b/' + controlCharFilename),
<ide> controlCharFilename);
<ide> if (!isWindows) {
<ide> assert.equal(path.extname(f), '.js');
<ide>
<ide> assert.equal(path.dirname(f).substr(-13),
<del> isWindows ? 'test\\parallel' : 'test/parallel');
<add> common.isWindows ? 'test\\parallel' : 'test/parallel');
<ide> assert.equal(path.dirname('/a/b/'), '/a');
<ide> assert.equal(path.dirname('/a/b'), '/a');
<ide> assert.equal(path.dirname('/a'), '/');
<ide> var joinTests =
<ide> ];
<ide>
<ide> // Windows-specific join tests
<del>if (isWindows) {
<add>if (common.isWindows) {
<ide> joinTests = joinTests.concat(
<ide> [// UNC path expected
<ide> [['//foo/bar'], '//foo/bar/'],
<ide> if (isWindows) {
<ide> // Run the join tests.
<ide> joinTests.forEach(function(test) {
<ide> var actual = path.join.apply(path, test[0]);
<del> var expected = isWindows ? test[1].replace(/\//g, '\\') : test[1];
<add> var expected = common.isWindows ? test[1].replace(/\//g, '\\') : test[1];
<ide> var message = 'path.join(' + test[0].map(JSON.stringify).join(',') + ')' +
<ide> '\n expect=' + JSON.stringify(expected) +
<ide> '\n actual=' + JSON.stringify(actual);
<ide> assert.equal(path.posix.normalize('a//b//./c'), 'a/b/c');
<ide> assert.equal(path.posix.normalize('a//b//.'), 'a/b');
<ide>
<ide> // path.resolve tests
<del>if (isWindows) {
<add>if (common.isWindows) {
<ide> // windows
<ide> var resolveTests =
<ide> // arguments result
<ide> assert.equal(path.posix.isAbsolute('bar/'), false);
<ide> assert.equal(path.posix.isAbsolute('./baz'), false);
<ide>
<ide> // path.relative tests
<del>if (isWindows) {
<add>if (common.isWindows) {
<ide> // windows
<ide> var relativeTests =
<ide> // arguments result
<ide> assert.equal(path.win32.delimiter, ';');
<ide> assert.equal(path.posix.delimiter, ':');
<ide>
<ide>
<del>if (isWindows)
<add>if (common.isWindows)
<ide> assert.deepEqual(path, path.win32, 'should be win32 path module');
<ide> else
<ide> assert.deepEqual(path, path.posix, 'should be posix path module');
<ide><path>test/parallel/test-process-remove-all-signal-listeners.js
<ide> 'use strict';
<del>if (process.platform === 'win32') {
<add>
<add>const assert = require('assert');
<add>const spawn = require('child_process').spawn;
<add>const common = require('../common');
<add>
<add>if (common.isWindows) {
<ide> // Win32 doesn't have signals, just a kindof emulation, insufficient
<ide> // for this test to apply.
<ide> return;
<ide> }
<ide>
<del>var assert = require('assert');
<del>var spawn = require('child_process').spawn;
<ide> var ok;
<ide>
<ide> if (process.argv[2] !== '--do-test') {
<ide><path>test/parallel/test-signal-handler.js
<ide> 'use strict';
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>
<ide> // SIGUSR1 and SIGHUP are not supported on Windows
<del>if (process.platform === 'win32') {
<add>if (common.isWindows) {
<ide> process.exit(0);
<ide> }
<ide>
<del>var common = require('../common');
<del>var assert = require('assert');
<del>
<ide> console.log('process.pid: ' + process.pid);
<ide>
<ide> var first = 0,
<ide><path>test/parallel/test-stdio-closed.js
<ide> var common = require('../common');
<ide> var assert = require('assert');
<ide> var spawn = require('child_process').spawn;
<ide>
<del>if (process.platform === 'win32') {
<add>if (common.isWindows) {
<ide> console.log('1..0 # Skipped: platform not supported.');
<ide> return;
<ide> }
<ide><path>test/parallel/test-tls-alert.js
<ide> var server = tls.Server({
<ide> '-connect', '127.0.0.1:' + common.PORT];
<ide>
<ide> // for the performance and stability issue in s_client on Windows
<del> if (process.platform === 'win32')
<add> if (common.isWindows)
<ide> args.push('-no_rand_screen');
<ide>
<ide> var client = spawn(common.opensslCli, args);
<ide><path>test/parallel/test-tls-dhe.js
<ide> function test(keylen, expectedCipher, cb) {
<ide> '-cipher', ciphers];
<ide>
<ide> // for the performance and stability issue in s_client on Windows
<del> if (process.platform === 'win32')
<add> if (common.isWindows)
<ide> args.push('-no_rand_screen');
<ide>
<ide> var client = spawn(common.opensslCli, args);
<ide><path>test/parallel/test-tls-ecdh-disable.js
<ide> server.listen(common.PORT, '127.0.0.1', function() {
<ide> ' -connect 127.0.0.1:' + common.PORT;
<ide>
<ide> // for the performance and stability issue in s_client on Windows
<del> if (process.platform === 'win32')
<add> if (common.isWindows)
<ide> cmd += ' -no_rand_screen';
<ide>
<ide> exec(cmd, function(err, stdout, stderr) {
<ide><path>test/parallel/test-tls-ecdh.js
<ide> server.listen(common.PORT, '127.0.0.1', function() {
<ide> ' -connect 127.0.0.1:' + common.PORT;
<ide>
<ide> // for the performance and stability issue in s_client on Windows
<del> if (process.platform === 'win32')
<add> if (common.isWindows)
<ide> cmd += ' -no_rand_screen';
<ide>
<ide> exec(cmd, function(err, stdout, stderr) {
<ide><path>test/parallel/test-tls-no-sslv3.js
<ide> server.listen(common.PORT, '127.0.0.1', function() {
<ide> '-connect', address];
<ide>
<ide> // for the performance and stability issue in s_client on Windows
<del> if (process.platform === 'win32')
<add> if (common.isWindows)
<ide> args.push('-no_rand_screen');
<ide>
<ide> var client = spawn(common.opensslCli, args, { stdio: 'inherit' });
<ide><path>test/parallel/test-tls-securepair-server.js
<ide> server.listen(common.PORT, function() {
<ide> var args = ['s_client', '-connect', '127.0.0.1:' + common.PORT];
<ide>
<ide> // for the performance and stability issue in s_client on Windows
<del> if (process.platform === 'win32')
<add> if (common.isWindows)
<ide> args.push('-no_rand_screen');
<ide>
<ide> var client = spawn(common.opensslCli, args);
<ide><path>test/parallel/test-tls-server-verify.js
<ide> function runClient(prefix, port, options, cb) {
<ide> var args = ['s_client', '-connect', '127.0.0.1:' + port];
<ide>
<ide> // for the performance issue in s_client on Windows
<del> if (process.platform === 'win32')
<add> if (common.isWindows)
<ide> args.push('-no_rand_screen');
<ide>
<ide> console.log(prefix + ' connecting with', options.name);
<ide><path>test/parallel/test-tls-session-cache.js
<ide> function doTest(testOptions, callback) {
<ide> ].concat(testOptions.tickets ? [] : '-no_ticket');
<ide>
<ide> // for the performance and stability issue in s_client on Windows
<del> if (process.platform === 'win32')
<add> if (common.isWindows)
<ide> args.push('-no_rand_screen');
<ide>
<ide> server.listen(common.PORT, function() {
<ide><path>test/parallel/test-tls-set-ciphers.js
<ide> server.listen(common.PORT, '127.0.0.1', function() {
<ide> ' -connect 127.0.0.1:' + common.PORT;
<ide>
<ide> // for the performance and stability issue in s_client on Windows
<del> if (process.platform === 'win32')
<add> if (common.isWindows)
<ide> cmd += ' -no_rand_screen';
<ide>
<ide> exec(cmd, function(err, stdout, stderr) {
<ide><path>test/parallel/test-umask.js
<ide> var assert = require('assert');
<ide>
<ide> // Note in Windows one can only set the "user" bits.
<ide> var mask;
<del>if (process.platform == 'win32') {
<add>if (common.isWindows) {
<ide> mask = '0600';
<ide> } else {
<ide> mask = '0664';
<ide><path>test/pummel/test-abort-fatal-error.js
<ide> var assert = require('assert');
<ide> var common = require('../common');
<ide>
<del>if (process.platform === 'win32') {
<add>if (common.isWindows) {
<ide> console.log('1..0 # Skipped: no RLIMIT_NOFILE on Windows');
<ide> return;
<ide> }
<ide><path>test/pummel/test-child-process-spawn-loop.js
<ide> var assert = require('assert');
<ide>
<ide> var spawn = require('child_process').spawn;
<ide>
<del>var is_windows = process.platform === 'win32';
<del>
<ide> var SIZE = 1000 * 1024;
<ide> var N = 40;
<ide> var finished = false;
<ide> function doSpawn(i) {
<ide>
<ide> child.on('close', function() {
<ide> // + 1 for \n or + 2 for \r\n on Windows
<del> assert.equal(SIZE + (is_windows ? 2 : 1), count);
<add> assert.equal(SIZE + (common.isWindows ? 2 : 1), count);
<ide> if (i < N) {
<ide> doSpawn(i + 1);
<ide> } else {
<ide><path>test/pummel/test-exec.js
<ide> var common = require('../common');
<ide> var assert = require('assert');
<ide> var exec = require('child_process').exec;
<ide>
<del>if (process.platform !== 'win32') {
<add>if (!common.isWindows) {
<ide> // Unix.
<ide> var SLEEP3_COMMAND = 'sleep 3';
<ide> } else {
<ide><path>test/pummel/test-keep-alive.js
<ide> 'use strict';
<del>if (process.platform === 'win32') {
<add>if (common.isWindows) {
<ide> console.log('1..0 # Skipped: no `wrk` on windows');
<ide> return;
<ide> }
<ide><path>test/sequential/test-child-process-emfile.js
<ide> var assert = require('assert');
<ide> var spawn = require('child_process').spawn;
<ide> var fs = require('fs');
<ide>
<del>if (process.platform === 'win32') {
<add>if (common.isWindows) {
<ide> console.log('1..0 # Skipped: no RLIMIT_NOFILE on Windows');
<ide> return;
<ide> }
<ide><path>test/sequential/test-child-process-execsync.js
<ide> assert.strictEqual(ret, msg + '\n',
<ide> var response;
<ide> var cwd;
<ide>
<del> if (process.platform === 'win32') {
<add> if (common.isWindows) {
<ide> cwd = 'c:\\';
<ide> response = execSync('echo %cd%', {cwd: cwd});
<ide> } else {
<ide><path>test/sequential/test-fs-watch.js
<ide> var assert = require('assert');
<ide> var path = require('path');
<ide> var fs = require('fs');
<ide>
<del>var expectFilePath = process.platform === 'win32' ||
<add>var expectFilePath = common.isWindows ||
<ide> process.platform === 'linux' ||
<ide> process.platform === 'darwin';
<ide>
<ide><path>test/sequential/test-regress-GH-3542.js
<ide> 'use strict';
<del>// This test is only relevant on Windows.
<del>if (process.platform !== 'win32') {
<del> return process.exit(0);
<del>}
<del>
<ide> var common = require('../common'),
<ide> assert = require('assert'),
<ide> fs = require('fs'),
<ide> path = require('path'),
<ide> succeeded = 0;
<ide>
<add>// This test is only relevant on Windows.
<add>if (!common.isWindows) {
<add> return process.exit(0);
<add>}
<add>
<ide> function test(p) {
<ide> var result = fs.realpathSync(p);
<ide> assert.strictEqual(result, path.resolve(p)); | 66 |
Javascript | Javascript | fix element inspector w/ start + end styles | bfea0e5524e281c6cbf938299fa254f103dd45c6 | <ide><path>Libraries/Inspector/resolveBoxStyle.js
<ide>
<ide> 'use strict';
<ide>
<add>const I18nManager = require('I18nManager');
<add>
<ide> /**
<del> * Resolve a style property into it's component parts, e.g.
<add> * Resolve a style property into its component parts.
<add> *
<add> * For example:
<ide> *
<del> * resolveProperties('margin', {margin: 5, marginBottom: 10})
<del> * ->
<del> * {top: 5, left: 5, right: 5, bottom: 10}
<add> * > resolveProperties('margin', {margin: 5, marginBottom: 10})
<add> * {top: 5, left: 5, right: 5, bottom: 10}
<ide> *
<del> * If none are set, returns false.
<add> * If no parts exist, this returns null.
<ide> */
<del>function resolveBoxStyle(prefix: string, style: Object): ?Object {
<del> const res = {};
<del> const subs = ['top', 'left', 'bottom', 'right'];
<del> let set = false;
<del> subs.forEach(sub => {
<del> res[sub] = style[prefix] || 0;
<del> });
<del> if (style[prefix]) {
<del> set = true;
<del> }
<del> if (style[prefix + 'Vertical']) {
<del> res.top = res.bottom = style[prefix + 'Vertical'];
<del> set = true;
<add>function resolveBoxStyle(
<add> prefix: string,
<add> style: Object,
<add>): ?$ReadOnly<{|
<add> bottom: number,
<add> left: number,
<add> right: number,
<add> top: number,
<add>|}> {
<add> let hasParts = false;
<add> const result = {
<add> bottom: 0,
<add> left: 0,
<add> right: 0,
<add> top: 0,
<add> };
<add>
<add> // TODO: Fix issues with multiple properties affecting the same side.
<add>
<add> const styleForAll = style[prefix];
<add> if (styleForAll != null) {
<add> for (const key of Object.keys(result)) {
<add> result[key] = styleForAll;
<add> }
<add> hasParts = true;
<ide> }
<del> if (style[prefix + 'Horizontal']) {
<del> res.left = res.right = style[prefix + 'Horizontal'];
<del> set = true;
<add>
<add> const styleForHorizontal = style[prefix + 'Horizontal'];
<add> if (styleForHorizontal != null) {
<add> result.left = styleForHorizontal;
<add> result.right = styleForHorizontal;
<add> hasParts = true;
<add> } else {
<add> const styleForLeft = style[prefix + 'Left'];
<add> if (styleForLeft != null) {
<add> result.left = styleForLeft;
<add> hasParts = true;
<add> }
<add>
<add> const styleForRight = style[prefix + 'Right'];
<add> if (styleForRight != null) {
<add> result.right = styleForRight;
<add> hasParts = true;
<add> }
<add>
<add> const styleForEnd = style[prefix + 'End'];
<add> if (styleForEnd != null) {
<add> if (I18nManager.isRTL && I18nManager.doLeftAndRightSwapInRTL) {
<add> result.left = styleForEnd;
<add> } else {
<add> result.right = styleForEnd;
<add> }
<add> hasParts = true;
<add> }
<add> const styleForStart = style[prefix + 'Start'];
<add> if (styleForStart != null) {
<add> if (I18nManager.isRTL && I18nManager.doLeftAndRightSwapInRTL) {
<add> result.right = styleForStart;
<add> } else {
<add> result.left = styleForStart;
<add> }
<add> hasParts = true;
<add> }
<ide> }
<del> subs.forEach(sub => {
<del> const val = style[prefix + capFirst(sub)];
<del> if (val) {
<del> res[sub] = val;
<del> set = true;
<add>
<add> const styleForVertical = style[prefix + 'Vertical'];
<add> if (styleForVertical != null) {
<add> result.bottom = styleForVertical;
<add> result.top = styleForVertical;
<add> hasParts = true;
<add> } else {
<add> const styleForBottom = style[prefix + 'Bottom'];
<add> if (styleForBottom != null) {
<add> result.bottom = styleForBottom;
<add> hasParts = true;
<add> }
<add>
<add> const styleForTop = style[prefix + 'Top'];
<add> if (styleForTop != null) {
<add> result.top = styleForTop;
<add> hasParts = true;
<ide> }
<del> });
<del> if (!set) {
<del> return;
<ide> }
<del> return res;
<del>}
<ide>
<del>function capFirst(text) {
<del> return text[0].toUpperCase() + text.slice(1);
<add> return hasParts ? result : null;
<ide> }
<ide>
<ide> module.exports = resolveBoxStyle; | 1 |
Ruby | Ruby | fix failing tests introduced by | eeb3879a114769f7b2c8470603cc06c61ed3c5f0 | <ide><path>activerecord/test/cases/connection_adapters/connection_swapping_nested_test.rb
<ide> def test_application_record_prevent_writes_can_be_changed
<ide> end
<ide> ensure
<ide> Object.send(:remove_const, :ApplicationRecord)
<add> ActiveRecord::Base.establish_connection :arunit
<ide> end
<ide> end
<ide> end | 1 |
Ruby | Ruby | reduce scope of ensure block, remove conditionals | 316d8d756cb7a466060fd1f61d1b789956d064d7 | <ide><path>Library/Homebrew/extend/fileutils.rb
<ide> def mktemp(prefix=name)
<ide> # /tmp volume to the other volume. So we let the user override the tmp
<ide> # prefix if they need to.
<ide>
<del> tempd = with_system_path { `mktemp -d #{HOMEBREW_TEMP}/#{prefix}-XXXXXX` }.chuzzle
<del> raise "Failed to create sandbox" if tempd.nil?
<add> tempd = with_system_path { `mktemp -d #{HOMEBREW_TEMP}/#{prefix}-XXXXXX` }.strip
<add> raise "Failed to create sandbox" if tempd.empty?
<ide> prevd = pwd
<del> cd tempd
<del> yield
<del> ensure
<del> cd prevd if prevd
<del> ignore_interrupts{ rm_r tempd } if tempd
<add> cd(tempd)
<add>
<add> begin
<add> yield
<add> ensure
<add> cd(prevd)
<add> ignore_interrupts { rm_r(tempd) }
<add> end
<ide> end
<ide> module_function :mktemp
<ide> | 1 |
PHP | PHP | apply fixes from styleci | 8f209d59cdc7e3991bac712b7fcf36c1f0d63fce | <ide><path>src/Illuminate/Http/Resources/Json/Resource.php
<ide> use JsonSerializable;
<ide> use Illuminate\Support\Collection;
<ide> use Illuminate\Container\Container;
<del>use Illuminate\Http\Resources\MissingValue;
<ide> use Illuminate\Contracts\Support\Arrayable;
<add>use Illuminate\Http\Resources\MissingValue;
<ide> use Illuminate\Contracts\Routing\UrlRoutable;
<ide> use Illuminate\Contracts\Support\Responsable;
<ide> use Illuminate\Http\Resources\DelegatesToResource;
<ide> protected function filter($data)
<ide> }
<ide>
<ide> if ($value instanceof MissingValue ||
<del> ($value instanceof Resource &&
<add> ($value instanceof self &&
<ide> $value->resource instanceof MissingValue)) {
<ide> unset($data[$key]);
<ide> }
<ide><path>tests/Integration/Http/ResourceTest.php
<ide> public function toArray($request)
<ide> }
<ide> }
<ide>
<del>class Subscription {}
<add>class Subscription
<add>{
<add>}
<ide>
<ide> class CommentCollection extends ResourceCollection
<ide> { | 2 |
Mixed | Text | support env for docker plugin set | efbed4500e30ff1a0eef4ff71fd46a58363d041b | <ide><path>api/server/router/plugin/plugin_routes.go
<ide> func (pr *pluginRouter) setPlugin(ctx context.Context, w http.ResponseWriter, r
<ide> if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
<ide> return err
<ide> }
<del> return pr.backend.Set(vars["name"], args)
<add> if err := pr.backend.Set(vars["name"], args); err != nil {
<add> return err
<add> }
<add> w.WriteHeader(http.StatusNoContent)
<add> return nil
<ide> }
<ide>
<ide> func (pr *pluginRouter) listPlugins(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide><path>docs/reference/api/docker_remote_api_v1.25.md
<ide> Content-Type: application/json
<ide> - **200** - no error
<ide> - **404** - plugin not installed
<ide>
<del><!-- TODO Document "docker plugin set" endpoint once implemented
<ide> ### Configure a plugin
<ide>
<del>`POST /plugins/(plugin name)/set`
<add>POST /plugins/(plugin name)/set`
<ide>
<del>**Status codes**:
<add>**Example request**:
<ide>
<del>- **500** - not implemented
<ide>
<del>-->
<add> POST /plugins/tiborvass/no-remove/set
<add> Content-Type: application/json
<add>
<add> ["DEBUG=1"]
<add>
<add>**Example response**:
<add>
<add> HTTP/1.1 204 No Content
<add>
<add>**Status codes**:
<add>
<add>- **204** - no error
<add>- **404** - plugin not installed
<ide>
<ide> ### Enable a plugin
<ide>
<ide><path>docs/reference/commandline/plugin_disable.md
<ide> tiborvass/no-remove latest A test plugin for Docker false
<ide> * [plugin inspect](plugin_inspect.md)
<ide> * [plugin install](plugin_install.md)
<ide> * [plugin rm](plugin_rm.md)
<add>* [plugin set](plugin_set.md)
<ide><path>docs/reference/commandline/plugin_enable.md
<ide> tiborvass/no-remove latest A test plugin for Docker true
<ide> * [plugin inspect](plugin_inspect.md)
<ide> * [plugin install](plugin_install.md)
<ide> * [plugin rm](plugin_rm.md)
<add>* [plugin set](plugin_set.md)
<ide><path>docs/reference/commandline/plugin_inspect.md
<ide> $ docker plugin inspect -f '{{.Id}}' tiborvass/no-remove:latest
<ide> * [plugin disable](plugin_disable.md)
<ide> * [plugin install](plugin_install.md)
<ide> * [plugin rm](plugin_rm.md)
<add>* [plugin set](plugin_set.md)
<ide><path>docs/reference/commandline/plugin_install.md
<ide> tiborvass/no-remove latest A test plugin for Docker true
<ide> * [plugin disable](plugin_disable.md)
<ide> * [plugin inspect](plugin_inspect.md)
<ide> * [plugin rm](plugin_rm.md)
<add>* [plugin set](plugin_set.md)
<ide><path>docs/reference/commandline/plugin_ls.md
<ide> tiborvass/no-remove latest A test plugin for Docker true
<ide> * [plugin inspect](plugin_inspect.md)
<ide> * [plugin install](plugin_install.md)
<ide> * [plugin rm](plugin_rm.md)
<add>* [plugin set](plugin_set.md)
<ide><path>docs/reference/commandline/plugin_rm.md
<ide> tiborvass/no-remove
<ide> * [plugin disable](plugin_disable.md)
<ide> * [plugin inspect](plugin_inspect.md)
<ide> * [plugin install](plugin_install.md)
<add>* [plugin set](plugin_set.md)
<ide><path>docs/reference/commandline/plugin_set.md
<add>---
<add>title: "plugin set"
<add>description: "the plugin set command description and usage"
<add>keywords: "plugin, set"
<add>advisory: "experimental"
<add>---
<add>
<add><!-- This file is maintained within the docker/docker Github
<add> repository at https://github.com/docker/docker/. Make all
<add> pull requests against that repo. If you see this file in
<add> another repository, consider it read-only there, as it will
<add> periodically be overwritten by the definitive file. Pull
<add> requests which include edits to this file in other repositories
<add> will be rejected.
<add>-->
<add>
<add># plugin set (experimental)
<add>
<add>```markdown
<add>Usage: docker plugin set PLUGIN key1=value1 [key2=value2...]
<add>
<add>Change settings for a plugin
<add>
<add>Options:
<add> --help Print usage
<add>```
<add>
<add>Change settings for a plugin. The plugin must be disabled.
<add>
<add>
<add>The following example installs change the env variable `DEBUG` of the
<add>`no-remove` plugin.
<add>
<add>```bash
<add>$ docker plugin inspect -f {{.Config.Env}} tiborvass/no-remove
<add>[DEBUG=0]
<add>
<add>$ docker plugin set DEBUG=1 tiborvass/no-remove
<add>
<add>$ docker plugin inspect -f {{.Config.Env}} tiborvass/no-remove
<add>[DEBUG=1]
<add>```
<add>
<add>## Related information
<add>
<add>* [plugin ls](plugin_ls.md)
<add>* [plugin enable](plugin_enable.md)
<add>* [plugin disable](plugin_disable.md)
<add>* [plugin inspect](plugin_inspect.md)
<add>* [plugin install](plugin_install.md)
<add>* [plugin rm](plugin_rm.md)
<ide><path>integration-cli/docker_cli_plugins_test.go
<ide> func (s *DockerSuite) TestPluginInstallDisableVolumeLs(c *check.C) {
<ide> dockerCmd(c, "volume", "ls")
<ide> }
<ide>
<add>func (s *DockerSuite) TestPluginSet(c *check.C) {
<add> testRequires(c, DaemonIsLinux, ExperimentalDaemon, Network)
<add> out, _ := dockerCmd(c, "plugin", "install", "--grant-all-permissions", "--disable", pName)
<add> c.Assert(strings.TrimSpace(out), checker.Contains, pName)
<add>
<add> env, _ := dockerCmd(c, "plugin", "inspect", "-f", "{{.Config.Env}}", pName)
<add> c.Assert(strings.TrimSpace(env), checker.Equals, "[DEBUG=0]")
<add>
<add> dockerCmd(c, "plugin", "set", pName, "DEBUG=1")
<add>
<add> env, _ = dockerCmd(c, "plugin", "inspect", "-f", "{{.Config.Env}}", pName)
<add> c.Assert(strings.TrimSpace(env), checker.Equals, "[DEBUG=1]")
<add>}
<add>
<ide> func (s *DockerSuite) TestPluginInstallImage(c *check.C) {
<ide> testRequires(c, DaemonIsLinux, ExperimentalDaemon)
<ide> out, _, err := dockerCmdWithError("plugin", "install", "redis")
<ide><path>plugin/backend.go
<ide> func (pm *Manager) Pull(name string, metaHeader http.Header, authConfig *types.A
<ide> }
<ide>
<ide> tag := distribution.GetTag(ref)
<del> p := v2.NewPlugin(ref.Name(), pluginID, pm.runRoot, tag)
<del> if err := p.InitPlugin(pm.libRoot); err != nil {
<add> p := v2.NewPlugin(ref.Name(), pluginID, pm.runRoot, pm.libRoot, tag)
<add> if err := p.InitPlugin(); err != nil {
<ide> return nil, err
<ide> }
<ide> pm.pluginStore.Add(p)
<ide><path>plugin/store/store_test.go
<ide> import (
<ide> )
<ide>
<ide> func TestFilterByCapNeg(t *testing.T) {
<del> p := v2.NewPlugin("test", "1234567890", "/run/docker", "latest")
<add> p := v2.NewPlugin("test", "1234567890", "/run/docker", "/var/lib/docker/plugins", "latest")
<ide>
<ide> iType := types.PluginInterfaceType{"volumedriver", "docker", "1.0"}
<ide> i := types.PluginManifestInterface{"plugins.sock", []types.PluginInterfaceType{iType}}
<ide> func TestFilterByCapNeg(t *testing.T) {
<ide> }
<ide>
<ide> func TestFilterByCapPos(t *testing.T) {
<del> p := v2.NewPlugin("test", "1234567890", "/run/docker", "latest")
<add> p := v2.NewPlugin("test", "1234567890", "/run/docker", "/var/lib/docker/plugins", "latest")
<ide>
<ide> iType := types.PluginInterfaceType{"volumedriver", "docker", "1.0"}
<ide> i := types.PluginManifestInterface{"plugins.sock", []types.PluginInterfaceType{iType}}
<ide><path>plugin/v2/plugin.go
<ide> package v2
<ide>
<ide> import (
<ide> "encoding/json"
<del> "errors"
<ide> "fmt"
<ide> "os"
<ide> "path/filepath"
<ide> type Plugin struct {
<ide> RefCount int `json:"-"`
<ide> Restart bool `json:"-"`
<ide> ExitChan chan bool `json:"-"`
<add> LibRoot string `json:"-"`
<ide> }
<ide>
<ide> const defaultPluginRuntimeDestination = "/run/docker/plugins"
<ide> func newPluginObj(name, id, tag string) types.Plugin {
<ide> }
<ide>
<ide> // NewPlugin creates a plugin.
<del>func NewPlugin(name, id, runRoot, tag string) *Plugin {
<add>func NewPlugin(name, id, runRoot, libRoot, tag string) *Plugin {
<ide> return &Plugin{
<ide> PluginObj: newPluginObj(name, id, tag),
<ide> RuntimeSourcePath: filepath.Join(runRoot, id),
<add> LibRoot: libRoot,
<ide> }
<ide> }
<ide>
<ide> func (p *Plugin) RemoveFromDisk() error {
<ide> }
<ide>
<ide> // InitPlugin populates the plugin object from the plugin manifest file.
<del>func (p *Plugin) InitPlugin(libRoot string) error {
<del> dt, err := os.Open(filepath.Join(libRoot, p.PluginObj.ID, "manifest.json"))
<add>func (p *Plugin) InitPlugin() error {
<add> dt, err := os.Open(filepath.Join(p.LibRoot, p.PluginObj.ID, "manifest.json"))
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func (p *Plugin) InitPlugin(libRoot string) error {
<ide> }
<ide> copy(p.PluginObj.Config.Args, p.PluginObj.Manifest.Args.Value)
<ide>
<del> f, err := os.Create(filepath.Join(libRoot, p.PluginObj.ID, "plugin-config.json"))
<add> return p.writeConfig()
<add>}
<add>
<add>func (p *Plugin) writeConfig() error {
<add> f, err := os.Create(filepath.Join(p.LibRoot, p.PluginObj.ID, "plugin-config.json"))
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func (p *Plugin) InitPlugin(libRoot string) error {
<ide>
<ide> // Set is used to pass arguments to the plugin.
<ide> func (p *Plugin) Set(args []string) error {
<del> m := make(map[string]string, len(args))
<del> for _, arg := range args {
<del> i := strings.Index(arg, "=")
<del> if i < 0 {
<del> return fmt.Errorf("No equal sign '=' found in %s", arg)
<add> p.Lock()
<add> defer p.Unlock()
<add>
<add> if p.PluginObj.Enabled {
<add> return fmt.Errorf("cannot set on an active plugin, disable plugin before setting")
<add> }
<add>
<add> sets, err := newSettables(args)
<add> if err != nil {
<add> return err
<add> }
<add>
<add>next:
<add> for _, s := range sets {
<add> // range over all the envs in the manifest
<add> for _, env := range p.PluginObj.Manifest.Env {
<add> // found the env in the manifest
<add> if env.Name == s.name {
<add> // is it settable ?
<add> if ok, err := s.isSettable(allowedSettableFieldsEnv, env.Settable); err != nil {
<add> return err
<add> } else if !ok {
<add> return fmt.Errorf("%q is not settable", s.prettyName())
<add> }
<add> // is it, so lets update the config in memory
<add> updateConfigEnv(&p.PluginObj.Config.Env, &s)
<add> continue next
<add> }
<ide> }
<del> m[arg[:i]] = arg[i+1:]
<add>
<add> //TODO: check devices, mount and args
<add>
<add> return fmt.Errorf("setting %q not found in the plugin configuration", s.name)
<ide> }
<del> return errors.New("not implemented")
<add>
<add> // update the config on disk
<add> return p.writeConfig()
<ide> }
<ide>
<ide> // ComputePrivileges takes the manifest file and computes the list of access necessary
<ide><path>plugin/v2/settable.go
<add>package v2
<add>
<add>import (
<add> "errors"
<add> "fmt"
<add> "strings"
<add>)
<add>
<add>type settable struct {
<add> name string
<add> field string
<add> value string
<add>}
<add>
<add>var (
<add> allowedSettableFieldsEnv = []string{"value"}
<add> allowedSettableFieldsArgs = []string{"value"}
<add> allowedSettableFieldsDevices = []string{"path"}
<add> allowedSettableFieldsMounts = []string{"source"}
<add>
<add> errMultipleFields = errors.New("multiple fields are settable, one must be specified")
<add> errInvalidFormat = errors.New("invalid format, must be <name>[.<field>][=<value>]")
<add>)
<add>
<add>func newSettables(args []string) ([]settable, error) {
<add> sets := make([]settable, 0, len(args))
<add> for _, arg := range args {
<add> set, err := newSettable(arg)
<add> if err != nil {
<add> return nil, err
<add> }
<add> sets = append(sets, set)
<add> }
<add> return sets, nil
<add>}
<add>
<add>func newSettable(arg string) (settable, error) {
<add> var set settable
<add> if i := strings.Index(arg, "="); i == 0 {
<add> return set, errInvalidFormat
<add> } else if i < 0 {
<add> set.name = arg
<add> } else {
<add> set.name = arg[:i]
<add> set.value = arg[i+1:]
<add> }
<add>
<add> if i := strings.LastIndex(set.name, "."); i > 0 {
<add> set.field = set.name[i+1:]
<add> set.name = arg[:i]
<add> }
<add>
<add> return set, nil
<add>}
<add>
<add>// prettyName return name.field if there is a field, otherwise name.
<add>func (set *settable) prettyName() string {
<add> if set.field != "" {
<add> return fmt.Sprintf("%s.%s", set.name, set.field)
<add> }
<add> return set.name
<add>}
<add>
<add>func (set *settable) isSettable(allowedSettableFields []string, settable []string) (bool, error) {
<add> if set.field == "" {
<add> if len(settable) == 1 {
<add> // if field is not specified and there only one settable, default to it.
<add> set.field = settable[0]
<add> } else if len(settable) > 1 {
<add> return false, errMultipleFields
<add> }
<add> }
<add>
<add> isAllowed := false
<add> for _, allowedSettableField := range allowedSettableFields {
<add> if set.field == allowedSettableField {
<add> isAllowed = true
<add> break
<add> }
<add> }
<add>
<add> if isAllowed {
<add> for _, settableField := range settable {
<add> if set.field == settableField {
<add> return true, nil
<add> }
<add> }
<add> }
<add>
<add> return false, nil
<add>}
<add>
<add>func updateConfigEnv(env *[]string, set *settable) {
<add> for i, e := range *env {
<add> if parts := strings.SplitN(e, "=", 2); parts[0] == set.name {
<add> (*env)[i] = fmt.Sprintf("%s=%s", set.name, set.value)
<add> return
<add> }
<add> }
<add>
<add> *env = append(*env, fmt.Sprintf("%s=%s", set.name, set.value))
<add>}
<ide><path>plugin/v2/settable_test.go
<add>package v2
<add>
<add>import (
<add> "reflect"
<add> "testing"
<add>)
<add>
<add>func TestNewSettable(t *testing.T) {
<add> contexts := []struct {
<add> arg string
<add> name string
<add> field string
<add> value string
<add> err error
<add> }{
<add> {"name=value", "name", "", "value", nil},
<add> {"name", "name", "", "", nil},
<add> {"name.field=value", "name", "field", "value", nil},
<add> {"name.field", "name", "field", "", nil},
<add> {"=value", "", "", "", errInvalidFormat},
<add> {"=", "", "", "", errInvalidFormat},
<add> }
<add>
<add> for _, c := range contexts {
<add> s, err := newSettable(c.arg)
<add> if err != c.err {
<add> t.Fatalf("expected error to be %v, got %v", c.err, err)
<add> }
<add>
<add> if s.name != c.name {
<add> t.Fatalf("expected name to be %q, got %q", c.name, s.name)
<add> }
<add>
<add> if s.field != c.field {
<add> t.Fatalf("expected field to be %q, got %q", c.field, s.field)
<add> }
<add>
<add> if s.value != c.value {
<add> t.Fatalf("expected value to be %q, got %q", c.value, s.value)
<add> }
<add>
<add> }
<add>}
<add>
<add>func TestIsSettable(t *testing.T) {
<add> contexts := []struct {
<add> allowedSettableFields []string
<add> set settable
<add> settable []string
<add> result bool
<add> err error
<add> }{
<add> {allowedSettableFieldsEnv, settable{}, []string{}, false, nil},
<add> {allowedSettableFieldsEnv, settable{field: "value"}, []string{}, false, nil},
<add> {allowedSettableFieldsEnv, settable{}, []string{"value"}, true, nil},
<add> {allowedSettableFieldsEnv, settable{field: "value"}, []string{"value"}, true, nil},
<add> {allowedSettableFieldsEnv, settable{field: "foo"}, []string{"value"}, false, nil},
<add> {allowedSettableFieldsEnv, settable{field: "foo"}, []string{"foo"}, false, nil},
<add> {allowedSettableFieldsEnv, settable{}, []string{"value1", "value2"}, false, errMultipleFields},
<add> }
<add>
<add> for _, c := range contexts {
<add> if res, err := c.set.isSettable(c.allowedSettableFields, c.settable); res != c.result {
<add> t.Fatalf("expected result to be %t, got %t", c.result, res)
<add> } else if err != c.err {
<add> t.Fatalf("expected error to be %v, got %v", c.err, err)
<add> }
<add> }
<add>}
<add>
<add>func TestUpdateConfigEnv(t *testing.T) {
<add> contexts := []struct {
<add> env []string
<add> set settable
<add> newEnv []string
<add> }{
<add> {[]string{}, settable{name: "DEBUG", value: "1"}, []string{"DEBUG=1"}},
<add> {[]string{"DEBUG=0"}, settable{name: "DEBUG", value: "1"}, []string{"DEBUG=1"}},
<add> {[]string{"FOO=0"}, settable{name: "DEBUG", value: "1"}, []string{"FOO=0", "DEBUG=1"}},
<add> {[]string{"FOO=0", "DEBUG=0"}, settable{name: "DEBUG", value: "1"}, []string{"FOO=0", "DEBUG=1"}},
<add> {[]string{"FOO=0", "DEBUG=0", "BAR=1"}, settable{name: "DEBUG", value: "1"}, []string{"FOO=0", "DEBUG=1", "BAR=1"}},
<add> }
<add>
<add> for _, c := range contexts {
<add> updateConfigEnv(&c.env, &c.set)
<add>
<add> if !reflect.DeepEqual(c.env, c.newEnv) {
<add> t.Fatalf("expected env to be %q, got %q", c.newEnv, c.env)
<add> }
<add> }
<add>} | 15 |
Go | Go | release the push lock at the end | 77a34920b24901da82f9e22138ef21ffc665d678 | <ide><path>server.go
<ide> func (srv *Server) ImagePush(job *engine.Job) engine.Status {
<ide> job.Error(err)
<ide> return engine.StatusErr
<ide> }
<add> defer srv.poolRemove("push", localName)
<add>
<ide> // Resolve the Repository name from fqn to endpoint + name
<ide> endpoint, remoteName, err := registry.ResolveRepositoryName(localName)
<ide> if err != nil { | 1 |
Text | Text | add strong emphasis. | 4ac31ad5a73f3f0c7d5b1e3edfd06173af556f21 | <ide><path>guide/english/wordpress/index.md
<ide> title: WordPress
<ide>
<ide> ## WordPress
<ide>
<del>WordPress is a free and open-source content management system based on PHP and MySQL. Features include robust user management, an extensible theming and plugin architecture, and a flexible template system. It is most associated with blogging but supports other types of web content including forums, media galleries, and online stores.
<add>WordPress is a free and open-source content management system based on **PHP** and **MySQL**. Features include robust user management, an extensible theming and plugin architecture, and a flexible template system. It is most associated with blogging but supports other types of web content including forums, media galleries, and online stores.
<ide>
<ide> WordPress powers over 30% of all websites and is by far the most used CMS on the planet. Backed by a huge community, this open source platform powers not only countless sites but a multi-billion dollar economy with themes, plugins, and custom software.
<ide> | 1 |
Ruby | Ruby | remove useless deup | 3429b0ccba036d09d1e6357e559be05efe3da969 | <ide><path>actionpack/lib/action_dispatch/routing/route_set.rb
<ide> def self.default_resources_path_names
<ide>
<ide> def initialize(request_class = ActionDispatch::Request)
<ide> self.named_routes = NamedRouteCollection.new
<del> self.resources_path_names = self.class.default_resources_path_names.dup
<add> self.resources_path_names = self.class.default_resources_path_names
<ide> self.default_url_options = {}
<ide> self.request_class = request_class
<ide> | 1 |
Javascript | Javascript | prevent parser throwing when err is null | 3a5f272606dd32b3d7bc2846f3b22b062744cb90 | <ide><path>tools/challenge-parser/parser/index.js
<ide> exports.parseMD = function parseMD(filename) {
<ide> if (!err) {
<ide> delete file.contents;
<ide> resolve(file.data);
<add> } else {
<add> err.message += ' in file ' + filename;
<add> reject(err);
<ide> }
<del>
<del> err.message += ' in file ' + filename;
<del> reject(err);
<ide> });
<ide> });
<ide> }; | 1 |
Python | Python | add like_num functionality to danish | 3b2cb107a37804b89792b1993088e59a78d26323 | <ide><path>spacy/lang/da/__init__.py
<ide>
<ide> from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
<ide> from .stop_words import STOP_WORDS
<add>from .lex_attrs import LEX_ATTRS
<ide>
<ide> from ..tokenizer_exceptions import BASE_EXCEPTIONS
<ide> from ..norm_exceptions import BASE_NORMS
<ide>
<ide> class DanishDefaults(Language.Defaults):
<ide> lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
<add> lex_attr_getters.update(LEX_ATTRS)
<ide> lex_attr_getters[LANG] = lambda text: 'da'
<ide> lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], BASE_NORMS)
<ide>
<ide><path>spacy/lang/da/lex_attrs.py
<add># coding: utf8
<add>from __future__ import unicode_literals
<add>
<add>from ...attrs import LIKE_NUM
<add>
<add># Source http://fjern-uv.dk/tal.php
<add>
<add>_num_words = """nul
<add>en et to tre fire fem seks syv otte ni ti
<add>elleve tolv tretten fjorten femten seksten sytten atten nitten tyve
<add>enogtyve toogtyve treogtyve fireogtyve femogtyve seksogtyve syvogtyve otteogtyve niogtyve tredive
<add>enogtredive toogtredive treogtredive fireogtredive femogtredive seksogtredive syvogtredive otteogtredive niogtredive fyrre
<add>enogfyrre toogfyrre treogfyrre fireogfyrre femgogfyrre seksogfyrre syvogfyrre otteogfyrre niogfyrre halvtreds
<add>enoghalvtreds tooghalvtreds treoghalvtreds fireoghalvtreds femoghalvtreds seksoghalvtreds syvoghalvtreds otteoghalvtreds nioghalvtreds tres
<add>enogtres toogtres treogtres fireogtres femogtres seksogtres syvogtres otteogtres niogtres halvfjerds
<add>enoghalvfjerds tooghalvfjerds treoghalvfjerds fireoghalvfjerds femoghalvfjerds seksoghalvfjerds syvoghalvfjerds otteoghalvfjerds nioghalvfjerds firs
<add>enogfirs toogfirs treogfirs fireogfirs femogfirs seksogfirs syvogfirs otteogfirs niogfirs halvfems
<add>enoghalvfems tooghalvfems treoghalvfems fireoghalvfems femoghalvfems seksoghalvfems syvoghalvfems otteoghalvfems nioghalvfems hundrede
<add>million milliard billion billiard trillion trilliard
<add>""".split()
<add>
<add># source http://www.duda.dk/video/dansk/grammatik/talord/talord.html
<add>
<add>_ordinal_words = """nulte
<add>første anden tredje fjerde femte sjette syvende ottende niende tiende
<add>elfte tolvte trettende fjortende femtende sekstende syttende attende nittende tyvende
<add>enogtyvende toogtyvende treogtyvende fireogtyvende femogtyvende seksogtyvende syvogtyvende otteogtyvende niogtyvende tredivte enogtredivte toogtredivte treogtredivte fireogtredivte femogtredivte seksogtredivte syvogtredivte otteogtredivte niogtredivte fyrretyvende
<add>enogfyrretyvende toogfyrretyvende treogfyrretyvende fireogfyrretyvende femogfyrretyvende seksogfyrretyvende syvogfyrretyvende otteogfyrretyvende niogfyrretyvende halvtredsindstyvende enoghalvtredsindstyvende
<add>tooghalvtredsindstyvende treoghalvtredsindstyvende fireoghalvtredsindstyvende femoghalvtredsindstyvende seksoghalvtredsindstyvende syvoghalvtredsindstyvende otteoghalvtredsindstyvende nioghalvtredsindstyvende
<add>tresindstyvende enogtresindstyvende toogtresindstyvende treogtresindstyvende fireogtresindstyvende femogtresindstyvende seksogtresindstyvende syvogtresindstyvende otteogtresindstyvende niogtresindstyvende halvfjerdsindstyvende
<add>enoghalvfjerdsindstyvende tooghalvfjerdsindstyvende treoghalvfjerdsindstyvende fireoghalvfjerdsindstyvende femoghalvfjerdsindstyvende seksoghalvfjerdsindstyvende syvoghalvfjerdsindstyvende otteoghalvfjerdsindstyvende nioghalvfjerdsindstyvende firsindstyvende
<add>enogfirsindstyvende toogfirsindstyvende treogfirsindstyvende fireogfirsindstyvende femogfirsindstyvende seksogfirsindstyvende syvogfirsindstyvende otteogfirsindstyvende niogfirsindstyvende halvfemsindstyvende
<add>enoghalvfemsindstyvende tooghalvfemsindstyvende treoghalvfemsindstyvende fireoghalvfemsindstyvende femoghalvfemsindstyvende seksoghalvfemsindstyvende syvoghalvfemsindstyvende otteoghalvfemsindstyvende nioghalvfemsindstyvende
<add>""".split()
<add>
<add>def like_num(text):
<add> text = text.replace(',', '').replace('.', '')
<add> if text.isdigit():
<add> return True
<add> if text.count('/') == 1:
<add> num, denom = text.split('/')
<add> if num.isdigit() and denom.isdigit():
<add> return True
<add> if text in _num_words:
<add> return True
<add> if text in _ordinal_words:
<add> return True
<add> return False
<add>
<add>LEX_ATTRS = {
<add> LIKE_NUM: like_num
<add>} | 2 |
Javascript | Javascript | update mailer names | 2f424def204b96081bec4883bea783aac0c1f829 | <ide><path>controllers/user.js
<ide> exports.postReset = function(req, res, next) {
<ide> });
<ide> var mailOptions = {
<ide> to: user.email,
<del> from: 'hackathon@starter.com',
<add> from: 'Team@freecodecamp.com',
<ide> subject: 'Your Free Code Camp password has been changed',
<ide> text: 'Hello,\n\n' +
<ide> 'This email is confirming that you requested to reset your password for your Free Code Camp account. This is your email: ' + user.email + '\n'
<ide> exports.postForgot = function(req, res, next) {
<ide> });
<ide> var mailOptions = {
<ide> to: user.email,
<del> from: 'team@freecodecamp.com',
<add> from: 'Team@freecodecamp.com',
<ide> subject: 'Reset your Free Code Camp password',
<ide> text: "You are receiving this email because you (or someone else) requested we reset your Free Code Camp account's password.\n\n" +
<ide> 'Please click on the following link, or paste this into your browser to complete the process:\n\n' + | 1 |
PHP | PHP | improve duplicate routes check | 22ac2597b809ea8d808fe159c75d2afa98fa7c4c | <ide><path>src/Command/RoutesCommand.php
<ide> public function execute(Arguments $args, ConsoleIo $io): ?int
<ide> $output = $duplicateRoutesCounter = [];
<ide>
<ide> foreach ($availableRoutes as $route) {
<del> $methods = $route->defaults['_method'] ?? '';
<add> $methods = isset($route->defaults['_method']) ? (array)$route->defaults['_method'] : [''];
<ide>
<ide> $item = [
<ide> $route->options['_name'] ?? $route->getName(),
<ide> public function execute(Arguments $args, ConsoleIo $io): ?int
<ide> $route->defaults['prefix'] ?? '',
<ide> $route->defaults['controller'] ?? '',
<ide> $route->defaults['action'] ?? '',
<del> is_string($methods) ? $methods : implode(', ', $methods),
<add> implode(', ', $methods),
<ide> ];
<ide>
<ide> if ($args->getOption('verbose')) {
<ide> public function execute(Arguments $args, ConsoleIo $io): ?int
<ide>
<ide> $output[] = $item;
<ide>
<del> if (!isset($duplicateRoutesCounter[$route->template])) {
<del> $duplicateRoutesCounter[$route->template] = 0;
<add> foreach ($methods as $method) {
<add> if (!isset($duplicateRoutesCounter[$route->template][$method])) {
<add> $duplicateRoutesCounter[$route->template][$method] = 0;
<add> }
<add>
<add> $duplicateRoutesCounter[$route->template][$method]++;
<ide> }
<del> $duplicateRoutesCounter[$route->template]++;
<ide> }
<ide>
<ide> if ($args->getOption('sort')) {
<ide> public function execute(Arguments $args, ConsoleIo $io): ?int
<ide> $duplicateRoutes = [];
<ide>
<ide> foreach ($availableRoutes as $route) {
<del> if ($duplicateRoutesCounter[$route->template] > 1) {
<del> $methods = $route->defaults['_method'] ?? '';
<del>
<del> $duplicateRoutes[] = [
<del> $route->options['_name'] ?? $route->getName(),
<del> $route->template,
<del> $route->defaults['plugin'] ?? '',
<del> $route->defaults['prefix'] ?? '',
<del> $route->defaults['controller'] ?? '',
<del> $route->defaults['action'] ?? '',
<del> is_string($methods) ? $methods : implode(', ', $methods),
<del> ];
<add> $methods = isset($route->defaults['_method']) ? (array)$route->defaults['_method'] : [''];
<add>
<add> foreach ($methods as $method) {
<add> if (
<add> $duplicateRoutesCounter[$route->template][$method] > 1 ||
<add> ($method === '' && count($duplicateRoutesCounter[$route->template]) > 1) ||
<add> ($method !== '' && isset($duplicateRoutesCounter[$route->template]['']))
<add> ) {
<add> $duplicateRoutes[] = [
<add> $route->options['_name'] ?? $route->getName(),
<add> $route->template,
<add> $route->defaults['plugin'] ?? '',
<add> $route->defaults['prefix'] ?? '',
<add> $route->defaults['controller'] ?? '',
<add> $route->defaults['action'] ?? '',
<add> implode(', ', $methods),
<add> ];
<add>
<add> break;
<add> }
<ide> }
<ide> }
<ide>
<ide><path>tests/TestCase/Command/RoutesCommandTest.php
<ide> public function testRouteDuplicateWarning(): void
<ide> new Route('/unique-path', [], ['_name' => '_bRoute'])
<ide> );
<ide>
<add> $builder->connect(
<add> new Route('/blog', ['_method' => 'GET'], ['_name' => 'blog-get'])
<add> );
<add> $builder->connect(
<add> new Route('/blog', [], ['_name' => 'blog-all'])
<add> );
<add>
<add> $builder->connect(
<add> new Route('/events', ['_method' => ['POST', 'PUT']], ['_name' => 'events-post'])
<add> );
<add> $builder->connect(
<add> new Route('/events', ['_method' => 'GET'], ['_name' => 'events-get'])
<add> );
<add>
<ide> $this->exec('routes');
<ide> $this->assertExitCode(Command::CODE_SUCCESS);
<ide> $this->assertOutputContainsRow([
<ide> public function testRouteDuplicateWarning(): void
<ide> '',
<ide> '',
<ide> ]);
<add> $this->assertOutputContainsRow([
<add> 'blog-get',
<add> '/blog',
<add> '',
<add> '',
<add> '',
<add> '',
<add> '',
<add> ]);
<add> $this->assertOutputContainsRow([
<add> 'blog-all',
<add> '/blog',
<add> '',
<add> '',
<add> '',
<add> '',
<add> '',
<add> ]);
<ide> }
<ide> } | 2 |
Ruby | Ruby | eliminate duplicate code from to_sql | 158197b91d34b5ef2a4c06fb12a440d0b88d693d | <ide><path>activerecord/lib/active_record/relation.rb
<ide> def to_sql
<ide> visitor = connection.visitor
<ide>
<ide> if eager_loading?
<del> join_dependency = construct_join_dependency
<del> relation = except :select
<del> relation = construct_relation_for_association_find(join_dependency, relation)
<add> find_with_associations { |rel| relation = rel }
<ide> end
<ide>
<ide> ast = relation.arel.ast
<ide><path>activerecord/lib/active_record/relation/finder_methods.rb
<ide> def find_with_associations
<ide> join_dependency = construct_join_dependency
<ide> relation = except :select
<ide> relation = construct_relation_for_association_find(join_dependency, relation)
<del> if ActiveRecord::NullRelation === relation
<del> []
<add> if block_given?
<add> yield relation
<ide> else
<del> rows = connection.select_all(relation.arel, 'SQL', relation.bind_values.dup)
<del> join_dependency.instantiate(rows)
<add> if ActiveRecord::NullRelation === relation
<add> []
<add> else
<add> rows = connection.select_all(relation.arel, 'SQL', relation.bind_values.dup)
<add> join_dependency.instantiate(rows)
<add> end
<ide> end
<ide> end
<ide> | 2 |
Text | Text | lose lgtm badge because we don't use it | bae08adc86c44268faaa0fe05ea0f2f91567ac9a | <ide><path>DIRECTORY.md
<ide>
<ide> ## Audio Filters
<ide> * [Butterworth Filter](audio_filters/butterworth_filter.py)
<add> * [Equal Loudness Filter](audio_filters/equal_loudness_filter.py)
<ide> * [Iir Filter](audio_filters/iir_filter.py)
<ide> * [Show Response](audio_filters/show_response.py)
<ide>
<ide> * [Binomial Coefficient](maths/binomial_coefficient.py)
<ide> * [Binomial Distribution](maths/binomial_distribution.py)
<ide> * [Bisection](maths/bisection.py)
<add> * [Carmichael Number](maths/carmichael_number.py)
<ide> * [Catalan Number](maths/catalan_number.py)
<ide> * [Ceil](maths/ceil.py)
<ide> * [Check Polygon](maths/check_polygon.py)
<ide><path>README.md
<ide> <a href="https://github.com/TheAlgorithms/Python/actions">
<ide> <img src="https://img.shields.io/github/workflow/status/TheAlgorithms/Python/build?label=CI&logo=github&style=flat-square" height="20" alt="GitHub Workflow Status">
<ide> </a>
<del> <a href="https://lgtm.com/projects/g/TheAlgorithms/Python/alerts">
<del> <img src="https://img.shields.io/lgtm/alerts/github/TheAlgorithms/Python.svg?label=LGTM&logo=LGTM&style=flat-square" height="20" alt="LGTM">
<del> </a>
<ide> <a href="https://github.com/pre-commit/pre-commit">
<ide> <img src="https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white&style=flat-square" height="20" alt="pre-commit">
<ide> </a> | 2 |
Javascript | Javascript | remove outdated {{with}} documentation | dac942a86eedc8f71727ae1bed7abfaac9aee935 | <ide><path>packages/ember-glimmer/lib/index.js
<ide> {{/each}}
<ide> {{/with}}
<ide> ```
<del>
<del> Without the `as` operator, it would be impossible to reference `user.name` in the example above.
<del>
<add>
<ide> NOTE: The alias should not reuse a name from the bound property path.
<ide>
<ide> For example: `{{#with foo.bar as |foo|}}` is not supported because it attempts to alias using | 1 |
PHP | PHP | add ability to skip a middleware | 6364f258860c846140675bc34468ab345be8af43 | <ide><path>src/Illuminate/Routing/Route.php
<ide> public function middleware($middleware = null)
<ide> return $this;
<ide> }
<ide>
<add> /**
<add> * Set which middleware(s) to skip
<add> *
<add> * @param array|string|null $middleware
<add> * @return $this|array
<add> */
<add> public function skipMiddleware($middleware = null)
<add> {
<add> if (is_null($middleware)) {
<add> return (array) ($this->action['skip_middleware'] ?? []);
<add> }
<add>
<add> if (is_string($middleware)) {
<add> $middleware = func_get_args();
<add> }
<add>
<add> $this->action['skip_middleware'] = array_merge(
<add> (array) ($this->action['skip_middleware'] ?? []), $middleware
<add> );
<add>
<add> return $this;
<add> }
<add>
<ide> /**
<ide> * Get the middleware for the route's controller.
<ide> *
<ide><path>src/Illuminate/Routing/Router.php
<ide> public function gatherRouteMiddleware(Route $route)
<ide> {
<ide> $middleware = collect($route->gatherMiddleware())->map(function ($name) {
<ide> return (array) MiddlewareNameResolver::resolve($name, $this->middleware, $this->middlewareGroups);
<del> })->flatten();
<add> })->flatten()->reject(function($name) use ($route) {
<add> return in_array($name, $route->getAction()['skip_middleware'] ?? [], true);
<add> });
<ide>
<ide> return $this->sortMiddleware($middleware);
<ide> }
<ide><path>tests/Routing/RouteRegistrarTest.php
<ide> public function testMiddlewareFluentRegistration()
<ide> $this->assertEquals(['seven'], $this->getRoute()->middleware());
<ide> }
<ide>
<add> public function testSkipMiddlewareRegistration()
<add> {
<add> $this->router->middleware(['one', 'two'])->get('users', function () {
<add> return 'all-users';
<add> })->skipMiddleware('one');
<add>
<add> $this->seeResponse('all-users', Request::create('users', 'GET'));
<add>
<add> $this->assertEquals(['one'], $this->getRoute()->skipMiddleware());
<add> }
<add>
<ide> public function testCanRegisterGetRouteWithClosureAction()
<ide> {
<ide> $this->router->middleware('get-middleware')->get('users', function () {
<ide><path>tests/Routing/RoutingRouteTest.php
<ide> public function testClosureMiddleware()
<ide> $this->assertSame('caught', $router->dispatch(Request::create('foo/bar', 'GET'))->getContent());
<ide> }
<ide>
<add> public function testMiddlewareCanBeSkipped()
<add> {
<add> $router = $this->getRouter();
<add> $router->aliasMiddleware('web', RoutingTestMiddlewareGroupTwo::class);
<add>
<add> $router->get('foo/bar', ['middleware' => 'web', function () {
<add> return 'hello';
<add> }])->skipMiddleware(RoutingTestMiddlewareGroupTwo::class);
<add>
<add> $this->assertEquals('hello', $router->dispatch(Request::create('foo/bar', 'GET'))->getContent());
<add> }
<add>
<ide> public function testMiddlewareWorksIfControllerThrowsHttpResponseException()
<ide> {
<ide> // Before calling controller | 4 |
Text | Text | add tests for exercise tracker | 7ad220d1ace80da69247b7c8877c96adec074092 | <ide><path>curriculum/challenges/english/05-apis-and-microservices/apis-and-microservices-projects/exercise-tracker.english.md
<ide> Start this project on Glitch using <a href='https://glitch.com/edit/#!/remix/clo
<ide>
<ide> ```yml
<ide> tests:
<add> - text: I can provide my own project, not the example url.
<add> testString: "getUserInput => {
<add> const url = getUserInput('url');
<add> assert(!(new RegExp('.*/fuschia-custard\\.glitch\\.me\\.*')).test(getUserInput('url')));
<add> }
<add> "
<add>
<ide> - text: I can create a user by posting form data username to /api/exercise/new-user and returned will be an object with username and <code>_id</code>.
<del> testString: ''
<add> testString: "async getUserInput => {
<add> const url = getUserInput('url');
<add> const res = await fetch(url + '/api/exercise/new-user', {
<add> method: 'POST',
<add> headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
<add> body: `username=fcc_test_${Date.now()}`.substr(0, 29)
<add> });
<add>
<add> if (res.ok) {
<add> const { _id, username } = await res.json();
<add> assert.exists(_id);
<add> assert.exists(username);
<add> } else {
<add> throw new Error(`${res.status} ${res.statusText}`);
<add> }
<add> }
<add> "
<ide> - text: I can get an array of all users by getting api/exercise/users with the same info as when creating a user.
<del> testString: ''
<add> testString: "async getUserInput => {
<add> const url = getUserInput('url');
<add> const res = await fetch(url + '/api/exercise/users');
<add>
<add> if (res.ok) {
<add> const data = await res.json();
<add> assert.isArray(data);
<add> } else {
<add> throw new Error(`${res.status} ${res.statusText}`);
<add> }
<add> }
<add> "
<ide> - text: 'I can add an exercise to any user by posting form data userId(_id), description, duration, and optionally date to /api/exercise/add. If no date supplied it will use current date. App will return the user object with the exercise fields added.'
<del> testString: ''
<add> testString: "async getUserInput => {
<add> const url = getUserInput('url');
<add> const res = await fetch(url + '/api/exercise/new-user', {
<add> method: 'POST',
<add> headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
<add> body: `username=fcc_test_${Date.now()}`.substr(0, 29)
<add> });
<add>
<add> if (res.ok) {
<add> const { _id, username } = await res.json();
<add> const expected = {
<add> username,
<add> description: 'test',
<add> duration: 60,
<add> _id,
<add> date: 'Mon Jan 01 1990'
<add> };
<add>
<add> const addRes = await fetch(url + '/api/exercise/add', {
<add> method: 'POST',
<add> headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
<add> body: `userId=${_id}&description=${expected.description}&duration=${expected.duration}&date=1990-01-01`
<add> });
<add> if (addRes.ok) {
<add> const actual = await addRes.json();
<add> assert.deepEqual(actual, expected);
<add> } else {
<add> throw new Error(`${addRes.status} ${addRes.statusText}`);
<add> }
<add> } else {
<add> throw new Error(`${res.status} ${res.statusText}`);
<add> }
<add> }
<add> "
<ide> - text: I can retrieve a full exercise log of any user by getting /api/exercise/log with a parameter of userId(_id). App will return the user object with added array log and count (total exercise count).
<del> testString: ''
<add> testString: "async getUserInput => {
<add> const url = getUserInput('url');
<add> const res = await fetch(url + '/api/exercise/new-user', {
<add> method: 'POST',
<add> headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
<add> body: `username=fcc_test_${Date.now()}`.substr(0, 29)
<add> });
<add>
<add> if (res.ok) {
<add> const { _id, username } = await res.json();
<add> const expected = {
<add> username,
<add> description: 'test',
<add> duration: 60,
<add> _id,
<add> date: new Date().toDateString()
<add> };
<add>
<add> const addRes = await fetch(url + '/api/exercise/add', {
<add> method: 'POST',
<add> headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
<add> body: `userId=${_id}&description=${expected.description}&duration=${expected.duration}`
<add> });
<add> if (addRes.ok) {
<add> const logRes = await fetch(url + `/api/exercise/log?userId=${_id}`);
<add> if (logRes.ok) {
<add> const { log } = await logRes.json();
<add> assert.isArray(log);
<add> assert.equal(1, log.length);
<add> } else {
<add> throw new Error(`${logRes.status} ${logRes.statusText}`);
<add> }
<add> } else {
<add> throw new Error(`${addRes.status} ${addRes.statusText}`);
<add> }
<add> } else {
<add> throw new Error(`${res.status} ${res.statusText}`);
<add> }
<add> }
<add> "
<ide> - text: 'I can retrieve part of the log of any user by also passing along optional parameters of from & to or limit. (Date format yyyy-mm-dd, limit = int)'
<del> testString: ''
<add> testString: "async getUserInput => {
<add> const url = getUserInput('url');
<add> const res = await fetch(url + '/api/exercise/new-user', {
<add> method: 'POST',
<add> headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
<add> body: `username=fcc_test_${Date.now()}`.substr(0, 29)
<add> });
<add>
<add> if (res.ok) {
<add> const { _id, username } = await res.json();
<add> const expected = {
<add> username,
<add> description: 'test',
<add> duration: 60,
<add> _id,
<add> date: new Date().toDateString()
<add> };
<add>
<add> const addExerciseRes = await fetch(url + '/api/exercise/add', {
<add> method: 'POST',
<add> headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
<add> body: `userId=${_id}&description=${expected.description}&duration=${expected.duration}&date=1990-01-01`
<add> });
<add> const addExerciseTwoRes = await fetch(url + '/api/exercise/add', {
<add> method: 'POST',
<add> headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
<add> body: `userId=${_id}&description=${expected.description}&duration=${expected.duration}&date=1990-01-02`
<add> });
<add> if (addExerciseRes.ok && addExerciseTwoRes.ok) {
<add> const logRes = await fetch(
<add> url + `/api/exercise/log?userId=${_id}&from=1989-12-31&to=1990-01-03`
<add> );
<add> if (logRes.ok) {
<add> const { log } = await logRes.json();
<add> assert.isArray(log);
<add> assert.equal(2, log.length);
<add> } else {
<add> throw new Error(`${logRes.status} ${logRes.statusText}`);
<add> }
<add>
<add> const limitRes = await fetch(
<add> url + `/api/exercise/log?userId=${_id}&limit=1`
<add> );
<add> if (limitRes.ok) {
<add> const { log } = await limitRes.json();
<add> assert.isArray(log);
<add> assert.equal(1, log.length);
<add> } else {
<add> throw new Error(`${limitRes.status} ${limitRes.statusText}`);
<add> }
<add> } else {
<add> throw new Error(`${res.status} ${res.statusText}`);
<add> }
<add> } else {
<add> throw new Error(`${res.status} ${res.statusText}`);
<add> }
<add> }
<add> "
<ide>
<ide> ```
<ide>
<ide> tests:
<ide>
<ide> ```js
<ide> /**
<del> Backend challenges don't need solutions,
<del> because they would need to be tested against a full working project.
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<ide> Please check our contributing guidelines to learn more.
<ide> */
<ide> ``` | 1 |
PHP | PHP | add setconnection to mocked method list | 81f4181d8950cc86958986820a2fba62fdce3424 | <ide><path>tests/TestCase/Database/Driver/SqlserverTest.php
<ide> public function testConnectionConfigCustom()
<ide> 'settings' => ['config1' => 'value1', 'config2' => 'value2'],
<ide> ];
<ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')
<del> ->setMethods(['_connect', 'getConnection'])
<add> ->setMethods(['_connect', 'setConnection', 'getConnection'])
<ide> ->setConstructorArgs([$config])
<ide> ->getMock();
<ide> $dsn = 'sqlsrv:Server=foo;Database=bar;MultipleActiveResultSets=false'; | 1 |
Go | Go | implement applylayer directly | 818c249bae8d29842834bf765299c86c09e6913e | <ide><path>archive/diff.go
<ide> package archive
<ide>
<ide> import (
<add> "archive/tar"
<add> "github.com/dotcloud/docker/utils"
<add> "io"
<ide> "os"
<ide> "path/filepath"
<ide> "strings"
<ide> "syscall"
<ide> "time"
<ide> )
<ide>
<add>// Linux device nodes are a bit weird due to backwards compat with 16 bit device nodes
<add>// The lower 8 bit is the lower 8 bit in the minor, the following 12 bits are the major,
<add>// and then there is the top 12 bits of then minor
<add>func mkdev(major int64, minor int64) uint32 {
<add> return uint32(((minor & 0xfff00) << 12) | ((major & 0xfff) << 8) | (minor & 0xff))
<add>}
<add>func timeToTimespec(time time.Time) (ts syscall.Timespec) {
<add> if time.IsZero() {
<add> // Return UTIME_OMIT special value
<add> ts.Sec = 0
<add> ts.Nsec = ((1 << 30) - 2)
<add> return
<add> }
<add> return syscall.NsecToTimespec(time.UnixNano())
<add>}
<add>
<ide> // ApplyLayer parses a diff in the standard layer format from `layer`, and
<ide> // applies it to the directory `dest`.
<ide> func ApplyLayer(dest string, layer Archive) error {
<del> // Poor man's diff applyer in 2 steps:
<add> // We need to be able to set any perms
<add> oldmask := syscall.Umask(0)
<add> defer syscall.Umask(oldmask)
<ide>
<del> // Step 1: untar everything in place
<del> if err := Untar(layer, dest, nil); err != nil {
<del> return err
<del> }
<add> tr := tar.NewReader(layer)
<ide>
<del> modifiedDirs := make(map[string]*syscall.Stat_t)
<del> addDir := func(file string) {
<del> d := filepath.Dir(file)
<del> if _, exists := modifiedDirs[d]; !exists {
<del> if s, err := os.Lstat(d); err == nil {
<del> if sys := s.Sys(); sys != nil {
<del> if stat, ok := sys.(*syscall.Stat_t); ok {
<del> modifiedDirs[d] = stat
<del> }
<del> }
<del> }
<del> }
<del> }
<add> var dirs []*tar.Header
<ide>
<del> // Step 2: walk for whiteouts and apply them, removing them in the process
<del> err := filepath.Walk(dest, func(fullPath string, f os.FileInfo, err error) error {
<add> // Iterate through the files in the archive.
<add> for {
<add> hdr, err := tr.Next()
<add> if err == io.EOF {
<add> // end of tar archive
<add> break
<add> }
<ide> if err != nil {
<del> if os.IsNotExist(err) {
<del> // This happens in the case of whiteouts in parent dir removing a directory
<del> // We just ignore it
<del> return filepath.SkipDir
<del> }
<ide> return err
<ide> }
<ide>
<del> // Rebase path
<del> path, err := filepath.Rel(dest, fullPath)
<del> if err != nil {
<del> return err
<add> // Skip AUFS metadata dirs
<add> if strings.HasPrefix(hdr.Name, ".wh..wh.") {
<add> continue
<ide> }
<del> path = filepath.Join("/", path)
<ide>
<del> // Skip AUFS metadata
<del> if matched, err := filepath.Match("/.wh..wh.*", path); err != nil {
<del> return err
<del> } else if matched {
<del> addDir(fullPath)
<del> if err := os.RemoveAll(fullPath); err != nil {
<add> path := filepath.Join(dest, hdr.Name)
<add> base := filepath.Base(path)
<add> if strings.HasPrefix(base, ".wh.") {
<add> originalBase := base[len(".wh."):]
<add> originalPath := filepath.Join(filepath.Dir(path), originalBase)
<add> if err := os.RemoveAll(originalPath); err != nil {
<ide> return err
<ide> }
<del> }
<add> } else {
<add> // If path exits we almost always just want to remove and replace it
<add> // The only exception is when it is a directory *and* the file from
<add> // the layer is also a directory. Then we want to merge them (i.e.
<add> // just apply the metadata from the layer).
<add> hasDir := false
<add> if fi, err := os.Lstat(path); err == nil {
<add> if fi.IsDir() && hdr.Typeflag == tar.TypeDir {
<add> hasDir = true
<add> } else {
<add> if err := os.RemoveAll(path); err != nil {
<add> return err
<add> }
<add> }
<add> }
<ide>
<del> filename := filepath.Base(path)
<del> if strings.HasPrefix(filename, ".wh.") {
<del> rmTargetName := filename[len(".wh."):]
<del> rmTargetPath := filepath.Join(filepath.Dir(fullPath), rmTargetName)
<add> switch hdr.Typeflag {
<add> case tar.TypeDir:
<add> if !hasDir {
<add> err = os.Mkdir(path, os.FileMode(hdr.Mode))
<add> if err != nil {
<add> return err
<add> }
<add> }
<add> dirs = append(dirs, hdr)
<ide>
<del> // Remove the file targeted by the whiteout
<del> addDir(rmTargetPath)
<del> if err := os.RemoveAll(rmTargetPath); err != nil {
<del> return err
<add> case tar.TypeReg, tar.TypeRegA:
<add> // Source is regular file
<add> file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, os.FileMode(hdr.Mode))
<add> if err != nil {
<add> return err
<add> }
<add> if _, err := io.Copy(file, tr); err != nil {
<add> file.Close()
<add> return err
<add> }
<add> file.Close()
<add>
<add> case tar.TypeBlock, tar.TypeChar, tar.TypeFifo:
<add> mode := uint32(hdr.Mode & 07777)
<add> switch hdr.Typeflag {
<add> case tar.TypeBlock:
<add> mode |= syscall.S_IFBLK
<add> case tar.TypeChar:
<add> mode |= syscall.S_IFCHR
<add> case tar.TypeFifo:
<add> mode |= syscall.S_IFIFO
<add> }
<add>
<add> if err := syscall.Mknod(path, mode, int(mkdev(hdr.Devmajor, hdr.Devminor))); err != nil {
<add> return err
<add> }
<add>
<add> case tar.TypeLink:
<add> if err := os.Link(filepath.Join(dest, hdr.Linkname), path); err != nil {
<add> return err
<add> }
<add>
<add> case tar.TypeSymlink:
<add> if err := os.Symlink(hdr.Linkname, path); err != nil {
<add> return err
<add> }
<add>
<add> default:
<add> utils.Debugf("unhandled type %d\n", hdr.Typeflag)
<ide> }
<del> // Remove the whiteout itself
<del> addDir(fullPath)
<del> if err := os.RemoveAll(fullPath); err != nil {
<add>
<add> if err = syscall.Lchown(path, hdr.Uid, hdr.Gid); err != nil {
<ide> return err
<ide> }
<add>
<add> // There is no LChmod, so ignore mode for symlink. Also, this
<add> // must happen after chown, as that can modify the file mode
<add> if hdr.Typeflag != tar.TypeSymlink {
<add> err = syscall.Chmod(path, uint32(hdr.Mode&07777))
<add> if err != nil {
<add> return err
<add> }
<add> }
<add>
<add> // Directories must be handled at the end to avoid further
<add> // file creation in them to modify the mtime
<add> if hdr.Typeflag != tar.TypeDir {
<add> ts := []syscall.Timespec{timeToTimespec(hdr.AccessTime), timeToTimespec(hdr.ModTime)}
<add> // syscall.UtimesNano doesn't support a NOFOLLOW flag atm, and
<add> if hdr.Typeflag != tar.TypeSymlink {
<add> if err := syscall.UtimesNano(path, ts); err != nil {
<add> return err
<add> }
<add> } else {
<add> if err := LUtimesNano(path, ts); err != nil {
<add> return err
<add> }
<add> }
<add> }
<ide> }
<del> return nil
<del> })
<del> if err != nil {
<del> return err
<ide> }
<ide>
<del> for k, v := range modifiedDirs {
<del> lastAccess := getLastAccess(v)
<del> lastModification := getLastModification(v)
<del> aTime := time.Unix(lastAccess.Unix())
<del> mTime := time.Unix(lastModification.Unix())
<del>
<del> if err := os.Chtimes(k, aTime, mTime); err != nil {
<add> for _, hdr := range dirs {
<add> path := filepath.Join(dest, hdr.Name)
<add> ts := []syscall.Timespec{timeToTimespec(hdr.AccessTime), timeToTimespec(hdr.ModTime)}
<add> if err := syscall.UtimesNano(path, ts); err != nil {
<ide> return err
<ide> }
<ide> }
<ide><path>archive/stat_darwin.go
<ide> func getLastAccess(stat *syscall.Stat_t) syscall.Timespec {
<ide> func getLastModification(stat *syscall.Stat_t) syscall.Timespec {
<ide> return stat.Mtimespec
<ide> }
<add>
<add>func LUtimesNano(path string, ts []syscall.Timespec) error {
<add> return nil
<add>}
<ide><path>archive/stat_linux.go
<ide> package archive
<ide>
<del>import "syscall"
<add>import (
<add> "syscall"
<add> "unsafe"
<add>)
<ide>
<ide> func getLastAccess(stat *syscall.Stat_t) syscall.Timespec {
<ide> return stat.Atim
<ide> func getLastAccess(stat *syscall.Stat_t) syscall.Timespec {
<ide> func getLastModification(stat *syscall.Stat_t) syscall.Timespec {
<ide> return stat.Mtim
<ide> }
<add>
<add>func LUtimesNano(path string, ts []syscall.Timespec) error {
<add> // These are not currently availible in syscall
<add> AT_FDCWD := -100
<add> AT_SYMLINK_NOFOLLOW := 0x100
<add>
<add> var _path *byte
<add> _path, err := syscall.BytePtrFromString(path)
<add> if err != nil {
<add> return err
<add> }
<add>
<add> if _, _, err := syscall.Syscall6(syscall.SYS_UTIMENSAT, uintptr(AT_FDCWD), uintptr(unsafe.Pointer(_path)), uintptr(unsafe.Pointer(&ts[0])), uintptr(AT_SYMLINK_NOFOLLOW), 0, 0); err != 0 && err != syscall.ENOSYS {
<add> return err
<add> }
<add>
<add> return nil
<add>} | 3 |
Mixed | Ruby | add support for que name to que adapter | d12a31b193616791b1fbaf244332baffb23067b6 | <ide><path>activejob/CHANGELOG.md
<add>* Add queue name support to Que adapter
<add>
<add> *Brad Nauta*, *Wojciech Wnętrzak*
<add>
<ide> * Don't run `after_enqueue` and `after_perform` callbacks if the callback chain is halted.
<ide>
<ide> class MyJob < ApplicationJob
<ide><path>activejob/lib/active_job/queue_adapters/que_adapter.rb
<ide> module QueueAdapters
<ide> # Rails.application.config.active_job.queue_adapter = :que
<ide> class QueAdapter
<ide> def enqueue(job) #:nodoc:
<del> que_job = JobWrapper.enqueue job.serialize, priority: job.priority
<add> que_job = JobWrapper.enqueue job.serialize, priority: job.priority, queue: job.queue_name
<ide> job.provider_job_id = que_job.attrs["job_id"]
<ide> que_job
<ide> end
<ide>
<ide> def enqueue_at(job, timestamp) #:nodoc:
<del> que_job = JobWrapper.enqueue job.serialize, priority: job.priority, run_at: Time.at(timestamp)
<add> que_job = JobWrapper.enqueue job.serialize, priority: job.priority, queue: job.queue_name, run_at: Time.at(timestamp)
<ide> job.provider_job_id = que_job.attrs["job_id"]
<ide> que_job
<ide> end
<ide><path>activejob/test/integration/queuing_test.rb
<ide> class QueuingTest < ActiveSupport::TestCase
<ide> end
<ide>
<ide> test "should not run jobs queued on a non-listening queue" do
<del> skip if adapter_is?(:inline, :async, :sucker_punch, :que)
<add> skip if adapter_is?(:inline, :async, :sucker_punch)
<ide> old_queue = TestJob.queue_name
<ide>
<ide> begin
<ide><path>activejob/test/support/integration/adapters/que.rb
<ide> def start_workers
<ide>
<ide> @thread = Thread.new do
<ide> loop do
<del> Que::Job.work
<add> Que::Job.work("integration_tests")
<ide> sleep 0.5
<ide> end
<ide> end
<ide><path>activejob/test/support/que/inline.rb
<ide> def self.enqueue(*args)
<ide> options = args.pop
<ide> options.delete(:run_at)
<ide> options.delete(:priority)
<add> options.delete(:queue)
<ide> args << options unless options.empty?
<ide> end
<ide> run(*args) | 5 |
Javascript | Javascript | fix sectionlist examples in documentation | 0e93f4fa293a81a673b0e8b4aca611cd777fce82 | <ide><path>Libraries/Lists/SectionList.js
<ide> type DefaultProps = typeof defaultProps;
<ide> * Simple Examples:
<ide> *
<ide> * <SectionList
<del> * renderItem={({item}) => <ListItem title={item.title} />}
<del> * renderSectionHeader={({section}) => <H1 title={section.title} />}
<add> * renderItem={({item}) => <ListItem title={item} />}
<add> * renderSectionHeader={({section}) => <Header title={section.title} />}
<ide> * sections={[ // homogenous rendering between sections
<ide> * {data: [...], title: ...},
<ide> * {data: [...], title: ...},
<ide> type DefaultProps = typeof defaultProps;
<ide> *
<ide> * <SectionList
<ide> * sections={[ // heterogeneous rendering between sections
<del> * {data: [...], title: ..., renderItem: ...},
<del> * {data: [...], title: ..., renderItem: ...},
<del> * {data: [...], title: ..., renderItem: ...},
<add> * {data: [...], renderItem: ...},
<add> * {data: [...], renderItem: ...},
<add> * {data: [...], renderItem: ...},
<ide> * ]}
<ide> * />
<ide> * | 1 |
PHP | PHP | apply fixes from styleci | 02591e21d6307d9ff34d406cf1857df13c15586c | <ide><path>tests/Database/DatabaseEloquentIntegrationTest.php
<ide> namespace Illuminate\Tests\Database;
<ide>
<ide> use Exception;
<del>use ReflectionObject;
<ide> use Illuminate\Support\Carbon;
<ide> use PHPUnit\Framework\TestCase;
<ide> use Illuminate\Database\Eloquent\Model; | 1 |
PHP | PHP | fix typo and use local variable | 7b33de43808f2f9f6c199c30e5ebffbb76362c22 | <ide><path>tests/Foundation/FoundationExceptionsHandlerTest.php
<ide> class FoundationExceptionsHandlerTest extends TestCase
<ide>
<ide> protected $handler;
<ide>
<del> protected $rquest;
<add> protected $request;
<ide>
<ide> public function setUp()
<ide> { | 1 |
Text | Text | add release notes for v1.4.12 | d16b60e0d3f372b1d522295914da7a89f37dbcbf | <ide><path>CHANGELOG.md
<add><a name="1.4.12"></a>
<add># 1.4.12 cultural-conservation (2016-06-15)
<add>
<add>_This release contains only documentation updates. Specifically, it restores the old (deprecated)
<add>version of the tutorial on the 1.4.x branch. If someone needs a version of the tutorial that is
<add>compatible with v1.4, they can find it at https://code.angularjs.org/1.4.12/docs/tutorial/._
<add>
<add>_As always, the latest and greatest version of the tutorial can be found on the master branch
<add>(at https://docs.angularjs.org/tutorial/). We strongly recommend using this version as it is kept
<add>up-to-date, showcases several new features introduced in v1.5 or later and follows modern best
<add>practices._
<add>
<add>
<ide> <a name="1.5.6"></a>
<ide> # 1.5.6 arrow-stringification (2016-05-27)
<ide> | 1 |
Go | Go | implement expose to builder | ae1e655fb1d95b5828a2b0cd67d19d090d04ff74 | <ide><path>builder.go
<ide> func (builder *Builder) Build(dockerfile io.Reader, stdout io.Writer) (*Image, e
<ide> // use the base as the new image
<ide> image = base
<ide>
<add> break
<add> case "expose":
<add> ports := strings.Split(arguments, " ")
<add>
<add> fmt.Fprintf(stdout, "EXPOSE %v\n", ports)
<add> if image == nil {
<add> return nil, fmt.Errorf("Please provide a source image with `from` prior to copy")
<add> }
<add>
<add> // Create the container and start it
<add> c, err := builder.Create(&Config{Image: image.Id, Cmd: []string{"", ""}})
<add> if err != nil {
<add> return nil, err
<add> }
<add> if err := c.Start(); err != nil {
<add> return nil, err
<add> }
<add> tmpContainers[c.Id] = struct{}{}
<add>
<add> // Commit the container
<add> base, err = builder.Commit(c, "", "", "", maintainer, &Config{PortSpecs: ports})
<add> if err != nil {
<add> return nil, err
<add> }
<add> tmpImages[base.Id] = struct{}{}
<add>
<add> fmt.Fprintf(stdout, "===> %s\n", base.ShortId())
<add>
<add> image = base
<ide> break
<ide> case "insert":
<ide> if image == nil { | 1 |
Java | Java | fix crash when borderxcolor is null on android | 9fba85569c24065a29a3f7667fca6071d986d20b | <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewProps.java
<ide> public static boolean isLayoutOnly(ReadableMap map, String prop) {
<ide> }
<ide> return true;
<ide> case BORDER_LEFT_COLOR:
<del> return map.getInt(BORDER_LEFT_COLOR) == Color.TRANSPARENT;
<add> return !map.isNull(BORDER_LEFT_COLOR) && map.getInt(BORDER_LEFT_COLOR) == Color.TRANSPARENT;
<ide> case BORDER_RIGHT_COLOR:
<del> return map.getInt(BORDER_RIGHT_COLOR) == Color.TRANSPARENT;
<add> return !map.isNull(BORDER_RIGHT_COLOR) && map.getInt(BORDER_RIGHT_COLOR) == Color.TRANSPARENT;
<ide> case BORDER_TOP_COLOR:
<del> return map.getInt(BORDER_TOP_COLOR) == Color.TRANSPARENT;
<add> return !map.isNull(BORDER_TOP_COLOR) && map.getInt(BORDER_TOP_COLOR) == Color.TRANSPARENT;
<ide> case BORDER_BOTTOM_COLOR:
<del> return map.getInt(BORDER_BOTTOM_COLOR) == Color.TRANSPARENT;
<add> return !map.isNull(BORDER_BOTTOM_COLOR) && map.getInt(BORDER_BOTTOM_COLOR) == Color.TRANSPARENT;
<ide> case BORDER_WIDTH:
<ide> return map.isNull(BORDER_WIDTH) || map.getDouble(BORDER_WIDTH) == 0d;
<ide> case BORDER_LEFT_WIDTH: | 1 |
PHP | PHP | apply fixes from styleci | 2fb344e80838297c358b6a5800601a9b0e1ece1b | <ide><path>src/Illuminate/Database/Connection.php
<ide> use Illuminate\Database\Schema\Builder as SchemaBuilder;
<ide> use Illuminate\Support\Arr;
<ide> use Illuminate\Support\Traits\Macroable;
<del>use LogicException;
<ide> use PDO;
<ide> use PDOStatement;
<ide> use RuntimeException; | 1 |
Python | Python | change ja inflection separator to semicolon | c4e3b7a5db7de8336e1e9edb424a8a6eb23940e9 | <ide><path>spacy/lang/ja/__init__.py
<ide> def _get_dtokens(self, sudachipy_tokens, need_sub_tokens: bool = True):
<ide> DetailedToken(
<ide> token.surface(), # orth
<ide> "-".join([xx for xx in token.part_of_speech()[:4] if xx != "*"]), # tag
<del> "|".join([xx for xx in token.part_of_speech()[4:] if xx != "*"]), # inf
<add> ";".join([xx for xx in token.part_of_speech()[4:] if xx != "*"]), # inf
<ide> token.dictionary_form(), # lemma
<ide> token.normalized_form(),
<ide> token.reading_form(), | 1 |
Python | Python | ensure scalars in finfo | 4e8b56df4b82feaa624a6c45859d0420ee7b2112 | <ide><path>numpy/lib/getlimits.py
<ide> def _init(self, dtype):
<ide> else:
<ide> raise ValueError,`dtype`
<ide>
<del> for word in ['tiny', 'precision', 'resolution','iexp',
<del> 'maxexp','minexp','epsneg','negep',
<add> for word in ['precision', 'iexp',
<add> 'maxexp','minexp','negep',
<ide> 'machep']:
<ide> setattr(self,word,getattr(machar, word))
<del> self.max = machar.huge
<add> for word in ['tiny','resolution','epsneg']:
<add> setattr(self,word,getattr(machar, word).squeeze())
<add> self.max = machar.huge.squeeze()
<ide> self.min = -self.max
<del> self.eps = machar.epsilon
<add> self.eps = machar.epsilon.squeeze()
<ide> self.nexp = machar.iexp
<ide> self.nmant = machar.it
<ide> self.machar = machar | 1 |
Text | Text | fix typo in repl doc | 21b37b23c1bf29b7b07b90186c46112e09afccc3 | <ide><path>doc/api/repl.md
<ide> The `repl.start()` method creates and starts a `repl.REPLServer` instance.
<ide> ## The Node.js REPL
<ide>
<ide> Node.js itself uses the `repl` module to provide its own interactive interface
<del>for executing JavaScript. This can used by executing the Node.js binary without
<del>passing any arguments (or by passing the `-i` argument):
<add>for executing JavaScript. This can be used by executing the Node.js binary
<add>without passing any arguments (or by passing the `-i` argument):
<ide>
<ide> ```js
<ide> $ node | 1 |
Python | Python | remove unnecessary blank line | 080795fecb72a68c1ab788e1a6f277641855bad0 | <ide><path>samples/core/get_started/premade_estimator.py
<ide> def main(argv):
<ide> template = ('\nPrediction is "{}" ({:.1f}%), expected "{}"')
<ide>
<ide> for pred_dict, expec in zip(predictions, expected):
<del>
<ide> class_id = pred_dict['class_ids'][0]
<ide> probability = pred_dict['probabilities'][class_id]
<ide> | 1 |
Python | Python | fix error in imagedatagenerator documentation | e85d3dc15072f774736eb0e3c216eb0b7da1db9a | <ide><path>keras/preprocessing/image.py
<ide> class ImageDataGenerator(object):
<ide> rotation_range: Int. Degree range for random rotations.
<ide> width_shift_range: Float (fraction of total width). Range for random horizontal shifts.
<ide> height_shift_range: Float (fraction of total height). Range for random vertical shifts.
<del> shear_range: Float. Shear Intensity (Shear angle in counter-clockwise direction as radians)
<add> shear_range: Float. Shear Intensity (Shear angle in counter-clockwise direction in degrees)
<ide> zoom_range: Float or [lower, upper]. Range for random zoom. If a float, `[lower, upper] = [1-zoom_range, 1+zoom_range]`.
<ide> channel_shift_range: Float. Range for random channel shifts.
<ide> fill_mode: One of {"constant", "nearest", "reflect" or "wrap"}. Default is 'nearest'. | 1 |
Text | Text | fix abortsignal example for stream.readable | 2723d2db7e17f4e37d1e4044eb11663aaf3f742e | <ide><path>doc/api/stream.md
<ide> Calling `abort` on the `AbortController` corresponding to the passed
<ide> on the readable created.
<ide>
<ide> ```js
<del>const fs = require('fs');
<add>const { Readable } = require('stream');
<ide> const controller = new AbortController();
<ide> const read = new Readable({
<ide> read(size) { | 1 |
Ruby | Ruby | add style_exceptions configuration | 80a46edee487163cb853c6a4ab81e5b81dc54d77 | <ide><path>Library/Homebrew/rubocops/extend/formula.rb
<ide> def on_class(node)
<ide>
<ide> class_node, parent_class_node, @body = *node
<ide> @formula_name = Pathname.new(@file_path).basename(".rb").to_s
<add> @tap_style_exceptions = nil
<ide> audit_formula(node, class_node, parent_class_node, @body)
<ide> end
<ide>
<ide> def formula_tap
<ide> match_obj[1]
<ide> end
<ide>
<add> # Returns whether the current formula exists in the given style exception list
<add> def tap_style_exception?(list)
<add> if @tap_style_exceptions.blank? && formula_tap.present?
<add> @tap_style_exceptions = {}
<add>
<add> style_exceptions_dir = "#{File.dirname(File.dirname(@file_path))}/style_exceptions/*.json"
<add> Pathname.glob(style_exceptions_dir).each do |exception_file|
<add> list_name = exception_file.basename.to_s.chomp(".json").to_sym
<add> list_contents = begin
<add> JSON.parse exception_file.read
<add> rescue JSON::ParserError
<add> nil
<add> end
<add> next if list_contents.blank?
<add>
<add> @tap_style_exceptions[list_name] = list_contents
<add> end
<add> end
<add>
<add> return false if @tap_style_exceptions.blank?
<add> return false unless @tap_style_exceptions.key? list
<add>
<add> @tap_style_exceptions[list].include? @formula_name
<add> end
<add>
<ide> private
<ide>
<ide> def formula_class?(node)
<ide><path>Library/Homebrew/tap.rb
<ide> class Tap
<ide> HOMEBREW_TAP_FORMULA_RENAMES_FILE = "formula_renames.json"
<ide> HOMEBREW_TAP_MIGRATIONS_FILE = "tap_migrations.json"
<ide> HOMEBREW_TAP_AUDIT_EXCEPTIONS_DIR = "audit_exceptions"
<add> HOMEBREW_TAP_STYLE_EXCEPTIONS_DIR = "style_exceptions"
<ide> HOMEBREW_TAP_PYPI_FORMULA_MAPPINGS = "pypi_formula_mappings.json"
<ide>
<ide> HOMEBREW_TAP_JSON_FILES = %W[
<ide> #{HOMEBREW_TAP_FORMULA_RENAMES_FILE}
<ide> #{HOMEBREW_TAP_MIGRATIONS_FILE}
<ide> #{HOMEBREW_TAP_AUDIT_EXCEPTIONS_DIR}/*.json
<add> #{HOMEBREW_TAP_STYLE_EXCEPTIONS_DIR}/*.json
<ide> #{HOMEBREW_TAP_PYPI_FORMULA_MAPPINGS}
<ide> ].freeze
<ide>
<ide> def clear_cache
<ide> @formula_renames = nil
<ide> @tap_migrations = nil
<ide> @audit_exceptions = nil
<add> @style_exceptions = nil
<ide> @pypi_formula_mappings = nil
<ide> @config = nil
<ide> remove_instance_variable(:@private) if instance_variable_defined?(:@private)
<ide> def audit_exceptions
<ide> @audit_exceptions = read_formula_list_directory "#{HOMEBREW_TAP_AUDIT_EXCEPTIONS_DIR}/*"
<ide> end
<ide>
<add> # Hash with style exceptions
<add> sig { returns(Hash) }
<add> def style_exceptions
<add> @style_exceptions = read_formula_list_directory "#{HOMEBREW_TAP_STYLE_EXCEPTIONS_DIR}/*"
<add> end
<add>
<ide> # Hash with pypi formula mappings
<ide> sig { returns(Hash) }
<ide> def pypi_formula_mappings
<ide> def audit_exceptions
<ide> end
<ide> end
<ide>
<add> # @private
<add> def style_exceptions
<add> @style_exceptions ||= begin
<add> self.class.ensure_installed!
<add> super
<add> end
<add> end
<add>
<add> # @private
<ide> def pypi_formula_mappings
<ide> @pypi_formula_mappings ||= begin
<ide> self.class.ensure_installed!
<ide><path>Library/Homebrew/tap_auditor.rb
<ide> module Homebrew
<ide> class TapAuditor
<ide> extend T::Sig
<ide>
<del> attr_reader :name, :path, :tap_audit_exceptions, :tap_pypi_formula_mappings, :problems
<add> attr_reader :name, :path, :tap_audit_exceptions, :tap_style_exceptions, :tap_pypi_formula_mappings, :problems
<ide>
<ide> sig { params(tap: Tap, strict: T.nilable(T::Boolean)).void }
<ide> def initialize(tap, strict:)
<ide> @name = tap.name
<ide> @path = tap.path
<ide> @tap_audit_exceptions = tap.audit_exceptions
<add> @tap_style_exceptions = tap.style_exceptions
<ide> @tap_pypi_formula_mappings = tap.pypi_formula_mappings
<ide> @problems = []
<ide> end
<ide> def audit_json_files
<ide> sig { void }
<ide> def audit_tap_formula_lists
<ide> check_formula_list_directory "audit_exceptions", @tap_audit_exceptions
<add> check_formula_list_directory "style_exceptions", @tap_style_exceptions
<ide> check_formula_list "pypi_formula_mappings", @tap_pypi_formula_mappings
<ide> end
<ide> | 3 |
Javascript | Javascript | remove string literal from strictequal() | 31b3273eaa02ee12188a4c7a64a0d4adfbe22670 | <ide><path>test/parallel/test-stream2-writable.js
<ide> for (let i = 0; i < chunks.length; i++) {
<ide> });
<ide>
<ide> tw.on('finish', common.mustCall(function() {
<del> assert.deepStrictEqual(tw.buffer, chunks, 'got chunks in the right order');
<add> // got chunks in the right order
<add> assert.deepStrictEqual(tw.buffer, chunks);
<ide> }));
<ide>
<ide> chunks.forEach(function(chunk) {
<ide> for (let i = 0; i < chunks.length; i++) {
<ide> });
<ide>
<ide> tw.on('finish', common.mustCall(function() {
<del> assert.deepStrictEqual(tw.buffer, chunks, 'got chunks in the right order');
<add> // got chunks in the right order
<add> assert.deepStrictEqual(tw.buffer, chunks);
<ide> }));
<ide>
<ide> let i = 0;
<ide> for (let i = 0; i < chunks.length; i++) {
<ide> let drains = 0;
<ide>
<ide> tw.on('finish', common.mustCall(function() {
<del> assert.deepStrictEqual(tw.buffer, chunks, 'got chunks in the right order');
<add> // got chunks in the right order
<add> assert.deepStrictEqual(tw.buffer, chunks);
<ide> assert.strictEqual(drains, 17);
<ide> }));
<ide>
<ide> for (let i = 0; i < chunks.length; i++) {
<ide> undefined ];
<ide>
<ide> tw.on('finish', function() {
<del> assert.deepStrictEqual(tw.buffer, chunks, 'got the expected chunks');
<add> // got the expected chunks
<add> assert.deepStrictEqual(tw.buffer, chunks);
<ide> });
<ide>
<ide> chunks.forEach(function(chunk, i) {
<ide> for (let i = 0; i < chunks.length; i++) {
<ide> undefined ];
<ide>
<ide> tw.on('finish', function() {
<del> assert.deepStrictEqual(tw.buffer, chunks, 'got the expected chunks');
<add> // got the expected chunks
<add> assert.deepStrictEqual(tw.buffer, chunks);
<ide> });
<ide>
<ide> chunks.forEach(function(chunk, i) {
<ide> for (let i = 0; i < chunks.length; i++) {
<ide>
<ide> tw.on('finish', common.mustCall(function() {
<ide> process.nextTick(common.mustCall(function() {
<del> assert.deepStrictEqual(tw.buffer, chunks,
<del> 'got chunks in the right order');
<del> assert.deepStrictEqual(callbacks._called, chunks, 'called all callbacks');
<add> // got chunks in the right order
<add> assert.deepStrictEqual(tw.buffer, chunks);
<add> // called all callbacks
<add> assert.deepStrictEqual(callbacks._called, chunks);
<ide> }));
<ide> }));
<ide> | 1 |
Go | Go | allow process isolation | c907c2486c0850030f8ac1819ac8c87631472c68 | <ide><path>daemon/daemon_windows.go
<ide> func verifyContainerResources(resources *containertypes.Resources, isHyperv bool
<ide> // hostconfig and config structures.
<ide> func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *containertypes.HostConfig, config *containertypes.Config, update bool) ([]string, error) {
<ide> warnings := []string{}
<del>
<add> osv := system.GetOSVersion()
<ide> hyperv := daemon.runAsHyperVContainer(hostConfig)
<del> if !hyperv && system.IsWindowsClient() && !system.IsIoTCore() {
<del> // @engine maintainers. This block should not be removed. It partially enforces licensing
<del> // restrictions on Windows. Ping @jhowardmsft if there are concerns or PRs to change this.
<del> return warnings, fmt.Errorf("Windows client operating systems only support Hyper-V containers")
<add>
<add> // On RS5, we allow (but don't strictly support) process isolation on Client SKUs.
<add> // Prior to RS5, we don't allow process isolation on Client SKUs.
<add> // @engine maintainers. This block should not be removed. It partially enforces licensing
<add> // restrictions on Windows. Ping @jhowardmsft if there are concerns or PRs to change this.
<add> if !hyperv && system.IsWindowsClient() && osv.Build < 17763 {
<add> return warnings, fmt.Errorf("Windows client operating systems earlier than version 1809 can only run Hyper-V containers")
<ide> }
<ide>
<ide> w, err := verifyContainerResources(&hostConfig.Resources, hyperv)
<ide> func (daemon *Daemon) stats(c *container.Container) (*types.StatsJSON, error) {
<ide> // daemon to run in. This is only applicable on Windows
<ide> func (daemon *Daemon) setDefaultIsolation() error {
<ide> daemon.defaultIsolation = containertypes.Isolation("process")
<del> // On client SKUs, default to Hyper-V. Note that IoT reports as a client SKU
<del> // but it should not be treated as such.
<del> if system.IsWindowsClient() && !system.IsIoTCore() {
<add> osv := system.GetOSVersion()
<add>
<add> // On client SKUs, default to Hyper-V. @engine maintainers. This
<add> // should not be removed. Ping @jhowardmsft is there are PRs to
<add> // to change this.
<add> if system.IsWindowsClient() {
<ide> daemon.defaultIsolation = containertypes.Isolation("hyperv")
<ide> }
<ide> for _, option := range daemon.configStore.ExecOptions {
<ide> func (daemon *Daemon) setDefaultIsolation() error {
<ide> daemon.defaultIsolation = containertypes.Isolation("hyperv")
<ide> }
<ide> if containertypes.Isolation(val).IsProcess() {
<del> if system.IsWindowsClient() && !system.IsIoTCore() {
<add> if system.IsWindowsClient() && osv.Build < 17763 {
<add> // On RS5, we allow (but don't strictly support) process isolation on Client SKUs.
<ide> // @engine maintainers. This block should not be removed. It partially enforces licensing
<ide> // restrictions on Windows. Ping @jhowardmsft if there are concerns or PRs to change this.
<del> return fmt.Errorf("Windows client operating systems only support Hyper-V containers")
<add> return fmt.Errorf("Windows client operating systems earlier than version 1809 can only run Hyper-V containers")
<ide> }
<ide> daemon.defaultIsolation = containertypes.Isolation("process")
<ide> } | 1 |
Text | Text | add new test to create a set of new checkboxes | b67e3d4305ca821bc4850d376a01558e8eea777a | <ide><path>curriculum/challenges/english/01-responsive-web-design/basic-html-and-html5/create-a-set-of-checkboxes.english.md
<ide> tests:
<ide> - text: Make sure each of your <code>label</code> elements has a closing tag.
<ide> testString: assert(code.match(/<\/label>/g) && code.match(/<label/g) && code.match(/<\/label>/g).length === code.match(/<label/g).length, 'Make sure each of your <code>label</code> elements has a closing tag.');
<ide> - text: Give your checkboxes the <code>name</code> attribute of <code>personality</code>.
<del> testString: assert($('label > input[type="checkbox"]').filter("[name='personality']").length > 2, 'Give your checkboxes the <code>name</code> attribute of <code>personality</code>.');
<del>
<add> testString: assert($('label > input[type="checkbox"]').filter('[name="personality"]').length > 2, 'Give your checkboxes the <code>name</code> attribute of <code>personality</code>.');
<add> - text: Each of your checkboxes should be added within the <code>form</code> tag.
<add> testString: assert($('label').parent().get(0).tagName.match('FORM'), 'Each of your checkboxes should be added within the <code>form</code> tag.');
<add>
<ide> ```
<ide>
<ide> </section> | 1 |
PHP | PHP | add missing changes and a test | c30ae3528e5ea831beff8585bf5e244458fd2755 | <ide><path>src/Illuminate/Pagination/Paginator.php
<ide> class Paginator implements ArrayableInterface, ArrayAccess, Countable, IteratorA
<ide> * @param \Illuminate\Pagination\Factory $factory
<ide> * @param array $items
<ide> * @param int $total
<del> * @param int $perPage
<add> * @param mixed $perPage
<ide> * @return void
<ide> */
<del> public function __construct(Factory $factory, array $items, $total, $perPage)
<add> public function __construct(Factory $factory, array $items, $total, $perPage = null)
<ide> {
<del> $this->items = $items;
<ide> $this->factory = $factory;
<del> $this->total = (int) $total;
<del> $this->perPage = (int) $perPage;
<add>
<add> // Paginator received only 3 parameters which means that it's being used
<add> // in cursor mode. In this mode third argument $total is used as $perPage.
<add> if (is_null($perPage))
<add> {
<add> $this->items = array_slice($items, 0, $perPage);
<add> $this->perPage = (int) $total;
<add>
<add> $cursor = array_slice($items, $this->perPage, 1);
<add> $this->cursor = empty($cursor) ? null : $cursor[0];
<add> }
<add> else
<add> {
<add> $this->items = $items;
<add> $this->total = (int) $total;
<add> $this->perPage = (int) $perPage;
<add> }
<ide> }
<ide>
<ide> /**
<ide><path>tests/Pagination/PaginationPaginatorTest.php
<ide> public function testPaginationContextIsSetupCorrectly()
<ide> }
<ide>
<ide>
<add> public function testPaginationContextIsSetupCorrectlyInCursorMode()
<add> {
<add> $p = new Paginator($factory = m::mock('Illuminate\Pagination\Factory'), array('foo', 'bar', 'baz'), 2);
<add> $factory->shouldReceive('getCurrentPage')->once()->andReturn(1);
<add> $p->setupPaginationContext();
<add>
<add> $this->assertEquals(2, $p->getLastPage());
<add> $this->assertEquals(1, $p->getCurrentPage());
<add> $this->assertEquals('baz', $p->getCursor());
<add> }
<add>
<add>
<ide> public function testPaginationContextSetsUpRangeCorrectly()
<ide> {
<ide> $p = new Paginator($factory = m::mock('Illuminate\Pagination\Factory'), array('foo', 'bar', 'baz'), 3, 2); | 2 |
Text | Text | add missing changes to generatekeypair(sync) | 6155499252199d12f1577c6e9321008e6cd9e89d | <ide><path>doc/api/crypto.md
<ide> changes:
<ide> - v12.17.0
<ide> pr-url: https://github.com/nodejs/node/pull/31178
<ide> description: Add support for Diffie-Hellman.
<add> - version: v12.0.0
<add> pr-url: https://github.com/nodejs/node/pull/26960
<add> description: Add support for RSA-PSS key pairs.
<ide> - version: v12.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/26774
<ide> description: Add ability to generate X25519 and X448 key pairs.
<ide> changes:
<ide> produce key objects if no encoding was specified.
<ide> -->
<ide>
<del>* `type`: {string} Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`,
<del> `'x25519'`, `'x448'`, or `'dh'`.
<add>* `type`: {string} Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`,
<add> `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`.
<ide> * `options`: {Object}
<ide> * `modulusLength`: {number} Key size in bits (RSA, DSA).
<ide> * `publicExponent`: {number} Public exponent (RSA). **Default:** `0x10001`.
<ide> changes:
<ide> * `publicKey`: {string | Buffer | KeyObject}
<ide> * `privateKey`: {string | Buffer | KeyObject}
<ide>
<del>Generates a new asymmetric key pair of the given `type`. RSA, DSA, EC, Ed25519,
<del>Ed448, X25519, X448, and DH are currently supported.
<add>Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC,
<add>Ed25519, Ed448, X25519, X448, and DH are currently supported.
<ide>
<ide> If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function
<ide> behaves as if [`keyObject.export()`][] had been called on its result. Otherwise,
<ide> changes:
<ide> - v12.17.0
<ide> pr-url: https://github.com/nodejs/node/pull/31178
<ide> description: Add support for Diffie-Hellman.
<add> - version: v12.0.0
<add> pr-url: https://github.com/nodejs/node/pull/26960
<add> description: Add support for RSA-PSS key pairs.
<add> - version: v12.0.0
<add> pr-url: https://github.com/nodejs/node/pull/26774
<add> description: Add ability to generate X25519 and X448 key pairs.
<ide> - version: v12.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/26554
<ide> description: Add ability to generate Ed25519 and Ed448 key pairs.
<ide> changes:
<ide> produce key objects if no encoding was specified.
<ide> -->
<ide>
<del>* `type`: {string} Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`,
<del> `'x25519'`, `'x448'`, or `'dh'`.
<add>* `type`: {string} Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`,
<add> `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`.
<ide> * `options`: {Object}
<ide> * `modulusLength`: {number} Key size in bits (RSA, DSA).
<ide> * `publicExponent`: {number} Public exponent (RSA). **Default:** `0x10001`.
<ide> changes:
<ide> * `publicKey`: {string | Buffer | KeyObject}
<ide> * `privateKey`: {string | Buffer | KeyObject}
<ide>
<del>Generates a new asymmetric key pair of the given `type`. RSA, DSA, EC, Ed25519,
<del>Ed448, X25519, X448, and DH are currently supported.
<add>Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC,
<add>Ed25519, Ed448, X25519, X448, and DH are currently supported.
<ide>
<ide> If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function
<ide> behaves as if [`keyObject.export()`][] had been called on its result. Otherwise, | 1 |
Text | Text | fix typo in fs.watch() description | 94fca845dff4bafba7f428bc7e876c1aa83fdd8d | <ide><path>doc/api/fs.md
<ide> changes:
<ide> * `persistent` {boolean} Indicates whether the process should continue to run
<ide> as long as files are being watched. default = `true`
<ide> * `recursive` {boolean} Indicates whether all subdirectories should be
<del> watched, or only the current directory. The applies when a directory is
<add> watched, or only the current directory. This applies when a directory is
<ide> specified, and only on supported platforms (See [Caveats][]). default =
<ide> `false`
<ide> * `encoding` {string} Specifies the character encoding to be used for the | 1 |
Text | Text | fix typo in entity_linker docs | 047d912904d8f239ba444ecf772a601678a0c6f1 | <ide><path>website/docs/api/entitylinker.md
<ide> applied to the `Doc` in order. Both [`__call__`](/api/entitylinker#call) and
<ide> | `batch_size` | The number of documents to buffer. Defaults to `128`. ~~int~~ |
<ide> | **YIELDS** | The processed documents in order. ~~Doc~~ |
<ide>
<del>## EntityLinker.set_kb {#initialize tag="method" new="3"}
<add>## EntityLinker.set_kb {#set_kb tag="method" new="3"}
<ide>
<ide> The `kb_loader` should be a function that takes a `Vocab` instance and creates
<ide> the `KnowledgeBase`, ensuring that the strings of the knowledge base are synced | 1 |
Javascript | Javascript | write files even on error | 400b75658beb6083bd8cfdb30adc75de35b4fc43 | <ide><path>server/build/webpack.js
<ide> export default async function createCompiler (dir, { hotReload = false } = {}) {
<ide> compress: { warnings: false },
<ide> sourceMap: false
<ide> }),
<del> new WriteFilePlugin({ log: false })
<add> new WriteFilePlugin({
<add> exitOnErrors: false,
<add> log: false
<add> })
<ide> ]
<ide>
<ide> const babelRuntimePath = require.resolve('babel-runtime/package') | 1 |
Text | Text | add tip format for comparison | 4d9cde43be2335ab78615ab7715e323f8c04a933 | <ide><path>docs/cookbook/cb-02-inline-styles tip.md
<add>---
<add>id: inline-styles-tip
<add>title: Inline Styles
<add>layout: docs
<add>permalink: inline-styles.html
<add>script: "cookbook/inline-styles.js"
<add>---
<add>
<add>In React, inline styles are nto specified as a string, but as an object whose key is the camelCased version of the style name, and whose value is the style's value in string:
<add>
<add>```html
<add>/** @jsx React.DOM */
<add>
<add>var divStyle = {
<add> color: 'white',
<add> backgroundColor: 'lightblue',
<add> WebkitTransition: 'all' // note the capital 'W' here
<add>};
<add>
<add>React.renderComponent(<div style={divStyle}>Hello World!</div>, mountNode);
<add>```
<add>
<add>Style keys are camelCased in order to be consistent with accessing the properties using node.style.___ in DOM. This also explains why WebkitTransition has an uppercase 'W'.
<ide><path>docs/cookbook/cb-02-inline-styles.md
<ide> permalink: inline-styles.html
<ide> script: "cookbook/inline-styles.js"
<ide> ---
<ide>
<del>## Q&A format
<del>
<ide> ### Problem
<ide> You want to put inline style to an element.
<ide>
<ide> React.renderComponent(<div style={divStyle}>Hello World!</div>, mountNode);
<ide>
<ide> ### Discussion
<ide> Style keys are camelCased in order to be consistent with accessing the properties using `node.style.___` in DOM. This also explains why `WebkitTransition` has an uppercase 'W'.
<del>
<del>## Tips format
<del>
<del>In React, inline styles are nto specified as a string, but as an object whose key is the camelCased version of the style name, and whose value is the style's value in string:
<del>
<del>```html
<del>/** @jsx React.DOM */
<del>
<del>var divStyle = {
<del> color: 'white',
<del> backgroundColor: 'lightblue',
<del> WebkitTransition: 'all' // note the capital 'W' here
<del>};
<del>
<del>React.renderComponent(<div style={divStyle}>Hello World!</div>, mountNode);
<del>```
<del>
<del>Style keys are camelCased in order to be consistent with accessing the properties using node.style.___ in DOM. This also explains why WebkitTransition has an uppercase 'W'. | 2 |
Text | Text | fix stable release date of 0.58.0 | 045688bc28ee08a722e2a1521d51f1f3293e46a2 | <ide><path>Releases.md
<ide> React Native follows a monthly release train. Every month, a new branch created
<ide> | ... | ... | ... |
<ide> | 0.56.0 | 1st of June | 1st of July |
<ide> | 0.57.0 | 1st of July | 1st of August |
<del>| 0.58.0 | 1st of August | 1st of October |
<add>| 0.58.0 | 1st of August | 1st of September |
<ide> | ... | ... | ... |
<ide>
<ide> ------------------- | 1 |
Ruby | Ruby | require yaml for xml mini isolation test | 57ab74cdb1304b6baf79d37886d08551e065b5d6 | <ide><path>activesupport/test/xml_mini_test.rb
<ide> require 'active_support/builder'
<ide> require 'active_support/core_ext/hash'
<ide> require 'active_support/core_ext/big_decimal'
<add>require 'yaml'
<ide>
<ide> module XmlMiniTest
<ide> class RenameKeyTest < ActiveSupport::TestCase | 1 |
Go | Go | trim all leading whitespace in a line | f1988f046f680c268e39d7b3f11374fe93c22365 | <ide><path>opts/envfile.go
<ide> func ParseEnvFile(filename string) ([]string, error) {
<ide> lines := []string{}
<ide> scanner := bufio.NewScanner(fh)
<ide> for scanner.Scan() {
<del> line := scanner.Text()
<add> // trim the line from all leading whitespace first
<add> line := strings.TrimLeft(scanner.Text(), whiteSpaces)
<ide> // line is not empty, and not starting with '#'
<ide> if len(line) > 0 && !strings.HasPrefix(line, "#") {
<ide> data := strings.SplitN(line, "=", 2)
<del>
<del> // trim the front of a variable, but nothing else
<del> variable := strings.TrimLeft(data[0], whiteSpaces)
<add> variable := data[0]
<ide>
<ide> if !EnvironmentVariableRegexp.MatchString(variable) {
<ide> return []string{}, ErrBadEnvVariable{fmt.Sprintf("variable '%s' is not a valid environment variable", variable)}
<ide><path>opts/envfile_test.go
<ide> func TestParseEnvFileGoodFile(t *testing.T) {
<ide>
<ide> _foobar=foobaz
<ide> `
<del>
<add> // Adding a newline + a line with pure whitespace.
<add> // This is being done like this instead of the block above
<add> // because it's common for editors to trim trailing whitespace
<add> // from lines, which becomes annoying since that's the
<add> // exact thing we need to test.
<add> content += "\n \t "
<ide> tmpFile := tmpFileWithContent(content, t)
<ide> defer os.Remove(tmpFile)
<ide> | 2 |
PHP | PHP | add an interface for eventdispatcher | 60f955ab8262d56ad921aac0e210caf72ac15c67 | <ide><path>src/Controller/Controller.php
<ide> use Cake\Controller\Exception\MissingActionException;
<ide> use Cake\Datasource\ModelAwareTrait;
<ide> use Cake\Event\Event;
<add>use Cake\Event\EventDispatcherInterface;
<ide> use Cake\Event\EventListenerInterface;
<ide> use Cake\Event\EventManagerTrait;
<ide> use Cake\Log\LogTrait;
<ide> * @property \Cake\Controller\Component\SecurityComponent $Security
<ide> * @link http://book.cakephp.org/3.0/en/controllers.html
<ide> */
<del>class Controller implements EventListenerInterface
<add>class Controller implements EventListenerInterface, EventDispatcherInterface
<ide> {
<ide>
<ide> use EventManagerTrait;
<ide><path>src/Datasource/RulesAwareTrait.php
<ide> use ArrayObject;
<ide> use Cake\Datasource\EntityInterface;
<ide> use Cake\Datasource\RulesChecker;
<add>use Cake\Event\EventDispatcherInterface;
<ide>
<ide> /**
<ide> * A trait that allows a class to build and apply application.
<ide> public function checkRules(EntityInterface $entity, $operation = RulesChecker::C
<ide> $rules = $this->rulesChecker();
<ide> $options = $options ?: new ArrayObject;
<ide> $options = is_array($options) ? new ArrayObject($options) : $options;
<del> $hasEvents = method_exists($this, 'dispatchEvent');
<add> $hasEvents = ($this instanceof EventDispatcherInterface);
<ide>
<ide> if ($hasEvents) {
<ide> $event = $this->dispatchEvent(
<ide><path>src/Event/EventDispatcherInterface.php
<add><?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @since 3.0.7
<add> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Event;
<add>
<add>use Cake\Event\EventManager;
<add>
<add>/**
<add> * Objects implementing this interface can emit events.
<add> *
<add> * Objects with this interface can trigger events, and have
<add> * an event manager retrieved from them.
<add> *
<add> * The Cake\Event\EventManagerTrait lets you easily implement
<add> * this interface.
<add> */
<add>interface EventDispatcherInterface
<add>{
<add> /**
<add> * Wrapper for creating and dispatching events.
<add> *
<add> * Returns a dispatched event.
<add> *
<add> * @param string $name Name of the event.
<add> * @param array|null $data Any value you wish to be transported with this event to
<add> * it can be read by listeners.
<add> * @param object|null $subject The object that this event applies to
<add> * ($this by default).
<add> *
<add> * @return \Cake\Event\Event
<add> */
<add> public function dispatchEvent($name, $data = null, $subject = null);
<add>
<add> /**
<add> * Returns the Cake\Event\EventManager manager instance for this object.
<add> *
<add> * You can use this instance to register any new listeners or callbacks to the
<add> * object events, or create your own events and trigger them at will.
<add> *
<add> * @param \Cake\Event\EventManager|null $eventManager the eventManager to set
<add> * @return \Cake\Event\EventManager
<add> */
<add> public function eventManager(EventManager $eventManager = null);
<add>}
<ide><path>src/ORM/Table.php
<ide> use Cake\Datasource\Exception\InvalidPrimaryKeyException;
<ide> use Cake\Datasource\RepositoryInterface;
<ide> use Cake\Datasource\RulesAwareTrait;
<add>use Cake\Event\EventDispatcherInterface;
<ide> use Cake\Event\EventListenerInterface;
<ide> use Cake\Event\EventManager;
<ide> use Cake\Event\EventManagerTrait;
<ide> *
<ide> * @see \Cake\Event\EventManager for reference on the events system.
<ide> */
<del>class Table implements RepositoryInterface, EventListenerInterface
<add>class Table implements RepositoryInterface, EventListenerInterface, EventDispatcherInterface
<ide> {
<ide>
<ide> use EventManagerTrait;
<ide><path>src/Validation/ValidatorAwareTrait.php
<ide> */
<ide> namespace Cake\Validation;
<ide>
<add>use Cake\Event\EventDispatcherInterface;
<ide> use Cake\Validation\Validator;
<ide>
<ide> /**
<ide> public function validator($name = null, Validator $validator = null)
<ide> if ($validator === null) {
<ide> $validator = new Validator();
<ide> $validator = $this->{'validation' . ucfirst($name)}($validator);
<del> if (method_exists($this, 'dispatchEvent')) {
<add> if ($this instanceof EventDispatcherInterface) {
<ide> $this->dispatchEvent('Model.buildValidator', compact('validator', 'name'));
<ide> }
<ide> }
<ide><path>src/View/View.php
<ide> use Cake\Cache\Cache;
<ide> use Cake\Core\App;
<ide> use Cake\Core\Plugin;
<add>use Cake\Event\EventDispatcherInterface;
<ide> use Cake\Event\EventManager;
<ide> use Cake\Event\EventManagerTrait;
<ide> use Cake\Log\LogTrait;
<ide> * @property \Cake\View\Helper\TimeHelper $Time
<ide> * @property \Cake\View\ViewBlock $Blocks
<ide> */
<del>class View
<add>class View implements EventDispatcherInterface
<ide> {
<ide>
<ide> use CellTrait; | 6 |
Python | Python | add test for serialization issue raised in | f0f2739ae3348f22d948351cdb143b14e6557056 | <ide><path>spacy/tests/serialize/test_serialize_empty_model.py
<add>import spacy
<add>import spacy.lang.en
<add>from spacy.pipeline import TextCategorizer
<add>
<add>def test_bytes_serialize_issue_1105():
<add> nlp = spacy.lang.en.English()
<add> tokenizer = nlp.tokenizer
<add> textcat = TextCategorizer(tokenizer.vocab, labels=['ENTITY', 'ACTION', 'MODIFIER'])
<add> textcat_bytes = textcat.to_bytes() | 1 |
Go | Go | add support for mac address restoring | b669025949f1dba1ad3af9bab6711736863d6e24 | <ide><path>daemon/container.go
<ide> func (container *Container) RestoreNetwork() error {
<ide>
<ide> eng := container.daemon.eng
<ide>
<del> // Re-allocate the interface with the same IP address.
<add> // Re-allocate the interface with the same IP and MAC address.
<ide> job := eng.Job("allocate_interface", container.ID)
<ide> job.Setenv("RequestedIP", container.NetworkSettings.IPAddress)
<add> job.Setenv("RequestedMac", container.NetworkSettings.MacAddress)
<ide> if err := job.Run(); err != nil {
<ide> return err
<ide> }
<ide><path>integration-cli/docker_cli_run_test.go
<ide> func TestRunMutableNetworkFiles(t *testing.T) {
<ide>
<ide> func TestRunStableIPAndPort(t *testing.T) {
<ide> const nContainers = 2
<del> var ids, ips, ports [nContainers]string
<add> var ids, ips, macs, ports [nContainers]string
<ide>
<ide> // Setup: Create a couple of containers and collect their IPs and public ports.
<ide> for i := 0; i < nContainers; i++ {
<ide> func TestRunStableIPAndPort(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> ids[i] = strings.TrimSpace(out)
<add>
<ide> ips[i], err = inspectField(ids[i], "NetworkSettings.IPAddress")
<ide> errorOut(err, t, out)
<ide> if ips[i] == "" {
<ide> t.Fatal("IP allocation failed")
<ide> }
<ide>
<add> macs[i], err = inspectField(ids[i], "NetworkSettings.MacAddress")
<add> errorOut(err, t, out)
<add>
<ide> portCmd := exec.Command(dockerBinary, "port", ids[i], "1234")
<ide> ports[i], _, err = runCommandWithOutput(portCmd)
<ide> errorOut(err, t, out)
<ide> func TestRunStableIPAndPort(t *testing.T) {
<ide> }
<ide> }
<ide>
<del> // Start the containers back, and ensure they are getting the same IPs and ports.
<add> // Start the containers back, and ensure they are getting the same IPs, MACs and ports.
<ide> for i, id := range ids {
<ide> runCmd := exec.Command(dockerBinary, "start", id)
<ide> out, _, err := runCommandWithOutput(runCmd)
<ide> errorOut(err, t, out)
<ide>
<ide> ip, err := inspectField(id, "NetworkSettings.IPAddress")
<ide> errorOut(err, t, out)
<add>
<add> mac, err := inspectField(id, "NetworkSettings.MacAddress")
<add> errorOut(err, t, out)
<add>
<ide> portCmd := exec.Command(dockerBinary, "port", ids[i], "1234")
<ide> port, _, err := runCommandWithOutput(portCmd)
<ide> errorOut(err, t, out)
<ide>
<ide> if ips[i] != ip {
<ide> t.Fatalf("Container started with a different IP: %s != %s", ip, ips[i])
<ide> }
<add> if macs[i] != mac {
<add> t.Fatalf("Container started with a different MAC: %s != %s", mac, macs[i])
<add> }
<ide> if ports[i] != port {
<ide> t.Fatalf("Container started with a different port: %s != %s", port, ports[i])
<ide> } | 2 |
Ruby | Ruby | remove dead code | d54bce6a1af251a32f759e2017e0f4d1bc8d8c53 | <ide><path>Library/Homebrew/compilers.rb
<ide> def compiler
<ide>
<ide> def priority_for(cc)
<ide> case cc
<del> when :clang then @versions.clang_build_version >= 318 ? 3 : 0.5
<del> when :gcc then 2.5
<del> when :llvm then 2
<add> when :clang then @versions.clang_build_version >= 318 ? 3 : 0.5
<add> when :gcc then 2.5
<add> when :llvm then 2
<ide> when :gcc_4_0 then 0.25
<del> # non-Apple gcc compilers
<del> else 1.5
<ide> end
<ide> end
<ide> end | 1 |
PHP | PHP | add return typehint and fix cs error | 6193a53cc2e34ed4a10f312519e6e6269674409f | <ide><path>src/ORM/Table.php
<ide> public function deleteManyOrFail(iterable $entities, $options = []): iterable
<ide> /**
<ide> * @param \Cake\Datasource\EntityInterface[]|\Cake\Datasource\ResultSetInterface $entities Entities to delete.
<ide> * @param array|\ArrayAccess $options Options used.
<del> * @return EntityInterface|null
<add> * @return \Cake\Datasource\EntityInterface|null
<ide> */
<del> protected function _deleteMany(iterable $entities, $options = [])
<add> protected function _deleteMany(iterable $entities, $options = []): ?EntityInterface
<ide> {
<ide> $options = new ArrayObject((array)$options + [
<ide> 'atomic' => true, | 1 |
Javascript | Javascript | use template literals as appropriate | 0aae941dbe0acf7c2bc920f563631bc20e5c075f | <ide><path>test/async-hooks/test-graph.signal.js
<ide> hooks.enable();
<ide> process.on('SIGUSR2', common.mustCall(onsigusr2, 2));
<ide>
<ide> let count = 0;
<del>exec('kill -USR2 ' + process.pid);
<add>exec(`kill -USR2 ${process.pid}`);
<ide>
<ide> function onsigusr2() {
<ide> count++;
<ide>
<ide> if (count === 1) {
<ide> // trigger same signal handler again
<del> exec('kill -USR2 ' + process.pid);
<add> exec(`kill -USR2 ${process.pid}`);
<ide> } else {
<ide> // install another signal handler
<ide> process.removeAllListeners('SIGUSR2');
<ide> process.on('SIGUSR2', common.mustCall(onsigusr2Again));
<ide>
<del> exec('kill -USR2 ' + process.pid);
<add> exec(`kill -USR2 ${process.pid}`);
<ide> }
<ide> }
<ide> | 1 |
Java | Java | fix map.put contract for headersadapter impl | 85262a7932eaafc466dbb805366811da5e91b23b | <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/NettyHeadersAdapter.java
<ide> public List<String> get(Object key) {
<ide> @Override
<ide> public List<String> put(String key, @Nullable List<String> value) {
<ide> List<String> previousValues = this.headers.getAll(key);
<del> this.headers.add(key, value);
<add> this.headers.set(key, value);
<ide> return previousValues;
<ide> }
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/TomcatHeadersAdapter.java
<ide> public List<String> get(Object key) {
<ide> @Nullable
<ide> public List<String> put(String key, List<String> value) {
<ide> List<String> previousValues = get(key);
<add> this.headers.removeHeader(key);
<ide> value.forEach(v -> this.headers.addValue(key).setString(v));
<ide> return previousValues;
<ide> }
<ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/HeadersAdaptersTests.java
<ide>
<ide> package org.springframework.http.server.reactive;
<ide>
<add>import java.util.Arrays;
<ide> import java.util.Locale;
<ide>
<ide> import io.netty.handler.codec.http.DefaultHttpHeaders;
<ide> import io.undertow.util.HeaderMap;
<ide> import org.apache.tomcat.util.http.MimeHeaders;
<ide> import org.eclipse.jetty.http.HttpFields;
<add>import org.junit.After;
<ide> import org.junit.Test;
<ide> import org.junit.runner.RunWith;
<ide> import org.junit.runners.Parameterized;
<ide> public static Object[][] arguments() {
<ide> };
<ide> }
<ide>
<add> @After
<add> public void tearDown() {
<add> this.headers.clear();
<add> }
<add>
<ide> @Test
<ide> public void getWithUnknownHeaderShouldReturnNull() {
<ide> assertNull(this.headers.get("Unknown"));
<ide> public void addShouldKeepOrdering() {
<ide> assertEquals("first", this.headers.get("TestHeader").get(0));
<ide> }
<ide>
<del>}
<add> @Test
<add> public void putShouldOverrideExisting() {
<add> this.headers.add("TestHeader", "first");
<add> this.headers.put("TestHeader", Arrays.asList("override"));
<add> assertEquals("override", this.headers.getFirst("TestHeader"));
<add> assertEquals(1, this.headers.get("TestHeader").size());
<add> }
<add>
<add>}
<ide>\ No newline at end of file | 3 |
Javascript | Javascript | allow preload modules with -i | ff64a4c3951a945e372160ec7405264d72ff92dd | <ide><path>src/node.js
<ide> }
<ide>
<ide> } else {
<add> startup.preloadModules();
<ide> // If -i or --interactive were passed, or stdin is a TTY.
<ide> if (process._forceRepl || NativeModule.require('tty').isatty(0)) {
<ide> // REPL
<ide><path>test/fixtures/define-global.js
<add>global.a = 'test';
<ide><path>test/parallel/test-preload.js
<ide> 'use strict';
<del>require('../common');
<add>const common = require('../common');
<ide> const assert = require('assert');
<ide> const path = require('path');
<ide> const child_process = require('child_process');
<ide> var fixture = function(name) {
<ide> var fixtureA = fixture('printA.js');
<ide> var fixtureB = fixture('printB.js');
<ide> var fixtureC = fixture('printC.js');
<add>const fixtureD = fixture('define-global.js');
<ide> var fixtureThrows = fixture('throws_error4.js');
<ide>
<ide> // test preloading a single module works
<ide> child_process.exec(nodeBinary + ' '
<ide> assert.equal(stdout, 'A\nB\nhello\n');
<ide> });
<ide>
<add>// test that preload works with -i
<add>const interactive = child_process.exec(nodeBinary + ' '
<add> + preloadOption([fixtureD])
<add> + '-i',
<add> common.mustCall(function(err, stdout, stderr) {
<add> assert.ifError(err);
<add> assert.strictEqual(stdout, `> 'test'\n> `);
<add> }));
<add>
<add>interactive.stdin.write('a\n');
<add>interactive.stdin.write('process.exit()\n');
<add>
<ide> child_process.exec(nodeBinary + ' '
<ide> + '--require ' + fixture('cluster-preload.js') + ' '
<ide> + fixture('cluster-preload-test.js'), | 3 |
Text | Text | add preload notice | e10096cd0c693f19ff27225ae0a5039a6d1870dc | <ide><path>packages/next/README.md
<ide> Since Next.js server-renders your pages, this allows all the future interaction
<ide>
<ide> > With prefetching Next.js only downloads JS code. When the page is getting rendered, you may need to wait for the data.
<ide>
<add>> `<link rel="preload">` is used for prefetching. Sometimes browsers will show a warning if the resource is not used within 3 seconds, these warnings can be ignored as per https://github.com/zeit/next.js/issues/6517#issuecomment-469063892
<add>
<ide> #### With `<Link>`
<ide>
<ide> You can add `prefetch` prop to any `<Link>` and Next.js will prefetch those pages in the background. | 1 |
Text | Text | add cache_if and cache_unless on caching doc | 861ec91e8c681302cec76d9bce278da829e85df1 | <ide><path>guides/source/caching_with_rails.md
<ide> This method generates a cache key that depends on all products and can be used i
<ide> All available products:
<ide> <% end %>
<ide> ```
<add>
<add>If you want to cache a fragment under certain condition you can use `cache_if` or `cache_unless`
<add>
<add>```erb
<add><% cache_if (condition, cache_key_for_products) do %>
<add> All available products:
<add><% end %>
<add>```
<add>
<ide> You can also use an Active Record model as the cache key:
<ide>
<ide> ```erb | 1 |
Go | Go | fix cache miss issue within docker build | 560a74af1562de007ba487e102fd00a2f658e6a0 | <ide><path>buildfile.go
<ide> func (b *buildFile) CmdRun(args string) error {
<ide>
<ide> utils.Debugf("Commang to be executed: %v", b.config.Cmd)
<ide>
<del> if cache, err := b.srv.ImageGetCached(b.image, config); err != nil {
<add> if cache, err := b.srv.ImageGetCached(b.image, b.config); err != nil {
<ide> return err
<ide> } else if cache != nil {
<del> utils.Debugf("Use cached version")
<add> utils.Debugf("[BUILDER] Use cached version")
<ide> b.image = cache.Id
<ide> return nil
<add> } else {
<add> utils.Debugf("[BUILDER] Cache miss")
<ide> }
<ide>
<ide> cid, err := b.run()
<ide> func (b *buildFile) CmdInsert(args string) error {
<ide> if err := container.Inject(file.Body, destPath); err != nil {
<ide> return err
<ide> }
<del> return b.commit(cid, cmd, fmt.Sprintf("INSERT %s in %s", sourceUrl, destPath))
<add> if err := b.commit(cid, cmd, fmt.Sprintf("INSERT %s in %s", sourceUrl, destPath)); err != nil {
<add> return err
<add> }
<add> b.config.Cmd = cmd
<add> return nil
<ide> }
<ide>
<ide> func (b *buildFile) CmdAdd(args string) error {
<ide> func (b *buildFile) commit(id string, autoCmd []string, comment string) error {
<ide> b.config.Image = b.image
<ide> if id == "" {
<ide> b.config.Cmd = []string{"/bin/sh", "-c", "#(nop) " + comment}
<add>
<add> if cache, err := b.srv.ImageGetCached(b.image, b.config); err != nil {
<add> return err
<add> } else if cache != nil {
<add> utils.Debugf("[BUILDER] Use cached version")
<add> b.image = cache.Id
<add> return nil
<add> } else {
<add> utils.Debugf("[BUILDER] Cache miss")
<add> }
<add>
<ide> if cid, err := b.run(); err != nil {
<ide> return err
<ide> } else {
<ide><path>server.go
<ide> func (srv *Server) ImageDelete(name string) error {
<ide> }
<ide>
<ide> func (srv *Server) ImageGetCached(imgId string, config *Config) (*Image, error) {
<del>
<del> // Retrieve all images
<del> images, err := srv.runtime.graph.All()
<add> byParent, err := srv.runtime.graph.ByParent()
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide>
<del> // Store the tree in a map of map (map[parentId][childId])
<del> imageMap := make(map[string]map[string]struct{})
<del> for _, img := range images {
<del> if _, exists := imageMap[img.Parent]; !exists {
<del> imageMap[img.Parent] = make(map[string]struct{})
<del> }
<del> imageMap[img.Parent][img.Id] = struct{}{}
<del> }
<del>
<ide> // Loop on the children of the given image and check the config
<del> for elem := range imageMap[imgId] {
<del> img, err := srv.runtime.graph.Get(elem)
<del> if err != nil {
<del> return nil, err
<del> }
<add> for _, img := range byParent[imgId] {
<ide> if CompareConfig(&img.ContainerConfig, config) {
<ide> return img, nil
<ide> } | 2 |
Ruby | Ruby | add dup leftover from 26710ab | c3bf3414ec92e02e7f3dc70394c4a7c5512bdbd1 | <ide><path>actionview/lib/action_view/helpers/tag_helper.rb
<ide> def content_tag_string(name, content, options, escape = true)
<ide>
<ide> def tag_options(options, escape = true)
<ide> return if options.blank?
<del> output = ""
<add> output = "".dup
<ide> sep = " "
<ide> options.each_pair do |key, value|
<ide> if TAG_PREFIXES.include?(key) && value.is_a?(Hash) | 1 |
Javascript | Javascript | fix an offset bug in binaryloader | 754b94720b29e7589ae5432dc8f6512fd1580c4f | <ide><path>examples/js/loaders/BinaryLoader.js
<ide> THREE.BinaryLoader.prototype = {
<ide>
<ide> for ( var i = 0; i < length; i ++ ) {
<ide>
<del> text += String.fromCharCode( charArray[ offset + i ] );
<add> text += String.fromCharCode( charArray[ i ] );
<ide>
<ide> }
<ide> | 1 |
Ruby | Ruby | add method to prepend and create a path | 996c7bd7d11035cd19a824e448b2bc940823bb3a | <ide><path>Library/Homebrew/extend/ENV/shared.rb
<ide> def prepend_path key, path
<ide> prepend key, path, File::PATH_SEPARATOR if File.directory? path
<ide> end
<ide>
<add> def prepend_create_path key, path
<add> path = Pathname.new(path) unless path.is_a? Pathname
<add> path.mkpath
<add> prepend_path key, path
<add> end
<add>
<ide> def remove keys, value
<ide> Array(keys).each do |key|
<ide> next unless self[key] | 1 |
Javascript | Javascript | fix the type of pdfdocumentloadingtask.destroy | 4ac62d8787e07516710449eaa4588bfbdfb52984 | <ide><path>src/display/api.js
<ide> function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
<ide> * {@link UNSUPPORTED_FEATURES} argument.
<ide> * @property {Promise<PDFDocumentProxy>} promise - Promise for document loading
<ide> * task completion.
<del> * @property {Promise<void>} destroy - Abort all network requests and destroy
<add> * @property {function} destroy - Abort all network requests and destroy
<ide> * the worker. Returns a promise that is resolved when destruction is
<ide> * completed.
<ide> */ | 1 |
Go | Go | fix false positive | 3676bd8569f4df28a4f850cd4814e3558d8c03f6 | <ide><path>integration-cli/docker_cli_build_test.go
<ide> func (s *DockerSuite) TestBuildNotVerboseFailureRemote(c *check.C) {
<ide> result.Assert(c, icmd.Expected{
<ide> ExitCode: 1,
<ide> })
<del> if strings.TrimSpace(quietResult.Stderr()) != strings.TrimSpace(result.Combined()) {
<add>
<add> // An error message should contain name server IP and port, like this:
<add> // "dial tcp: lookup something.invalid on 172.29.128.11:53: no such host"
<add> // The IP:port need to be removed in order to not trigger a test failur
<add> // when more than one nameserver is configured.
<add> // While at it, also strip excessive newlines.
<add> normalize := func(msg string) string {
<add> return strings.TrimSpace(regexp.MustCompile("[1-9][0-9.]+:[0-9]+").ReplaceAllLiteralString(msg, "<ip:port>"))
<add> }
<add>
<add> if normalize(quietResult.Stderr()) != normalize(result.Combined()) {
<ide> c.Fatal(fmt.Errorf("Test[%s] expected that quiet stderr and verbose stdout are equal; quiet [%v], verbose [%v]", name, quietResult.Stderr(), result.Combined()))
<ide> }
<ide> } | 1 |
Go | Go | add usage to snapshotter adapter | f0a9e54d200e317eb12ccbe9fee1d0c3a49366f5 | <ide><path>builder/builder-next/adapters/snapshot/snapshot.go
<ide> package snapshot
<ide> import (
<ide> "context"
<ide> "path/filepath"
<add> "strconv"
<ide> "strings"
<ide> "sync"
<ide>
<ide> func (s *snapshotter) Update(ctx context.Context, info snapshots.Info, fieldpath
<ide> }
<ide>
<ide> func (s *snapshotter) Usage(ctx context.Context, key string) (snapshots.Usage, error) {
<del> return snapshots.Usage{}, nil
<add> usage := snapshots.Usage{}
<add> if l, err := s.getLayer(key); err != nil {
<add> return usage, err
<add> } else if l != nil {
<add> s, err := l.DiffSize()
<add> if err != nil {
<add> return usage, err
<add> }
<add> usage.Size = s
<add> return usage, nil
<add> }
<add>
<add> size := int64(-1)
<add> if err := s.db.View(func(tx *bolt.Tx) error {
<add> b := tx.Bucket([]byte(key))
<add> if b == nil {
<add> return nil
<add> }
<add> v := b.Get(keySize)
<add> if v != nil {
<add> s, err := strconv.Atoi(string(v))
<add> if err != nil {
<add> return err
<add> }
<add> size = int64(s)
<add> }
<add> return nil
<add> }); err != nil {
<add> return usage, err
<add> }
<add>
<add> if size != -1 {
<add> usage.Size = size
<add> return usage, nil
<add> }
<add>
<add> id, _ := s.getGraphDriverID(key)
<add>
<add> info, err := s.Stat(ctx, key)
<add> if err != nil {
<add> return usage, err
<add> }
<add> var parent string
<add> if info.Parent != "" {
<add> parent, _ = s.getGraphDriverID(info.Parent)
<add> }
<add>
<add> diffSize, err := s.opt.GraphDriver.DiffSize(id, parent)
<add> if err != nil {
<add> return usage, err
<add> }
<add>
<add> if err := s.db.Update(func(tx *bolt.Tx) error {
<add> b, err := tx.CreateBucketIfNotExists([]byte(key))
<add> if err != nil {
<add> return err
<add> }
<add> return b.Put(keySize, []byte(strconv.Itoa(int(diffSize))))
<add> }); err != nil {
<add> return usage, err
<add> }
<add> usage.Size = int64(diffSize)
<add> return usage, nil
<ide> }
<ide>
<ide> func (s *snapshotter) Close() error { | 1 |
Go | Go | add time since exit in docker ps | 15a267b57d2394dd5cb697f9a80b6df4fc939a76 | <ide><path>runtime/state.go
<ide> func (s *State) String() string {
<ide> }
<ide> return fmt.Sprintf("Up %s", utils.HumanDuration(time.Now().UTC().Sub(s.StartedAt)))
<ide> }
<del> return fmt.Sprintf("Exit %d", s.ExitCode)
<add> return fmt.Sprintf("Exited (%d) %s ago", s.ExitCode, utils.HumanDuration(time.Now().UTC().Sub(s.FinishedAt)))
<ide> }
<ide>
<ide> func (s *State) IsRunning() bool { | 1 |
Ruby | Ruby | align them assignments | 49cb4ed845e730f69fb2a26a594976039d3d2559 | <ide><path>activerecord/lib/active_record/attribute_assignment.rb
<ide> def attributes=(new_attributes)
<ide> def assign_attributes(new_attributes, options = {})
<ide> return if new_attributes.blank?
<ide>
<del> attributes = new_attributes.stringify_keys
<del> multi_parameter_attributes = []
<add> attributes = new_attributes.stringify_keys
<add> multi_parameter_attributes = []
<ide> nested_parameter_attributes = []
<del> previous_options = @mass_assignment_options
<del> @mass_assignment_options = options
<add> previous_options = @mass_assignment_options
<add> @mass_assignment_options = options
<ide>
<ide> unless options[:without_protection]
<ide> attributes = sanitize_for_mass_assignment(attributes, mass_assignment_role) | 1 |
Go | Go | keep state in core on container | 25a26977173632b5966838d910550a921ef5a853 | <ide><path>container.go
<ide> func (container *Container) Start() (err error) {
<ide> return err
<ide> }
<ide>
<add> container.State.SetRunning(container.process.Pid())
<add>
<ide> // Init the lock
<ide> container.waitLock = make(chan struct{})
<ide>
<ide> func (container *Container) monitor() {
<ide> container.stdin, container.stdinPipe = io.Pipe()
<ide> }
<ide>
<add> exitCode := container.process.GetExitCode()
<add> container.State.SetStopped(exitCode)
<add>
<ide> // Release the lock
<ide> close(container.waitLock)
<ide>
<ide><path>execdriver/driver.go
<ide> import (
<ide> "errors"
<ide> "io"
<ide> "os/exec"
<del> "sync"
<ide> "syscall"
<ide> "time"
<ide> )
<ide> type Network struct {
<ide> Mtu int
<ide> }
<ide>
<del>type State struct {
<del> sync.RWMutex
<del> running bool
<del> pid int
<del> exitCode int
<del> startedAt time.Time
<del> finishedAt time.Time
<del>}
<del>
<del>func (s *State) IsRunning() bool {
<del> s.RLock()
<del> defer s.RUnlock()
<del> return s.running
<del>}
<del>
<del>func (s *State) SetRunning() error {
<del> s.Lock()
<del> defer s.Unlock()
<del> s.running = true
<del> return nil
<del>}
<del>
<del>func (s *State) SetStopped(exitCode int) error {
<del> s.Lock()
<del> defer s.Unlock()
<del> s.exitCode = exitCode
<del> s.running = false
<del> return nil
<del>}
<del>
<del>// Container / Process / Whatever, we can redefine the conatiner here
<del>// to be what it should be and not have to carry the baggage of the
<del>// container type in the core with backward compat. This is what a
<del>// driver needs to execute a process inside of a conatiner. This is what
<del>// a container is at it's core.
<ide> type Process struct {
<del> State State
<del>
<ide> Name string // unique name for the conatienr
<ide> Privileged bool
<ide> User string
<ide> func (c *Process) SetCmd(cmd *exec.Cmd) error {
<ide> return nil
<ide> }
<ide>
<add>func (c *Process) Pid() int {
<add> return c.cmd.Process.Pid
<add>}
<add>
<ide> func (c *Process) StdinPipe() (io.WriteCloser, error) {
<ide> return c.cmd.StdinPipe()
<ide> }
<ide><path>execdriver/lxc/driver.go
<ide> func NewDriver(root string) (execdriver.Driver, error) {
<ide> }
<ide>
<ide> func (d *driver) Start(c *execdriver.Process) error {
<del> if c.State.IsRunning() {
<del> return nil
<del> }
<del>
<ide> params := []string{
<ide> startPath,
<ide> "-n", c.Name,
<ide> func (d *driver) Stop(c *execdriver.Process) error {
<ide> return err
<ide> }
<ide> }
<del> exitCode := c.GetExitCode()
<del> return c.State.SetStopped(exitCode)
<add> return nil
<ide> }
<ide>
<ide> func (d *driver) Kill(c *execdriver.Process, sig int) error {
<del> c.State.Lock()
<del> defer c.State.Unlock()
<ide> return d.kill(c, sig)
<ide> }
<ide>
<ide> begin:
<ide> return err
<ide> }
<ide> }
<del> exitCode := c.GetExitCode()
<del> return c.State.SetStopped(exitCode)
<add> return nil
<ide> }
<ide>
<ide> func (d *driver) kill(c *execdriver.Process, sig int) error {
<ide> func (d *driver) waitForStart(cmd *exec.Cmd, c *execdriver.Process) error {
<ide> // the end of this loop
<ide> for now := time.Now(); time.Since(now) < 5*time.Second; {
<ide> // If the container dies while waiting for it, just return
<del> if !c.State.IsRunning() {
<del> return nil
<del> }
<add> /*
<add> if !c.State.IsRunning() {
<add> return nil
<add> }
<add> */
<ide> output, err := exec.Command("lxc-info", "-s", "-n", c.Name).CombinedOutput()
<ide> if err != nil {
<ide> output, err = exec.Command("lxc-info", "-s", "-n", c.Name).CombinedOutput() | 3 |
Javascript | Javascript | remove dead code | 7394e89ff6167cf371e17cb43ff8d5c2f10d539c | <ide><path>lib/tls.js
<ide> SecurePair.prototype.destroy = function() {
<ide>
<ide> if (!this._doneFlag) {
<ide> this._doneFlag = true;
<del>
<del> if (this.ssl.timer) {
<del> clearTimeout(this.ssl.timer);
<del> this.ssl.timer = null;
<del> }
<del>
<ide> this.ssl.error = null;
<ide> this.ssl.close();
<ide> this.ssl = null; | 1 |
Ruby | Ruby | use sql statement to the read_query list for mysql | a960f93971bfb182c6e16e894788e3bc2cc60b5e | <ide><path>activerecord/lib/active_record/connection_adapters/mysql/database_statements.rb
<ide> def query(sql, name = nil) # :nodoc:
<ide> end
<ide>
<ide> READ_QUERY = ActiveRecord::ConnectionAdapters::AbstractAdapter.build_read_query_regexp(
<del> :begin, :commit, :explain, :select, :set, :show, :release, :savepoint, :rollback, :describe, :desc, :with
<add> :begin, :commit, :explain, :select, :set, :show, :release, :savepoint, :rollback, :describe, :desc, :with, :use
<ide> ) # :nodoc:
<ide> private_constant :READ_QUERY
<ide>
<ide><path>activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb
<ide> def test_statement_timeout_error_codes
<ide> end
<ide> end
<ide>
<add> def test_doesnt_error_when_a_use_query_is_called_while_preventing_writes
<add> @connection_handler.while_preventing_writes do
<add> db_name = ActiveRecord::Base.configurations["arunit"][:database]
<add> assert_nil @conn.execute("USE #{db_name}")
<add> end
<add> end
<add>
<ide> private
<ide> def with_example_table(definition = "id int auto_increment primary key, number int, data varchar(255)", &block)
<ide> super(@conn, "ex", definition, &block) | 2 |
Javascript | Javascript | use valuefn over curry | faf0c3e4c1b6f79b00f92f1231491f7569ecd25e | <ide><path>test/ng/directive/ngModelSpec.js
<ide> describe('ngModel', function() {
<ide>
<ide>
<ide> it('should only validate to true if all validations are true', function() {
<del> var curry = function(v) {
<del> return function() {
<del> return v;
<del> };
<del> };
<del>
<ide> ctrl.$modelValue = undefined;
<del> ctrl.$validators.a = curry(true);
<del> ctrl.$validators.b = curry(true);
<del> ctrl.$validators.c = curry(false);
<add> ctrl.$validators.a = valueFn(true);
<add> ctrl.$validators.b = valueFn(true);
<add> ctrl.$validators.c = valueFn(false);
<ide>
<ide> ctrl.$validate();
<ide> expect(ctrl.$valid).toBe(false);
<ide>
<del> ctrl.$validators.c = curry(true);
<add> ctrl.$validators.c = valueFn(true);
<ide>
<ide> ctrl.$validate();
<ide> expect(ctrl.$valid).toBe(true);
<ide> describe('ngModel', function() {
<ide>
<ide>
<ide> it('should register invalid validations on the $error object', function() {
<del> var curry = function(v) {
<del> return function() {
<del> return v;
<del> };
<del> };
<del>
<ide> ctrl.$modelValue = undefined;
<del> ctrl.$validators.unique = curry(false);
<del> ctrl.$validators.tooLong = curry(false);
<del> ctrl.$validators.notNumeric = curry(true);
<add> ctrl.$validators.unique = valueFn(false);
<add> ctrl.$validators.tooLong = valueFn(false);
<add> ctrl.$validators.notNumeric = valueFn(true);
<ide>
<ide> ctrl.$validate();
<ide> | 1 |
Ruby | Ruby | keep time_tag docs up-to-date | 46bb787c0482f4b7b7f9d18454806d5ef8863243 | <ide><path>actionview/lib/action_view/helpers/date_helper.rb
<ide> def select_year(date, options = {}, html_options = {})
<ide> # <time datetime="2010-11-04T17:55:45+01:00">November 04, 2010 17:55</time>
<ide> # time_tag Date.yesterday, 'Yesterday' # =>
<ide> # <time datetime="2010-11-03">Yesterday</time>
<del> # time_tag Date.today, pubdate: true # =>
<del> # <time datetime="2010-11-04" pubdate="pubdate">November 04, 2010</time>
<ide> # time_tag Date.today, datetime: Date.today.strftime('%G-W%V') # =>
<ide> # <time datetime="2010-W44">November 04, 2010</time>
<ide> # | 1 |
Text | Text | add another solution | ad5e844cb518be90efecfa2473cc61f16db083d2 | <ide><path>guide/english/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller/index.md
<ide> You will definitely need recursion or another way to go beyond two level arrays
<ide> * We replace the double comma with one, then split it back into an array.
<ide> * map through the array and fix object values and convert string numbers to regular numbers.
<ide>
<add>##  Advanced Code Solution 2:
<add>
<add> const steamrollArray = arr => arr.flat(Infinity);
<add>
<add>
<add>### Code Explanation:
<add>
<add>* Use `Array.flat()` to flatten an array with `Infinity` as a parameter for the depth.
<add>
<ide> ##  NOTES FOR CONTRIBUTIONS:
<ide>
<ide> *  **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution. | 1 |
Text | Text | clarify use of two-branch models | 6501b587c06b525eeda92b5f318bee8d74b9cc5c | <ide><path>docs/templates/getting-started/sequential-model-guide.md
<ide> final_model.add(Dense(10, activation='softmax'))
<ide>
<ide> <img src="http://s3.amazonaws.com/keras.io/img/two_branches_sequential_model.png" alt="two branch Sequential" style="width: 400px;"/>
<ide>
<add>Such a two-branch model can then be trained via e.g.:
<add>
<add>```python
<add>final_model.compile(optimizer='rmsprop', loss='categorical_crossentropy')
<add>final_model.fit([input_data_1, input_data_2], targets) # we pass on data array per model input
<add>```
<add>
<ide> The `Merge` layer supports a number of pre-defined modes:
<ide>
<ide> - `sum` (default): element-wise sum | 1 |
Text | Text | fix typos for ng-switch-changed workaround | 58adaa66346eeaf54cab5d7de9936e17aadb0d4c | <ide><path>CHANGELOG.md
<ide> Example:
<ide> angular.module("switchChangeWorkaround", []).
<ide> directive("onSwitchChanged", function() {
<ide> return {
<del> linke: function($scope, $attrs) {
<del> $scope.$parent.$eval($attrs.change);
<add> link: function($scope, $element, $attrs) {
<add> $scope.$parent.$eval($attrs.onSwitchChanged);
<ide> }
<ide> };
<ide> }); | 1 |
PHP | PHP | improve pagination accessibility | d7cf66e4fb37a0120bf6a31712e5dd686506883e | <ide><path>src/Illuminate/Pagination/resources/views/bootstrap-4.blade.php
<ide> @if ($paginator->hasPages())
<del> <ul class="pagination">
<add> <ul class="pagination" role="navigation">
<ide> {{-- Previous Page Link --}}
<ide> @if ($paginator->onFirstPage())
<del> <li class="page-item disabled"><span class="page-link">‹</span></li>
<add> <li class="page-item disabled" aria-disabled="true" aria-label="@lang('pagination.previous')">
<add> <span class="page-link" aria-hidden="true">‹</span>
<add> </li>
<ide> @else
<del> <li class="page-item"><a class="page-link" href="{{ $paginator->previousPageUrl() }}" rel="prev">‹</a></li>
<add> <li class="page-item">
<add> <a class="page-link" href="{{ $paginator->previousPageUrl() }}" rel="prev" aria-label="@lang('pagination.previous')">‹</a>
<add> </li>
<ide> @endif
<ide>
<ide> {{-- Pagination Elements --}}
<ide> @foreach ($elements as $element)
<ide> {{-- "Three Dots" Separator --}}
<ide> @if (is_string($element))
<del> <li class="page-item disabled"><span class="page-link">{{ $element }}</span></li>
<add> <li class="page-item disabled" aria-disabled="true"><span class="page-link">{{ $element }}</span></li>
<ide> @endif
<ide>
<ide> {{-- Array Of Links --}}
<ide> @if (is_array($element))
<ide> @foreach ($element as $page => $url)
<ide> @if ($page == $paginator->currentPage())
<del> <li class="page-item active"><span class="page-link">{{ $page }}</span></li>
<add> <li class="page-item active" aria-current="page"><span class="page-link">{{ $page }}</span></li>
<ide> @else
<ide> <li class="page-item"><a class="page-link" href="{{ $url }}">{{ $page }}</a></li>
<ide> @endif
<ide>
<ide> {{-- Next Page Link --}}
<ide> @if ($paginator->hasMorePages())
<del> <li class="page-item"><a class="page-link" href="{{ $paginator->nextPageUrl() }}" rel="next">›</a></li>
<add> <li class="page-item">
<add> <a class="page-link" href="{{ $paginator->nextPageUrl() }}" rel="next" aria-label="@lang('pagination.next')">›</a>
<add> </li>
<ide> @else
<del> <li class="page-item disabled"><span class="page-link">›</span></li>
<add> <li class="page-item disabled" aria-disabled="true" aria-label="@lang('pagination.next')">
<add> <span class="page-link" aria-hidden="true">›</span>
<add> </li>
<ide> @endif
<ide> </ul>
<ide> @endif
<ide><path>src/Illuminate/Pagination/resources/views/default.blade.php
<ide> @if ($paginator->hasPages())
<del> <ul class="pagination">
<add> <ul class="pagination" role="navigation">
<ide> {{-- Previous Page Link --}}
<ide> @if ($paginator->onFirstPage())
<del> <li class="disabled"><span>‹</span></li>
<add> <li class="disabled" aria-disabled="true" aria-label="@lang('pagination.previous')">
<add> <span aria-hidden="true">‹</span>
<add> </li>
<ide> @else
<del> <li><a href="{{ $paginator->previousPageUrl() }}" rel="prev">‹</a></li>
<add> <li>
<add> <a href="{{ $paginator->previousPageUrl() }}" rel="prev" aria-label="@lang('pagination.previous')">‹</a>
<add> </li>
<ide> @endif
<ide>
<ide> {{-- Pagination Elements --}}
<ide> @foreach ($elements as $element)
<ide> {{-- "Three Dots" Separator --}}
<ide> @if (is_string($element))
<del> <li class="disabled"><span>{{ $element }}</span></li>
<add> <li class="disabled" aria-disabled="true"><span>{{ $element }}</span></li>
<ide> @endif
<ide>
<ide> {{-- Array Of Links --}}
<ide> @if (is_array($element))
<ide> @foreach ($element as $page => $url)
<ide> @if ($page == $paginator->currentPage())
<del> <li class="active"><span>{{ $page }}</span></li>
<add> <li class="active" aria-current="page"><span>{{ $page }}</span></li>
<ide> @else
<ide> <li><a href="{{ $url }}">{{ $page }}</a></li>
<ide> @endif
<ide>
<ide> {{-- Next Page Link --}}
<ide> @if ($paginator->hasMorePages())
<del> <li><a href="{{ $paginator->nextPageUrl() }}" rel="next">›</a></li>
<add> <li>
<add> <a href="{{ $paginator->nextPageUrl() }}" rel="next" aria-label="@lang('pagination.next')">›</a>
<add> </li>
<ide> @else
<del> <li class="disabled"><span>›</span></li>
<add> <li class="disabled" aria-disabled="true" aria-label="@lang('pagination.next')">
<add> <span aria-hidden="true">›</span>
<add> </li>
<ide> @endif
<ide> </ul>
<ide> @endif
<ide><path>src/Illuminate/Pagination/resources/views/semantic-ui.blade.php
<ide> @if ($paginator->hasPages())
<del> <div class="ui pagination menu">
<add> <div class="ui pagination menu" role="navigation">
<ide> {{-- Previous Page Link --}}
<ide> @if ($paginator->onFirstPage())
<del> <a class="icon item disabled"> <i class="left chevron icon"></i> </a>
<add> <a class="icon item disabled" aria-disabled="true" aria-label="@lang('pagination.previous')"> <i class="left chevron icon"></i> </a>
<ide> @else
<del> <a class="icon item" href="{{ $paginator->previousPageUrl() }}" rel="prev"> <i class="left chevron icon"></i> </a>
<add> <a class="icon item" href="{{ $paginator->previousPageUrl() }}" rel="prev" aria-label="@lang('pagination.previous')"> <i class="left chevron icon"></i> </a>
<ide> @endif
<ide>
<ide> {{-- Pagination Elements --}}
<ide> @foreach ($elements as $element)
<ide> {{-- "Three Dots" Separator --}}
<ide> @if (is_string($element))
<del> <a class="icon item disabled">{{ $element }}</a>
<add> <a class="icon item disabled" aria-disabled="true">{{ $element }}</a>
<ide> @endif
<ide>
<ide> {{-- Array Of Links --}}
<ide> @if (is_array($element))
<ide> @foreach ($element as $page => $url)
<ide> @if ($page == $paginator->currentPage())
<del> <a class="item active" href="{{ $url }}">{{ $page }}</a>
<add> <a class="item active" href="{{ $url }}" aria-current="page">{{ $page }}</a>
<ide> @else
<ide> <a class="item" href="{{ $url }}">{{ $page }}</a>
<ide> @endif
<ide>
<ide> {{-- Next Page Link --}}
<ide> @if ($paginator->hasMorePages())
<del> <a class="icon item" href="{{ $paginator->nextPageUrl() }}" rel="next"> <i class="right chevron icon"></i> </a>
<add> <a class="icon item" href="{{ $paginator->nextPageUrl() }}" rel="next" aria-label="@lang('pagination.next')"> <i class="right chevron icon"></i> </a>
<ide> @else
<del> <a class="icon item disabled"> <i class="right chevron icon"></i> </a>
<add> <a class="icon item disabled" aria-disabled="true" aria-label="@lang('pagination.next')"> <i class="right chevron icon"></i> </a>
<ide> @endif
<ide> </div>
<ide> @endif
<ide><path>src/Illuminate/Pagination/resources/views/simple-bootstrap-4.blade.php
<ide> @if ($paginator->hasPages())
<del> <ul class="pagination">
<add> <ul class="pagination" role="navigation">
<ide> {{-- Previous Page Link --}}
<ide> @if ($paginator->onFirstPage())
<del> <li class="page-item disabled"><span class="page-link">@lang('pagination.previous')</span></li>
<add> <li class="page-item disabled" aria-disabled="true">
<add> <span class="page-link">@lang('pagination.previous')</span>
<add> </li>
<ide> @else
<del> <li class="page-item"><a class="page-link" href="{{ $paginator->previousPageUrl() }}" rel="prev">@lang('pagination.previous')</a></li>
<add> <li class="page-item">
<add> <a class="page-link" href="{{ $paginator->previousPageUrl() }}" rel="prev">@lang('pagination.previous')</a>
<add> </li>
<ide> @endif
<ide>
<ide> {{-- Next Page Link --}}
<ide> @if ($paginator->hasMorePages())
<del> <li class="page-item"><a class="page-link" href="{{ $paginator->nextPageUrl() }}" rel="next">@lang('pagination.next')</a></li>
<add> <li class="page-item">
<add> <a class="page-link" href="{{ $paginator->nextPageUrl() }}" rel="next">@lang('pagination.next')</a>
<add> </li>
<ide> @else
<del> <li class="page-item disabled"><span class="page-link">@lang('pagination.next')</span></li>
<add> <li class="page-item disabled" aria-disabled="true">
<add> <span class="page-link">@lang('pagination.next')</span>
<add> </li>
<ide> @endif
<ide> </ul>
<ide> @endif
<ide><path>src/Illuminate/Pagination/resources/views/simple-default.blade.php
<ide> @if ($paginator->hasPages())
<del> <ul class="pagination">
<add> <ul class="pagination" role="navigation">
<ide> {{-- Previous Page Link --}}
<ide> @if ($paginator->onFirstPage())
<del> <li class="disabled"><span>@lang('pagination.previous')</span></li>
<add> <li class="disabled" aria-disabled="true"><span>@lang('pagination.previous')</span></li>
<ide> @else
<ide> <li><a href="{{ $paginator->previousPageUrl() }}" rel="prev">@lang('pagination.previous')</a></li>
<ide> @endif
<ide> @if ($paginator->hasMorePages())
<ide> <li><a href="{{ $paginator->nextPageUrl() }}" rel="next">@lang('pagination.next')</a></li>
<ide> @else
<del> <li class="disabled"><span>@lang('pagination.next')</span></li>
<add> <li class="disabled" aria-disabled="true"><span>@lang('pagination.next')</span></li>
<ide> @endif
<ide> </ul>
<ide> @endif | 5 |
PHP | PHP | add affordances for allowempty() and file uploads | 68a105538194b20fd9b40af1aa729c78c01a5d76 | <ide><path>src/Validation/Validator.php
<ide> public function requirePresence($field, $mode = true, $message = null)
<ide> * });
<ide> * ```
<ide> *
<add> * This method will correctly detect empty file uploads and date/time/datetime fields.
<add> *
<ide> * Because this and `notEmpty()` modify the same internal state, the last
<ide> * method called will take precedence.
<ide> *
<ide> protected function _fieldIsEmpty($data)
<ide> if (empty($data) && $data !== '0' && $data !== false && $data !== 0 && $data !== 0.0) {
<ide> return true;
<ide> }
<del> if (is_array($data) && (isset($data['year']) || isset($data['hour']))) {
<add> $isArray = is_array($data);
<add> if ($isArray && (isset($data['year']) || isset($data['hour']))) {
<ide> $value = implode('', $data);
<ide> return strlen($value) === 0;
<ide> }
<add> if ($isArray && isset($data['name'], $data['type'], $data['tmp_name'], $data['error'])) {
<add> return (int)$data['error'] === UPLOAD_ERR_NO_FILE;
<add> }
<ide> return false;
<ide> }
<ide>
<ide><path>tests/TestCase/Validation/ValidatorTest.php
<ide> public function testAllowEmptyDateTime()
<ide> $this->assertEmpty($result, 'No errors on empty time');
<ide> }
<ide>
<add> /**
<add> * Tests the allowEmpty method with file fields.
<add> *
<add> * @return void
<add> */
<add> public function testAllowEmptyFileFields()
<add> {
<add> $validator = new Validator;
<add> $validator->allowEmpty('picture')
<add> ->add('picture', 'file', ['rule' => 'uploadedFile']);
<add>
<add> $data = [
<add> 'picture' => [
<add> 'name' => '',
<add> 'type' => '',
<add> 'tmp_name' => '',
<add> 'error' => UPLOAD_ERR_NO_FILE,
<add> ]
<add> ];
<add> $result = $validator->errors($data);
<add> $this->assertEmpty($result, 'No errors on empty date');
<add>
<add> $data = [
<add> 'picture' => [
<add> 'name' => 'fake.png',
<add> 'type' => '',
<add> 'tmp_name' => '',
<add> 'error' => UPLOAD_ERR_OK,
<add> ]
<add> ];
<add> $result = $validator->errors($data);
<add> $this->assertNotEmpty($result, 'Invalid file should be caught still.');
<add> }
<add>
<ide> /**
<ide> * Test the notEmpty() method.
<ide> * | 2 |
Javascript | Javascript | replace imagecanvas by scratchcanvas | 000d6402580dcd99efdca83031ac2e3b1055bd31 | <ide><path>pdf.js
<ide> var Encodings = {
<ide> }
<ide> };
<ide>
<del>function ImageCanvas(width, height) {
<del> var tmpCanvas = this.canvas = document.createElement("canvas");
<del> tmpCanvas.width = width;
<del> tmpCanvas.height = height;
<add>function ScratchCanvas(width, height) {
<add> var canvas = document.createElement("canvas");
<add> canvas.width = width;
<add> canvas.height = height;
<ide>
<del> this.ctx = tmpCanvas.getContext("2d");
<del> this.imgData = this.ctx.getImageData(0, 0, width, height);
<del>}
<del>
<del>ImageCanvas.prototype.putImageData = function(imgData) {
<del> this.ctx.putImageData(imgData, 0, 0);
<del>}
<add> this.getContext = function(kind) {
<add> return canvas.getContext(kind);
<add> }
<ide>
<del>ImageCanvas.prototype.getCanvas = function() {
<del> return this.canvas;
<add> this.getCanvas = function() {
<add> return canvas;
<add> }
<ide> }
<ide>
<ide> var CanvasGraphics = (function() {
<ide> var CanvasGraphics = (function() {
<ide> this.pendingClip = null;
<ide> this.res = null;
<ide> this.xobjs = null;
<del> this.ImageCanvas = imageCanvas || ImageCanvas;
<add> this.ScratchCanvas = imageCanvas || ScratchCanvas;
<ide> }
<ide>
<ide> constructor.prototype = {
<ide> var CanvasGraphics = (function() {
<ide> // handle matte object
<ide> }
<ide>
<del> var tmpCanvas = new this.ImageCanvas(w, h);
<del> // var tmpCanvas = document.createElement("canvas");
<del> // tmpCanvas.width = w;
<del> // tmpCanvas.height = h;
<del> //
<del> // var tmpCtx = tmpCanvas.getContext("2d");
<del> // var imgData = tmpCtx.getImageData(0, 0, w, h);
<del> // var pixels = imgData.data;
<del> var imgData = tmpCanvas.imgData;
<add> var tmpCanvas = new this.ScratchCanvas(w, h);
<add> var tmpCtx = tmpCanvas.getContext("2d");
<add> var imgData = tmpCtx.getImageData(0, 0, w, h);
<ide> var pixels = imgData.data;
<ide>
<ide> if (bitsPerComponent != 8)
<ide> var CanvasGraphics = (function() {
<ide> TODO("Images with "+ numComps + " components per pixel");
<ide> }
<ide> }
<del> tmpCanvas.putImageData(imgData, 0, 0);
<add> tmpCtx.putImageData(imgData, 0, 0);
<ide> ctx.drawImage(tmpCanvas.getCanvas(), 0, -h);
<ide> this.restore();
<ide> }, | 1 |
PHP | PHP | improve eager loading performance | 352e8abcf1354e73cbab6473d6467dd92960d38e | <ide><path>src/Illuminate/Database/Eloquent/Relations/BelongsTo.php
<ide> public function addEagerConstraints(array $models)
<ide> // our eagerly loading query so it returns the proper models from execution.
<ide> $key = $this->related->getTable().'.'.$this->ownerKey;
<ide>
<del> $this->query->whereIn($key, $this->getEagerModelKeys($models));
<add> $whereIn = $this->whereInMethod($this->related, $this->ownerKey);
<add>
<add> $this->query->{$whereIn}($key, $this->getEagerModelKeys($models));
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php
<ide> protected function addWhereConstraints()
<ide> */
<ide> public function addEagerConstraints(array $models)
<ide> {
<del> $this->query->whereIn($this->getQualifiedForeignPivotKeyName(), $this->getKeys($models, $this->parentKey));
<add> $whereIn = $this->whereInMethod($this->parent, $this->parentKey);
<add>
<add> $this->query->{$whereIn}($this->getQualifiedForeignPivotKeyName(), $this->getKeys($models, $this->parentKey));
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php
<ide> public function throughParentSoftDeletes()
<ide> */
<ide> public function addEagerConstraints(array $models)
<ide> {
<del> $this->query->whereIn(
<add> $whereIn = $this->whereInMethod($this->farParent, $this->localKey);
<add>
<add> $this->query->{$whereIn}(
<ide> $this->getQualifiedFirstKeyName(), $this->getKeys($models, $this->localKey)
<ide> );
<ide> }
<ide><path>src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php
<ide> public function addConstraints()
<ide> */
<ide> public function addEagerConstraints(array $models)
<ide> {
<del> $whereIn = in_array($this->parent->getKeyType(), ['int', 'integer']) ? 'whereInRaw' : 'whereIn';
<add> $whereIn = $this->whereInMethod($this->parent, $this->localKey);
<ide>
<ide> $this->query->{$whereIn}(
<ide> $this->foreignKey, $this->getKeys($models, $this->localKey)
<ide><path>src/Illuminate/Database/Eloquent/Relations/Relation.php
<ide> public function relatedUpdatedAt()
<ide> return $this->related->getUpdatedAtColumn();
<ide> }
<ide>
<add> /**
<add> * Get the name of the "where in" method for eager loading.
<add> *
<add> * @param \Illuminate\Database\Eloquent\Model $model
<add> * @param string $key
<add> * @return string
<add> */
<add> protected function whereInMethod(Model $model, $key)
<add> {
<add> return $model->getKeyName() === last(explode('.', $key))
<add> && in_array($model->getKeyType(), ['int', 'integer'])
<add> ? 'whereInRaw'
<add> : 'whereIn';
<add> }
<add>
<ide> /**
<ide> * Set or get the morph map for polymorphic relations.
<ide> *
<ide><path>tests/Database/DatabaseEloquentBelongsToTest.php
<ide> public function testUpdateMethodRetrievesModelAndUpdates()
<ide> public function testEagerConstraintsAreProperlyAdded()
<ide> {
<ide> $relation = $this->getRelation();
<del> $relation->getQuery()->shouldReceive('whereIn')->once()->with('relation.id', ['foreign.value', 'foreign.value.two']);
<add> $relation->getRelated()->shouldReceive('getKeyName')->andReturn('id');
<add> $relation->getRelated()->shouldReceive('getKeyType')->andReturn('int');
<add> $relation->getQuery()->shouldReceive('whereInRaw')->once()->with('relation.id', ['foreign.value', 'foreign.value.two']);
<ide> $models = [new EloquentBelongsToModelStub, new EloquentBelongsToModelStub, new AnotherEloquentBelongsToModelStub];
<ide> $relation->addEagerConstraints($models);
<ide> }
<ide>
<ide> public function testIdsInEagerConstraintsCanBeZero()
<ide> {
<ide> $relation = $this->getRelation();
<del> $relation->getQuery()->shouldReceive('whereIn')->once()->with('relation.id', ['foreign.value', 0]);
<add> $relation->getRelated()->shouldReceive('getKeyName')->andReturn('id');
<add> $relation->getRelated()->shouldReceive('getKeyType')->andReturn('int');
<add> $relation->getQuery()->shouldReceive('whereInRaw')->once()->with('relation.id', ['foreign.value', 0]);
<ide> $models = [new EloquentBelongsToModelStub, new EloquentBelongsToModelStubWithZeroId];
<ide> $relation->addEagerConstraints($models);
<ide> }
<ide> public function testAssociateMethodSetsForeignKeyOnModelById()
<ide> public function testDefaultEagerConstraintsWhenIncrementing()
<ide> {
<ide> $relation = $this->getRelation();
<del> $relation->getQuery()->shouldReceive('whereIn')->once()->with('relation.id', m::mustBe([null]));
<add> $relation->getRelated()->shouldReceive('getKeyName')->andReturn('id');
<add> $relation->getRelated()->shouldReceive('getKeyType')->andReturn('int');
<add> $relation->getQuery()->shouldReceive('whereInRaw')->once()->with('relation.id', m::mustBe([null]));
<ide> $models = [new MissingEloquentBelongsToModelStub, new MissingEloquentBelongsToModelStub];
<ide> $relation->addEagerConstraints($models);
<ide> }
<ide> public function testDefaultEagerConstraintsWhenIncrementingAndNonIntKeyType()
<ide> public function testDefaultEagerConstraintsWhenNotIncrementing()
<ide> {
<ide> $relation = $this->getRelation(null, false);
<del> $relation->getQuery()->shouldReceive('whereIn')->once()->with('relation.id', m::mustBe([null]));
<add> $relation->getRelated()->shouldReceive('getKeyName')->andReturn('id');
<add> $relation->getRelated()->shouldReceive('getKeyType')->andReturn('int');
<add> $relation->getQuery()->shouldReceive('whereInRaw')->once()->with('relation.id', m::mustBe([null]));
<ide> $models = [new MissingEloquentBelongsToModelStub, new MissingEloquentBelongsToModelStub];
<ide> $relation->addEagerConstraints($models);
<ide> }
<ide><path>tests/Database/DatabaseEloquentHasManyTest.php
<ide> public function testRelationIsProperlyInitialized()
<ide> public function testEagerConstraintsAreProperlyAdded()
<ide> {
<ide> $relation = $this->getRelation();
<add> $relation->getParent()->shouldReceive('getKeyName')->once()->andReturn('id');
<ide> $relation->getParent()->shouldReceive('getKeyType')->once()->andReturn('int');
<ide> $relation->getQuery()->shouldReceive('whereInRaw')->once()->with('table.foreign_key', [1, 2]);
<ide> $model1 = new EloquentHasManyModelStub;
<ide> public function testEagerConstraintsAreProperlyAdded()
<ide> public function testEagerConstraintsAreProperlyAddedWithStringKey()
<ide> {
<ide> $relation = $this->getRelation();
<add> $relation->getParent()->shouldReceive('getKeyName')->once()->andReturn('id');
<ide> $relation->getParent()->shouldReceive('getKeyType')->once()->andReturn('string');
<ide> $relation->getQuery()->shouldReceive('whereIn')->once()->with('table.foreign_key', [1, 2]);
<ide> $model1 = new EloquentHasManyModelStub;
<ide><path>tests/Database/DatabaseEloquentHasOneTest.php
<ide> public function testRelationIsProperlyInitialized()
<ide> public function testEagerConstraintsAreProperlyAdded()
<ide> {
<ide> $relation = $this->getRelation();
<add> $relation->getParent()->shouldReceive('getKeyName')->once()->andReturn('id');
<ide> $relation->getParent()->shouldReceive('getKeyType')->once()->andReturn('int');
<ide> $relation->getQuery()->shouldReceive('whereInRaw')->once()->with('table.foreign_key', [1, 2]);
<ide> $model1 = new EloquentHasOneModelStub;
<ide><path>tests/Database/DatabaseEloquentMorphTest.php
<ide> public function testMorphOneSetsProperConstraints()
<ide> public function testMorphOneEagerConstraintsAreProperlyAdded()
<ide> {
<ide> $relation = $this->getOneRelation();
<add> $relation->getParent()->shouldReceive('getKeyName')->once()->andReturn('id');
<ide> $relation->getParent()->shouldReceive('getKeyType')->once()->andReturn('string');
<ide> $relation->getQuery()->shouldReceive('whereIn')->once()->with('table.morph_id', [1, 2]);
<ide> $relation->getQuery()->shouldReceive('where')->once()->with('table.morph_type', get_class($relation->getParent()));
<ide> public function testMorphManySetsProperConstraints()
<ide> public function testMorphManyEagerConstraintsAreProperlyAdded()
<ide> {
<ide> $relation = $this->getManyRelation();
<add> $relation->getParent()->shouldReceive('getKeyName')->once()->andReturn('id');
<ide> $relation->getParent()->shouldReceive('getKeyType')->once()->andReturn('int');
<ide> $relation->getQuery()->shouldReceive('whereInRaw')->once()->with('table.morph_id', [1, 2]);
<ide> $relation->getQuery()->shouldReceive('where')->once()->with('table.morph_type', get_class($relation->getParent()));
<ide><path>tests/Database/DatabaseEloquentMorphToManyTest.php
<ide> public function tearDown()
<ide> public function testEagerConstraintsAreProperlyAdded()
<ide> {
<ide> $relation = $this->getRelation();
<del> $relation->getQuery()->shouldReceive('whereIn')->once()->with('taggables.taggable_id', [1, 2]);
<add> $relation->getParent()->shouldReceive('getKeyName')->andReturn('id');
<add> $relation->getParent()->shouldReceive('getKeyType')->andReturn('int');
<add> $relation->getQuery()->shouldReceive('whereInRaw')->once()->with('taggables.taggable_id', [1, 2]);
<ide> $relation->getQuery()->shouldReceive('where')->once()->with('taggables.taggable_type', get_class($relation->getParent()));
<ide> $model1 = new EloquentMorphToManyModelStub;
<ide> $model1->id = 1; | 10 |
Text | Text | clarify http timeouts | 02601c247db8a7b147065f5757af5ac47165e517 | <ide><path>doc/api/http.md
<ide> also be accessed at `request.connection`.
<ide> This event can also be explicitly emitted by users to inject connections
<ide> into the HTTP server. In that case, any [`Duplex`][] stream can be passed.
<ide>
<add>If `socket.setTimeout()` is called here, the timeout will be replaced with
<add>`server.keepAliveTimeout` when the socket has served a request (if
<add>`server.keepAliveTimeout` is non-zero).
<add>
<ide> ### Event: 'request'
<ide> <!-- YAML
<ide> added: v0.1.0 | 1 |
Go | Go | remove unused service.tlsconfig() | 2f466a9f884f28601c3b15e7f6e2c6aa683b8afd | <ide><path>registry/service.go
<ide> type Service interface {
<ide> ResolveRepository(name reference.Named) (*RepositoryInfo, error)
<ide> Search(ctx context.Context, term string, limit int, authConfig *types.AuthConfig, userAgent string, headers map[string][]string) (*registry.SearchResults, error)
<ide> ServiceConfig() *registry.ServiceConfig
<del> TLSConfig(hostname string) (*tls.Config, error)
<ide> LoadAllowNondistributableArtifacts([]string) error
<ide> LoadMirrors([]string) error
<ide> LoadInsecureRegistries([]string) error
<ide> type APIEndpoint struct {
<ide> TLSConfig *tls.Config
<ide> }
<ide>
<del>// TLSConfig constructs a client TLS configuration based on server defaults
<del>func (s *defaultService) TLSConfig(hostname string) (*tls.Config, error) {
<del> s.mu.RLock()
<del> secure := s.config.isSecureIndex(hostname)
<del> s.mu.RUnlock()
<del>
<del> return newTLSConfig(hostname, secure)
<del>}
<del>
<ide> // LookupPullEndpoints creates a list of v2 endpoints to try to pull from, in order of preference.
<ide> // It gives preference to mirrors over the actual registry, and HTTPS over plain HTTP.
<ide> func (s *defaultService) LookupPullEndpoints(hostname string) (endpoints []APIEndpoint, err error) { | 1 |
Go | Go | add srcname() method to return interface name | f2c60095836a7ccf374d0aae42a0aa3bc2dd7285 | <ide><path>libnetwork/endpoint_info.go
<ide> type InterfaceInfo interface {
<ide>
<ide> // LinkLocalAddresses returns the list of link-local (IPv4/IPv6) addresses assigned to the endpoint.
<ide> LinkLocalAddresses() []*net.IPNet
<add>
<add> // SrcName returns the name of the interface w/in the container
<add> SrcName() string
<ide> }
<ide>
<ide> type endpointInterface struct {
<ide> func (epi *endpointInterface) LinkLocalAddresses() []*net.IPNet {
<ide> return epi.llAddrs
<ide> }
<ide>
<add>func (epi *endpointInterface) SrcName() string {
<add> return epi.srcName
<add>}
<add>
<ide> func (epi *endpointInterface) SetNames(srcName string, dstPrefix string) error {
<ide> epi.srcName = srcName
<ide> epi.dstPrefix = dstPrefix | 1 |
Go | Go | fix content-type for legacy | 0b403b35318a68d848bd9d7cddcf850d2fa7bfa7 | <ide><path>api/api.go
<ide> func getImagesJSON(eng *engine.Engine, version float64, w http.ResponseWriter, r
<ide> outsLegacy.Add(outLegacy)
<ide> }
<ide> }
<add> w.Header().Set("Content-Type", "application/json")
<ide> if _, err := outsLegacy.WriteListTo(w); err != nil {
<ide> return err
<ide> }
<ide> func getContainersJSON(eng *engine.Engine, version float64, w http.ResponseWrite
<ide> ports.ReadListFrom([]byte(out.Get("Ports")))
<ide> out.Set("Ports", displayablePorts(ports))
<ide> }
<add> w.Header().Set("Content-Type", "application/json")
<ide> if _, err = outs.WriteListTo(w); err != nil {
<ide> return err
<ide> } | 1 |
Ruby | Ruby | fix some default_cc behavior | 30cbb25147416620ff64e6ba6d047d5304dff25b | <ide><path>Library/Homebrew/utils.rb
<ide> def dev_tools_path
<ide> def default_cc
<ide> cc = `/usr/bin/xcrun -find cc 2> /dev/null`.chomp
<ide> cc = "#{dev_tools_path}/cc" if cc.empty?
<del> Pathname.new(cc).realpath.basename.to_s
<add> Pathname.new(cc).realpath.basename.to_s rescue nil
<ide> end
<ide>
<ide> def default_compiler
<ide> def gcc_40_build_version
<ide> end
<ide> end
<ide>
<del> # usually /Developer
<ide> def xcode_prefix
<ide> @xcode_prefix ||= begin
<del> path = `/usr/bin/xcode-select -print-path 2>&1`.chomp
<add> path = `/usr/bin/xcode-select -print-path 2>/dev/null`.chomp
<ide> path = Pathname.new path
<ide> if path.directory? and path.absolute?
<ide> path | 1 |
Python | Python | add doc string to creation test class | 781cb48ab247ff76d51a6e20603d7e763768276d | <ide><path>numpy/core/tests/test_numeric.py
<ide> def test_basic(self):
<ide>
<ide> class TestCreationFuncs(TestCase):
<ide>
<add> '''Test ones, zeros, empty and filled'''
<add>
<ide> def setUp(self):
<ide> self.dtypes = ('b', 'i', 'u', 'f', 'c', 'S', 'a', 'U', 'V')
<ide> self.orders = {'C': 'c_contiguous', 'F': 'f_contiguous'} | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.