content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
PHP
PHP
remove trailing whitespace
ae8a540101976d38d9114d2e62bd424dc34513b1
<ide><path>lib/Cake/Error/ExceptionRenderer.php <ide> protected function _getController($exception) { <ide> $startup = false; <ide> } <ide> // Retry RequestHandler, as another aspect of startupProcess() <del> // could have failed. Ignore any exceptions out of startup, as <add> // could have failed. Ignore any exceptions out of startup, as <ide> // there could be userland input data parsers. <ide> if ($startup === false && <ide> !empty($controller) &&
1
PHP
PHP
update typehints to match cacheinterface method
25432da03e8fedfc935e678fce7a3cb4672ed99b
<ide><path>src/Cache/Cache.php <ide> public static function read(string $key, string $config = 'default') <ide> * <ide> * @param iterable $keys An array or Traversable of keys to fetch from the cache <ide> * @param string $config optional name of the configuration to use. Defaults to 'default' <del> * @return array An array containing, for each of the given $keys, <add> * @return iterable An array containing, for each of the given $keys, <ide> * the cached data or false if cached data could not be retrieved. <ide> * @throws \Cake\Cache\InvalidArgumentException <ide> */ <del> public static function readMany(iterable $keys, string $config = 'default'): array <add> public static function readMany(iterable $keys, string $config = 'default'): iterable <ide> { <ide> return static::pool($config)->getMultiple($keys); <ide> } <ide><path>src/Cache/CacheEngine.php <ide> protected function ensureValidType($iterable, string $check = self::CHECK_VALUE) <ide> * <ide> * @param iterable $keys A list of keys that can obtained in a single operation. <ide> * @param mixed $default Default value to return for keys that do not exist. <del> * @return array A list of key value pairs. Cache keys that do not exist or are stale will have $default as value. <add> * @return iterable A list of key value pairs. Cache keys that do not exist or are stale will have $default as value. <ide> * @throws \Cake\Cache\InvalidArgumentException If $keys is neither an array nor a Traversable, <ide> * or if any of the $keys are not a legal value. <ide> */ <del> public function getMultiple($keys, $default = null): array <add> public function getMultiple($keys, $default = null): iterable <ide> { <ide> $this->ensureValidType($keys); <ide>
2
Python
Python
use raise with context instead of reraise
89c927a2b4d7df571371521d6a044931869788e3
<ide><path>celery/backends/base.py <ide> from celery.exceptions import (ChordError, ImproperlyConfigured, <ide> NotRegistered, TaskRevokedError, TimeoutError, <ide> BackendGetMetaError, BackendStoreError) <del>from celery.five import PY3, items, reraise <add>from celery.five import PY3, items <ide> from celery.result import (GroupResult, ResultBase, ResultSet, <ide> allow_join_result, result_from_tuple) <ide> from celery.utils.collections import BufferMap <ide> from celery.utils.serialization import (create_exception_cls, <ide> ensure_serializable, <ide> get_pickleable_exception, <del> get_pickled_exception) <add> get_pickled_exception, <add> raise_with_context) <ide> from celery.utils.time import get_exponential_backoff_interval <ide> <ide> __all__ = ('BaseBackend', 'KeyValueStoreBackend', 'DisabledBackend') <ide> def store_result(self, task_id, result, state, <ide> self.max_sleep_between_retries_ms, True) / 1000 <ide> self._sleep(sleep_amount) <ide> else: <del> reraise( <del> BackendStoreError, <add> raise_with_context( <ide> BackendStoreError("failed to store result on the backend", task_id=task_id, state=state), <del> traceback, <ide> ) <ide> else: <ide> raise <ide> def get_task_meta(self, task_id, cache=True): <ide> meta = self._get_task_meta_for(task_id) <ide> break <ide> except Exception as exc: <del> tb = sys.exc_info()[2] <ide> if self.always_retry and self.exception_safe_to_retry(exc): <ide> if retries < self.max_retries: <ide> retries += 1 <ide> def get_task_meta(self, task_id, cache=True): <ide> self.max_sleep_between_retries_ms, True) / 1000 <ide> self._sleep(sleep_amount) <ide> else: <del> reraise( <del> BackendGetMetaError, <add> raise_with_context( <ide> BackendGetMetaError("failed to get meta", task_id=task_id), <del> tb, <ide> ) <ide> else: <ide> raise
1
Javascript
Javascript
add hasownproperty checks where appropriate
6c331fba07d49f05594d6014899e2c95d159b5f2
<ide><path>src/addons/transitions/ReactTransitionChildMapping.js <ide> var ReactTransitionChildMapping = { <ide> <ide> var pendingKeys = []; <ide> for (var prevKey in prev) { <del> if (next[prevKey]) { <add> if (next.hasOwnProperty(prevKey)) { <ide> if (pendingKeys.length) { <ide> nextKeysPending[prevKey] = pendingKeys; <ide> pendingKeys = []; <ide> var ReactTransitionChildMapping = { <ide> var i; <ide> var childMapping = {}; <ide> for (var nextKey in next) { <del> if (nextKeysPending[nextKey]) { <add> if (nextKeysPending.hasOwnProperty(nextKey)) { <ide> for (i = 0; i < nextKeysPending[nextKey].length; i++) { <ide> var pendingNextKey = nextKeysPending[nextKey][i]; <ide> childMapping[nextKeysPending[nextKey][i]] = getValueForKey( <ide><path>src/addons/update.js <ide> function update(value, spec) { <ide> } <ide> <ide> for (var k in spec) { <del> if (!ALL_COMMANDS_SET[k]) { <add> if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) { <ide> nextValue[k] = update(value[k], spec[k]); <ide> } <ide> } <ide><path>src/browser/ReactEventEmitter.js <ide> var topEventMapping = { <ide> var topListenersIDKey = "_reactListenersID" + String(Math.random()).slice(2); <ide> <ide> function getListeningForDocument(mountAt) { <del> if (mountAt[topListenersIDKey] == null) { <add> if (!mountAt.hasOwnProperty(topListenersIDKey)) { <ide> mountAt[topListenersIDKey] = reactTopListenersCounter++; <ide> alreadyListeningTo[mountAt[topListenersIDKey]] = {}; <ide> } <ide> var ReactEventEmitter = merge(ReactEventEmitterMixin, { <ide> var topLevelTypes = EventConstants.topLevelTypes; <ide> for (var i = 0, l = dependencies.length; i < l; i++) { <ide> var dependency = dependencies[i]; <del> if (!isListening[dependency]) { <add> if (!( <add> isListening.hasOwnProperty(dependency) && <add> isListening[dependency] <add> )) { <ide> var topLevelType = topLevelTypes[dependency]; <ide> <ide> if (topLevelType === topLevelTypes.topWheel) { <ide> var ReactEventEmitter = merge(ReactEventEmitterMixin, { <ide> // to make sure blur and focus event listeners are only attached once <ide> isListening[topLevelTypes.topBlur] = true; <ide> isListening[topLevelTypes.topFocus] = true; <del> } else if (topEventMapping[dependency]) { <add> } else if (topEventMapping.hasOwnProperty(dependency)) { <ide> trapBubbledEvent(topLevelType, topEventMapping[dependency], mountAt); <ide> } <ide> <ide><path>src/browser/eventPlugins/AnalyticsEventPluginFactory.js <ide> function extractEvents( <ide> topLevelTargetID, <ide> nativeEvent) { <ide> var currentEvent = topLevelTypesToAnalyticsEvent[topLevelType]; <del> if (!currentEvent || !topLevelTarget || !topLevelTarget.attributes) { <add> if (!currentEvent || !topLevelTarget) { <ide> return null; <ide> } <ide> <del> var analyticsIDAttribute = topLevelTarget.attributes[ANALYTICS_ID]; <del> var analyticsEventsAttribute = topLevelTarget.attributes[ANALYTICS_EVENTS]; <del> if (!analyticsIDAttribute || !analyticsEventsAttribute) { <add> var analyticsID = topLevelTarget.getAttribute(ANALYTICS_ID); <add> var analyticsEventsStr = topLevelTarget.getAttribute(ANALYTICS_EVENTS); <add> if (!analyticsID || !analyticsEventsStr) { <ide> return null; <ide> } <ide> <del> var analyticsEventsArr = analyticsEventsAttribute.value.split(","); <del> var analyticsID = analyticsIDAttribute.value; <del> if (!analyticsData[analyticsID]) { <add> var analyticsEventsArr = analyticsEventsStr.split(","); <add> if (!analyticsData.hasOwnProperty(analyticsID)) { <ide> initAnalyticsDataForID(analyticsID, analyticsEventsArr); <ide> } <ide> <ide><path>src/browser/ui/ReactDOMComponent.js <ide> ReactDOMComponent.Mixin = { <ide> if (propValue == null) { <ide> continue; <ide> } <del> if (registrationNameModules[propKey]) { <add> if (registrationNameModules.hasOwnProperty(propKey)) { <ide> putListener(this._rootNodeID, propKey, propValue, transaction); <ide> } else { <ide> if (propKey === STYLE) { <ide> ReactDOMComponent.Mixin = { <ide> styleUpdates[styleName] = ''; <ide> } <ide> } <del> } else if (registrationNameModules[propKey]) { <add> } else if (registrationNameModules.hasOwnProperty(propKey)) { <ide> deleteListener(this._rootNodeID, propKey); <ide> } else if ( <ide> DOMProperty.isStandardName[propKey] || <ide> ReactDOMComponent.Mixin = { <ide> // Relies on `updateStylesByID` not mutating `styleUpdates`. <ide> styleUpdates = nextProp; <ide> } <del> } else if (registrationNameModules[propKey]) { <add> } else if (registrationNameModules.hasOwnProperty(propKey)) { <ide> putListener(this._rootNodeID, propKey, nextProp, transaction); <ide> } else if ( <ide> DOMProperty.isStandardName[propKey] || <ide><path>src/browser/ui/dom/DOMProperty.js <ide> var DOMPropertyInjection = { <ide> <ide> for (var propName in Properties) { <ide> invariant( <del> !DOMProperty.isStandardName[propName], <add> !DOMProperty.isStandardName.hasOwnProperty(propName), <ide> 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' + <ide> '\'%s\' which has already been injected. You may be accidentally ' + <ide> 'injecting the same DOM property config twice, or you may be ' + <ide> var DOMPropertyInjection = { <ide> var lowerCased = propName.toLowerCase(); <ide> DOMProperty.getPossibleStandardName[lowerCased] = propName; <ide> <del> var attributeName = DOMAttributeNames[propName]; <del> if (attributeName) { <add> if (DOMAttributeNames.hasOwnProperty(propName)) { <add> var attributeName = DOMAttributeNames[propName]; <ide> DOMProperty.getPossibleStandardName[attributeName] = propName; <add> DOMProperty.getAttributeName[propName] = attributeName; <add> } else { <add> DOMProperty.getAttributeName[propName] = lowerCased; <ide> } <ide> <del> DOMProperty.getAttributeName[propName] = attributeName || lowerCased; <del> <ide> DOMProperty.getPropertyName[propName] = <del> DOMPropertyNames[propName] || propName; <del> <del> var mutationMethod = DOMMutationMethods[propName]; <del> if (mutationMethod) { <del> DOMProperty.getMutationMethod[propName] = mutationMethod; <add> DOMPropertyNames.hasOwnProperty(propName) ? <add> DOMPropertyNames[propName] : <add> propName; <add> <add> if (DOMMutationMethods.hasOwnProperty(propName)) { <add> DOMProperty.getMutationMethod[propName] = DOMMutationMethods[propName]; <add> } else { <add> DOMProperty.getMutationMethod[propName] = null; <ide> } <ide> <ide> var propConfig = Properties[propName]; <ide><path>src/browser/ui/dom/DOMPropertyOperations.js <ide> if (__DEV__) { <ide> var warnedProperties = {}; <ide> <ide> var warnUnknownProperty = function(name) { <del> if (reactProps[name] || warnedProperties[name]) { <add> if (reactProps.hasOwnProperty(name) && reactProps[name] || <add> warnedProperties.hasOwnProperty(name) && warnedProperties[name]) { <ide> return; <ide> } <ide> <ide> warnedProperties[name] = true; <ide> var lowerCasedName = name.toLowerCase(); <ide> <ide> // data-* attributes should be lowercase; suggest the lowercase version <del> var standardName = DOMProperty.isCustomAttribute(lowerCasedName) ? <del> lowerCasedName : DOMProperty.getPossibleStandardName[lowerCasedName]; <add> var standardName = ( <add> DOMProperty.isCustomAttribute(lowerCasedName) ? <add> lowerCasedName : <add> DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? <add> DOMProperty.getPossibleStandardName[lowerCasedName] : <add> null <add> ); <ide> <ide> // For now, only warn when we have a suggested correction. This prevents <ide> // logging too much when using transferPropsTo. <ide> var DOMPropertyOperations = { <ide> * @return {?string} Markup string, or null if the property was invalid. <ide> */ <ide> createMarkupForProperty: function(name, value) { <del> if (DOMProperty.isStandardName[name]) { <add> if (DOMProperty.isStandardName.hasOwnProperty(name) && <add> DOMProperty.isStandardName[name]) { <ide> if (shouldIgnoreValue(name, value)) { <ide> return ''; <ide> } <ide> var DOMPropertyOperations = { <ide> * @param {*} value <ide> */ <ide> setValueForProperty: function(node, name, value) { <del> if (DOMProperty.isStandardName[name]) { <add> if (DOMProperty.isStandardName.hasOwnProperty(name) && <add> DOMProperty.isStandardName[name]) { <ide> var mutationMethod = DOMProperty.getMutationMethod[name]; <ide> if (mutationMethod) { <ide> mutationMethod(node, value); <ide> var DOMPropertyOperations = { <ide> * @param {string} name <ide> */ <ide> deleteValueForProperty: function(node, name) { <del> if (DOMProperty.isStandardName[name]) { <add> if (DOMProperty.isStandardName.hasOwnProperty(name) && <add> DOMProperty.isStandardName[name]) { <ide> var mutationMethod = DOMProperty.getMutationMethod[name]; <ide> if (mutationMethod) { <ide> mutationMethod(node, undefined); <ide><path>src/browser/ui/dom/dangerousStyleValue.js <ide> <ide> var CSSProperty = require('CSSProperty'); <ide> <add>var isUnitlessNumber = CSSProperty.isUnitlessNumber; <add> <ide> /** <del> * Convert a value into the proper css writable value. The `styleName` name <del> * name should be logical (no hyphens), as specified <add> * Convert a value into the proper css writable value. The style name `name` <add> * should be logical (no hyphens), as specified <ide> * in `CSSProperty.isUnitlessNumber`. <ide> * <del> * @param {string} styleName CSS property name such as `topMargin`. <add> * @param {string} name CSS property name such as `topMargin`. <ide> * @param {*} value CSS property value such as `10px`. <ide> * @return {string} Normalized style value with dimensions applied. <ide> */ <del>function dangerousStyleValue(styleName, value) { <add>function dangerousStyleValue(name, value) { <ide> // Note that we've removed escapeTextForBrowser() calls here since the <ide> // whole string will be escaped when the attribute is injected into <ide> // the markup. If you provide unsafe user data here they can inject <ide> function dangerousStyleValue(styleName, value) { <ide> } <ide> <ide> var isNonNumeric = isNaN(value); <del> if (isNonNumeric || value === 0 || CSSProperty.isUnitlessNumber[styleName]) { <add> if (isNonNumeric || value === 0 || <add> isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) { <ide> return '' + value; // cast to string <ide> } <ide> <ide><path>src/core/ReactCompositeComponent.js <ide> function validateTypeDef(Constructor, typeDef, location) { <ide> } <ide> <ide> function validateMethodOverride(proto, name) { <del> var specPolicy = ReactCompositeComponentInterface[name]; <add> var specPolicy = ReactCompositeComponentInterface.hasOwnProperty(name) ? <add> ReactCompositeComponentInterface[name] : <add> null; <ide> <ide> // Disallow overriding of base class methods unless explicitly allowed. <ide> if (ReactCompositeComponentMixin.hasOwnProperty(name)) { <ide> var ReactCompositeComponentMixin = { <ide> var props = merge(newProps); <ide> var defaultProps = this._defaultProps; <ide> for (var propName in defaultProps) { <del> if (typeof props[propName] === 'undefined') { <add> if (!props.hasOwnProperty(propName) || <add> typeof props[propName] === 'undefined') { <ide> props[propName] = defaultProps[propName]; <ide> } <ide> } <ide><path>src/event/EventPluginRegistry.js <ide> function recomputePluginOrdering() { <ide> */ <ide> function publishEventForPlugin(dispatchConfig, PluginModule, eventName) { <ide> invariant( <del> !EventPluginRegistry.eventNameDispatchConfigs[eventName], <add> !EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName), <ide> 'EventPluginHub: More than one plugin attempted to publish the same ' + <ide> 'event name, `%s`.', <ide> eventName <ide> var EventPluginRegistry = { <ide> continue; <ide> } <ide> var PluginModule = injectedNamesToPlugins[pluginName]; <del> if (namesToPlugins[pluginName] !== PluginModule) { <add> if (!namesToPlugins.hasOwnProperty(pluginName) || <add> namesToPlugins[pluginName] !== PluginModule) { <ide> invariant( <ide> !namesToPlugins[pluginName], <ide> 'EventPluginRegistry: Cannot inject two different event plugins ' +
10
Python
Python
update timedistributed docs
76c553e68f8f64ab49c255b4b0c1336c5243ac46
<ide><path>keras/layers/wrappers.py <ide> class TimeDistributed(Wrapper): <ide> model = Sequential() <ide> model.add(TimeDistributed(Dense(8), input_shape=(10, 16))) <ide> # now model.output_shape == (None, 10, 8) <add> ``` <add> <add> The output will then have shape `(32, 10, 8)`. <ide> <del> # subsequent layers: no need for input_shape <add> In subsequent layers, there is no need for the `input_shape`: <add> <add> ```python <ide> model.add(TimeDistributed(Dense(32))) <ide> # now model.output_shape == (None, 10, 32) <ide> ``` <ide> <del> The output will then have shape `(32, 10, 8)`. <add> The output will then have shape `(32, 10, 32)`. <ide> <ide> `TimeDistributed` can be used with arbitrary layers, not just `Dense`, <ide> for instance with a `Conv2D` layer:
1
Python
Python
allow broadcasting in merge layer
50057d8fe23de4e88c1b0b45eafc5bffd922a941
<ide><path>keras/layers/merge.py <ide> def __init__(self, **kwargs): <ide> def _merge_function(self, inputs): <ide> raise NotImplementedError <ide> <add> def _compute_elemwise_op_output_shape(self, shape1, shape2): <add> """Computes the shape of the resultant of an elementwise operation. <add> <add> # Arguments <add> shape1: tuple or None. Shape of the first tensor <add> shape2: tuple or None. Shape of the second tensor <add> <add> # Returns <add> expected output shape when an element-wise operation is <add> carried out on 2 tensors with shapes shape1 and shape2. <add> tuple or None. <add> <add> # Raises <add> ValueError if shape1 and shape2 are not compaible for <add> element-wise operations <add> """ <add> if None in [shape1, shape2]: <add> return None <add> elif len(shape1) < len(shape2): <add> return _compute_elemwise_op_output_shape(shape2, shape1) <add> elif len(shape2) == 0: <add> return shape1 <add> output_shape = list(shape1[:-len(shape2)]) <add> for i, j in zip(shape1[-len(shape2):], shape2): <add> if i is None or j is None: <add> output_shape.append(None) <add> elif i == 1: <add> output_shape.append(j) <add> elif j == 1: <add> output_shape.append(i) <add> else: <add> if i != j: <add> raise ValueError('Operands could not be broadcast ' <add> 'together with shapes ' + <add> str(shape1) + ' ' + str(shape2)) <add> output_shape.append(i) <add> return tuple(output_shape) <add> <ide> def build(self, input_shape): <ide> # Used purely for shape validation. <ide> if not isinstance(input_shape, list): <ide> def build(self, input_shape): <ide> raise ValueError('A merge layer should be called ' <ide> 'on a list of at least 2 inputs. ' <ide> 'Got ' + str(len(input_shape)) + ' inputs.') <del> if all([shape is None for shape in input_shape]): <del> return <del> # TODO: handle shapes with None entries. <del> input_shapes_set = set(input_shape) <del> if None in input_shapes_set: <del> input_shapes_set.remove(None) <del> if len(input_shapes_set) > 1: <del> raise ValueError('Only tensors of same shape can ' <del> 'be merged by layer' + self.name + <del> ' Got input shapes: %s' % input_shape) <add> batch_sizes = [s[0] for s in input_shape if s is not None] <add> batch_sizes = set(batch_sizes) <add> batch_sizes -= set([None]) <add> if len(batch_sizes) > 1: <add> raise ValueError('Can not merge tensors with different ' <add> 'batch sizes. Got tensors with shapes : ' + <add> str(input_shape)) <add> if input_shape[0] is None: <add> output_shape = None <add> else: <add> output_shape = input_shape[0][1:] <add> for i in range(1, len(input_shape)): <add> if input_shape[i] is None: <add> shape = None <add> else: <add> shape = input_shape[i][1:] <add> output_shape = self._compute_elemwise_op_output_shape(output_shape, shape) <add> # If the inputs have different ranks, we have to reshape them <add> # to make them broadcastable. <add> if None not in input_shape and len(set(map(len, input_shape))) == 1: <add> self._reshape_required = False <add> else: <add> self._reshape_required = True <ide> <ide> def call(self, inputs): <del> return self._merge_function(inputs) <add> if self._reshape_required: <add> reshaped_inputs = [] <add> input_ndims = list(map(K.ndim, inputs)) <add> if None not in input_ndims: <add> # If ranks of all inputs are available, <add> # we simply expand each of them at axis=1 <add> # until all of them have the same rank. <add> max_ndim = max(input_ndims) <add> for x in inputs: <add> x_ndim = K.ndim(x) <add> for _ in range(max_ndim - x_ndim): <add> x = K.expand_dims(x, 1) <add> reshaped_inputs.append(x) <add> return self._merge_function(reshaped_inputs) <add> else: <add> # Transpose all inputs so that batch size is the last dimension. <add> # (batch_size, dim1, dim2, ... ) -> (dim1, dim2, ... , batch_size) <add> transposed = False <add> for x in inputs: <add> x_ndim = K.ndim(x) <add> if x_ndim is None: <add> x_shape = K.shape(x) <add> batch_size = x_shape[0] <add> new_shape = K.concatenate([x_shape[1:], K.expand_dims(batch_size)]) <add> x_transposed = K.reshape(x, K.stack([batch_size, K.prod(x_shape[1:])])) <add> x_transposed = K.permute_dimensions(x_transposed, (1, 0)) <add> x_transposed = K.reshape(x_transposed, new_shape) <add> reshaped_inputs.append(x_transposed) <add> transposed = True <add> elif x_ndim > 1: <add> dims = list(range(1, x_ndim)) + [0] <add> reshaped_inputs.append(K.permute_dimensions(x, dims)) <add> transposed = True <add> else: <add> # We don't transpose inputs if they are 1D vectors or scalars. <add> reshaped_inputs.append(x) <add> y = self._merge_function(reshaped_inputs) <add> y_ndim = K.ndim(y) <add> if transposed: <add> # If inputs have been transposed, we have to transpose the output too. <add> if y_ndim is None: <add> y_shape = K.shape(y) <add> y_ndim = K.shape(y_shape)[0] <add> batch_size = y_shape[y_ndim - 1] <add> new_shape = K.concatenate([K.expand_dims(batch_size), y_shape[:y_ndim - 1]]) <add> y = K.reshape(y, (-1, batch_size)) <add> y = K.permute_dimensions(y, (1, 0)) <add> y = K.reshape(y, new_shape) <add> elif y_ndim > 1: <add> dims = [y_ndim - 1] + list(range(y_ndim - 1)) <add> y = K.permute_dimensions(y, dims) <add> return y <add> else: <add> return self._merge_function(inputs) <add> <add> def compute_output_shape(self, input_shape): <add> if input_shape[0] is None: <add> output_shape = None <add> else: <add> output_shape = input_shape[0][1:] <add> for i in range(1, len(input_shape)): <add> if input_shape[i] is None: <add> shape = None <add> else: <add> shape = input_shape[i][1:] <add> output_shape = self._compute_elemwise_op_output_shape(output_shape, shape) <add> batch_sizes = [s[0] for s in input_shape if s is not None] <add> batch_sizes = set(batch_sizes) <add> batch_sizes -= set([None]) <add> if len(batch_sizes) == 1: <add> output_shape = (batch_sizes[0],) + output_shape <add> else: <add> output_shape = (None,) + output_shape <add> return output_shape <ide> <ide> def compute_output_shape(self, input_shape): <ide> # Layers that change the shape should already implement <ide><path>tests/keras/layers/merge_test.py <ide> from numpy.testing import assert_allclose <ide> from keras import layers <ide> from keras import models <add>from keras import backend as K <ide> from keras.utils.test_utils import layer_test <ide> from keras.utils.test_utils import keras_test <ide> from keras.layers import merge <ide> def test_merge_dot(): <ide> assert_allclose(out, expected, atol=1e-4) <ide> <ide> <add>@keras_test <add>def test_merge_broadcast(): <add> # shapes provided <add> i1 = layers.Input(shape=(4, 5)) <add> i2 = layers.Input(shape=(5,)) <add> ops = [layers.add, layers.maximum] <add> for op in ops: <add> o = op([i1, i2]) <add> assert o._keras_shape == (None, 4, 5) <add> model = models.Model([i1, i2], o) <add> <add> x1 = np.random.random((2, 4, 5)) <add> x2 = np.random.random((2, 5)) <add> out = model.predict([x1, x2]) <add> assert out.shape == (2, 4, 5) <add> <add> # shapes not provided <add> i1 = layers.Input(shape=(None, None)) <add> i2 = layers.Input(shape=(None,)) <add> ops = [layers.add, layers.maximum] <add> for op in ops: <add> o = op([i1, i2]) <add> assert o._keras_shape == (None, None, None) <add> model = models.Model([i1, i2], o) <add> <add> x1 = np.random.random((2, 4, 5)) <add> x2 = np.random.random((2, 5)) <add> out = model.predict([x1, x2]) <add> assert out.shape == (2, 4, 5) <add> <add> # ndim not provided <add> if K.backend() == 'tensorflow': <add> k_ndim = K.ndim <add> K.ndim = lambda _: None <add> <add> i1 = layers.Input(shape=(None, None)) <add> i2 = layers.Input(shape=(None,)) <add> ops = [layers.add, layers.maximum] <add> for op in ops: <add> o = op([i1, i2]) <add> assert o._keras_shape == (None, None, None) <add> model = models.Model([i1, i2], o) <add> <add> x1 = np.random.random((2, 4, 5)) <add> x2 = np.random.random((2, 5)) <add> out = model.predict([x1, x2]) <add> assert out.shape == (2, 4, 5) <add> K.ndim = k_ndim <add> <add> <ide> if __name__ == '__main__': <ide> pytest.main([__file__])
2
Ruby
Ruby
add test for `decide_between_versions`
933499089cbba28ba37cc8671685c85d6cd9c6e0
<ide><path>Library/Homebrew/dev-cmd/bump-unversioned-casks.rb <ide> def self.guess_cask_version(cask, installer) <ide> end <ide> <ide> info_plist_paths.each do |info_plist_path| <del> if (version = version_from_info_plist(cask, info_plist_path)) <add> if (version = version_from_info_plist(info_plist_path)) <ide> return version <ide> end <ide> end <ide> def self.guess_cask_version(cask, installer) <ide> <ide> package_info_path = extract_dir/"PackageInfo" <ide> if package_info_path.exist? <del> if (version = version_from_package_info(cask, package_info_path)) <add> if (version = version_from_package_info(package_info_path)) <ide> return version <ide> end <ide> else <ide> def self.guess_cask_version(cask, installer) <ide> end <ide> end <ide> <del> sig { params(cask: Cask::Cask, info_plist_path: Pathname).returns(T.nilable(String)) } <del> def self.version_from_info_plist(cask, info_plist_path) <add> sig { params(info_plist_path: Pathname).returns(T.nilable(String)) } <add> def self.version_from_info_plist(info_plist_path) <ide> plist = system_command!("plutil", args: ["-convert", "xml1", "-o", "-", info_plist_path]).plist <ide> <ide> short_version = plist["CFBundleShortVersionString"] <ide> version = plist["CFBundleVersion"] <ide> <del> return decide_between_versions(cask, short_version, version) if short_version && version <add> return decide_between_versions(short_version, version) if short_version && version <ide> end <ide> <del> sig { params(cask: Cask::Cask, package_info_path: Pathname).returns(T.nilable(String)) } <del> def self.version_from_package_info(cask, package_info_path) <add> sig { params(package_info_path: Pathname).returns(T.nilable(String)) } <add> def self.version_from_package_info(package_info_path) <ide> contents = package_info_path.read <ide> <ide> short_version = contents[/CFBundleShortVersionString="([^"]*)"/, 1] <ide> version = contents[/CFBundleVersion="([^"]*)"/, 1] <ide> <del> return decide_between_versions(cask, short_version, version) if short_version && version <add> return decide_between_versions(short_version, version) if short_version && version <ide> end <ide> <ide> sig do <del> params(cask: Cask::Cask, short_version: T.nilable(String), version: T.nilable(String)) <add> params(short_version: T.nilable(String), version: T.nilable(String)) <ide> .returns(T.nilable(String)) <ide> end <del> def self.decide_between_versions(cask, short_version, version) <del> return "#{short_version},#{version}" if short_version && version && cask.version.include?(",") <add> def self.decide_between_versions(short_version, version) <ide> <del> return cask.version.to_s if [short_version, version].include?(cask.version.to_s) <add> return short_version if short_version == version <ide> <ide> short_version_match = short_version&.match?(/\A\d+(\.\d+)+\Z/) <ide> version_match = version&.match?(/\A\d+(\.\d+)+\Z/) <ide> <ide> if short_version_match && version_match <ide> return version if version.length > short_version.length && version.start_with?(short_version) <ide> return short_version if short_version.length > version.length && short_version.start_with?(version) <del> elsif short_version_match <del> return short_version <del> elsif version_match <del> return version <ide> end <ide> <add> return "#{short_version},#{version}" if short_version&.match?(/\A\d+(\.\d+)*\Z/) && version&.match?(/\A\d+\Z/) <add> <ide> short_version || version <ide> end <ide> <ide><path>Library/Homebrew/test/dev-cmd/bump-unversioned-casks_spec.rb <add># typed: false <add># frozen_string_literal: true <add> <add>require "cmd/shared_examples/args_parse" <add>require "dev-cmd/bump-unversioned-casks" <add> <add>describe "Homebrew.bump_unversioned_casks_args" do <add> it_behaves_like "parseable arguments" <add> <add> describe "::decide_between_versions" do <add> expected_mappings = { <add> [nil, nil] => nil, <add> ["1.2", nil] => "1.2", <add> [nil, "1.2.3"] => "1.2.3", <add> ["1.2", "1.2.3"] => "1.2.3", <add> ["1.2.3", "1.2"] => "1.2.3", <add> ["1.2.3", "8312"] => "1.2.3,8312", <add> ["2021", "2006"] => "2021,2006", <add> } <add> <add> expected_mappings.each do |(short_version, version), expected_version| <add> it "maps (#{short_version}, #{version}) to #{expected_version}" do <add> expect(Homebrew.decide_between_versions(short_version, version)).to eq expected_version <add> end <add> end <add> end <add>end
2
Javascript
Javascript
extract a utility method on project
6d2e298de1d04326be8ab14c0846e14b4897e4f1
<ide><path>src/project.js <ide> class Project extends Model { <ide> } <ide> } <ide> <del> getDirectoryForProjectPath (projectPath) { <del> let directory = null <add> getProvidedDirectoryForProjectPath (projectPath) { <ide> for (let provider of this.directoryProviders) { <ide> if (typeof provider.directoryForURISync === 'function') { <del> directory = provider.directoryForURISync(projectPath) <del> if (directory) break <add> const directory = provider.directoryForURISync(projectPath) <add> if (directory) { <add> return directory <add> } <ide> } <ide> } <add> return null <add> } <add> <add> getDirectoryForProjectPath (projectPath) { <add> let directory = this.getProvidedDirectoryForProjectPath(projectPath) <ide> if (directory == null) { <ide> directory = this.defaultDirectoryProvider.directoryForURISync(projectPath) <ide> }
1
Python
Python
fix model templates
763ece2feadf51fc5a26c5acbcdf49bab119f3bd
<ide><path>templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_tf_{{cookiecutter.lowercase_modelname}}.py <ide> def __init__(self, config: {{cookiecutter.camelcase_modelname}}Config, input_emb <ide> def build(self, input_shape: tf.TensorShape): <ide> self.bias = self.add_weight(shape=(self.vocab_size,), initializer="zeros", trainable=True, name="bias") <ide> <del> super().build(input_shape=input_shape) <add> super().build(input_shape) <ide> <ide> def get_output_embeddings(self) -> tf.keras.layers.Layer: <ide> return self.input_embeddings <ide> def serving_output(self, output: TFBaseModelOutput) -> TFBaseModelOutput: <ide> hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None <ide> attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None <ide> <del> return TFBaseModelOutput( <del> last_hidden_state=output.last_hidden_state, hidden_states=hs, attentions=attns, <del> ) <add> return TFBaseModelOutput(last_hidden_state=output.last_hidden_state, hidden_states=hs, attentions=attns) <ide> <ide> <ide> @add_start_docstrings("""{{cookiecutter.modelname}} Model with a `language modeling` head on top. """, {{cookiecutter.uppercase_modelname}}_START_DOCSTRING)
1
Text
Text
add a summary paragraph.
76bf9b9d7e2cf4ac5305f5047666f034ba710c4c
<ide><path>guide/english/agile/minimum-viable-product/index.md <ide> The idea is to rapidly build a minimum set of features that is enough to deploy <ide> - It demonstrates enough future benefit to retain early adopters. <ide> - It provides a feedback loop to guide future development. <ide> <add>The advantage of iterative MVP (instead of building full scale goal product without delivering any value along the way) is the ability of very quick market verification. <add> <ide> Learn more about MVP: <ide> <a href='https://youtu.be/MHJn_SubN4E' target='_blank' rel='nofollow'>What is a Minimum Viable Product (MVP)</a> <ide>
1
PHP
PHP
throw exception on missing required parameter
4a414c58a634eea030dcafff10b7161ab46684cb
<ide><path>src/Illuminate/Container/BoundMethod.php <ide> namespace Illuminate\Container; <ide> <ide> use Closure; <add>use Illuminate\Contracts\Container\BindingResolutionException; <ide> use InvalidArgumentException; <ide> use ReflectionFunction; <ide> use ReflectionMethod; <ide> protected static function addDependencyForCallParameter($container, $parameter, <ide> $dependencies[] = $container->make($parameter->getClass()->name); <ide> } elseif ($parameter->isDefaultValueAvailable()) { <ide> $dependencies[] = $parameter->getDefaultValue(); <add> } elseif(!$parameter->isOptional() && !array_key_exists($parameter->name, $parameters)) { <add> $message = "Unresolvable dependency resolving [$parameter] in class {$parameter->getDeclaringClass()->getName()}"; <add> <add> throw new BindingResolutionException($message); <ide> } <ide> } <ide> <ide><path>tests/Container/ContainerCallTest.php <ide> <ide> use Closure; <ide> use Illuminate\Container\Container; <add>use Illuminate\Contracts\Container\BindingResolutionException; <ide> use PHPUnit\Framework\TestCase; <ide> use ReflectionException; <ide> use stdClass; <ide> public function testCallWithCallableObject() <ide> $this->assertInstanceOf(ContainerCallConcreteStub::class, $result[0]); <ide> $this->assertSame('jeffrey', $result[1]); <ide> } <add> <add> public function testCallWithoutRequiredParamsThrowsException() <add> { <add> $this->expectException(BindingResolutionException::class); <add> $this->expectExceptionMessage('Unresolvable dependency resolving [Parameter #0 [ <required> $foo ]] in class Illuminate\Tests\Container\ContainerTestCallStub'); <add> <add> $container = new Container; <add> $container->call(ContainerTestCallStub::class . '@unresolvable'); <add> } <ide> } <ide> <ide> class ContainerTestCallStub
2
Javascript
Javascript
stop unnecessary `jquery.fn` extension
3a55a881c6a911a6ab1d100a0bbfa5d6c482afe1
<ide><path>packages/ember-handlebars/tests/handlebars_test.js <ide> var firstChild = nthChild; <ide> <ide> var originalLog, logCalls; <ide> <del>(function() { <add>var caretPosition = function (element) { <add> var ctrl = element[0]; <add> var caretPos = 0; <ide> <del> Ember.$.fn.caretPosition = function() { <del> var ctrl = this[0]; <add> // IE Support <add> if (document.selection) { <add> ctrl.focus(); <add> var selection = document.selection.createRange(); <ide> <del> var CaretPos = 0; <del> // IE Support <del> if (document.selection) { <add> selection.moveStart('character', -ctrl.value.length); <ide> <del> ctrl.focus(); <del> var Sel = document.selection.createRange (); <del> <del> Sel.moveStart ('character', -ctrl.value.length); <del> <del> CaretPos = Sel.text.length; <del> } <del> // Firefox support <del> else if (ctrl.selectionStart || ctrl.selectionStart === '0') { <del> CaretPos = ctrl.selectionStart; <del> } <del> <del> return (CaretPos); <del> }; <del> <del> <del> Ember.$.fn.setCaretPosition = function(pos) { <del> var ctrl = this[0]; <add> caretPos = selection.text.length; <add> } <add> // Firefox support <add> else if (ctrl.selectionStart || ctrl.selectionStart === '0') { <add> caretPos = ctrl.selectionStart; <add> } <ide> <del> if(ctrl.setSelectionRange) { <del> ctrl.focus(); <del> ctrl.setSelectionRange(pos,pos); <del> } else if (ctrl.createTextRange) { <del> var range = ctrl.createTextRange(); <del> range.collapse(true); <del> range.moveEnd('character', pos); <del> range.moveStart('character', pos); <del> range.select(); <del> } <del> }; <add> return caretPos; <add>}; <ide> <del>})(); <add>var setCaretPosition = function (element, pos) { <add> var ctrl = element[0]; <add> <add> if (ctrl.setSelectionRange) { <add> ctrl.focus(); <add> ctrl.setSelectionRange(pos,pos); <add> } else if (ctrl.createTextRange) { <add> var range = ctrl.createTextRange(); <add> range.collapse(true); <add> range.moveEnd('character', pos); <add> range.moveStart('character', pos); <add> range.select(); <add> } <add>}; <ide> <ide> var view; <ide> <ide> test("should not reset cursor position when text field receives keyUp event", fu <ide> }); <ide> <ide> view.$().val('Brosiedoon, King of the Brocean'); <del> view.$().setCaretPosition(5); <add> setCaretPosition(view.$(), 5); <ide> <ide> Ember.run(function() { <ide> view.trigger('keyUp', {}); <ide> }); <ide> <del> equal(view.$().caretPosition(), 5, "The keyUp event should not result in the cursor being reset due to the bindAttr observers"); <add> equal(caretPosition(view.$()), 5, "The keyUp event should not result in the cursor being reset due to the bindAttr observers"); <ide> <ide> Ember.run(function() { <ide> view.destroy();
1
PHP
PHP
update use of deprecated method
f71159032c608705fd1aaf3b79c2f5acbd0a530c
<ide><path>tests/TestCase/Database/Type/BinaryTypeTest.php <ide> public function testToPHP() <ide> $this->assertNull($this->type->toPHP(null, $this->driver)); <ide> <ide> $result = $this->type->toPHP('some data', $this->driver); <del> $this->assertInternalType('resource', $result); <add> $this->assertIsResource($result); <ide> <ide> $fh = fopen(__FILE__, 'r'); <ide> $result = $this->type->toPHP($fh, $this->driver); <ide><path>tests/TestCase/Database/Type/BinaryUuidTypeTest.php <ide> public function testToPHP() <ide> $fh = fopen(__FILE__, 'r'); <ide> $result = $this->type->toPHP($fh, $this->driver); <ide> $this->assertSame($fh, $result); <del> $this->assertInternalType('resource', $result); <add> $this->assertIsResource($result); <ide> fclose($fh); <ide> } <ide>
2
PHP
PHP
remove unused variables
3e8ab0ad8f5086e8ef3d0f5766f1a0e48b21bce1
<ide><path>src/TestSuite/Fixture/FixtureManager.php <ide> public function load($test) <ide> $this->_insertionMap[$configName] = []; <ide> } <ide> <del> foreach ($fixtures as $name => $fixture) { <add> foreach ($fixtures as $fixture) { <ide> if (in_array($fixture->table, $tables)) { <ide> try { <ide> $fixture->dropConstraints($db); <ide> public function load($test) <ide> } <ide> } <ide> <del> foreach ($fixtures as $name => $fixture) { <add> foreach ($fixtures as $fixture) { <ide> try { <ide> $fixture->createConstraints($db); <ide> } catch (PDOException $e) {
1
Javascript
Javascript
add test for range clamping
5bae5f47889e751e5ebf3560814c8cb1c57af6e1
<ide><path>test/scale/linear-test.js <ide> suite.addBatch({ <ide> assert.inDelta(x(-.5), 1, 1e-6); <ide> assert.inDelta(x(.5), .5, 1e-6); <ide> assert.inDelta(x(1.5), 0, 1e-6); <add> }, <add> "can clamp to the range": function(linear) { <add> var x = linear().clamp(true); <add> assert.inDelta(x.invert(-.5), 0, 1e-6); <add> assert.inDelta(x.invert(.5), .5, 1e-6); <add> assert.inDelta(x.invert(1.5), 1, 1e-6); <add> var x = linear().range([1, 0]).clamp(true); <add> assert.inDelta(x.invert(-.5), 1, 1e-6); <add> assert.inDelta(x.invert(.5), .5, 1e-6); <add> assert.inDelta(x.invert(1.5), 0, 1e-6); <ide> } <ide> }, <ide>
1
Javascript
Javascript
remove control.$form and use nullformctrl
4806d28a29ae5c3f83d8f97c11e692ca2313c9ab
<ide><path>src/directive/form.js <ide> var nullFormCtrl = { <ide> $addControl: noop, <ide> $removeControl: noop, <del> $setValidity: noop <add> $setValidity: noop, <add> $setDirty: noop <ide> } <ide> <ide> /** <ide><path>src/directive/input.js <ide> var inputDirective = [function() { <ide> * @description <ide> * <ide> */ <del>var NgModelController = ['$scope', '$exceptionHandler', '$attrs', 'ngModel', <del> function($scope, $exceptionHandler, $attr, ngModel) { <add>var NgModelController = ['$scope', '$exceptionHandler', '$attrs', 'ngModel', '$element', <add> function($scope, $exceptionHandler, $attr, ngModel, $element) { <ide> this.$viewValue = Number.NaN; <ide> this.$modelValue = Number.NaN; <ide> this.$parsers = []; <ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', 'ngModel', <ide> this.$render = noop; <ide> this.$name = $attr.name; <ide> <add> var parentForm = $element.inheritedData('$formController') || nullFormCtrl; <ide> <ide> /** <ide> * @ngdoc function <ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', 'ngModel', <ide> this.$valid = false; <ide> } <ide> <del> if (this.$form) { <del> this.$form.$setValidity(validationErrorKey, isValid, this); <del> } <add> parentForm.$setValidity(validationErrorKey, isValid, this); <ide> }; <ide> <ide> <ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', 'ngModel', <ide> if (this.$pristine) { <ide> this.$dirty = true; <ide> this.$pristine = false; <del> if (this.$form) this.$form.$setDirty(); <add> parentForm.$setDirty(); <ide> } <ide> <ide> forEach(this.$parsers, function(fn) { <ide> var ngModelDirective = [function() { <ide> // notify others, especially parent forms <ide> <ide> var modelCtrl = ctrls[0], <del> formCtrl = ctrls[1]; <del> <del> modelCtrl.$form = formCtrl; <add> formCtrl = ctrls[1] || nullFormCtrl; <ide> <del> if (formCtrl) formCtrl.$addControl(modelCtrl); <add> formCtrl.$addControl(modelCtrl); <ide> <ide> forEach(['valid', 'invalid', 'pristine', 'dirty'], function(name) { <ide> scope.$watch(function() { <ide> var ngModelDirective = [function() { <ide> }); <ide> <ide> element.bind('$destroy', function() { <del> if (formCtrl) formCtrl.$removeControl(modelCtrl); <add> formCtrl.$removeControl(modelCtrl); <ide> }); <ide> } <ide> }; <ide><path>test/directive/inputSpec.js <ide> 'use strict'; <ide> <ide> describe('NgModelController', function() { <del> var ctrl, scope, ngModelAccessor; <add> var ctrl, scope, ngModelAccessor, element, parentFormCtrl; <ide> <ide> beforeEach(inject(function($rootScope, $controller) { <ide> var attrs = {name: 'testAlias'}; <ide> <add> parentFormCtrl = { <add> $setValidity: jasmine.createSpy('$setValidity'), <add> $setDirty: jasmine.createSpy('$setDirty') <add> } <add> <add> element = jqLite('<form><input></form>'); <add> element.data('$formController', parentFormCtrl); <add> <ide> scope = $rootScope; <ide> ngModelAccessor = jasmine.createSpy('ngModel accessor'); <del> ctrl = $controller(NgModelController, {$scope: scope, ngModel: ngModelAccessor, $attrs: attrs}); <del> <add> ctrl = $controller(NgModelController, { <add> $scope: scope, $element: element.find('input'), ngModel: ngModelAccessor, $attrs: attrs <add> }); <ide> // mock accessor (locals) <ide> ngModelAccessor.andCallFake(function(val) { <ide> if (isDefined(val)) scope.value = val; <ide> describe('NgModelController', function() { <ide> })); <ide> <ide> <add> afterEach(function() { <add> dealoc(element); <add> }); <add> <add> <ide> it('should init the properties', function() { <ide> expect(ctrl.$dirty).toBe(false); <ide> expect(ctrl.$pristine).toBe(true); <ide> describe('NgModelController', function() { <ide> describe('setValidity', function() { <ide> <ide> it('should propagate invalid to the parent form only when valid', function() { <del> var spy = jasmine.createSpy('setValidity'); <del> ctrl.$form = {$setValidity: spy}; <del> <add> expect(parentFormCtrl.$setValidity).not.toHaveBeenCalled(); <ide> ctrl.$setValidity('ERROR', false); <del> expect(spy).toHaveBeenCalledOnceWith('ERROR', false, ctrl); <add> expect(parentFormCtrl.$setValidity).toHaveBeenCalledOnceWith('ERROR', false, ctrl); <ide> <del> spy.reset(); <add> parentFormCtrl.$setValidity.reset(); <ide> ctrl.$setValidity('ERROR', false); <del> expect(spy).not.toHaveBeenCalled(); <add> expect(parentFormCtrl.$setValidity).not.toHaveBeenCalled(); <ide> }); <ide> <ide> <ide> describe('NgModelController', function() { <ide> <ide> <ide> it('should emit $valid only when $invalid', function() { <del> var spy = jasmine.createSpy('setValidity'); <del> ctrl.$form = {$setValidity: spy}; <del> <ide> ctrl.$setValidity('ERROR', true); <del> expect(spy).not.toHaveBeenCalled(); <add> expect(parentFormCtrl.$setValidity).not.toHaveBeenCalled(); <ide> <ide> ctrl.$setValidity('ERROR', false); <del> expect(spy).toHaveBeenCalledOnceWith('ERROR', false, ctrl); <del> spy.reset(); <add> expect(parentFormCtrl.$setValidity).toHaveBeenCalledOnceWith('ERROR', false, ctrl); <add> parentFormCtrl.$setValidity.reset(); <ide> ctrl.$setValidity('ERROR', true); <del> expect(spy).toHaveBeenCalledOnceWith('ERROR', true, ctrl); <add> expect(parentFormCtrl.$setValidity).toHaveBeenCalledOnceWith('ERROR', true, ctrl); <ide> }); <ide> }); <ide> <ide> describe('NgModelController', function() { <ide> }); <ide> <ide> <del> it('should call parentForm.setDirty only when pristine', function() { <del> var spy = jasmine.createSpy('setDirty'); <del> ctrl.$form = {$setDirty: spy}; <del> <add> it('should call parentForm.$setDirty only when pristine', function() { <ide> ctrl.$setViewValue(''); <ide> expect(ctrl.$pristine).toBe(false); <ide> expect(ctrl.$dirty).toBe(true); <del> expect(spy).toHaveBeenCalledOnce(); <add> expect(parentFormCtrl.$setDirty).toHaveBeenCalledOnce(); <ide> <del> spy.reset(); <add> parentFormCtrl.$setDirty.reset(); <ide> ctrl.$setViewValue(''); <ide> expect(ctrl.$pristine).toBe(false); <ide> expect(ctrl.$dirty).toBe(true); <del> expect(spy).not.toHaveBeenCalled(); <add> expect(parentFormCtrl.$setDirty).not.toHaveBeenCalled(); <ide> }); <ide> }); <ide>
3
Go
Go
fix concurrent uploads that share layers
5c99eebe81958a227dfaed1145840374ce50bbbb
<ide><path>distribution/push_v2.go <ide> type v2Pusher struct { <ide> config *ImagePushConfig <ide> repo distribution.Repository <ide> <del> // pushState is state built by the Download functions. <add> // pushState is state built by the Upload functions. <ide> pushState pushState <ide> } <ide> <ide> type v2PushDescriptor struct { <ide> repoInfo reference.Named <ide> repo distribution.Repository <ide> pushState *pushState <add> remoteDescriptor distribution.Descriptor <ide> } <ide> <ide> func (pd *v2PushDescriptor) Key() string { <ide> func (pd *v2PushDescriptor) DiffID() layer.DiffID { <ide> return pd.layer.DiffID() <ide> } <ide> <del>func (pd *v2PushDescriptor) Upload(ctx context.Context, progressOutput progress.Output) error { <add>func (pd *v2PushDescriptor) Upload(ctx context.Context, progressOutput progress.Output) (distribution.Descriptor, error) { <ide> diffID := pd.DiffID() <ide> <ide> pd.pushState.Lock() <del> if _, ok := pd.pushState.remoteLayers[diffID]; ok { <add> if descriptor, ok := pd.pushState.remoteLayers[diffID]; ok { <ide> // it is already known that the push is not needed and <ide> // therefore doing a stat is unnecessary <ide> pd.pushState.Unlock() <ide> progress.Update(progressOutput, pd.ID(), "Layer already exists") <del> return nil <add> return descriptor, nil <ide> } <ide> pd.pushState.Unlock() <ide> <ide> func (pd *v2PushDescriptor) Upload(ctx context.Context, progressOutput progress. <ide> descriptor, exists, err := layerAlreadyExists(ctx, v2Metadata, pd.repoInfo, pd.repo, pd.pushState) <ide> if err != nil { <ide> progress.Update(progressOutput, pd.ID(), "Image push failed") <del> return retryOnError(err) <add> return distribution.Descriptor{}, retryOnError(err) <ide> } <ide> if exists { <ide> progress.Update(progressOutput, pd.ID(), "Layer already exists") <ide> pd.pushState.Lock() <ide> pd.pushState.remoteLayers[diffID] = descriptor <ide> pd.pushState.Unlock() <del> return nil <add> return descriptor, nil <ide> } <ide> } <ide> <ide> func (pd *v2PushDescriptor) Upload(ctx context.Context, progressOutput progress. <ide> <ide> // Cache mapping from this layer's DiffID to the blobsum <ide> if err := pd.v2MetadataService.Add(diffID, metadata.V2Metadata{Digest: mountFrom.Digest, SourceRepository: pd.repoInfo.FullName()}); err != nil { <del> return xfer.DoNotRetry{Err: err} <add> return distribution.Descriptor{}, xfer.DoNotRetry{Err: err} <ide> } <del> return nil <add> return err.Descriptor, nil <ide> case nil: <ide> // blob upload session created successfully, so begin the upload <ide> mountAttemptsRemaining = 0 <ide> func (pd *v2PushDescriptor) Upload(ctx context.Context, progressOutput progress. <ide> if layerUpload == nil { <ide> layerUpload, err = bs.Create(ctx) <ide> if err != nil { <del> return retryOnError(err) <add> return distribution.Descriptor{}, retryOnError(err) <ide> } <ide> } <ide> defer layerUpload.Close() <ide> <ide> arch, err := pd.layer.TarStream() <ide> if err != nil { <del> return xfer.DoNotRetry{Err: err} <add> return distribution.Descriptor{}, xfer.DoNotRetry{Err: err} <ide> } <ide> <ide> // don't care if this fails; best effort <ide> func (pd *v2PushDescriptor) Upload(ctx context.Context, progressOutput progress. <ide> nn, err := layerUpload.ReadFrom(tee) <ide> compressedReader.Close() <ide> if err != nil { <del> return retryOnError(err) <add> return distribution.Descriptor{}, retryOnError(err) <ide> } <ide> <ide> pushDigest := digester.Digest() <ide> if _, err := layerUpload.Commit(ctx, distribution.Descriptor{Digest: pushDigest}); err != nil { <del> return retryOnError(err) <add> return distribution.Descriptor{}, retryOnError(err) <ide> } <ide> <ide> logrus.Debugf("uploaded layer %s (%s), %d bytes", diffID, pushDigest, nn) <ide> progress.Update(progressOutput, pd.ID(), "Pushed") <ide> <ide> // Cache mapping from this layer's DiffID to the blobsum <ide> if err := pd.v2MetadataService.Add(diffID, metadata.V2Metadata{Digest: pushDigest, SourceRepository: pd.repoInfo.FullName()}); err != nil { <del> return xfer.DoNotRetry{Err: err} <add> return distribution.Descriptor{}, xfer.DoNotRetry{Err: err} <ide> } <ide> <ide> pd.pushState.Lock() <ide> func (pd *v2PushDescriptor) Upload(ctx context.Context, progressOutput progress. <ide> // speaks the v2 protocol. <ide> pd.pushState.confirmedV2 = true <ide> <del> pd.pushState.remoteLayers[diffID] = distribution.Descriptor{ <add> descriptor := distribution.Descriptor{ <ide> Digest: pushDigest, <ide> MediaType: schema2.MediaTypeLayer, <ide> Size: nn, <ide> } <add> pd.pushState.remoteLayers[diffID] = descriptor <ide> <ide> pd.pushState.Unlock() <ide> <del> return nil <add> return descriptor, nil <add>} <add> <add>func (pd *v2PushDescriptor) SetRemoteDescriptor(descriptor distribution.Descriptor) { <add> pd.remoteDescriptor = descriptor <ide> } <ide> <ide> func (pd *v2PushDescriptor) Descriptor() distribution.Descriptor { <del> // Not necessary to lock pushStatus because this is always <del> // called after all the mutation in pushStatus. <del> // By the time this function is called, every layer will have <del> // an entry in remoteLayers. <del> return pd.pushState.remoteLayers[pd.DiffID()] <add> return pd.remoteDescriptor <ide> } <ide> <ide> // layerAlreadyExists checks if the registry already know about any of the <ide><path>distribution/xfer/upload.go <ide> import ( <ide> "time" <ide> <ide> "github.com/Sirupsen/logrus" <add> "github.com/docker/distribution" <ide> "github.com/docker/docker/layer" <ide> "github.com/docker/docker/pkg/progress" <ide> "golang.org/x/net/context" <ide> func NewLayerUploadManager(concurrencyLimit int) *LayerUploadManager { <ide> type uploadTransfer struct { <ide> Transfer <ide> <del> diffID layer.DiffID <del> err error <add> remoteDescriptor distribution.Descriptor <add> err error <ide> } <ide> <ide> // An UploadDescriptor references a layer that may need to be uploaded. <ide> type UploadDescriptor interface { <ide> // DiffID should return the DiffID for this layer. <ide> DiffID() layer.DiffID <ide> // Upload is called to perform the Upload. <del> Upload(ctx context.Context, progressOutput progress.Output) error <add> Upload(ctx context.Context, progressOutput progress.Output) (distribution.Descriptor, error) <add> // SetRemoteDescriptor provides the distribution.Descriptor that was <add> // returned by Upload. This descriptor is not to be confused with <add> // the UploadDescriptor interface, which is used for internally <add> // identifying layers that are being uploaded. <add> SetRemoteDescriptor(descriptor distribution.Descriptor) <ide> } <ide> <ide> // Upload is a blocking function which ensures the listed layers are present on <ide> type UploadDescriptor interface { <ide> func (lum *LayerUploadManager) Upload(ctx context.Context, layers []UploadDescriptor, progressOutput progress.Output) error { <ide> var ( <ide> uploads []*uploadTransfer <del> dedupDescriptors = make(map[string]struct{}) <add> dedupDescriptors = make(map[string]*uploadTransfer) <ide> ) <ide> <ide> for _, descriptor := range layers { <ide> func (lum *LayerUploadManager) Upload(ctx context.Context, layers []UploadDescri <ide> if _, present := dedupDescriptors[key]; present { <ide> continue <ide> } <del> dedupDescriptors[key] = struct{}{} <ide> <ide> xferFunc := lum.makeUploadFunc(descriptor) <ide> upload, watcher := lum.tm.Transfer(descriptor.Key(), xferFunc, progressOutput) <ide> defer upload.Release(watcher) <ide> uploads = append(uploads, upload.(*uploadTransfer)) <add> dedupDescriptors[key] = upload.(*uploadTransfer) <ide> } <ide> <ide> for _, upload := range uploads { <ide> func (lum *LayerUploadManager) Upload(ctx context.Context, layers []UploadDescri <ide> } <ide> } <ide> } <add> for _, l := range layers { <add> l.SetRemoteDescriptor(dedupDescriptors[l.Key()].remoteDescriptor) <add> } <ide> <ide> return nil <ide> } <ide> func (lum *LayerUploadManager) makeUploadFunc(descriptor UploadDescriptor) DoFun <ide> return func(progressChan chan<- progress.Progress, start <-chan struct{}, inactive chan<- struct{}) Transfer { <ide> u := &uploadTransfer{ <ide> Transfer: NewTransfer(), <del> diffID: descriptor.DiffID(), <ide> } <ide> <ide> go func() { <ide> func (lum *LayerUploadManager) makeUploadFunc(descriptor UploadDescriptor) DoFun <ide> <ide> retries := 0 <ide> for { <del> err := descriptor.Upload(u.Transfer.Context(), progressOutput) <add> remoteDescriptor, err := descriptor.Upload(u.Transfer.Context(), progressOutput) <ide> if err == nil { <add> u.remoteDescriptor = remoteDescriptor <ide> break <ide> } <ide> <ide><path>distribution/xfer/upload_test.go <ide> import ( <ide> "testing" <ide> "time" <ide> <add> "github.com/docker/distribution" <ide> "github.com/docker/distribution/digest" <ide> "github.com/docker/docker/layer" <ide> "github.com/docker/docker/pkg/progress" <ide> func (u *mockUploadDescriptor) DiffID() layer.DiffID { <ide> return u.diffID <ide> } <ide> <add>// SetRemoteDescriptor is not used in the mock. <add>func (u *mockUploadDescriptor) SetRemoteDescriptor(remoteDescriptor distribution.Descriptor) { <add>} <add> <ide> // Upload is called to perform the upload. <del>func (u *mockUploadDescriptor) Upload(ctx context.Context, progressOutput progress.Output) error { <add>func (u *mockUploadDescriptor) Upload(ctx context.Context, progressOutput progress.Output) (distribution.Descriptor, error) { <ide> if u.currentUploads != nil { <ide> defer atomic.AddInt32(u.currentUploads, -1) <ide> <ide> if atomic.AddInt32(u.currentUploads, 1) > maxUploadConcurrency { <del> return errors.New("concurrency limit exceeded") <add> return distribution.Descriptor{}, errors.New("concurrency limit exceeded") <ide> } <ide> } <ide> <ide> // Sleep a bit to simulate a time-consuming upload. <ide> for i := int64(0); i <= 10; i++ { <ide> select { <ide> case <-ctx.Done(): <del> return ctx.Err() <add> return distribution.Descriptor{}, ctx.Err() <ide> case <-time.After(10 * time.Millisecond): <ide> progressOutput.WriteProgress(progress.Progress{ID: u.ID(), Current: i, Total: 10}) <ide> } <ide> } <ide> <ide> if u.simulateRetries != 0 { <ide> u.simulateRetries-- <del> return errors.New("simulating retry") <add> return distribution.Descriptor{}, errors.New("simulating retry") <ide> } <ide> <del> return nil <add> return distribution.Descriptor{}, nil <ide> } <ide> <ide> func uploadDescriptors(currentUploads *int32) []UploadDescriptor { <ide><path>integration-cli/docker_cli_push_test.go <ide> func (s *DockerSchema1RegistrySuite) TestPushEmptyLayer(c *check.C) { <ide> testPushEmptyLayer(c) <ide> } <ide> <add>// testConcurrentPush pushes multiple tags to the same repo <add>// concurrently. <add>func testConcurrentPush(c *check.C) { <add> repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) <add> <add> repos := []string{} <add> for _, tag := range []string{"push1", "push2", "push3"} { <add> repo := fmt.Sprintf("%v:%v", repoName, tag) <add> _, err := buildImage(repo, fmt.Sprintf(` <add> FROM busybox <add> ENTRYPOINT ["/bin/echo"] <add> ENV FOO foo <add> ENV BAR bar <add> CMD echo %s <add>`, repo), true) <add> c.Assert(err, checker.IsNil) <add> repos = append(repos, repo) <add> } <add> <add> // Push tags, in parallel <add> results := make(chan error) <add> <add> for _, repo := range repos { <add> go func(repo string) { <add> _, _, err := runCommandWithOutput(exec.Command(dockerBinary, "push", repo)) <add> results <- err <add> }(repo) <add> } <add> <add> for range repos { <add> err := <-results <add> c.Assert(err, checker.IsNil, check.Commentf("concurrent push failed with error: %v", err)) <add> } <add> <add> // Clear local images store. <add> args := append([]string{"rmi"}, repos...) <add> dockerCmd(c, args...) <add> <add> // Re-pull and run individual tags, to make sure pushes succeeded <add> for _, repo := range repos { <add> dockerCmd(c, "pull", repo) <add> dockerCmd(c, "inspect", repo) <add> out, _ := dockerCmd(c, "run", "--rm", repo) <add> c.Assert(strings.TrimSpace(out), checker.Equals, "/bin/sh -c echo "+repo) <add> } <add>} <add> <add>func (s *DockerRegistrySuite) TestConcurrentPush(c *check.C) { <add> testConcurrentPush(c) <add>} <add> <add>func (s *DockerSchema1RegistrySuite) TestConcurrentPush(c *check.C) { <add> testConcurrentPush(c) <add>} <add> <ide> func (s *DockerRegistrySuite) TestCrossRepositoryLayerPush(c *check.C) { <ide> sourceRepoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) <ide> // tag the image to upload it to the private registry
4
Python
Python
add blocksize arg for ftp hook
64412ee867fe0918cc3b616b3fb0b72dcd88125c
<ide><path>airflow/providers/ftp/hooks/ftp.py <ide> import datetime <ide> import ftplib <ide> import os.path <del>from typing import Any, List, Optional, Tuple <add>from typing import Any, Callable, List, Optional, Tuple <ide> <ide> from airflow.hooks.base import BaseHook <ide> <ide> def delete_directory(self, path: str) -> None: <ide> conn = self.get_conn() <ide> conn.rmd(path) <ide> <del> def retrieve_file(self, remote_full_path, local_full_path_or_buffer, callback=None): <add> def retrieve_file( <add> self, <add> remote_full_path: str, <add> local_full_path_or_buffer: Any, <add> callback: Optional[Callable] = None, <add> block_size: int = 8192, <add> ) -> None: <ide> """ <ide> Transfers the remote file to a local location. <ide> <ide> def retrieve_file(self, remote_full_path, local_full_path_or_buffer, callback=No <ide> that writing to a file or buffer will need to be handled inside the <ide> callback. <ide> [default: output_handle.write()] <add> :param block_size: file is transferred in chunks of default size 8192 <add> or as set by user <ide> <ide> .. code-block:: python <ide> <ide> def write_to_file_with_progress(data): <ide> <ide> """ <ide> conn = self.get_conn() <del> <ide> is_path = isinstance(local_full_path_or_buffer, str) <ide> <ide> # without a callback, default to writing to a user-provided file or <ide> # file-like buffer <ide> if not callback: <ide> if is_path: <del> <ide> output_handle = open(local_full_path_or_buffer, 'wb') <ide> else: <ide> output_handle = local_full_path_or_buffer <add> <ide> callback = output_handle.write <del> else: <del> output_handle = None <ide> <ide> remote_path, remote_file_name = os.path.split(remote_full_path) <ide> conn.cwd(remote_path) <ide> self.log.info('Retrieving file from FTP: %s', remote_full_path) <del> conn.retrbinary(f'RETR {remote_file_name}', callback) <add> conn.retrbinary(f'RETR {remote_file_name}', callback, block_size) <ide> self.log.info('Finished retrieving file from FTP: %s', remote_full_path) <ide> <ide> if is_path and output_handle: <ide> output_handle.close() <ide> <del> def store_file(self, remote_full_path: str, local_full_path_or_buffer: Any) -> None: <add> def store_file( <add> self, remote_full_path: str, local_full_path_or_buffer: Any, block_size: int = 8192 <add> ) -> None: <ide> """ <ide> Transfers a local file to the remote location. <ide> <ide> def store_file(self, remote_full_path: str, local_full_path_or_buffer: Any) -> N <ide> :param remote_full_path: full path to the remote file <ide> :param local_full_path_or_buffer: full path to the local file or a <ide> file-like buffer <add> :param block_size: file is transferred in chunks of default size 8192 <add> or as set by user <ide> """ <ide> conn = self.get_conn() <del> <ide> is_path = isinstance(local_full_path_or_buffer, str) <ide> <ide> if is_path: <del> <ide> input_handle = open(local_full_path_or_buffer, 'rb') <ide> else: <ide> input_handle = local_full_path_or_buffer <ide> remote_path, remote_file_name = os.path.split(remote_full_path) <ide> conn.cwd(remote_path) <del> conn.storbinary(f'STOR {remote_file_name}', input_handle) <add> conn.storbinary(f'STOR {remote_file_name}', input_handle, block_size) <ide> <ide> if is_path: <ide> input_handle.close() <ide><path>tests/providers/ftp/hooks/test_ftp.py <ide> def test_retrieve_file(self): <ide> _buffer = io.StringIO('buffer') <ide> with fh.FTPHook() as ftp_hook: <ide> ftp_hook.retrieve_file(self.path, _buffer) <del> self.conn_mock.retrbinary.assert_called_once_with('RETR path', _buffer.write) <add> self.conn_mock.retrbinary.assert_called_once_with('RETR path', _buffer.write, 8192) <ide> <ide> def test_retrieve_file_with_callback(self): <ide> func = mock.Mock() <ide> _buffer = io.StringIO('buffer') <ide> with fh.FTPHook() as ftp_hook: <ide> ftp_hook.retrieve_file(self.path, _buffer, callback=func) <del> self.conn_mock.retrbinary.assert_called_once_with('RETR path', func) <add> self.conn_mock.retrbinary.assert_called_once_with('RETR path', func, 8192) <ide> <ide> def test_connection_success(self): <ide> with fh.FTPHook() as ftp_hook:
2
Go
Go
modify test to include /dev/shm sharing
3f631b0d94d57e6dc677a8cd86ecc9233c30e98f
<ide><path>integration-cli/docker_cli_run_test.go <ide> func (s *DockerSuite) TestRunModeIpcHost(c *check.C) { <ide> func (s *DockerSuite) TestRunModeIpcContainer(c *check.C) { <ide> testRequires(c, SameHostDaemon, DaemonIsLinux) <ide> <del> out, _ := dockerCmd(c, "run", "-d", "busybox", "top") <add> out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", "echo -n test > /dev/shm/test && top") <ide> <ide> id := strings.TrimSpace(out) <ide> state, err := inspectField(id, "State.Running") <ide> func (s *DockerSuite) TestRunModeIpcContainer(c *check.C) { <ide> if parentContainerIpc != out { <ide> c.Fatalf("IPC different with --ipc=container:%s %s != %s\n", id, parentContainerIpc, out) <ide> } <add> <add> catOutput, _ := dockerCmd(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "cat", "/dev/shm/test") <add> if catOutput != "test" { <add> c.Fatalf("Output of /dev/shm/test expected test but found: %s", catOutput) <add> } <ide> } <ide> <ide> func (s *DockerSuite) TestRunModeIpcContainerNotExists(c *check.C) {
1
Ruby
Ruby
use respond_to_missing for timewithzone
14762dc5effbc7bb9ae94cb5af895a9a33512867
<ide><path>activesupport/lib/active_support/time_with_zone.rb <ide> def marshal_load(variables) <ide> end <ide> <ide> # Ensure proxy class responds to all methods that underlying time instance responds to. <del> def respond_to?(sym, include_priv = false) <add> def respond_to_missing?(sym, include_priv) <ide> # consistently respond false to acts_like?(:date), regardless of whether #time is a Time or DateTime <del> return false if sym.to_s == 'acts_like_date?' <del> super || time.respond_to?(sym, include_priv) <add> return false if sym.to_sym == :acts_like_date? <add> time.respond_to?(sym, include_priv) <ide> end <ide> <ide> # Send the missing method to +time+ instance, and wrap result in a new TimeWithZone with the existing +time_zone+. <ide><path>activesupport/test/core_ext/time_with_zone_test.rb <ide> def test_instance_created_with_local_time_enforces_fall_dst_rules <ide> def test_ruby_19_weekday_name_query_methods <ide> %w(sunday? monday? tuesday? wednesday? thursday? friday? saturday?).each do |name| <ide> assert_respond_to @twz, name <add> assert_equal @twz.send(name), @twz.method(name).call <ide> end <ide> end <ide>
2
Javascript
Javascript
avoid a string allocation in getmanageditem
ef3a68f61ec28c76191341b11e9f7de122113aba
<ide><path>lib/FileSystemInfo.js <ide> const mergeMaps = (a, b) => { <ide> }; <ide> <ide> const getManagedItem = (managedPath, path) => { <del> const remaining = path.slice(managedPath.length); <del> let i = 0; <add> let i = managedPath.length; <ide> let slashes = 2; <del> loop: while (i < remaining.length) { <del> switch (remaining.charCodeAt(i)) { <add> loop: while (i < path.length) { <add> switch (path.charCodeAt(i)) { <ide> case 47: // slash <ide> case 92: // backslash <ide> if (--slashes === 0) break loop; <ide> const getManagedItem = (managedPath, path) => { <ide> } <ide> i++; <ide> } <del> return path.slice(0, managedPath.length + i); <add> return path.slice(0, i); <ide> }; <ide> <ide> class FileSystemInfo {
1
PHP
PHP
fix cs error
f6a7c58c1fca61d8540f7e9f0eda469d24d398b5
<ide><path>src/Mailer/Mailer.php <ide> public function __call(string $method, array $args) <ide> public function set($key, $value = null) <ide> { <ide> deprecationWarning('Mailer::set() is deprecated. Use setViewVars() instead.'); <add> <ide> return $this->setViewVars($key, $value); <ide> } <ide> <ide><path>src/View/Helper/NumberHelper.php <ide> public function formatDelta($value, array $options = []): string <ide> */ <ide> public function defaultCurrency($currency): ?string <ide> { <del> deprecationWarning('NumberHelper::defaultCurrency() is deprecated. Use setDefaultCurrency() and getDefaultCurrency() instead.'); <add> deprecationWarning( <add> 'NumberHelper::defaultCurrency() is deprecated. Use setDefaultCurrency() and getDefaultCurrency() instead.' <add> ); <ide> <ide> return $this->_engine->defaultCurrency($currency); <ide> }
2
Text
Text
update code example for windows in stream.md
9278ce202ac6d188faeff514b67f4646786efc58
<ide><path>doc/api/stream.md <ide> const server = http.createServer((req, res) => { <ide> res.write(typeof data); <ide> res.end(); <ide> } catch (er) { <del> // uh oh! bad json! <add> // uh oh! bad json! <ide> res.statusCode = 400; <ide> return res.end(`error: ${er.message}`); <ide> } <ide> const server = http.createServer((req, res) => { <ide> <ide> server.listen(1337); <ide> <del>// $ curl localhost:1337 -d '{}' <add>// $ curl localhost:1337 -d "{}" <ide> // object <del>// $ curl localhost:1337 -d '"foo"' <add>// $ curl localhost:1337 -d "\"foo\"" <ide> // string <del>// $ curl localhost:1337 -d 'not json' <del>// error: Unexpected token o <add>// $ curl localhost:1337 -d "not json" <add>// error: Unexpected token o in JSON at position 1 <ide> ``` <ide> <ide> [Writable][] streams (such as `res` in the example) expose methods such as
1
PHP
PHP
resolve phpdoc errors and typos
baa6e84d178e285a01d41ed18d11d0552e4e6efc
<ide><path>lib/Cake/Model/Datasource/Database/Connection.php <ide> /** <ide> * Represents a connection with a database server <ide> * <del> **/ <add> */ <ide> class Connection { <ide> <ide> use TypeConverter; <ide> class Connection { <ide> * Contains the configuration params for this connection <ide> * <ide> * @var array <del> **/ <add> */ <ide> protected $_config; <ide> <ide> /** <ide> * Driver object, responsible for creating the real connection <ide> * and provide specific SQL dialect <ide> * <del> * @var Cake\Model\Datasource\Database\Driver <del> **/ <add> * @var \Cake\Model\Datasource\Database\Driver <add> */ <ide> protected $_driver; <ide> <ide> /** <ide> * Whether connection was established or not <ide> * <ide> * @var boolean <del> **/ <add> */ <ide> protected $_connected = false; <ide> <ide> /** <ide> * Contains how many nested transactions have been started <ide> * <ide> * @var int <del> **/ <add> */ <ide> protected $_transactionLevel = 0; <ide> <ide> /** <ide> * Whether a transaction is active in this connection <ide> * <ide> * @var int <del> **/ <add> */ <ide> protected $_transactionStarted = false; <ide> <ide> /** <ide> * Whether this connection can and should use savepoints for nested <ide> * transactions <ide> * <ide> * @var boolean <del> **/ <add> */ <ide> protected $_useSavePoints = false; <ide> <ide> /** <ide> * Constructor <ide> * <ide> * @param array $config configuration for connecting to database <del> * @throws \Cake\Model\Datasource\Database\Exception\MissingDriverException if driver class can not be found <del> * @throws \Cake\Model\Datasource\Database\Exception\MissingExtensionException if driver cannot be used <del> * @return void <del> **/ <add> * @throws MissingDriverException if driver class can not be found <add> * @throws MissingExtensionException if driver cannot be used <add> * @return self <add> */ <ide> public function __construct($config) { <ide> $this->_config = $config; <ide> if (!class_exists($config['datasource'])) { <ide> public function __construct($config) { <ide> * <ide> * @param string|Driver $driver <ide> * @return Driver <del> **/ <add> */ <ide> public function driver($driver = null) { <ide> if ($driver === null) { <ide> return $this->_driver; <ide> public function driver($driver = null) { <ide> /** <ide> * Connects to the configured database <ide> * <del> * @throws \Cake\Model\Datasource\Database\Exception\MissingConnectionException if credentials are invalid <add> * @throws MissingConnectionException if credentials are invalid <ide> * @return boolean true on success or false if already connected <del> **/ <add> */ <ide> public function connect() { <ide> if ($this->_connected) { <ide> return false; <ide> public function connect() { <ide> * Disconnects from database server <ide> * <ide> * @return void <del> **/ <add> */ <ide> public function disconnect() { <ide> $this->_driver->disconnect(); <ide> $this->_connected = false; <ide> public function disconnect() { <ide> * Returns whether connection to database server was already stablished <ide> * <ide> * @return boolean <del> **/ <add> */ <ide> public function isConnected() { <ide> return $this->_connected; <ide> } <ide> public function isConnected() { <ide> * Prepares a sql statement to be executed <ide> * <ide> * @param string $sql <del> * @return Cake\Model\Datasource\Database\Statement <del> **/ <add> * @return \Cake\Model\Datasource\Database\Statement <add> */ <ide> public function prepare($sql) { <ide> $this->connect(); <ide> return $this->_driver->prepare($sql); <ide> public function prepare($sql) { <ide> * @param string $query SQL to be executed and interpolated with $params <ide> * @param array $params list or associative array of params to be interpolated in $query as values <ide> * @param array $types list or associative array of types to be used for casting values in query <del> * @return Cake\Model\Datasource\Database\Statement executed statement <del> **/ <add> * @return \Cake\Model\Datasource\Database\Statement executed statement <add> */ <ide> public function execute($query, array $params = array(), array $types = array()) { <ide> $this->connect(); <ide> if ($params) { <ide> public function execute($query, array $params = array(), array $types = array()) <ide> /** <ide> * Executes a SQL statement and returns the Statement object as result <ide> * <del> * @return Cake\Model\Datasource\Database\Statement <del> **/ <add> * @param string $sql <add> * @return \Cake\Model\Datasource\Database\Statement <add> */ <ide> public function query($sql) { <ide> $this->connect(); <ide> $statement = $this->prepare($sql); <ide> public function query($sql) { <ide> * <ide> * @param string $table the table to update values in <ide> * @param array $data values to be inserted <del> * @params array $types list of associative array containing the types to be used for casting <del> * @return Cake\Model\Datasource\Database\Statement <del> **/ <add> * @param array $types list of associative array containing the types to be used for casting <add> * @return \Cake\Model\Datasource\Database\Statement <add> */ <ide> public function insert($table, array $data, array $types = array()) { <ide> $this->connect(); <ide> $keys = array_keys($data); <ide> public function insert($table, array $data, array $types = array()) { <ide> * @param array $data values to be updated <ide> * @param array $conditions conditions to be set for update statement <ide> * @param array $types list of associative array containing the types to be used for casting <del> * @return Cake\Model\Datasource\Database\Statement <del> **/ <add> * @return \Cake\Model\Datasource\Database\Statement <add> */ <ide> public function update($table, array $data, array $conditions = array(), $types = array()) { <ide> $this->connect(); <ide> $keys = array_keys($data); <ide> public function update($table, array $data, array $conditions = array(), $types <ide> * @param string $table the table to delete rows from <ide> * @param array $conditions conditions to be set for delete statement <ide> * @param array $types list of associative array containing the types to be used for casting <del> * @return Cake\Model\Datasource\Database\Statement <del> **/ <add> * @return \Cake\Model\Datasource\Database\Statement <add> */ <ide> public function delete($table, $conditions = array(), $types = array()) { <ide> $this->connect(); <ide> $conditionsKeys = array_keys($conditions); <ide> public function delete($table, $conditions = array(), $types = array()) { <ide> * Starts a new transaction <ide> * <ide> * @return void <del> **/ <add> */ <ide> public function begin() { <ide> $this->connect(); <ide> if (!$this->_transactionStarted) { <ide> public function begin() { <ide> * Commits current transaction <ide> * <ide> * @return boolean true on success, false otherwise <del> **/ <add> */ <ide> public function commit() { <ide> if (!$this->_transactionStarted) { <ide> return false; <ide> public function commit() { <ide> /** <ide> * Rollback current transaction <ide> * <del> * @return void <del> **/ <add> * @return boolean <add> */ <ide> public function rollback() { <ide> if (!$this->_transactionStarted) { <ide> return false; <ide> public function rollback() { <ide> * `$connection->useSavePoints(false)` Disables usage of savepoints and returns false <ide> * `$connection->useSavePoints()` Returns current status <ide> * <add> * @param boolean|null $enable <ide> * @return boolean true if enabled, false otherwise <del> **/ <add> */ <ide> public function useSavePoints($enable = null) { <ide> if ($enable === null) { <ide> return $this->_useSavePoints; <ide> public function useSavePoints($enable = null) { <ide> /** <ide> * Creates a new save point for nested transactions <ide> * <add> * @param string $name <ide> * @return void <del> **/ <add> */ <ide> public function createSavePoint($name) { <ide> $this->connect(); <ide> $this->execute($this->_driver->savePointSQL($name)); <ide> public function createSavePoint($name) { <ide> /** <ide> * Releases a save point by its name <ide> * <add> * @param string $name <ide> * @return void <del> **/ <add> */ <ide> public function releaseSavePoint($name) { <ide> $this->connect(); <ide> $this->execute($this->_driver->releaseSavePointSQL($name)); <ide> public function releaseSavePoint($name) { <ide> /** <ide> * Rollsback a save point by its name <ide> * <add> * @param string $name <ide> * @return void <del> **/ <add> */ <ide> public function rollbackSavepoint($name) { <ide> $this->connect(); <ide> $this->execute($this->_driver->rollbackSavePointSQL($name)); <ide> public function rollbackSavepoint($name) { <ide> * Quotes value to be used safely in database query <ide> * <ide> * @param mixed $value <del> * @param Type to be used for determining kind of quoting to perform <add> * @param string $type Type to be used for determining kind of quoting to perform <ide> * @return mixed quoted value <del> **/ <add> */ <ide> public function quote($value, $type = null) { <ide> $this->connect(); <ide> list($value, $type) = $this->cast($value, $type); <ide> public function quote($value, $type = null) { <ide> * <ide> * @param string $identifier <ide> * @return string <del> **/ <add> */ <ide> public function quoteIdentifier($identifier) { <ide> return $this->_driver->quoteIdentifier($identifier); <ide> } <ide> public function quoteIdentifier($identifier) { <ide> * <ide> * @param string $table table name or sequence to get last insert value from <ide> * @return string|integer <del> **/ <add> */ <ide> public function lastInsertId($table) { <ide> $this->connect(); <ide> return $this->_driver->lastInsertId($table); <ide> public function lastInsertId($table) { <ide> /** <ide> * Simple conditions parser joined by AND <ide> * <del> * @param array conditions key value array or list of conditions to be joined <add> * @param array $conditions key value array or list of conditions to be joined <ide> * to construct a WHERE clause <ide> * @return string <del> **/ <add> */ <ide> protected function _parseConditions($conditions) { <ide> $params = array(); <ide> if (empty($conditions)) {
1
PHP
PHP
remove all references to environmentvariables
cf1d3f289b345b9e8da636887cf5f19219dd86f9
<ide><path>src/Illuminate/Foundation/Application.php <ide> use Illuminate\Routing\RoutingServiceProvider; <ide> use Illuminate\Contracts\Support\ResponsePreparer; <ide> use Illuminate\Exception\ExceptionServiceProvider; <del>use Illuminate\Config\FileEnvironmentVariablesLoader; <ide> use Symfony\Component\HttpKernel\HttpKernelInterface; <ide> use Symfony\Component\HttpKernel\TerminableInterface; <ide> use Symfony\Component\HttpKernel\Exception\HttpException; <ide> public function getConfigLoader() <ide> return new FileLoader(new Filesystem, $this['path.config']); <ide> } <ide> <del> /** <del> * Get the environment variables loader instance. <del> * <del> * @return \Illuminate\Config\EnvironmentVariablesLoaderInterface <del> */ <del> public function getEnvironmentVariablesLoader() <del> { <del> return new FileEnvironmentVariablesLoader(new Filesystem, $this['path.base']); <del> } <del> <ide> /** <ide> * Get the service provider repository instance. <ide> * <ide><path>src/Illuminate/Foundation/Console/Optimize/config.php <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Support/NamespacedItemResolver.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Config/FileLoader.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Config/LoaderInterface.php', <del> $basePath.'/vendor/laravel/framework/src/Illuminate/Config/EnvironmentVariablesLoaderInterface.php', <del> $basePath.'/vendor/laravel/framework/src/Illuminate/Config/FileEnvironmentVariablesLoader.php', <del> $basePath.'/vendor/laravel/framework/src/Illuminate/Config/EnvironmentVariables.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/AliasLoader.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/ProviderRepository.php',
2
Text
Text
update markdown text
bda98247b1e1558620fa3bdf9b66299fe44e48a1
<ide><path>client/src/pages/guide/english/csharp/for-loop/index.md <ide> for (; i < 5;) <ide> ``` <ide> <ide> ### Other Resources <del>- [Microsoft Documentation](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/for) <ide>\ No newline at end of file <add>- [Microsoft Documentation](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/for) <add> <add>## End
1
Ruby
Ruby
avoid method_missing and reduce method calls
a8b4bdb3d6efefe658a0ac4cfb28b69fba494704
<ide><path>activerecord/lib/active_record/relation/batches.rb <ide> def find_each(options = {}) <ide> def find_in_batches(options = {}) <ide> relation = self <ide> <del> if orders.present? || taken.present? <add> unless arel.orders.blank? && arel.taken.blank? <ide> ActiveRecord::Base.logger.warn("Scoped order and limit are ignored, it's forced to be batch order and batch size") <ide> end <ide>
1
Javascript
Javascript
fix eslint styles
19ffb5cf1c50e9d91d0a7a35152d20f175a2385d
<ide><path>lib/_debugger.js <ide> Protocol.prototype.execute = function(d) { <ide> if (len - this.bodyStartByteIndex < this.contentLength) { <ide> break; <ide> } <del> // pass thru <add> // falls through <ide> case 'body': <ide> var resRawByteLength = Buffer.byteLength(res.raw, 'utf8'); <ide> <ide> Protocol.prototype.execute = function(d) { <ide> <ide> default: <ide> throw new Error('Unknown state'); <del> break; <ide> } <ide> }; <ide> <ide> Client.prototype.req = function(req, cb) { <ide> <ide> Client.prototype.reqVersion = function(cb) { <ide> cb = cb || function() {}; <del> this.req({ command: 'version' } , function(err, body, res) { <add> this.req({ command: 'version' }, function(err, body, res) { <ide> if (err) return cb(err); <ide> cb(null, res.body.body.V8Version, res.body.running); <ide> }); <ide> Client.prototype.reqFrameEval = function(expression, frame, cb) { <ide> // reqBacktrace(cb) <ide> // TODO: from, to, bottom <ide> Client.prototype.reqBacktrace = function(cb) { <del> this.req({ command: 'backtrace', arguments: { inlineRefs: true } } , cb); <add> this.req({ command: 'backtrace', arguments: { inlineRefs: true } }, cb); <ide> }; <ide> <ide> <ide> Client.prototype.reqScripts = function(cb) { <ide> var self = this; <ide> cb = cb || function() {}; <ide> <del> this.req({ command: 'scripts' } , function(err, res) { <add> this.req({ command: 'scripts' }, function(err, res) { <ide> if (err) return cb(err); <ide> <ide> for (var i = 0; i < res.length; i++) { <ide><path>lib/_http_incoming.js <ide> IncomingMessage.prototype._addHeaderLine = function(field, value, dest) { <ide> } <ide> break; <ide> <add> /* eslint-disable max-len */ <ide> // list is taken from: <ide> // https://mxr.mozilla.org/mozilla/source/netwerk/protocol/http/src/nsHttpHeaderArray.cpp <add> /* eslint-enable max-len */ <ide> case 'content-type': <ide> case 'content-length': <ide> case 'user-agent': <ide> IncomingMessage.prototype._addHeaderLine = function(field, value, dest) { <ide> <ide> default: <ide> // make comma-separated list <del> if (dest[field] !== undefined) <add> if (dest[field] !== undefined) { <ide> dest[field] += ', ' + value; <del> else { <add> } else { <ide> dest[field] = value; <ide> } <ide> } <ide><path>lib/_http_outgoing.js <ide> OutgoingMessage.prototype.setTimeout = function(msecs, callback) { <ide> this.once('socket', function(socket) { <ide> socket.setTimeout(msecs); <ide> }); <del> } else <add> } else { <ide> this.socket.setTimeout(msecs); <add> } <ide> }; <ide> <ide> <ide><path>lib/_http_server.js <ide> function Server(requestListener) { <ide> this.addListener('request', requestListener); <ide> } <ide> <add> /* eslint-disable max-len */ <ide> // Similar option to this. Too lazy to write my own docs. <ide> // http://www.squid-cache.org/Doc/config/half_closed_clients/ <ide> // http://wiki.squid-cache.org/SquidFaq/InnerWorkings#What_is_a_half-closed_filedescriptor.3F <add> /* eslint-enable max-len */ <ide> this.httpAllowHalfOpen = false; <ide> <ide> this.addListener('connection', connectionListener); <ide><path>lib/_stream_readable.js <ide> function howMuchToRead(n, state) { <ide> if (!state.ended) { <ide> state.needReadable = true; <ide> return 0; <del> } else <add> } else { <ide> return state.length; <add> } <ide> } <ide> <ide> return n; <ide> Readable.prototype.wrap = function(stream) { <ide> if (this[i] === undefined && typeof stream[i] === 'function') { <ide> this[i] = function(method) { return function() { <ide> return stream[method].apply(stream, arguments); <del> }}(i); <add> }; }(i); <ide> } <ide> } <ide> <ide><path>lib/_stream_writable.js <ide> Writable.WritableState = WritableState; <ide> <ide> const util = require('util'); <ide> const Stream = require('stream'); <del>const debug = util.debuglog('stream'); <ide> <ide> util.inherits(Writable, Stream); <ide> <ide> function writeOrBuffer(stream, state, chunk, encoding, cb) { <ide> } else { <ide> state.bufferedRequest = state.lastBufferedRequest; <ide> } <del> } <del> else <add> } else { <ide> doWrite(stream, state, false, len, chunk, encoding, cb); <add> } <ide> <ide> return ret; <ide> } <ide> function finishMaybe(stream, state) { <ide> prefinish(stream, state); <ide> state.finished = true; <ide> stream.emit('finish'); <del> } else <add> } else { <ide> prefinish(stream, state); <add> } <ide> } <ide> return need; <ide> } <ide><path>lib/_tls_legacy.js <ide> function onnewsession(key, session) { <ide> <ide> if (self.ssl) <ide> self.ssl.newSessionDone(); <del> }; <add> } <ide> } <ide> <ide> <ide><path>lib/assert.js <ide> assert.doesNotThrow = function(block, /*optional*/message) { <ide> _throws.apply(this, [false].concat(pSlice.call(arguments))); <ide> }; <ide> <del>assert.ifError = function(err) { if (err) {throw err;}}; <add>assert.ifError = function(err) { if (err) throw err; }; <ide><path>lib/child_process.js <ide> SocketListSend.prototype._request = function(msg, cmd, callback) { <ide> function onclose() { <ide> self.slave.removeListener('internalMessage', onreply); <ide> callback(new Error('Slave closed before reply')); <del> }; <add> } <ide> <ide> function onreply(msg) { <ide> if (!(msg.cmd === cmd && msg.key === self.key)) return; <ide> self.slave.removeListener('disconnect', onclose); <ide> self.slave.removeListener('internalMessage', onreply); <ide> <ide> callback(null, msg); <del> }; <add> } <ide> <ide> this.slave.once('disconnect', onclose); <ide> this.slave.on('internalMessage', onreply); <ide><path>lib/cluster.js <ide> const SCHED_RR = 2; <ide> <ide> const uv = process.binding('uv'); <ide> <del>const cluster = new EventEmitter; <add>const cluster = new EventEmitter(); <ide> module.exports = cluster; <ide> cluster.Worker = Worker; <ide> cluster.isWorker = ('NODE_UNIQUE_ID' in process.env); <ide> RoundRobinHandle.prototype.add = function(worker, send) { <ide> function done() { <ide> if (self.handle.getsockname) { <ide> var out = {}; <del> var err = self.handle.getsockname(out); <add> self.handle.getsockname(out); <ide> // TODO(bnoordhuis) Check err. <ide> send(null, { sockname: out }, null); <del> } <del> else { <add> } else { <ide> send(null, null, null); // UNIX socket. <ide> } <ide> self.handoff(worker); // In case there are connections pending. <ide> else <ide> function masterInit() { <ide> cluster.workers = {}; <ide> <del> var intercom = new EventEmitter; <add> var intercom = new EventEmitter(); <ide> cluster.settings = {}; <ide> <ide> // XXX(bnoordhuis) Fold cluster.schedulingPolicy into cluster.settings? <ide><path>lib/console.js <ide> Console.prototype.timeEnd = function(label) { <ide> Console.prototype.trace = function trace() { <ide> // TODO probably can to do this better with V8's debug object once that is <ide> // exposed. <del> var err = new Error; <add> var err = new Error(); <ide> err.name = 'Trace'; <ide> err.message = util.format.apply(this, arguments); <ide> Error.captureStackTrace(err, trace); <ide><path>lib/crypto.js <ide> function Verify(algorithm, options) { <ide> if (!(this instanceof Verify)) <ide> return new Verify(algorithm, options); <ide> <del> this._handle = new binding.Verify; <add> this._handle = new binding.Verify(); <ide> this._handle.init(algorithm); <ide> <ide> stream.Writable.call(this, options); <ide><path>lib/dgram.js <ide> function lookup6(address, callback) { <ide> <ide> function newHandle(type) { <ide> if (type == 'udp4') { <del> var handle = new UDP; <add> var handle = new UDP(); <ide> handle.lookup = lookup4; <ide> return handle; <ide> } <ide> <ide> if (type == 'udp6') { <del> var handle = new UDP; <add> var handle = new UDP(); <ide> handle.lookup = lookup6; <ide> handle.bind = handle.bind6; <ide> handle.send = handle.send6; <ide> Socket.prototype.send = function(buffer, <ide> if (ex) { <ide> if (callback) callback(ex); <ide> self.emit('error', ex); <del> } <del> else if (self._handle) { <add> } else if (self._handle) { <ide> var req = new SendWrap(); <ide> req.buffer = buffer; // Keep reference alive. <ide> req.length = length; <ide><path>lib/dns.js <ide> function resolver(bindingName) { <ide> if (err) throw errnoException(err, bindingName); <ide> callback.immediately = true; <ide> return req; <del> } <add> }; <ide> } <ide> <ide> <ide><path>lib/events.js <ide> EventEmitter.prototype.removeListener = <ide> if (--this._eventsCount === 0) { <ide> this._events = {}; <ide> return this; <del> } else <add> } else { <ide> delete events[type]; <add> } <ide> } else { <ide> spliceOne(list, position); <ide> } <ide><path>lib/fs.js <ide> function rethrow() { <ide> // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and <ide> // is fairly slow to generate. <ide> if (DEBUG) { <del> var backtrace = new Error; <add> var backtrace = new Error(); <ide> return function(err) { <ide> if (err) { <ide> backtrace.stack = err.name + ': ' + err.message + <ide><path>lib/net.js <ide> Socket.prototype._destroy = function(exception, cb) { <ide> }); <ide> self._writableState.errorEmitted = true; <ide> } <del> }; <add> } <ide> <ide> if (this.destroyed) { <ide> debug('already destroyed, fire error callbacks'); <ide> Server.prototype.listen = function() { <ide> Server.prototype.address = function() { <ide> if (this._handle && this._handle.getsockname) { <ide> var out = {}; <del> var err = this._handle.getsockname(out); <add> this._handle.getsockname(out); <ide> // TODO(bnoordhuis) Check err and throw? <ide> return out; <ide> } else if (this._pipeName) { <ide><path>lib/querystring.js <ide> QueryString.unescapeBuffer = function(s, decodeSpaces) { <ide> break; <ide> case charCode('+'): <ide> if (decodeSpaces) c = charCode(' '); <del> // pass thru <add> // falls through <ide> default: <ide> out[outIndex++] = c; <ide> break; <ide><path>lib/repl.js <ide> function REPLServer(prompt, <ide> <ide> // Display prompt again <ide> self.displayPrompt(); <del> }; <add> } <ide> }); <ide> <ide> self.on('SIGCONT', function() { <ide><path>lib/url.js <ide> const querystring = require('querystring'); <ide> function urlParse(url, parseQueryString, slashesDenoteHost) { <ide> if (url instanceof Url) return url; <ide> <del> var u = new Url; <add> var u = new Url(); <ide> u.parse(url, parseQueryString, slashesDenoteHost); <ide> return u; <ide> } <ide><path>lib/util.js <ide> exports.format = function(f) { <ide> } catch (_) { <ide> return '[Circular]'; <ide> } <add> // falls through <ide> default: <ide> return x; <ide> } <ide><path>src/node.js <ide> if (process._exiting) <ide> return; <ide> <del> var args = undefined; <add> var args; <ide> if (arguments.length > 1) { <ide> args = []; <ide> for (var i = 1; i < arguments.length; i++) <ide> if (!process.emit('unhandledRejection', reason, promise)) { <ide> // Nobody is listening. <ide> // TODO(petkaantonov) Take some default action, see #830 <del> } else <add> } else { <ide> hadListeners = true; <add> } <ide> } <ide> } <ide> return hadListeners;
22
Java
Java
apply @safevarargs to managedmap.ofentries(...)
6e2e45d18f7b016fba15d73db08a05fe530813a2
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java <ide> public ManagedMap(int initialCapacity) { <ide> * @return a {@code Map} containing the specified mappings <ide> * @since 5.3.16 <ide> */ <add> @SafeVarargs <ide> @SuppressWarnings("unchecked") <ide> public static <K,V> ManagedMap<K,V> ofEntries(Entry<? extends K, ? extends V>... entries) { <ide> ManagedMap<K,V > map = new ManagedMap<>();
1
Javascript
Javascript
remove unneccessary assignement
a58f98edd316dfea85cb477071da9362df21ab74
<ide><path>examples/js/geometries/LightningStrike.js <ide> THREE.LightningStrike.prototype.createDefaultSubrayCreationCallbacks = function <ide> var childSubraySeed = random1() * ( currentCycle + 1 ); <ide> <ide> var isActive = phase % period <= dutyCycle * period; <del> <del> probability = lightningStrike.subrayProbability; <add> <ide> var probability = 0; <ide> <ide> if ( isActive ) { <ide><path>examples/jsm/geometries/LightningStrike.js <ide> LightningStrike.prototype.createDefaultSubrayCreationCallbacks = function () { <ide> var childSubraySeed = random1() * ( currentCycle + 1 ); <ide> <ide> var isActive = phase % period <= dutyCycle * period; <del> <del> probability = lightningStrike.subrayProbability; <add> <ide> var probability = 0; <ide> <ide> if ( isActive ) {
2
Ruby
Ruby
remove deprecated new_from_hash_copying_default
2ff2b98032409d162cd2a0ffc1b21c63057f628d
<ide><path>activesupport/lib/active_support/hash_with_indifferent_access.rb <ide> def default(*args) <ide> end <ide> end <ide> <del> def self.new_from_hash_copying_default(hash) <del> ActiveSupport::Deprecation.warn(<<-MSG.squish) <del> `ActiveSupport::HashWithIndifferentAccess.new_from_hash_copying_default` <del> has been deprecated, and will be removed in Rails 5.1. The behavior of <del> this method is now identical to the behavior of `.new`. <del> MSG <del> new(hash) <del> end <del> <ide> def self.[](*args) <ide> new.merge!(Hash[*args]) <ide> end <ide><path>activesupport/test/core_ext/hash_ext_test.rb <ide> def test_to_hash_with_raising_default_proc <ide> assert_nothing_raised { hash.to_hash } <ide> end <ide> <del> def test_new_from_hash_copying_default_should_not_raise_when_default_proc_does <del> hash = Hash.new <del> hash.default_proc = proc { |h, k| raise "walrus" } <del> <del> assert_deprecated { HashWithIndifferentAccess.new_from_hash_copying_default(hash) } <del> end <del> <ide> def test_new_with_to_hash_conversion_copies_default <ide> normal_hash = Hash.new(3) <ide> normal_hash[:a] = 1
2
Ruby
Ruby
expand destdir in case a relative path is given
60fe954bfd6a8fe50ff576cd502ef92c25d41fe6
<ide><path>Library/Homebrew/cmd/unpack.rb <ide> def unpack <ide> raise FormulaUnspecifiedError if formulae.empty? <ide> <ide> if dir = ARGV.value("destdir") <del> unpack_dir = Pathname.new(dir) <add> unpack_dir = Pathname.new(dir).expand_path <ide> unpack_dir.mkpath <ide> else <ide> unpack_dir = Pathname.pwd
1
Text
Text
fix some grammar errors on guide doc
3ffc3635b9f144a054d65fca4adf502d1545551a
<ide><path>guides/source/active_record_querying.md <ide> clients.each do |client| <ide> end <ide> ``` <ide> <del>This code looks fine at the first sight. But the problem lies within the total number of queries executed. The above code executes 1 (to find 10 clients) + 10 (one per each client to load the address) = **11** queries in total. <add>This code looks fine at first sight. But the problem lies within the total number of queries executed. The above code executes 1 (to find 10 clients) + 10 (one per each client to load the address) = **11** queries in total. <ide> <ide> **Solution to N + 1 queries problem** <ide> <ide> User.active.inactive <ide> # SELECT "users".* FROM "users" WHERE "users"."state" = 'active' AND "users"."state" = 'inactive' <ide> ``` <ide> <del>We can mix and match `scope` and `where` conditions and the final sql <add>We can mix and match `scope` and `where` conditions and the final SQL <ide> will have all conditions joined with `AND`. <ide> <ide> ```ruby <ide> Client.connection.select_all("SELECT first_name, created_at FROM clients WHERE i <ide> <ide> ### `pluck` <ide> <del>`pluck` can be used to query single or multiple columns from the underlying table of a model. It accepts a list of column names as argument and returns an array of values of the specified columns with the corresponding data type. <add>`pluck` can be used to query single or multiple columns from the underlying table of a model. It accepts a list of column names as an argument and returns an array of values of the specified columns with the corresponding data type. <ide> <ide> ```ruby <ide> Client.where(active: true).pluck(:id) <ide><path>guides/source/active_record_validations.md <ide> controller-level validations. Here's a summary of the pros and cons: <ide> * Controller-level validations can be tempting to use, but often become <ide> unwieldy and difficult to test and maintain. Whenever possible, it's a good <ide> idea to keep your controllers skinny, as it will make your application a <del> pleasure to work with in the long run. <add> pleasure to work within the long run. <ide> <ide> Choose these in certain, specific cases. It's the opinion of the Rails team <ide> that model-level validations are the most appropriate in most circumstances. <ide><path>guides/source/autoloading_and_reloading_constants.md <ide> Similarly, in the Rails console, if you have a user instance and reload: <ide> > reload! <ide> ``` <ide> <del>the `user` object is instance of a stale class object. Ruby gives you a new class if you evaluate `User` again, but does not update the class `user` is instance of. <add>the `user` object is an instance of a stale class object. Ruby gives you a new class if you evaluate `User` again, but does not update the class `user` is an instance of. <ide> <ide> Another use case of this gotcha is subclassing reloadable classes in a place that is not reloaded: <ide>
3
Text
Text
fix typo in http2stream.close param default
d3600e513ae277534e9a37b51489ec8584fbf3dc
<ide><path>doc/api/http2.md <ide> added: v8.4.0 <ide> --> <ide> <ide> * code {number} Unsigned 32-bit integer identifying the error code. **Default:** <del> `http2.constant.NGHTTP2_NO_ERROR` (`0x00`) <add> `http2.constants.NGHTTP2_NO_ERROR` (`0x00`) <ide> * `callback` {Function} An optional function registered to listen for the <ide> `'close'` event. <ide> * Returns: {undefined}
1
Ruby
Ruby
remove redundant code
dbacaff1c391f615fcbd18cbfffdf089e57fa332
<ide><path>actionpack/lib/action_dispatch/middleware/public_exceptions.rb <ide> def render_format(status, content_type, body) <ide> end <ide> <ide> def render_html(status) <del> found = false <del> path = "#{public_path}/#{status}.#{I18n.locale}.html" if I18n.locale <del> path = "#{public_path}/#{status}.html" unless path && (found = File.exist?(path)) <add> path = "#{public_path}/#{status}.#{I18n.locale}.html" <add> path = "#{public_path}/#{status}.html" unless (found = File.exist?(path)) <ide> <ide> if found || File.exist?(path) <ide> render_format(status, 'text/html', File.read(path))
1
Java
Java
fix ambiguous imports
97ab170928f91847de51d8094a0bcf363de82b22
<ide><path>rxjava-core/src/test/java/rx/operators/OperationDistinctTest.java <ide> package rx.operators; <ide> <add>import static org.mockito.Matchers.*; <add>import static org.mockito.Mockito.*; <add>import static org.mockito.MockitoAnnotations.*; <add>import static rx.operators.OperationDistinct.*; <add> <add>import java.util.Comparator; <add> <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> import org.mockito.InOrder; <ide> import org.mockito.Mock; <add> <ide> import rx.Observable; <ide> import rx.Observer; <ide> import rx.util.functions.Func1; <ide> <del>import java.util.Comparator; <del> <del>import static org.mockito.Matchers.any; <del>import static org.mockito.Matchers.anyString; <del>import static org.mockito.Mockito.*; <del>import static org.mockito.Mockito.never; <del>import static org.mockito.MockitoAnnotations.initMocks; <del>import static rx.Observable.*; <del>import static rx.operators.OperationDistinct.distinct; <del> <ide> public class OperationDistinctTest { <ide> <ide> @Mock <ide> public void before() { <ide> <ide> @Test <ide> public void testDistinctOfNone() { <del> Observable<String> src = empty(); <del> create(distinct(src)).subscribe(w); <add> Observable<String> src = Observable.empty(); <add> Observable.create(distinct(src)).subscribe(w); <ide> <ide> verify(w, never()).onNext(anyString()); <ide> verify(w, never()).onError(any(Throwable.class)); <ide> public void testDistinctOfNone() { <ide> <ide> @Test <ide> public void testDistinctOfNoneWithKeySelector() { <del> Observable<String> src = empty(); <del> create(distinct(src, TO_UPPER_WITH_EXCEPTION)).subscribe(w); <add> Observable<String> src = Observable.empty(); <add> Observable.create(distinct(src, TO_UPPER_WITH_EXCEPTION)).subscribe(w); <ide> <ide> verify(w, never()).onNext(anyString()); <ide> verify(w, never()).onError(any(Throwable.class)); <ide> public void testDistinctOfNoneWithKeySelector() { <ide> <ide> @Test <ide> public void testDistinctOfNormalSource() { <del> Observable<String> src = from("a", "b", "c", "c", "c", "b", "b", "a", "e"); <del> create(distinct(src)).subscribe(w); <add> Observable<String> src = Observable.from("a", "b", "c", "c", "c", "b", "b", "a", "e"); <add> Observable.create(distinct(src)).subscribe(w); <ide> <ide> InOrder inOrder = inOrder(w); <ide> inOrder.verify(w, times(1)).onNext("a"); <ide> public void testDistinctOfNormalSource() { <ide> <ide> @Test <ide> public void testDistinctOfNormalSourceWithKeySelector() { <del> Observable<String> src = from("a", "B", "c", "C", "c", "B", "b", "a", "E"); <del> create(distinct(src, TO_UPPER_WITH_EXCEPTION)).subscribe(w); <add> Observable<String> src = Observable.from("a", "B", "c", "C", "c", "B", "b", "a", "E"); <add> Observable.create(distinct(src, TO_UPPER_WITH_EXCEPTION)).subscribe(w); <ide> <ide> InOrder inOrder = inOrder(w); <ide> inOrder.verify(w, times(1)).onNext("a"); <ide> public void testDistinctOfNormalSourceWithKeySelector() { <ide> <ide> @Test <ide> public void testDistinctOfNormalSourceWithComparator() { <del> Observable<String> src = from("1", "12", "123", "aaa", "321", "12", "21", "1", "12345"); <del> create(distinct(src, COMPARE_LENGTH)).subscribe(w); <add> Observable<String> src = Observable.from("1", "12", "123", "aaa", "321", "12", "21", "1", "12345"); <add> Observable.create(distinct(src, COMPARE_LENGTH)).subscribe(w); <ide> <ide> InOrder inOrder = inOrder(w); <ide> inOrder.verify(w, times(1)).onNext("1"); <ide> public void testDistinctOfNormalSourceWithComparator() { <ide> <ide> @Test <ide> public void testDistinctOfNormalSourceWithKeySelectorAndComparator() { <del> Observable<String> src = from("a", "x", "ab", "abc", "cba", "de", "x", "a", "abcd"); <del> create(distinct(src, TO_UPPER_WITH_EXCEPTION, COMPARE_LENGTH)).subscribe(w); <add> Observable<String> src = Observable.from("a", "x", "ab", "abc", "cba", "de", "x", "a", "abcd"); <add> Observable.create(distinct(src, TO_UPPER_WITH_EXCEPTION, COMPARE_LENGTH)).subscribe(w); <ide> <ide> InOrder inOrder = inOrder(w); <ide> inOrder.verify(w, times(1)).onNext("a"); <ide> public void testDistinctOfNormalSourceWithKeySelectorAndComparator() { <ide> <ide> @Test <ide> public void testDistinctOfNormalSourceWithKeySelectorAndComparatorAndTwoSubscriptions() { <del> Observable<String> src = from("a", "x", "ab", "abc", "cba", "de", "x", "a", "abcd"); <del> create(distinct(src, TO_UPPER_WITH_EXCEPTION, COMPARE_LENGTH)).subscribe(w); <add> Observable<String> src = Observable.from("a", "x", "ab", "abc", "cba", "de", "x", "a", "abcd"); <add> Observable.create(distinct(src, TO_UPPER_WITH_EXCEPTION, COMPARE_LENGTH)).subscribe(w); <ide> <ide> InOrder inOrder = inOrder(w); <ide> inOrder.verify(w, times(1)).onNext("a"); <ide> inOrder.verify(w, times(1)).onNext("x"); <del> create(distinct(src, TO_UPPER_WITH_EXCEPTION, COMPARE_LENGTH)).subscribe(w2); <add> Observable.create(distinct(src, TO_UPPER_WITH_EXCEPTION, COMPARE_LENGTH)).subscribe(w2); <ide> inOrder.verify(w, times(1)).onNext("abc"); <ide> inOrder.verify(w, times(1)).onNext("abcd"); <ide> inOrder.verify(w, times(1)).onCompleted(); <ide> public void testDistinctOfNormalSourceWithKeySelectorAndComparatorAndTwoSubscrip <ide> <ide> @Test <ide> public void testDistinctOfSourceWithNulls() { <del> Observable<String> src = from(null, "a", "a", null, null, "b", null); <del> create(distinct(src)).subscribe(w); <add> Observable<String> src = Observable.from(null, "a", "a", null, null, "b", null); <add> Observable.create(distinct(src)).subscribe(w); <ide> <ide> InOrder inOrder = inOrder(w); <ide> inOrder.verify(w, times(1)).onNext(null); <ide> public void testDistinctOfSourceWithNulls() { <ide> <ide> @Test <ide> public void testDistinctOfSourceWithExceptionsFromKeySelector() { <del> Observable<String> src = from("a", "b", null, "c"); <del> create(distinct(src, TO_UPPER_WITH_EXCEPTION)).subscribe(w); <add> Observable<String> src = Observable.from("a", "b", null, "c"); <add> Observable.create(distinct(src, TO_UPPER_WITH_EXCEPTION)).subscribe(w); <ide> <ide> InOrder inOrder = inOrder(w); <ide> inOrder.verify(w, times(1)).onNext("a"); <ide><path>rxjava-core/src/test/java/rx/operators/OperationDistinctUntilChangedTest.java <ide> package rx.operators; <ide> <add>import static org.mockito.Matchers.*; <add>import static org.mockito.Mockito.*; <add>import static org.mockito.MockitoAnnotations.*; <add>import static rx.operators.OperationDistinctUntilChanged.*; <add> <add>import java.util.Comparator; <add> <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> import org.mockito.InOrder; <ide> import org.mockito.Mock; <add> <ide> import rx.Observable; <ide> import rx.Observer; <ide> import rx.util.functions.Func1; <ide> <del>import java.util.Comparator; <del> <del>import static org.mockito.Matchers.any; <del>import static org.mockito.Matchers.anyString; <del>import static org.mockito.Mockito.*; <del>import static org.mockito.Mockito.never; <del>import static org.mockito.MockitoAnnotations.initMocks; <del>import static rx.Observable.*; <del>import static rx.operators.OperationDistinctUntilChanged.distinctUntilChanged; <del> <ide> public class OperationDistinctUntilChangedTest { <ide> <ide> @Mock <ide> public void before() { <ide> <ide> @Test <ide> public void testDistinctUntilChangedOfNone() { <del> Observable<String> src = empty(); <del> create(distinctUntilChanged(src)).subscribe(w); <add> Observable<String> src = Observable.empty(); <add> Observable.create(distinctUntilChanged(src)).subscribe(w); <ide> <ide> verify(w, never()).onNext(anyString()); <ide> verify(w, never()).onError(any(Throwable.class)); <ide> public void testDistinctUntilChangedOfNone() { <ide> <ide> @Test <ide> public void testDistinctUntilChangedOfNoneWithKeySelector() { <del> Observable<String> src = empty(); <del> create(distinctUntilChanged(src, TO_UPPER_WITH_EXCEPTION)).subscribe(w); <add> Observable<String> src = Observable.empty(); <add> Observable.create(distinctUntilChanged(src, TO_UPPER_WITH_EXCEPTION)).subscribe(w); <ide> <ide> verify(w, never()).onNext(anyString()); <ide> verify(w, never()).onError(any(Throwable.class)); <ide> public void testDistinctUntilChangedOfNoneWithKeySelector() { <ide> <ide> @Test <ide> public void testDistinctUntilChangedOfNormalSource() { <del> Observable<String> src = from("a", "b", "c", "c", "c", "b", "b", "a", "e"); <del> create(distinctUntilChanged(src)).subscribe(w); <add> Observable<String> src = Observable.from("a", "b", "c", "c", "c", "b", "b", "a", "e"); <add> Observable.create(distinctUntilChanged(src)).subscribe(w); <ide> <ide> InOrder inOrder = inOrder(w); <ide> inOrder.verify(w, times(1)).onNext("a"); <ide> public void testDistinctUntilChangedOfNormalSource() { <ide> <ide> @Test <ide> public void testDistinctUntilChangedOfNormalSourceWithKeySelector() { <del> Observable<String> src = from("a", "b", "c", "C", "c", "B", "b", "a", "e"); <del> create(distinctUntilChanged(src, TO_UPPER_WITH_EXCEPTION)).subscribe(w); <add> Observable<String> src = Observable.from("a", "b", "c", "C", "c", "B", "b", "a", "e"); <add> Observable.create(distinctUntilChanged(src, TO_UPPER_WITH_EXCEPTION)).subscribe(w); <ide> <ide> InOrder inOrder = inOrder(w); <ide> inOrder.verify(w, times(1)).onNext("a"); <ide> public void testDistinctUntilChangedOfNormalSourceWithKeySelector() { <ide> <ide> @Test <ide> public void testDistinctUntilChangedOfSourceWithNulls() { <del> Observable<String> src = from(null, "a", "a", null, null, "b", null, null); <del> create(distinctUntilChanged(src)).subscribe(w); <add> Observable<String> src = Observable.from(null, "a", "a", null, null, "b", null, null); <add> Observable.create(distinctUntilChanged(src)).subscribe(w); <ide> <ide> InOrder inOrder = inOrder(w); <ide> inOrder.verify(w, times(1)).onNext(null); <ide> public void testDistinctUntilChangedOfSourceWithNulls() { <ide> <ide> @Test <ide> public void testDistinctUntilChangedOfSourceWithExceptionsFromKeySelector() { <del> Observable<String> src = from("a", "b", null, "c"); <del> create(distinctUntilChanged(src, TO_UPPER_WITH_EXCEPTION)).subscribe(w); <add> Observable<String> src = Observable.from("a", "b", null, "c"); <add> Observable.create(distinctUntilChanged(src, TO_UPPER_WITH_EXCEPTION)).subscribe(w); <ide> <ide> InOrder inOrder = inOrder(w); <ide> inOrder.verify(w, times(1)).onNext("a"); <ide> public void testDistinctUntilChangedOfSourceWithExceptionsFromKeySelector() { <ide> <ide> @Test <ide> public void testDistinctUntilChangedWithComparator() { <del> Observable<String> src = from("a", "b", "c", "aa", "bb", "c", "ddd"); <del> create(distinctUntilChanged(src, COMPARE_LENGTH)).subscribe(w); <add> Observable<String> src = Observable.from("a", "b", "c", "aa", "bb", "c", "ddd"); <add> Observable.create(distinctUntilChanged(src, COMPARE_LENGTH)).subscribe(w); <ide> InOrder inOrder = inOrder(w); <ide> inOrder.verify(w, times(1)).onNext("a"); <ide> inOrder.verify(w, times(1)).onNext("aa"); <ide> public void testDistinctUntilChangedWithComparator() { <ide> <ide> @Test <ide> public void testDistinctUntilChangedWithComparatorAndKeySelector() { <del> Observable<String> src = from("a", "b", "x", "aa", "bb", "c", "ddd"); <del> create(distinctUntilChanged(src, TO_UPPER_WITH_EXCEPTION, COMPARE_LENGTH)).subscribe(w); <add> Observable<String> src = Observable.from("a", "b", "x", "aa", "bb", "c", "ddd"); <add> Observable.create(distinctUntilChanged(src, TO_UPPER_WITH_EXCEPTION, COMPARE_LENGTH)).subscribe(w); <ide> InOrder inOrder = inOrder(w); <ide> inOrder.verify(w, times(1)).onNext("a"); <ide> inOrder.verify(w, times(1)).onNext("x"); <ide> public void testDistinctUntilChangedWithComparatorAndKeySelector() { <ide> <ide> @Test <ide> public void testDistinctUntilChangedWithComparatorAndKeySelectorandTwoSubscriptions() { <del> Observable<String> src = from("a", "b", "x", "aa", "bb", "c", "ddd"); <del> create(distinctUntilChanged(src, TO_UPPER_WITH_EXCEPTION, COMPARE_LENGTH)).subscribe(w); <add> Observable<String> src = Observable.from("a", "b", "x", "aa", "bb", "c", "ddd"); <add> Observable.create(distinctUntilChanged(src, TO_UPPER_WITH_EXCEPTION, COMPARE_LENGTH)).subscribe(w); <ide> InOrder inOrder = inOrder(w); <ide> inOrder.verify(w, times(1)).onNext("a"); <ide> inOrder.verify(w, times(1)).onNext("x"); <del> create(distinctUntilChanged(src, TO_UPPER_WITH_EXCEPTION, COMPARE_LENGTH)).subscribe(w2); <add> Observable.create(distinctUntilChanged(src, TO_UPPER_WITH_EXCEPTION, COMPARE_LENGTH)).subscribe(w2); <ide> inOrder.verify(w, times(1)).onNext("c"); <ide> inOrder.verify(w, times(1)).onNext("ddd"); <ide> inOrder.verify(w, times(1)).onCompleted(); <ide><path>rxjava-core/src/test/java/rx/operators/OperationFirstOrDefaultTest.java <ide> package rx.operators; <ide> <add>import static org.mockito.Matchers.*; <add>import static org.mockito.Mockito.*; <add>import static org.mockito.MockitoAnnotations.*; <add>import static rx.operators.OperationFirstOrDefault.*; <add> <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> import org.mockito.Mock; <add> <ide> import rx.Observable; <ide> import rx.Observer; <ide> import rx.util.functions.Func1; <ide> <del>import static org.mockito.Matchers.any; <del>import static org.mockito.Matchers.anyString; <del>import static org.mockito.Mockito.never; <del>import static org.mockito.Mockito.*; <del>import static org.mockito.MockitoAnnotations.initMocks; <del>import static rx.Observable.*; <del>import static rx.operators.OperationFirstOrDefault.firstOrDefault; <del> <ide> public class OperationFirstOrDefaultTest { <ide> <ide> @Mock <ide> public void before() { <ide> <ide> @Test <ide> public void testFirstOrElseOfNone() { <del> Observable<String> src = empty(); <del> create(firstOrDefault(src, "default")).subscribe(w); <add> Observable<String> src = Observable.empty(); <add> Observable.create(firstOrDefault(src, "default")).subscribe(w); <ide> <ide> verify(w, times(1)).onNext(anyString()); <ide> verify(w, times(1)).onNext("default"); <ide> public void testFirstOrElseOfNone() { <ide> <ide> @Test <ide> public void testFirstOrElseOfSome() { <del> Observable<String> src = from("a", "b", "c"); <del> create(firstOrDefault(src, "default")).subscribe(w); <add> Observable<String> src = Observable.from("a", "b", "c"); <add> Observable.create(firstOrDefault(src, "default")).subscribe(w); <ide> <ide> verify(w, times(1)).onNext(anyString()); <ide> verify(w, times(1)).onNext("a"); <ide> public void testFirstOrElseOfSome() { <ide> <ide> @Test <ide> public void testFirstOrElseWithPredicateOfNoneMatchingThePredicate() { <del> Observable<String> src = from("a", "b", "c"); <del> create(firstOrDefault(src, IS_D, "default")).subscribe(w); <add> Observable<String> src = Observable.from("a", "b", "c"); <add> Observable.create(firstOrDefault(src, IS_D, "default")).subscribe(w); <ide> <ide> verify(w, times(1)).onNext(anyString()); <ide> verify(w, times(1)).onNext("default"); <ide> public void testFirstOrElseWithPredicateOfNoneMatchingThePredicate() { <ide> <ide> @Test <ide> public void testFirstOrElseWithPredicateOfSome() { <del> Observable<String> src = from("a", "b", "c", "d", "e", "f"); <del> create(firstOrDefault(src, IS_D, "default")).subscribe(w); <add> Observable<String> src = Observable.from("a", "b", "c", "d", "e", "f"); <add> Observable.create(firstOrDefault(src, IS_D, "default")).subscribe(w); <ide> <ide> verify(w, times(1)).onNext(anyString()); <ide> verify(w, times(1)).onNext("d"); <ide><path>rxjava-core/src/test/java/rx/operators/OperationSkipWhileTest.java <ide> package rx.operators; <ide> <add>import static org.mockito.Matchers.*; <add>import static org.mockito.Mockito.*; <add>import static rx.operators.OperationSkipWhile.*; <add> <ide> import org.junit.Test; <ide> import org.mockito.InOrder; <add> <ide> import rx.Observable; <ide> import rx.Observer; <ide> import rx.util.functions.Func1; <ide> import rx.util.functions.Func2; <ide> <del>import static org.mockito.Matchers.any; <del>import static org.mockito.Matchers.anyInt; <del>import static org.mockito.Mockito.*; <del>import static rx.Observable.create; <del>import static rx.operators.OperationSkipWhile.skipWhile; <del>import static rx.operators.OperationSkipWhile.skipWhileWithIndex; <del> <ide> public class OperationSkipWhileTest { <ide> <ide> @SuppressWarnings("unchecked") <ide> public Boolean call(Integer value, Integer index) { <ide> @Test <ide> public void testSkipWithIndex() { <ide> Observable<Integer> src = Observable.from(1, 2, 3, 4, 5); <del> create(skipWhileWithIndex(src, INDEX_LESS_THAN_THREE)).subscribe(w); <add> Observable.create(skipWhileWithIndex(src, INDEX_LESS_THAN_THREE)).subscribe(w); <ide> <ide> InOrder inOrder = inOrder(w); <ide> inOrder.verify(w, times(1)).onNext(4); <ide> public void testSkipWithIndex() { <ide> @Test <ide> public void testSkipEmpty() { <ide> Observable<Integer> src = Observable.empty(); <del> create(skipWhile(src, LESS_THAN_FIVE)).subscribe(w); <add> Observable.create(skipWhile(src, LESS_THAN_FIVE)).subscribe(w); <ide> verify(w, never()).onNext(anyInt()); <ide> verify(w, never()).onError(any(Throwable.class)); <ide> verify(w, times(1)).onCompleted(); <ide> public void testSkipEmpty() { <ide> @Test <ide> public void testSkipEverything() { <ide> Observable<Integer> src = Observable.from(1, 2, 3, 4, 3, 2, 1); <del> create(skipWhile(src, LESS_THAN_FIVE)).subscribe(w); <add> Observable.create(skipWhile(src, LESS_THAN_FIVE)).subscribe(w); <ide> verify(w, never()).onNext(anyInt()); <ide> verify(w, never()).onError(any(Throwable.class)); <ide> verify(w, times(1)).onCompleted(); <ide> public void testSkipEverything() { <ide> @Test <ide> public void testSkipNothing() { <ide> Observable<Integer> src = Observable.from(5, 3, 1); <del> create(skipWhile(src, LESS_THAN_FIVE)).subscribe(w); <add> Observable.create(skipWhile(src, LESS_THAN_FIVE)).subscribe(w); <ide> <ide> InOrder inOrder = inOrder(w); <ide> inOrder.verify(w, times(1)).onNext(5); <ide> public void testSkipNothing() { <ide> @Test <ide> public void testSkipSome() { <ide> Observable<Integer> src = Observable.from(1, 2, 3, 4, 5, 3, 1, 5); <del> create(skipWhile(src, LESS_THAN_FIVE)).subscribe(w); <add> Observable.create(skipWhile(src, LESS_THAN_FIVE)).subscribe(w); <ide> <ide> InOrder inOrder = inOrder(w); <ide> inOrder.verify(w, times(1)).onNext(5); <ide> public void testSkipSome() { <ide> @Test <ide> public void testSkipError() { <ide> Observable<Integer> src = Observable.from(1, 2, 42, 5, 3, 1); <del> create(skipWhile(src, LESS_THAN_FIVE)).subscribe(w); <add> Observable.create(skipWhile(src, LESS_THAN_FIVE)).subscribe(w); <ide> <ide> InOrder inOrder = inOrder(w); <ide> inOrder.verify(w, never()).onNext(anyInt());
4
Python
Python
fix undefined variable in conllu script
7441fce7ba68474798ae9b46e26b28ce0b2d992b
<ide><path>examples/training/conllu.py <ide> def get_token_conllu(token, i): <ide> n = 1 <ide> while token.nbor(n)._.inside_fused: <ide> n += 1 <del> id_ = '%d-%d' % (k, k+n) <add> id_ = '%d-%d' % (i, i+n) <ide> lines = [id_, token.text, '_', '_', '_', '_', '_', '_', '_', '_'] <ide> else: <ide> lines = []
1
PHP
PHP
add multiple cookies to a response
2883c1688cb0bfc7f760d31e7b08bcc5d9dcb830
<ide><path>src/Illuminate/Http/RedirectResponse.php <ide> public function withCookie(Cookie $cookie) <ide> return $this; <ide> } <ide> <add> /** <add> * Add multiple cookies to the response. <add> * <add> * @param array $cookie <add> * @return $this <add> */ <add> public function withCookies(array $cookies) <add> { <add> foreach ($cookies as $cookie) <add> { <add> $this->headers->setCookie($cookie); <add> } <add> <add> return $this; <add> } <add> <ide> /** <ide> * Flash an array of input to the session. <ide> *
1
Ruby
Ruby
fix indentation mismatch
1b94d5dc6500a34803fda784d87a361b532b3fb4
<ide><path>activesupport/lib/active_support/cache/file_store.rb <ide> def search_dir(dir, &callback) <ide> end <ide> end <ide> end <del> end <add> end <ide> end <ide> end <ide><path>activesupport/lib/active_support/callbacks.rb <ide> def evaluate_method(method, *args, &block) <ide> "Callbacks must be a symbol denoting the method to call, a string to be evaluated, " + <ide> "a block to be invoked, or an object responding to the callback method." <ide> end <del> end <add> end <ide> end <ide> <ide> def should_run_callback?(*args) <ide><path>activesupport/lib/active_support/core_ext/hash/conversions.rb <ide> def to_xml(options = {}) <ide> XML_FORMATTING[type_name] ? XML_FORMATTING[type_name].call(value) : value, <ide> attributes <ide> ) <del> end <add> end <ide> end <ide> end <ide>
3
Go
Go
remove os() from layer interface
c94d34f783944ff6586846ccd11e86925fcee171
<ide><path>distribution/xfer/download_test.go <ide> func (ml *mockLayer) DiffSize() (size int64, err error) { <ide> return 0, nil <ide> } <ide> <del>func (ml *mockLayer) OS() string { <del> return ml.os <del>} <del> <ide> func (ml *mockLayer) Metadata() (map[string]string, error) { <ide> return make(map[string]string), nil <ide> } <ide> func (ls *mockLayerStore) DriverName() string { <ide> return "mock" <ide> } <ide> <del>func (ls *mockLayerStore) OS() string { <del> return runtime.GOOS <del>} <del> <ide> type mockDownloadDescriptor struct { <ide> currentDownloads *int32 <ide> id string <ide><path>image/store.go <ide> func (is *store) Delete(id ID) ([]layer.Metadata, error) { <ide> if imageMeta == nil { <ide> return nil, fmt.Errorf("unrecognized image ID %s", id.String()) <ide> } <add> img, err := is.Get(id) <add> if err != nil { <add> return nil, fmt.Errorf("unrecognized image %s, %v", id.String(), err) <add> } <add> if !system.IsOSSupported(img.OperatingSystem()) { <add> return nil, fmt.Errorf("unsupported image operating system %q", img.OperatingSystem()) <add> } <ide> for id := range imageMeta.children { <ide> is.fs.DeleteMetadata(id.Digest(), "parent") <ide> } <ide> func (is *store) Delete(id ID) ([]layer.Metadata, error) { <ide> is.fs.Delete(id.Digest()) <ide> <ide> if imageMeta.layer != nil { <del> return is.lss[imageMeta.layer.OS()].Release(imageMeta.layer) <add> return is.lss[img.OperatingSystem()].Release(imageMeta.layer) <ide> } <ide> return nil, nil <ide> } <ide><path>layer/empty.go <ide> func (el *emptyLayer) Parent() Layer { <ide> return nil <ide> } <ide> <del>func (el *emptyLayer) OS() string { <del> return "" <del>} <del> <ide> func (el *emptyLayer) Size() (size int64, err error) { <ide> return 0, nil <ide> } <ide><path>layer/layer.go <ide> type Layer interface { <ide> // Parent returns the next layer in the layer chain. <ide> Parent() Layer <ide> <del> // OS returns the operating system of the layer <del> OS() string <del> <ide> // Size returns the size of the entire layer chain. The size <ide> // is calculated from the total size of all files in the layers. <ide> Size() (int64, error) <ide> type RWLayer interface { <ide> <ide> // Metadata returns the low level metadata for the mutable layer <ide> Metadata() (map[string]string, error) <del> <del> // OS returns the operating system of the writable layer <del> OS() string <ide> } <ide> <ide> // Metadata holds information about a <ide> type Store interface { <ide> Cleanup() error <ide> DriverStatus() [][2]string <ide> DriverName() string <del> OS() string <ide> } <ide> <ide> // DescribableStore represents a layer store capable of storing <ide><path>layer/layer_store.go <ide> func (ls *layerStore) DriverName() string { <ide> return ls.driver.String() <ide> } <ide> <del>func (ls *layerStore) OS() string { <del> return ls.os <del>} <del> <ide> type naiveDiffPathDriver struct { <ide> graphdriver.Driver <ide> } <ide><path>layer/mounted_layer.go <ide> func (ml *mountedLayer) Parent() Layer { <ide> return nil <ide> } <ide> <del>func (ml *mountedLayer) OS() string { <del> return ml.layerStore.os <del>} <del> <ide> func (ml *mountedLayer) Size() (int64, error) { <ide> return ml.layerStore.driver.DiffSize(ml.mountID, ml.cacheParent()) <ide> } <ide><path>layer/ro_layer.go <ide> func (rl *roLayer) Parent() Layer { <ide> return rl.parent <ide> } <ide> <del>func (rl *roLayer) OS() string { <del> return rl.layerStore.os <del>} <del> <ide> func (rl *roLayer) Size() (size int64, err error) { <ide> if rl.parent != nil { <ide> size, err = rl.parent.Size() <ide><path>migrate/v1/migratev1_test.go <ide> func (l *mockLayer) DiffSize() (int64, error) { <ide> return 0, nil <ide> } <ide> <del>func (l *mockLayer) OS() string { <del> return "" <del>} <del> <ide> func (l *mockLayer) Metadata() (map[string]string, error) { <ide> return nil, nil <ide> }
8
Javascript
Javascript
update stability index linking logic
cb023a3e7078e03bbb7881e98eb250aaca82ae55
<ide><path>tools/doc/html.js <ide> function preprocessElements({ filename }) { <ide> <ide> // Do not link to the section we are already in. <ide> const noLinking = filename.includes('documentation') && <del> heading !== null && heading.children[0].value === 'Stability Index'; <add> heading !== null && heading.children[0].value === 'Stability index'; <ide> <ide> // Collapse blockquote and paragraph into a single node <ide> node.type = 'paragraph';
1
Text
Text
add info on env variables for formula cookbook
d5f6e4cd34ba2550499876ed4c8988e183b3465c
<ide><path>docs/Formula-Cookbook.md <ide> Homebrew provides two formula DSL methods for launchd plist files: <ide> * [`plist_name`](https://www.rubydoc.info/github/Homebrew/brew/master/Formula#plist_name-instance_method) will return e.g. `homebrew.mxcl.<formula>` <ide> * [`plist_path`](https://www.rubydoc.info/github/Homebrew/brew/master/Formula#plist_path-instance_method) will return e.g. `/usr/local/Cellar/foo/0.1/homebrew.mxcl.foo.plist` <ide> <add>### Using environment variables <add> <add>Homebrew has multiple levels of environment variable filtering which affects variables available to formulae. <add> <add>Firstly, the overall environment in which Homebrew runs is filtered to avoid environment contamination breaking from-source builds ([ref](https://github.com/Homebrew/brew/issues/932)). In particular, this process filters all but the given whitelisted variables, but allows environment variables prefixed with `HOMEBREW_`. The specific implementation can be seen in the [`brew`](https://github.com/Homebrew/brew/blob/master/bin/brew) script. <add> <add>The second level of filtering removes sensitive environment variables (such as credentials like keys, passwords or tokens) to avoid malicious subprocesses obtaining them ([ref](https://github.com/Homebrew/brew/pull/2524)). This has the effect of preventing any such variables from reaching a formula's Ruby code as they are filtered before it is called. The specific implementation can be seen in the [`clear_sensitive_environment` method](https://github.com/Homebrew/brew/blob/master/Library/Homebrew/extend/ENV.rb). <add> <add>In summary, environment variables used by a formula need to conform to these filtering rules in order to be available. <add> <ide> ## Updating formulae <ide> <ide> Eventually a new version of the software will be released. In this case you should update the [`url`](https://www.rubydoc.info/github/Homebrew/brew/master/Formula#url-class_method) and [`sha256`](https://www.rubydoc.info/github/Homebrew/brew/master/Formula#sha256%3D-class_method). If a [`revision`](https://www.rubydoc.info/github/Homebrew/brew/master/Formula#revision%3D-class_method) line exists outside any `bottle do` block *and* the new release is stable rather than devel, it should be removed.
1
PHP
PHP
fix additional missing api doc tags
33a5b6e451b710ee59a0eecd262ef3ed78221a7c
<ide><path>lib/Cake/Model/Datasource/Database/Sqlite.php <ide> public function column($real) { <ide> /** <ide> * Generate ResultSet <ide> * <del> * @param mixed $results <add> * @param mixed $results The results to modify. <ide> * @return void <ide> */ <ide> public function resultSet($results) { <ide> public function resultSet($results) { <ide> $index = 0; <ide> $j = 0; <ide> <del> //PDO::getColumnMeta is experimental and does not work with sqlite3, <del> // so try to figure it out based on the querystring <add> // PDO::getColumnMeta is experimental and does not work with sqlite3, <add> // so try to figure it out based on the querystring <ide> $querystring = $results->queryString; <ide> if (stripos($querystring, 'SELECT') === 0) { <ide> $last = strripos($querystring, 'FROM'); <ide><path>lib/Cake/Model/Datasource/DboSource.php <ide> public function rawQuery($sql, $params = array()) { <ide> * - log - Whether or not the query should be logged to the memory log. <ide> * <ide> * @param string $sql SQL statement <del> * @param array $options <del> * @param array $params values to be bound to the query <add> * @param array $options The options for executing the query. <add> * @param array $params values to be bound to the query. <ide> * @return mixed Resource or object representing the result set, or false on failure <ide> */ <ide> public function execute($sql, $options = array(), $params = array()) { <ide> public function lastError(PDOStatement $query = null) { <ide> * Returns number of affected rows in previous database operation. If no previous operation exists, <ide> * this returns false. <ide> * <del> * @param mixed $source <add> * @param mixed $source The source to check. <ide> * @return integer Number of affected rows <ide> */ <ide> public function lastAffected($source = null) { <ide> public function fetchResult() { <ide> /** <ide> * Modifies $result array to place virtual fields in model entry where they belongs to <ide> * <del> * @param array $result Reference to the fetched row <add> * @param array &$result Reference to the fetched row <ide> * @return void <ide> */ <ide> public function fetchVirtualField(&$result) { <ide> public function read(Model $Model, $queryData = array(), $recursive = null) { <ide> * <ide> * The primary model is always excluded, because the filtering is later done by Model::_filterResults(). <ide> * <del> * @param array $resultSet Reference of resultset to be filtered. <add> * @param array &$resultSet Reference of resultset to be filtered. <ide> * @param Model $Model Instance of model to operate against. <ide> * @param array $filtered List of classes already filtered, to be skipped. <ide> * @return array Array of results that have been filtered through $Model->afterFind. <ide> protected function _filterResults(&$resultSet, Model $Model, $filtered = array() <ide> * @param string $type Association type, one of the model association types ie. hasMany. <ide> * @param string $association Association name. <ide> * @param array $assocData Association data. <del> * @param array $queryData An array of queryData information containing keys similar to Model::find(). <add> * @param array &$queryData An array of queryData information containing keys similar to Model::find(). <ide> * @param boolean $external Whether or not the association query is on an external datasource. <del> * @param array $resultSet Existing results. <add> * @param array &$resultSet Existing results. <ide> * @param integer $recursive Number of levels of association. <del> * @param array $stack <add> * @param array $stack A list with joined models. <ide> * @return mixed <ide> * @throws CakeException when results cannot be created. <ide> */ <ide> protected function _fetchHasAndBelongsToMany(Model $Model, $query, $ids, $associ <ide> * <ide> * Note: this function also deals with the formatting of the data. <ide> * <del> * @param array $resultSet Data to merge into. <add> * @param array &$resultSet Data to merge into. <ide> * @param array $assocResultSet Data to merge. <ide> * @param string $association Name of Model being merged. <ide> * @param Model $Model Model being merged onto. <ide> protected function _mergeHasMany(&$resultSet, $assocResultSet, $association, Mod <ide> /** <ide> * Merge association of merge into data <ide> * <del> * @param array $data <del> * @param array $merge <del> * @param string $association <del> * @param string $type <del> * @param boolean $selfJoin <add> * @param array &$data The data to merge. <add> * @param array &$merge The data to merge. <add> * @param string $association The association name to merge. <add> * @param string $type The type of association <add> * @param boolean $selfJoin Whether or not this is a self join. <ide> * @return void <ide> */ <ide> protected function _mergeAssociation(&$data, &$merge, $association, $type, $selfJoin = false) { <ide> protected function _mergeAssociation(&$data, &$merge, $association, $type, $self <ide> * <ide> * When no fields are set, all the $Model fields are returned. <ide> * <del> * @param Model $Model <add> * @param Model $Model The model to prepare. <ide> * @param array $queryData An array of queryData information containing keys similar to Model::find(). <ide> * @return array Array containing SQL fields. <ide> */ <ide> public function prepareFields(Model $Model, $queryData) { <ide> * <ide> * This is merely a convenient wrapper to DboSource::buildStatement(). <ide> * <del> * @param Model $Model <add> * @param Model $Model The model to build an association query for. <ide> * @param array $queryData An array of queryData information containing keys similar to Model::find(). <ide> * @return string String containing an SQL statement. <ide> * @see DboSource::buildStatement() <ide> public function buildAssociationQuery(Model $Model, $queryData) { <ide> * @param string $type Association type, one of the model association types ie. hasMany. <ide> * @param string $association Association name. <ide> * @param array $assocData Association data. <del> * @param array $queryData An array of queryData information containing keys similar to Model::find(). <add> * @param array &$queryData An array of queryData information containing keys similar to Model::find(). <ide> * @param boolean $external Whether or not the association query is on an external datasource. <ide> * @return mixed <ide> * String representing a query. <ide> public function buildStatement($query, Model $Model) { <ide> /** <ide> * Renders a final SQL JOIN statement <ide> * <del> * @param array $data <add> * @param array $data The data to generate a join statement for. <ide> * @return string <ide> */ <ide> public function renderJoinStatement($data) { <ide> public function renderStatement($type, $data) { <ide> /** <ide> * Merges a mixed set of string/array conditions. <ide> * <del> * @param mixed $query <del> * @param mixed $assoc <add> * @param mixed $query The query to merge conditions for. <add> * @param mixed $assoc The association names. <ide> * @return array <ide> */ <ide> protected function _mergeConditions($query, $assoc) { <ide> protected function _mergeConditions($query, $assoc) { <ide> * Generates and executes an SQL UPDATE statement for given model, fields, and values. <ide> * For databases that do not support aliases in UPDATE queries. <ide> * <del> * @param Model $Model <del> * @param array $fields <del> * @param array $values <del> * @param mixed $conditions <add> * @param Model $Model The model to update. <add> * @param array $fields The fields to update <add> * @param array $values The values fo the fields. <add> * @param mixed $conditions The conditions for the update. When non-empty $values will not be quoted. <ide> * @return boolean Success <ide> */ <ide> public function update(Model $Model, $fields = array(), $values = null, $conditions = null) { <ide> public function update(Model $Model, $fields = array(), $values = null, $conditi <ide> /** <ide> * Quotes and prepares fields and values for an SQL UPDATE statement <ide> * <del> * @param Model $Model <del> * @param array $fields <add> * @param Model $Model The model to prepare fields for. <add> * @param array $fields The fields to update. <ide> * @param boolean $quoteValues If values should be quoted, or treated as SQL snippets <ide> * @param boolean $alias Include the model alias in the field name <ide> * @return array Fields and values, quoted and prepared <ide> protected function _prepareUpdateFields(Model $Model, $fields, $quoteValues = tr <ide> * Generates and executes an SQL DELETE statement. <ide> * For databases that do not support aliases in UPDATE queries. <ide> * <del> * @param Model $Model <del> * @param mixed $conditions <add> * @param Model $Model The model to delete from <add> * @param mixed $conditions The conditions to use. If empty the model's primary key will be used. <ide> * @return boolean Success <ide> */ <ide> public function delete(Model $Model, $conditions = null) { <ide> public function delete(Model $Model, $conditions = null) { <ide> * Gets a list of record IDs for the given conditions. Used for multi-record updates and deletes <ide> * in databases that do not support aliases in UPDATE/DELETE queries. <ide> * <del> * @param Model $Model <del> * @param mixed $conditions <add> * @param Model $Model The model to find matching records for. <add> * @param mixed $conditions The conditions to match against. <ide> * @return array List of record IDs <ide> */ <ide> protected function _matchRecords(Model $Model, $conditions = null) { <ide> protected function _matchRecords(Model $Model, $conditions = null) { <ide> /** <ide> * Returns an array of SQL JOIN conditions from a model's associations. <ide> * <del> * @param Model $Model <add> * @param Model $Model The model to get joins for.2 <ide> * @return array <ide> */ <ide> protected function _getJoins(Model $Model) { <ide> protected function _getJoins(Model $Model) { <ide> /** <ide> * Returns an SQL calculation, i.e. COUNT() or MAX() <ide> * <del> * @param Model $Model <add> * @param Model $Model The model to get a calculated field for. <ide> * @param string $func Lowercase name of SQL function, i.e. 'count' or 'max' <ide> * @param array $params Function parameters (any values must be quoted manually) <ide> * @return string An SQL calculation function <ide> protected function _rollbackNested() { <ide> /** <ide> * Returns the ID generated from the previous INSERT operation. <ide> * <del> * @param mixed $source <add> * @param mixed $source The source to get an id for. <ide> * @return mixed <ide> */ <ide> public function lastInsertId($source = null) { <ide> public function lastInsertId($source = null) { <ide> * If conditions are supplied then they will be returned. If a model doesn't exist and no conditions <ide> * were provided either null or false will be returned based on what was input. <ide> * <del> * @param Model $Model <add> * @param Model $Model The model to get conditions for. <ide> * @param string|array|boolean $conditions Array of conditions, conditions string, null or false. If an array of conditions, <ide> * or string conditions those conditions will be returned. With other values the model's existence will be checked. <ide> * If the model doesn't exist a null or false will be returned depending on the input value. <ide> public function defaultConditions(Model $Model, $conditions, $useAlias = true) { <ide> /** <ide> * Returns a key formatted like a string Model.fieldname(i.e. Post.title, or Country.name) <ide> * <del> * @param Model $Model <del> * @param string $key <del> * @param string $assoc <add> * @param Model $Model The model to get a key for. <add> * @param string $key The key field. <add> * @param string $assoc The association name. <ide> * @return string <ide> */ <ide> public function resolveKey(Model $Model, $key, $assoc = null) { <ide> public function resolveKey(Model $Model, $key, $assoc = null) { <ide> /** <ide> * Private helper method to remove query metadata in given data array. <ide> * <del> * @param array $data <add> * @param array $data The data to scrub. <ide> * @return array <ide> */ <ide> protected function _scrubQueryData($data) { <ide> protected function _scrubQueryData($data) { <ide> /** <ide> * Converts model virtual fields into sql expressions to be fetched later <ide> * <del> * @param Model $Model <add> * @param Model $Model The model to get virtual fields for. <ide> * @param string $alias Alias table name <ide> * @param array $fields virtual fields to be used on query <ide> * @return array <ide> protected function _constructVirtualFields(Model $Model, $alias, $fields) { <ide> /** <ide> * Generates the fields list of an SQL query. <ide> * <del> * @param Model $Model <add> * @param Model $Model The model to get fields for. <ide> * @param string $alias Alias table name <del> * @param mixed $fields <add> * @param mixed $fields The provided list of fields. <ide> * @param boolean $quote If false, returns fields array unquoted <ide> * @return array <ide> */ <ide> protected function _parseKey($key, $value, Model $Model = null) { <ide> /** <ide> * Quotes Model.fields <ide> * <del> * @param string $conditions <add> * @param string $conditions The conditions to quote. <ide> * @return string or false if no match <ide> */ <ide> protected function _quoteFields($conditions) { <ide> public function order($keys, $direction = 'ASC', Model $Model = null) { <ide> * Create a GROUP BY SQL clause. <ide> * <ide> * @param string|array $fields Group By fields <del> * @param Model $Model <add> * @param Model $Model The model to get group by fields for. <ide> * @return string Group By clause or null. <ide> */ <ide> public function group($fields, Model $Model = null) { <ide> public function length($real) { <ide> * Translates between PHP boolean values and Database (faked) boolean values <ide> * <ide> * @param mixed $data Value to be translated <del> * @param boolean $quote <add> * @param boolean $quote Whether or not the field should be cast to a string. <ide> * @return string|boolean Converted boolean value <ide> */ <ide> public function boolean($data, $quote = false) { <ide> public function createSchema($schema, $tableName = null) { <ide> } <ide> <ide> /** <del> * Generate a alter syntax from CakeSchema::compare() <add> * Generate a alter syntax from CakeSchema::compare() <ide> * <del> * @param mixed $compare <del> * @param string $table <add> * @param mixed $compare The comparison data. <add> * @param string $table The table name. <ide> * @return boolean <ide> */ <ide> public function alterSchema($compare, $table = null) { <ide> protected function _buildFieldParameters($columnString, $columnData, $position) <ide> /** <ide> * Format indexes for create table. <ide> * <del> * @param array $indexes <del> * @param string $table <add> * @param array $indexes The indexes to build <add> * @param string $table The table name. <ide> * @return array <ide> */ <ide> public function buildIndex($indexes, $table = null) { <ide> public function buildIndex($indexes, $table = null) { <ide> /** <ide> * Read additional table parameters <ide> * <del> * @param string $name <add> * @param string $name The table name to read. <ide> * @return array <ide> */ <ide> public function readTableParameters($name) { <ide> public function readTableParameters($name) { <ide> /** <ide> * Format parameters for create table <ide> * <del> * @param array $parameters <del> * @param string $table <add> * @param array $parameters The parameters to create SQL for. <add> * @param string $table The table name. <ide> * @return array <ide> */ <ide> public function buildTableParameters($parameters, $table = null) { <ide> public function buildTableParameters($parameters, $table = null) { <ide> /** <ide> * Guesses the data type of an array <ide> * <del> * @param string $value <del> * @return void <add> * @param string $value The value to introspect for type data. <add> * @return string <ide> */ <ide> public function introspectType($value) { <ide> if (!is_array($value)) {
2
Javascript
Javascript
remove old comments
6f310b55534ad3cbeeb2fb5993678bedc4ad3390
<ide><path>Libraries/Interaction/FrameRateLogger.js <ide> const FrameRateLogger = { <ide> ); <ide> } <ide> if (NativeModules.FrameRateLogger) { <del> // Freeze the object to avoid the prepack warning (PP0017) about leaking <del> // unfrozen objects. <ide> // Needs to clone the object first to avoid modifying the argument. <ide> const optionsClone = { <ide> debug: !!options.debug, <ide> reportStackTraces: !!options.reportStackTraces, <ide> }; <del> Object.freeze(optionsClone); <del> Object.seal(optionsClone); <ide> NativeModules.FrameRateLogger.setGlobalOptions(optionsClone); <ide> } <ide> },
1
Javascript
Javascript
fix morph multimaterial
b4c85224bd0113cbe24b87e9cd9e5cfb527f32c4
<ide><path>examples/js/loaders/FBXLoader.js <ide> THREE.FBXLoader = ( function () { <ide> <ide> setupMorphMaterials: function () { <ide> <add> var self = this; <ide> sceneGraph.traverse( function ( child ) { <ide> <ide> if ( child.isMesh ) { <ide> <del> if ( child.geometry.morphAttributes.position || child.geometry.morphAttributes.normal ) { <del> <del> var uuid = child.uuid; <del> var matUuid = child.material.uuid; <add> if ( child.geometry.morphAttributes.position && child.geometry.morphAttributes.position.length ) { <ide> <del> // if a geometry has morph targets, it cannot share the material with other geometries <del> var sharedMat = false; <add> if ( Array.isArray( child.material ) ) { <ide> <del> sceneGraph.traverse( function ( child ) { <add> child.material.forEach( function ( material, i ) { <ide> <del> if ( child.isMesh ) { <add> self.setupMorphMaterial( child, material, i ); <ide> <del> if ( child.material.uuid === matUuid && child.uuid !== uuid ) sharedMat = true; <del> <del> } <add> } ); <ide> <del> } ); <add> } else { <ide> <del> if ( sharedMat === true ) child.material = child.material.clone(); <add> self.setupMorphMaterial( child, child.material ); <ide> <del> child.material.morphTargets = true; <add> } <ide> <ide> } <ide> <ide> THREE.FBXLoader = ( function () { <ide> <ide> }, <ide> <add> setupMorphMaterial: function ( child, material, index ) { <add> <add> var uuid = child.uuid; <add> var matUuid = material.uuid; <add> <add> // if a geometry has morph targets, it cannot share the material with other geometries <add> var sharedMat = false; <add> <add> sceneGraph.traverse( function ( node ) { <add> <add> if ( node.isMesh ) { <add> <add> if ( Array.isArray( node.material ) ) { <add> <add> node.material.forEach( function ( mat ) { <add> <add> if ( mat.uuid === matUuid && node.uuid !== uuid ) sharedMat = true; <add> <add> } ); <add> <add> } else if ( node.material.uuid === matUuid && node.uuid !== uuid ) sharedMat = true; <add> <add> } <add> <add> } ); <add> <add> if ( sharedMat === true ) { <add> <add> var clonedMat = material.clone(); <add> clonedMat.morphTargets = true; <add> <add> if ( index === undefined ) child.material = clonedMat; <add> else child.material[ index ] = clonedMat; <add> <add> } else material.morphTargets = true; <add> <add> } <add> <ide> }; <ide> <ide> // parse Geometry data from FBXTree and return map of BufferGeometries <ide> THREE.FBXLoader = ( function () { <ide> var initialRotation = new THREE.Quaternion(); <ide> var initialScale = new THREE.Vector3(); <ide> <del> rawTracks.transform.decompose( initialPosition, initialRotation, initialScale ); <add> if ( rawTracks.transform ) rawTracks.transform.decompose( initialPosition, initialRotation, initialScale ); <ide> <ide> initialPosition = initialPosition.toArray(); <ide> initialRotation = new THREE.Euler().setFromQuaternion( initialRotation, rawTracks.eulerOrder ).toArray();
1
Ruby
Ruby
improve #configured_migrate_path logic
8af4165a18f63f337dcb8fe8c4f90454b22c151d
<ide><path>activerecord/lib/rails/generators/active_record/migration.rb <ide> def default_migrate_path <ide> end <ide> <ide> def configured_migrate_path <del> return unless database = options[:database] <del> config = ActiveRecord::Base.configurations.configs_for( <add> config = Array(ActiveRecord::Base.configurations.configs_for( <ide> env_name: Rails.env, <del> name: database <del> ) <del> config&.migrations_paths <add> name: options[:database], <add> )).first <add> Array(config&.migrations_paths).first <ide> end <ide> end <ide> end
1
Javascript
Javascript
add test case
9bec35433c05a179c2534b51d42fb61b1eb90200
<ide><path>test/ProfilingPlugin.test.js <ide> describe("Profiling Plugin", function () { <ide> if (err) return done(err); <ide> if (!fs.existsSync(outputPath)) <ide> return done(new Error("Folder should be created.")); <add> const data = require(finalPath); <add> const maxTs = data.reduce((max, entry) => Math.max(max, entry.ts), 0); <add> const minTs = data[0].ts; <add> const duration = maxTs - minTs; <add> expect(duration).toBeLessThan(10000 * 1000); <add> const cpuProfile = data.find(entry => entry.name === "CpuProfile"); <add> expect(cpuProfile).toBeTypeOf("object"); <add> const profile = cpuProfile.args.data.cpuProfile; <add> expect(profile.startTime).toBeGreaterThanOrEqual(minTs); <add> expect(profile.endTime).toBeLessThanOrEqual(maxTs); <ide> done(); <ide> }); <ide> });
1
Java
Java
avoid npe in pathmatchconfigurer
4c08c276f79e00f66d56344b9aca901f1b326e0c
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/PathMatchConfigurer.java <ide> public PathMatchConfigurer addPathPrefix(String prefix, Predicate<Class<?>> pred <ide> * {@code false} and use of this property becomes unnecessary. <ide> */ <ide> @Deprecated <del> public PathMatchConfigurer setUseSuffixPatternMatch(Boolean suffixPatternMatch) { <add> public PathMatchConfigurer setUseSuffixPatternMatch(@Nullable Boolean suffixPatternMatch) { <ide> this.suffixPatternMatch = suffixPatternMatch; <del> this.preferPathMatcher |= suffixPatternMatch; <add> this.preferPathMatcher |= (suffixPatternMatch != null && suffixPatternMatch); <ide> return this; <ide> } <ide> <ide> public PathMatchConfigurer setUseSuffixPatternMatch(Boolean suffixPatternMatch) <ide> * config options. <ide> */ <ide> @Deprecated <del> public PathMatchConfigurer setUseRegisteredSuffixPatternMatch(Boolean registeredSuffixPatternMatch) { <add> public PathMatchConfigurer setUseRegisteredSuffixPatternMatch(@Nullable Boolean registeredSuffixPatternMatch) { <ide> this.registeredSuffixPatternMatch = registeredSuffixPatternMatch; <del> this.preferPathMatcher |= registeredSuffixPatternMatch; <add> this.preferPathMatcher |= (registeredSuffixPatternMatch != null && registeredSuffixPatternMatch); <ide> return this; <ide> } <ide>
1
Javascript
Javascript
add exception for file protocol request
88130689589872cd6f19866680162abb46a39d7a
<ide><path>lib/adapters/xhr.js <ide> module.exports = function xhrAdapter(config) { <ide> <ide> // The request errored out and we didn't get a response, this will be <ide> // handled by onerror instead <del> if (request.status === 0) { <add> // With one exception: request that using file: protocol, most browsers <add> // will return status as 0 even though it's a successful request <add> if (request.status === 0 && request.responseURL.indexOf('file:') !== 0) { <ide> return; <ide> } <ide>
1
Ruby
Ruby
remove superfluous assignment in cookies
bed5825f775bdf2a1af6eec9dc1f4071dbde5ead
<ide><path>actionpack/lib/action_dispatch/middleware/cookies.rb <ide> def []=(key, options) <ide> options = { :value => value } <ide> end <ide> <del> value = @cookies[key.to_s] = value <add> @cookies[key.to_s] = value <ide> <ide> handle_options(options) <ide>
1
Javascript
Javascript
use spread object
c52ebc06da0a247e2e7aa66e5ae6ba35a9f1d222
<ide><path>test/fixtures/v8-coverage/spawn-subprocess-no-cov.js <ide> const { spawnSync } = require('child_process'); <del>const env = Object.assign({}, process.env, { NODE_V8_COVERAGE: '' }); <add>const env = { ...process.env, NODE_V8_COVERAGE: '' }; <ide> spawnSync(process.execPath, [require.resolve('./subprocess')], { <ide> env: env <ide> }); <ide><path>test/fixtures/v8-coverage/spawn-subprocess.js <ide> const { spawnSync } = require('child_process'); <del>const env = Object.assign({}, process.env); <add>const env = { ...process.env }; <ide> delete env.NODE_V8_COVERAGE <ide> spawnSync(process.execPath, [require.resolve('./subprocess')], { <ide> env: env <ide><path>test/parallel/test-child-process-env.js <ide> const os = require('os'); <ide> <ide> const spawn = require('child_process').spawn; <ide> <del>const env = Object.assign({}, process.env, { <add>const env = { <add> ...process.env, <ide> 'HELLO': 'WORLD', <ide> 'UNDEFINED': undefined, <ide> 'NULL': null, <ide> 'EMPTY': '' <del>}); <add>}; <ide> Object.setPrototypeOf(env, { <ide> 'FOO': 'BAR' <ide> }); <ide><path>test/parallel/test-child-process-exec-env.js <ide> if (!common.isWindows) { <ide> child = exec('/usr/bin/env', { env: { 'HELLO': 'WORLD' } }, after); <ide> } else { <ide> child = exec('set', <del> { env: Object.assign({}, process.env, { 'HELLO': 'WORLD' }) }, <add> { env: { ...process.env, 'HELLO': 'WORLD' } }, <ide> after); <ide> } <ide> <ide><path>test/parallel/test-child-process-fork-no-shell.js <ide> const expected = common.isWindows ? '%foo%' : '$foo'; <ide> if (process.argv[2] === undefined) { <ide> const child = cp.fork(__filename, [expected], { <ide> shell: true, <del> env: Object.assign({}, process.env, { foo: 'bar' }) <add> env: { ...process.env, foo: 'bar' } <ide> }); <ide> <ide> child.on('exit', common.mustCall((code, signal) => { <ide><path>test/parallel/test-child-process-spawn-shell.js <ide> command.on('close', common.mustCall((code, signal) => { <ide> <ide> // Verify that the environment is properly inherited <ide> const env = cp.spawn(`"${process.execPath}" -pe process.env.BAZ`, { <del> env: Object.assign({}, process.env, { BAZ: 'buzz' }), <add> env: { ...process.env, BAZ: 'buzz' }, <ide> encoding: 'utf8', <ide> shell: true <ide> }); <ide><path>test/parallel/test-child-process-spawnsync-shell.js <ide> assert.strictEqual(command.stdout.toString().trim(), 'bar'); <ide> <ide> // Verify that the environment is properly inherited <ide> const env = cp.spawnSync(`"${process.execPath}" -pe process.env.BAZ`, { <del> env: Object.assign({}, process.env, { BAZ: 'buzz' }), <add> env: { ...process.env, BAZ: 'buzz' }, <ide> shell: true <ide> }); <ide> <ide><path>test/parallel/test-cli-node-options-disallowed.js <ide> disallow('--v8-options'); <ide> disallow('--'); <ide> <ide> function disallow(opt) { <del> const env = Object.assign({}, process.env, { NODE_OPTIONS: opt }); <add> const env = { ...process.env, NODE_OPTIONS: opt }; <ide> exec(process.execPath, { cwd: tmpdir.path, env }, common.mustCall((err) => { <ide> const message = err.message.split(/\r?\n/)[1]; <ide> const expect = `${process.execPath}: ${opt} is not allowed in NODE_OPTIONS`; <ide><path>test/parallel/test-crypto-fips.js <ide> testHelper( <ide> [], <ide> FIPS_DISABLED, <ide> 'require("crypto").getFips()', <del> Object.assign({}, process.env, { 'OPENSSL_CONF': '' })); <add> { ...process.env, 'OPENSSL_CONF': '' }); <ide> <ide> // --enable-fips should turn FIPS mode on <ide> testHelper( <ide><path>test/parallel/test-env-var-no-warnings.js <ide> if (process.argv[2] === 'child') { <ide> process.emitWarning('foo'); <ide> } else { <ide> function test(newEnv) { <del> const env = Object.assign({}, process.env, newEnv); <add> const env = { ...process.env, ...newEnv }; <ide> const cmd = `"${process.execPath}" "${__filename}" child`; <ide> <ide> cp.exec(cmd, { env }, common.mustCall((err, stdout, stderr) => { <ide><path>test/parallel/test-fs-readfile-error.js <ide> const fixtures = require('../common/fixtures'); <ide> function test(env, cb) { <ide> const filename = fixtures.path('test-fs-readfile-error.js'); <ide> const execPath = `"${process.execPath}" "${filename}"`; <del> const options = { env: Object.assign({}, process.env, env) }; <add> const options = { env: { ...process.env, ...env } }; <ide> exec(execPath, options, (err, stdout, stderr) => { <ide> assert(err); <ide> assert.strictEqual(stdout, ''); <ide><path>test/parallel/test-http-server-stale-close.js <ide> if (process.env.NODE_TEST_FORK_PORT) { <ide> }); <ide> server.listen(0, function() { <ide> fork(__filename, { <del> env: Object.assign({}, process.env, { <del> NODE_TEST_FORK_PORT: this.address().port <del> }) <add> env: { ...process.env, NODE_TEST_FORK_PORT: this.address().port } <ide> }); <ide> }); <ide> } <ide><path>test/parallel/test-https-agent-additional-options.js <ide> function variations(iter, port, cb) { <ide> // Save `value` for check the next time. <ide> value = next.value.val; <ide> const [key, val] = next.value; <del> https.get(Object.assign({}, getBaseOptions(port), { [key]: val }), <add> https.get({ ...getBaseOptions(port), [key]: val }, <ide> variations(iter, port, cb)); <ide> } <ide> })); <ide><path>test/parallel/test-icu-data-dir.js <ide> const expected = <ide> } <ide> <ide> { <del> const env = Object.assign({}, process.env, { NODE_ICU_DATA: '/' }); <add> const env = { ...process.env, NODE_ICU_DATA: '/' }; <ide> const child = spawnSync(process.execPath, ['-e', '0'], { env }); <ide> assert(child.stderr.toString().includes(expected)); <ide> } <ide><path>test/parallel/test-module-loading-globalpaths.js <ide> if (process.argv[2] === 'child') { <ide> <ide> const testFixturesDir = fixtures.path(path.basename(__filename, '.js')); <ide> <del> const env = Object.assign({}, process.env); <add> const env = { ...process.env }; <ide> // Unset NODE_PATH. <ide> delete env.NODE_PATH; <ide> <ide><path>test/parallel/test-net-connect-options-fd.js <ide> tmpdir.refresh(); <ide> <ide> function testClients(getSocketOpt, getConnectOpt, getConnectCb) { <ide> const cloneOptions = (index) => <del> Object.assign({}, getSocketOpt(index), getConnectOpt(index)); <add> ({ ...getSocketOpt(index), ...getConnectOpt(index) }); <ide> return [ <ide> net.connect(cloneOptions(0), getConnectCb(0)), <ide> net.connect(cloneOptions(1)) <ide><path>test/parallel/test-pending-deprecation.js <ide> switch (process.argv[2]) { <ide> <ide> // Test the NODE_PENDING_DEPRECATION environment var. <ide> fork(__filename, ['env'], { <del> env: Object.assign({}, process.env, { NODE_PENDING_DEPRECATION: 1 }), <add> env: { ...process.env, NODE_PENDING_DEPRECATION: 1 }, <ide> execArgv: ['--expose-internals'], <ide> silent: true <ide> }).on('exit', common.mustCall((code) => { <ide><path>test/parallel/test-process-redirect-warnings-env.js <ide> tmpdir.refresh(); <ide> const warnmod = require.resolve(fixtures.path('warnings.js')); <ide> const warnpath = path.join(tmpdir.path, 'warnings.txt'); <ide> <del>fork(warnmod, { env: Object.assign({}, process.env, <del> { NODE_REDIRECT_WARNINGS: warnpath }) }) <add>fork(warnmod, { env: { ...process.env, NODE_REDIRECT_WARNINGS: warnpath } }) <ide> .on('exit', common.mustCall(() => { <ide> fs.readFile(warnpath, 'utf8', common.mustCall((err, data) => { <ide> assert.ifError(err); <ide><path>test/parallel/test-stdin-script-child.js <ide> const assert = require('assert'); <ide> const { spawn } = require('child_process'); <ide> for (const args of [[], ['-']]) { <ide> const child = spawn(process.execPath, args, { <del> env: Object.assign({}, process.env, { <del> NODE_DEBUG: process.argv[2] <del> }) <add> env: { ...process.env, <add> NODE_DEBUG: process.argv[2] <add> } <ide> }); <ide> const wanted = `${child.pid}\n`; <ide> let found = ''; <ide><path>test/parallel/test-tls-env-bad-extra-ca.js <ide> if (process.env.CHILD) { <ide> return tls.createServer({}); <ide> } <ide> <del>const env = Object.assign({}, process.env, { <add>const env = { <add> ...process.env, <ide> CHILD: 'yes', <ide> NODE_EXTRA_CA_CERTS: `${fixtures.fixturesDir}/no-such-file-exists-🐢`, <del>}); <add>}; <ide> <ide> const opts = { <ide> env: env, <ide><path>test/parallel/test-tls-env-extra-ca-file-load.js <ide> if (process.argv[2] !== 'child') { <ide> } <ide> } else { <ide> const NODE_EXTRA_CA_CERTS = fixtures.path('keys', 'ca1-cert.pem'); <del> const extendsEnv = (obj) => Object.assign({}, process.env, obj); <add> const extendsEnv = (obj) => ({ ...process.env, ...obj }); <ide> <ide> [ <ide> extendsEnv({ CHILD_USE_EXTRA_CA_CERTS: 'yes', NODE_EXTRA_CA_CERTS }), <ide><path>test/parallel/test-tls-env-extra-ca-no-crypto.js <ide> if (process.argv[2] === 'child') { <ide> fork( <ide> __filename, <ide> ['child'], <del> { env: Object.assign({}, process.env, { NODE_EXTRA_CA_CERTS }) }, <add> { env: { ...process.env, NODE_EXTRA_CA_CERTS } }, <ide> ).on('exit', common.mustCall(function(status) { <ide> // Client did not succeed in connecting <ide> assert.strictEqual(status, 0); <ide><path>test/parallel/test-tls-env-extra-ca.js <ide> const server = tls.createServer(options, common.mustCall(function(s) { <ide> s.end('bye'); <ide> server.close(); <ide> })).listen(0, common.mustCall(function() { <del> const env = Object.assign({}, process.env, { <add> const env = { <add> ...process.env, <ide> CHILD: 'yes', <ide> PORT: this.address().port, <ide> NODE_EXTRA_CA_CERTS: fixtures.path('keys', 'ca1-cert.pem') <del> }); <add> }; <ide> <ide> fork(__filename, { env }).on('exit', common.mustCall(function(status) { <ide> // Client did not succeed in connecting
23
Python
Python
add skip to fix unnoticed bug with good imports
f6c45afb6ffa9fc1bd3d3637f7d38e423798dce9
<ide><path>scripts/flaskext_migrate.py <ide> def fix_from_imports(red): <ide> from_imports = red.find_all("FromImport") <ide> for x, node in enumerate(from_imports): <ide> values = node.value <add> if len(values) < 2: <add> continue <ide> if (values[0].value == 'flask') and (values[1].value == 'ext'): <ide> # Case 1 <ide> if len(node.value) == 3: <ide><path>scripts/test_import_migration.py <ide> def test_named_module_import(): <ide> assert output == "import flask_foo as foobar" <ide> <ide> <del>def test__named_from_import(): <add>def test_named_from_import(): <ide> red = RedBaron("from flask.ext.foo import bar as baz") <ide> output = migrate.fix_tester(red) <ide> assert output == "from flask_foo import bar as baz" <ide> def test_nested_function_call_migration(): <ide> output = migrate.fix_tester(red) <ide> assert output == ("import flask_foo\n\n" <ide> "flask_foo.bar(var)") <add> <add> <add>def test_no_change_to_import(): <add> red = RedBaron("from flask import Flask") <add> output = migrate.fix_tester(red) <add> assert output == "from flask import Flask"
2
Ruby
Ruby
fix rubocop warnings
4e090530b11bbd61c13024bbdb1ef82387b5fb86
<ide><path>Library/Homebrew/cmd/log.rb <ide> def log <ide> <ide> private <ide> <del> def git_log(path=nil) <add> def git_log(path = nil) <ide> if File.exist? "#{`git rev-parse --show-toplevel`.chomp}/.git/shallow" <ide> opoo <<-EOS.undent <ide> The git repository is a shallow clone therefore the filtering may be incorrect.
1
Mixed
Ruby
recommend mandatory starttls for google
89fdd5e34e053183b069595f40c5834559b0920c
<ide><path>actionmailer/lib/action_mailer/base.rb <ide> module ActionMailer <ide> # This is a symbol and one of <tt>:plain</tt> (will send the password Base64 encoded), <tt>:login</tt> (will <ide> # send the password Base64 encoded) or <tt>:cram_md5</tt> (combines a Challenge/Response mechanism to exchange <ide> # information and a cryptographic Message Digest 5 algorithm to hash important information) <del> # * <tt>:enable_starttls</tt> - Use STARTTLS when connecting to your SMTP server and fail if unsupported. Defaults to <tt>false</tt>. <add> # * <tt>:enable_starttls</tt> - Use STARTTLS when connecting to your SMTP server and fail if unsupported. Defaults <add> # to <tt>false</tt>. Requires at least version 2.7 of the Mail gem. <ide> # * <tt>:enable_starttls_auto</tt> - Detects if STARTTLS is enabled in your SMTP server and starts <ide> # to use it. Defaults to <tt>true</tt>. <ide> # * <tt>:openssl_verify_mode</tt> - When using TLS, you can set how OpenSSL checks the certificate. This is <ide><path>guides/source/action_mailer_basics.md <ide> Add this to your `config/environments/$RAILS_ENV.rb` file to send via Gmail: <ide> ```ruby <ide> config.action_mailer.delivery_method = :smtp <ide> config.action_mailer.smtp_settings = { <del> address: 'smtp.gmail.com', <del> port: 587, <del> domain: 'example.com', <del> user_name: '<username>', <del> password: '<password>', <del> authentication: 'plain', <del> enable_starttls_auto: true, <del> open_timeout: 5, <del> read_timeout: 5 } <del>``` <del> <del>NOTE: On July 15, 2014, Google increased [its security measures](https://support.google.com/accounts/answer/6010255) to block attempts from apps it deems less secure. <add> address: 'smtp.gmail.com', <add> port: 587, <add> domain: 'example.com', <add> user_name: '<username>', <add> password: '<password>', <add> authentication: 'plain', <add> enable_starttls: true, <add> open_timeout: 5, <add> read_timeout: 5 } <add>``` <add> <add>If you are using an old version of the Mail gem (2.6.x or earlier), use `enable_starttls_auto` instead of `enable_starttls`. <add> <add>NOTE: Google [blocks sign-ins](https://support.google.com/accounts/answer/6010255) from apps it deems less secure. <ide> You can change your Gmail settings [here](https://www.google.com/settings/security/lesssecureapps) to allow the attempts. If your Gmail account has 2-factor authentication enabled, <ide> then you will need to set an [app password](https://myaccount.google.com/apppasswords) and use that instead of your regular password. <ide>
2
Ruby
Ruby
update latesttag in all cases
a94f6ec50c5bc27bcd5b13e134462bebe6e3e347
<ide><path>Library/Homebrew/cmd/update-report.rb <ide> def output_update_report <ide> "git", "-C", HOMEBREW_REPOSITORY, "tag", "--list", "--sort=-version:refname", "*.*" <ide> ).lines.first.chomp <ide> <add> Settings.write "latesttag", new_tag if new_tag != old_tag <add> <ide> if old_tag.blank? || (new_tag == old_tag) <ide> puts "Updated Homebrew from #{shorten_revision(initial_revision)} to #{shorten_revision(current_revision)}." <ide> else <ide> def output_update_report <ide> <ide> puts <ide> ohai "Homebrew was updated to version #{new_tag}" <del> Settings.write "latesttag", new_tag if new_tag != old_tag <ide> if new_tag.split(".").last == "0" <ide> puts <<~EOS <ide> More detailed release notes are available on the Homebrew Blog:
1
Ruby
Ruby
freeze modelname cache_key also
24c7f41b4fdc411e35131f9065852a685032211f
<ide><path>activesupport/lib/active_support/core_ext/module/model_naming.rb <ide> def initialize(name) <ide> super <ide> @singular = underscore.tr('/', '_').freeze <ide> @plural = @singular.pluralize.freeze <del> @cache_key = tableize <add> @cache_key = tableize.freeze <ide> @partial_path = "#{@cache_key}/#{demodulize.underscore}".freeze <ide> end <ide> end
1
Javascript
Javascript
add galician locale (es-gl)
47afb426c6f3ec439bebdaa6e5ec4c7200d5d12b
<ide><path>build.js <ide> var JSHINT_CONFIG = { <ide> "strict": false, <ide> "white": true <ide> }; <del>var LANG_MINIFY = "de en-gb es eu fr it kr nb nl pl pt ru sv".split(" "); <del>var LANG_TEST = "de en en-gb es eu fr it kr nb nl pl pt ru sv".split(" "); <add>var LANG_MINIFY = "de en-gb es es-gl eu fr it kr nb nl pl pt ru sv".split(" "); <add>var LANG_TEST = "de en en-gb es es-gl eu fr it kr nb nl pl pt ru sv".split(" "); <ide> var LANG_PREFIX = "(function() { var moment; if (typeof window === 'undefined') { moment = require('../../moment'); module = QUnit.module; } else { moment = window.moment; }"; <ide> var LANG_SUFFIX = "})();"; <ide> var VERSION = '1.2.0'; <ide><path>lang/es-gl.js <add>(function () { <add> var lang = { <add> months : "Xaneiro_Febreiro_Marzo_Abril_Maio_Xuño_Xullo_Agosto_Setembro_Octubro_Novembro_Decembro".split("_"), <add> monthsShort : "Xan._Feb._Mar._Abr._Mai._Xuñ._Xul._Ago._Set._Out._Nov._Dec.".split("_"), <add> weekdays : "Domingo_Luns_Martes_Mércores_Xoves_Venres_Sábado".split("_"), <add> weekdaysShort : "Dom._Lun._Mar._Mér._Xov._Ven._Sáb.".split("_"), <add> longDateFormat : { <add> LT : "H:mm", <add> L : "DD/MM/YYYY", <add> LL : "D MMMM YYYY", <add> LLL : "D MMMM YYYY LT", <add> LLLL : "dddd D MMMM YYYY LT" <add> }, <add> meridiem : { <add> AM : 'AM', <add> am : 'am', <add> PM : 'PM', <add> pm : 'pm' <add> }, <add> calendar : { <add> sameDay : function () { <add> return '[hoxe ' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; <add> }, <add> nextDay : function () { <add> return '[mañá ' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; <add> }, <add> nextWeek : function () { <add> return 'dddd [' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; <add> }, <add> lastDay : function () { <add> return '[onte ' + ((this.hours() !== 1) ? 'á' : 'a') + '] LT'; <add> }, <add> lastWeek : function () { <add> return '[o] dddd [pasado ' + ((this.hours() !== 1) ? 'ás' : '') + '] LT'; <add> }, <add> sameElse : 'L' <add> }, <add> relativeTime : { <add> future : "en %s", <add> past : "fai %s", <add> s : "uns segundo", <add> m : "un minuto", <add> mm : "%d minutos", <add> h : "unha hora", <add> hh : "%d horas", <add> d : "un día", <add> dd : "%d días", <add> M : "un mes", <add> MM : "%d meses", <add> y : "un ano", <add> yy : "%d anos" <add> }, <add> ordinal : function (number) { <add> return 'º'; <add> } <add> }; <add> <add> // Node <add> if (typeof module !== 'undefined') { <add> module.exports = lang; <add> } <add> // Browser <add> if (typeof window !== 'undefined' && this.moment && this.moment.lang) { <add> this.moment.lang('es-gl', lang); <add> } <add>}()); <ide><path>lang/test/es-gl.js <add> <add>/************************************************** <add> Spanish <add> *************************************************/ <add> <add>module("lang:es-gl"); <add> <add>test("parse", 96, function() { <add> moment.lang('es-gl'); <add> var tests = "Xaneiro Xan._Febreiro Feb._Marzo Mar._Abril Abr._Maio Mai._Xuño Xuñ._Xullo Xul._Agosto Ago._Setembro Set._Octubro Out._Novembro Nov._Decembro Dec.".split("_"); <add> <add> var i; <add> function equalTest(input, mmm, i) { <add> equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); <add> } <add> for (i = 0; i < 12; i++) { <add> tests[i] = tests[i].split(' '); <add> equalTest(tests[i][0], 'MMM', i); <add> equalTest(tests[i][1], 'MMM', i); <add> equalTest(tests[i][0], 'MMMM', i); <add> equalTest(tests[i][1], 'MMMM', i); <add> equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); <add> equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); <add> equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); <add> equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); <add> } <add>}); <add> <add>test("format ordinal", 31, function() { <add> moment.lang('es'); <add> equal(moment([2011, 0, 1]).format('DDDo'), '1º', '1º'); <add> equal(moment([2011, 0, 2]).format('DDDo'), '2º', '2º'); <add> equal(moment([2011, 0, 3]).format('DDDo'), '3º', '3º'); <add> equal(moment([2011, 0, 4]).format('DDDo'), '4º', '4º'); <add> equal(moment([2011, 0, 5]).format('DDDo'), '5º', '5º'); <add> equal(moment([2011, 0, 6]).format('DDDo'), '6º', '6º'); <add> equal(moment([2011, 0, 7]).format('DDDo'), '7º', '7º'); <add> equal(moment([2011, 0, 8]).format('DDDo'), '8º', '8º'); <add> equal(moment([2011, 0, 9]).format('DDDo'), '9º', '9º'); <add> equal(moment([2011, 0, 10]).format('DDDo'), '10º', '10º'); <add> <add> equal(moment([2011, 0, 11]).format('DDDo'), '11º', '11º'); <add> equal(moment([2011, 0, 12]).format('DDDo'), '12º', '12º'); <add> equal(moment([2011, 0, 13]).format('DDDo'), '13º', '13º'); <add> equal(moment([2011, 0, 14]).format('DDDo'), '14º', '14º'); <add> equal(moment([2011, 0, 15]).format('DDDo'), '15º', '15º'); <add> equal(moment([2011, 0, 16]).format('DDDo'), '16º', '16º'); <add> equal(moment([2011, 0, 17]).format('DDDo'), '17º', '17º'); <add> equal(moment([2011, 0, 18]).format('DDDo'), '18º', '18º'); <add> equal(moment([2011, 0, 19]).format('DDDo'), '19º', '19º'); <add> equal(moment([2011, 0, 20]).format('DDDo'), '20º', '20º'); <add> <add> equal(moment([2011, 0, 21]).format('DDDo'), '21º', '21º'); <add> equal(moment([2011, 0, 22]).format('DDDo'), '22º', '22º'); <add> equal(moment([2011, 0, 23]).format('DDDo'), '23º', '23º'); <add> equal(moment([2011, 0, 24]).format('DDDo'), '24º', '24º'); <add> equal(moment([2011, 0, 25]).format('DDDo'), '25º', '25º'); <add> equal(moment([2011, 0, 26]).format('DDDo'), '26º', '26º'); <add> equal(moment([2011, 0, 27]).format('DDDo'), '27º', '27º'); <add> equal(moment([2011, 0, 28]).format('DDDo'), '28º', '28º'); <add> equal(moment([2011, 0, 29]).format('DDDo'), '29º', '29º'); <add> equal(moment([2011, 0, 30]).format('DDDo'), '30º', '30º'); <add> <add> equal(moment([2011, 0, 31]).format('DDDo'), '31º', '31º'); <add>}); <add> <add>test("format month", 12, function() { <add> moment.lang('es-gl'); <add> var expected = "Xaneiro Xan._Febreiro Feb._Marzo Mar._Abril Abr._Maio Mai._Xuño Xuñ._Xullo Xul._Agosto Ago._Setembro Set._Octubro Out._Novembro Nov._Decembro Dec.".split("_"); <add> var i; <add> for (i = 0; i < expected.length; i++) { <add> equal(moment([2011, i, 0]).format('MMMM MMM'), expected[i], expected[i]); <add> } <add>}); <add> <add>test("format week", 7, function() { <add> moment.lang('es-gl'); <add> var expected = "Domingo Dom._Luns Lun._Martes Mar._Mércores Mér._Xoves Xov._Venres Ven._Sábado Sáb.".split("_"); <add> <add> var i; <add> for (i = 0; i < expected.length; i++) { <add> equal(moment([2011, 0, 2 + i]).format('dddd ddd'), expected[i], expected[i]); <add> } <add>}); <add> <add>test("from", 30, function() { <add> moment.lang('es-gl'); <add> var start = moment([2007, 1, 28]); <add> <add> equal(start.from(moment([2007, 1, 28]).add({s:44}), true), "uns segundo", "44 seconds = a few seconds"); <add> equal(start.from(moment([2007, 1, 28]).add({s:45}), true), "un minuto", "45 seconds = a minute"); <add> equal(start.from(moment([2007, 1, 28]).add({s:89}), true), "un minuto", "89 seconds = a minute"); <add> equal(start.from(moment([2007, 1, 28]).add({s:90}), true), "2 minutos", "90 seconds = 2 minutes"); <add> equal(start.from(moment([2007, 1, 28]).add({m:44}), true), "44 minutos", "44 minutes = 44 minutes"); <add> equal(start.from(moment([2007, 1, 28]).add({m:45}), true), "unha hora", "45 minutes = an hour"); <add> equal(start.from(moment([2007, 1, 28]).add({m:89}), true), "unha hora", "89 minutes = an hour"); <add> equal(start.from(moment([2007, 1, 28]).add({m:90}), true), "2 horas", "90 minutes = 2 hours"); <add> equal(start.from(moment([2007, 1, 28]).add({h:5}), true), "5 horas", "5 hours = 5 hours"); <add> equal(start.from(moment([2007, 1, 28]).add({h:21}), true), "21 horas", "21 hours = 21 hours"); <add> equal(start.from(moment([2007, 1, 28]).add({h:22}), true), "un día", "22 hours = a day"); <add> equal(start.from(moment([2007, 1, 28]).add({h:35}), true), "un día", "35 hours = a day"); <add> equal(start.from(moment([2007, 1, 28]).add({h:36}), true), "2 días", "36 hours = 2 days"); <add> equal(start.from(moment([2007, 1, 28]).add({d:1}), true), "un día", "1 day = a day"); <add> equal(start.from(moment([2007, 1, 28]).add({d:5}), true), "5 días", "5 days = 5 days"); <add> equal(start.from(moment([2007, 1, 28]).add({d:25}), true), "25 días", "25 days = 25 days"); <add> equal(start.from(moment([2007, 1, 28]).add({d:26}), true), "un mes", "26 days = a month"); <add> equal(start.from(moment([2007, 1, 28]).add({d:30}), true), "un mes", "30 days = a month"); <add> equal(start.from(moment([2007, 1, 28]).add({d:45}), true), "un mes", "45 days = a month"); <add> equal(start.from(moment([2007, 1, 28]).add({d:46}), true), "2 meses", "46 days = 2 months"); <add> equal(start.from(moment([2007, 1, 28]).add({d:74}), true), "2 meses", "75 days = 2 months"); <add> equal(start.from(moment([2007, 1, 28]).add({d:76}), true), "3 meses", "76 days = 3 months"); <add> equal(start.from(moment([2007, 1, 28]).add({M:1}), true), "un mes", "1 month = a month"); <add> equal(start.from(moment([2007, 1, 28]).add({M:5}), true), "5 meses", "5 months = 5 months"); <add> equal(start.from(moment([2007, 1, 28]).add({d:344}), true), "11 meses", "344 days = 11 months"); <add> equal(start.from(moment([2007, 1, 28]).add({d:345}), true), "un ano", "345 days = a year"); <add> equal(start.from(moment([2007, 1, 28]).add({d:547}), true), "un ano", "547 days = a year"); <add> equal(start.from(moment([2007, 1, 28]).add({d:548}), true), "2 anos", "548 days = 2 years"); <add> equal(start.from(moment([2007, 1, 28]).add({y:1}), true), "un ano", "1 year = a year"); <add> equal(start.from(moment([2007, 1, 28]).add({y:5}), true), "5 anos", "5 years = 5 years"); <add>}); <add> <add>test("suffix", 2, function() { <add> moment.lang('es-gl'); <add> equal(moment(30000).from(0), "en uns segundo", "prefix"); <add> equal(moment(0).from(30000), "fai uns segundo", "suffix"); <add>}); <add> <add> <add>test("now from now", 1, function() { <add> moment.lang('es-gl'); <add> equal(moment().fromNow(), "fai uns segundo", "now from now should display as in the past"); <add>}); <add> <add> <add>test("fromNow", 2, function() { <add> moment.lang('es-gl'); <add> equal(moment().add({s:30}).fromNow(), "en uns segundo", "en unos segundos"); <add> equal(moment().add({d:5}).fromNow(), "en 5 días", "en 5 días"); <add>}); <add> <add> <add>test("calendar day", 7, function() { <add> moment.lang('es-gl'); <add> <add> var a = moment().hours(2).minutes(0).seconds(0); <add> <add> equal(moment(a).calendar(), "hoxe ás 2:00", "today at the same time"); <add> equal(moment(a).add({ m: 25 }).calendar(), "hoxe ás 2:25", "Now plus 25 min"); <add> equal(moment(a).add({ h: 1 }).calendar(), "hoxe ás 3:00", "Now plus 1 hour"); <add> equal(moment(a).add({ d: 1 }).calendar(), "mañá ás 2:00", "tomorrow at the same time"); <add> equal(moment(a).add({ d: 1, h : -1 }).calendar(), "mañá a 1:00", "tomorrow minus 1 hour"); <add> equal(moment(a).subtract({ h: 1 }).calendar(), "hoxe a 1:00", "Now minus 1 hour"); <add> equal(moment(a).subtract({ d: 1 }).calendar(), "onte á 2:00", "yesterday at the same time"); <add>}); <add> <add>test("calendar next week", 15, function() { <add> moment.lang('es-gl'); <add> <add> var i; <add> var m; <add> <add> for (i = 2; i < 7; i++) { <add> m = moment().add({ d: i }); <add> equal(m.calendar(), m.format('dddd [' + ((m.hours() !== 1) ? 'ás' : 'a') + '] LT'), "Today + " + i + " days current time"); <add> m.hours(0).minutes(0).seconds(0).milliseconds(0); <add> equal(m.calendar(), m.format('dddd [' + ((m.hours() !== 1) ? 'ás' : 'a') + '] LT'), "Today + " + i + " days beginning of day"); <add> m.hours(23).minutes(59).seconds(59).milliseconds(999); <add> equal(m.calendar(), m.format('dddd [' + ((m.hours() !== 1) ? 'ás' : 'a') + '] LT'), "Today + " + i + " days end of day"); <add> } <add>}); <add> <add>test("calendar last week", 15, function() { <add> moment.lang('es-gl'); <add> <add> for (i = 2; i < 7; i++) { <add> m = moment().subtract({ d: i }); <add> equal(m.calendar(), m.format('[o] dddd [pasado ' + ((m.hours() !== 1) ? 'ás' : 'a') + '] LT'), "Today - " + i + " days current time"); <add> m.hours(0).minutes(0).seconds(0).milliseconds(0); <add> equal(m.calendar(), m.format('[o] dddd [pasado ' + ((m.hours() !== 1) ? 'ás' : 'a') + '] LT'), "Today - " + i + " days beginning of day"); <add> m.hours(23).minutes(59).seconds(59).milliseconds(999); <add> equal(m.calendar(), m.format('[o] dddd [pasado ' + ((m.hours() !== 1) ? 'ás' : 'a') + '] LT'), "Today - " + i + " days end of day"); <add> } <add>}); <add> <add>test("calendar all else", 4, function() { <add> moment.lang('es-gl'); <add> var weeksAgo = moment().subtract({ w: 1 }); <add> var weeksFromNow = moment().add({ w: 1 }); <add> <add> equal(weeksAgo.calendar(), weeksAgo.format('L'), "1 week ago"); <add> equal(weeksFromNow.calendar(), weeksFromNow.format('L'), "in 1 week"); <add> <add> weeksAgo = moment().subtract({ w: 2 }); <add> weeksFromNow = moment().add({ w: 2 }); <add> <add> equal(weeksAgo.calendar(), weeksAgo.format('L'), "2 weeks ago"); <add> equal(weeksFromNow.calendar(), weeksFromNow.format('L'), "in 2 weeks"); <add>});
3
Go
Go
use sub-tests, and use gotest.tools
8e3f9fd032ddf9c42844a05c5a5ea7c6c002f6f2
<ide><path>volume/mounts/lcow_parser_test.go <ide> package mounts // import "github.com/docker/docker/volume/mounts" <ide> <ide> import ( <add> "fmt" <ide> "strings" <ide> "testing" <ide> <ide> "github.com/docker/docker/api/types/mount" <add> "gotest.tools/v3/assert" <ide> ) <ide> <ide> func TestLCOWParseMountRaw(t *testing.T) { <ide> func TestLCOWParseMountRawSplit(t *testing.T) { <ide> } <ide> <ide> for i, c := range cases { <del> t.Logf("case %d", i) <del> m, err := parser.ParseMountRaw(c.bind, c.driver) <del> if c.fail { <del> if err == nil { <del> t.Errorf("Expected error, was nil, for spec %s\n", c.bind) <add> c := c <add> t.Run(fmt.Sprintf("%d_%s", i, c.bind), func(t *testing.T) { <add> m, err := parser.ParseMountRaw(c.bind, c.driver) <add> if c.fail { <add> assert.ErrorContains(t, err, "", "expected an error") <add> return <ide> } <del> continue <del> } <del> <del> if m == nil || err != nil { <del> t.Errorf("ParseMountRaw failed for spec '%s', driver '%s', error '%v'", c.bind, c.driver, err) <del> continue <del> } <del> <del> if m.Destination != c.expDest { <del> t.Errorf("Expected destination '%s, was %s', for spec '%s'", c.expDest, m.Destination, c.bind) <del> } <del> <del> if m.Source != c.expSource { <del> t.Errorf("Expected source '%s', was '%s', for spec '%s'", c.expSource, m.Source, c.bind) <del> } <ide> <del> if m.Name != c.expName { <del> t.Errorf("Expected name '%s', was '%s' for spec '%s'", c.expName, m.Name, c.bind) <del> } <del> <del> if m.Driver != c.expDriver { <del> t.Errorf("Expected driver '%s', was '%s', for spec '%s'", c.expDriver, m.Driver, c.bind) <del> } <del> <del> if m.RW != c.expRW { <del> t.Errorf("Expected RW '%v', was '%v' for spec '%s'", c.expRW, m.RW, c.bind) <del> } <del> if m.Type != c.expType { <del> t.Fatalf("Expected type '%s', was '%s', for spec '%s'", c.expType, m.Type, c.bind) <del> } <add> assert.NilError(t, err) <add> assert.Equal(t, m.Destination, c.expDest) <add> assert.Equal(t, m.Source, c.expSource) <add> assert.Equal(t, m.Name, c.expName) <add> assert.Equal(t, m.Driver, c.expDriver) <add> assert.Equal(t, m.RW, c.expRW) <add> assert.Equal(t, m.Type, c.expType) <add> }) <ide> } <ide> } <ide><path>volume/mounts/linux_parser_test.go <ide> func TestLinuxParseMountRawSplit(t *testing.T) { <ide> } <ide> <ide> for i, c := range cases { <del> t.Logf("case %d", i) <del> m, err := parser.ParseMountRaw(c.bind, c.driver) <del> if c.fail { <del> if err == nil { <del> t.Errorf("Expected error, was nil, for spec %s\n", c.bind) <add> c := c <add> t.Run(fmt.Sprintf("%d_%s", i, c.bind), func(t *testing.T) { <add> m, err := parser.ParseMountRaw(c.bind, c.driver) <add> if c.fail { <add> assert.ErrorContains(t, err, "", "expected an error") <add> return <ide> } <del> continue <del> } <del> <del> if m == nil || err != nil { <del> t.Errorf("ParseMountRaw failed for spec '%s', driver '%s', error '%v'", c.bind, c.driver, err) <del> continue <del> } <del> <del> if m.Destination != c.expDest { <del> t.Errorf("Expected destination '%s, was %s', for spec '%s'", c.expDest, m.Destination, c.bind) <del> } <del> <del> if m.Source != c.expSource { <del> t.Errorf("Expected source '%s', was '%s', for spec '%s'", c.expSource, m.Source, c.bind) <del> } <ide> <del> if m.Name != c.expName { <del> t.Errorf("Expected name '%s', was '%s' for spec '%s'", c.expName, m.Name, c.bind) <del> } <del> <del> if m.Driver != c.expDriver { <del> t.Errorf("Expected driver '%s', was '%s', for spec '%s'", c.expDriver, m.Driver, c.bind) <del> } <del> <del> if m.RW != c.expRW { <del> t.Errorf("Expected RW '%v', was '%v' for spec '%s'", c.expRW, m.RW, c.bind) <del> } <del> if m.Type != c.expType { <del> t.Fatalf("Expected type '%s', was '%s', for spec '%s'", c.expType, m.Type, c.bind) <del> } <add> assert.NilError(t, err) <add> assert.Equal(t, m.Destination, c.expDest) <add> assert.Equal(t, m.Source, c.expSource) <add> assert.Equal(t, m.Name, c.expName) <add> assert.Equal(t, m.Driver, c.expDriver) <add> assert.Equal(t, m.RW, c.expRW) <add> assert.Equal(t, m.Type, c.expType) <add> }) <ide> } <ide> } <ide> <ide><path>volume/mounts/windows_parser_test.go <ide> func TestWindowsParseMountRawSplit(t *testing.T) { <ide> } <ide> <ide> for i, c := range cases { <del> t.Logf("case %d", i) <del> m, err := parser.ParseMountRaw(c.bind, c.driver) <del> if c.fail { <del> if err == nil { <del> t.Errorf("Expected error, was nil, for spec %s\n", c.bind) <add> c := c <add> t.Run(fmt.Sprintf("%d_%s", i, c.bind), func(t *testing.T) { <add> m, err := parser.ParseMountRaw(c.bind, c.driver) <add> if c.fail { <add> assert.ErrorContains(t, err, "", "expected an error") <add> return <ide> } <del> continue <del> } <del> <del> if m == nil || err != nil { <del> t.Errorf("ParseMountRaw failed for spec '%s', driver '%s', error '%v'", c.bind, c.driver, err) <del> continue <del> } <del> <del> if m.Destination != c.expDest { <del> t.Errorf("Expected destination '%s, was %s', for spec '%s'", c.expDest, m.Destination, c.bind) <del> } <del> <del> if m.Source != c.expSource { <del> t.Errorf("Expected source '%s', was '%s', for spec '%s'", c.expSource, m.Source, c.bind) <del> } <ide> <del> if m.Name != c.expName { <del> t.Errorf("Expected name '%s', was '%s' for spec '%s'", c.expName, m.Name, c.bind) <del> } <del> <del> if m.Driver != c.expDriver { <del> t.Errorf("Expected driver '%s', was '%s', for spec '%s'", c.expDriver, m.Driver, c.bind) <del> } <del> <del> if m.RW != c.expRW { <del> t.Errorf("Expected RW '%v', was '%v' for spec '%s'", c.expRW, m.RW, c.bind) <del> } <del> if m.Type != c.expType { <del> t.Fatalf("Expected type '%s', was '%s', for spec '%s'", c.expType, m.Type, c.bind) <del> } <add> assert.NilError(t, err) <add> assert.Equal(t, m.Destination, c.expDest) <add> assert.Equal(t, m.Source, c.expSource) <add> assert.Equal(t, m.Name, c.expName) <add> assert.Equal(t, m.Driver, c.expDriver) <add> assert.Equal(t, m.RW, c.expRW) <add> assert.Equal(t, m.Type, c.expType) <add> }) <ide> } <ide> } <ide>
3
PHP
PHP
remove underscore prefix from request attribute
3283845606c869339c95666b5eec9b96208c6baa
<ide><path>src/Controller/Component/SecurityComponent.php <ide> public function generateToken(ServerRequest $request): ServerRequest <ide> 'unlockedFields' => $this->_config['unlockedFields'], <ide> ]; <ide> <del> return $request->withAttribute('_formToken', [ <add> return $request->withAttribute('formToken', [ <ide> 'unlockedFields' => $token['unlockedFields'], <ide> ]); <ide> } <ide><path>src/View/Helper/FormHelper.php <ide> protected function _csrfField(): string <ide> { <ide> $request = $this->_View->getRequest(); <ide> <del> $formToken = $request->getAttribute('_formToken'); <add> $formToken = $request->getAttribute('formToken'); <ide> if (!empty($formToken['unlockedFields'])) { <ide> foreach ($formToken['unlockedFields'] as $unlocked) { <ide> $this->_unlockedFields[] = $unlocked; <ide> public function end(array $secureAttributes = []): string <ide> { <ide> $out = ''; <ide> <del> if ($this->requestType !== 'get' && $this->_View->getRequest()->getAttribute('_formToken')) { <add> if ($this->requestType !== 'get' && $this->_View->getRequest()->getAttribute('formToken')) { <ide> $out .= $this->secure($this->fields, $secureAttributes); <ide> $this->fields = []; <ide> $this->_unlockedFields = []; <ide> public function end(array $secureAttributes = []): string <ide> */ <ide> public function secure(array $fields = [], array $secureAttributes = []): string <ide> { <del> if (!$this->_View->getRequest()->getAttribute('_formToken')) { <add> if (!$this->_View->getRequest()->getAttribute('formToken')) { <ide> return ''; <ide> } <ide> $debugSecurity = Configure::read('debug'); <ide> public function date(string $fieldName, array $options = []): string <ide> protected function _initInputField(string $field, array $options = []): array <ide> { <ide> if (!isset($options['secure'])) { <del> $options['secure'] = (bool)$this->_View->getRequest()->getAttribute('_formToken'); <add> $options['secure'] = (bool)$this->_View->getRequest()->getAttribute('formToken'); <ide> } <ide> $context = $this->_getContext(); <ide> <ide><path>tests/TestCase/Controller/Component/SecurityComponentTest.php <ide> public function testGenerateToken(): void <ide> $request = $this->Controller->getRequest(); <ide> $request = $this->Security->generateToken($request); <ide> <del> $securityToken = $request->getAttribute('_formToken'); <add> $securityToken = $request->getAttribute('formToken'); <ide> $this->assertNotEmpty($securityToken); <ide> $this->assertSame([], $securityToken['unlockedFields']); <ide> } <ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testCreateClearingFields() <ide> */ <ide> public function testValidateHashNoModel() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', 'foo')); <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', 'foo')); <ide> <ide> $fields = ['anything']; <ide> $result = $this->Form->secure($fields); <ide> public function testValidateHashNoModel() <ide> */ <ide> public function testNoCheckboxLocking() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', 'foo')); <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', 'foo')); <ide> $this->assertSame([], $this->Form->fields); <ide> <ide> $this->Form->checkbox('check', ['value' => '1']); <ide> public function testFormSecurityFields() <ide> { <ide> $fields = ['Model.password', 'Model.username', 'Model.valid' => '0']; <ide> <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', 'testKey')); <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', 'testKey')); <ide> $result = $this->Form->secure($fields); <ide> <ide> $hash = hash_hmac('sha1', serialize($fields) . session_id(), Security::getSalt()); <ide> public function testFormSecurityFieldsNoDebugMode() <ide> Configure::write('debug', false); <ide> $fields = ['Model.password', 'Model.username', 'Model.valid' => '0']; <ide> <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', 'testKey')); <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', 'testKey')); <ide> $result = $this->Form->secure($fields); <ide> <ide> $hash = hash_hmac('sha1', serialize($fields) . session_id(), Security::getSalt()); <ide> public function testFileUploadFieldTypeGenerationForBinaries() <ide> */ <ide> public function testFormSecurityMultipleFields() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', 'foo')); <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', 'foo')); <ide> <ide> $fields = [ <ide> 'Model.0.password', 'Model.0.username', 'Model.0.hidden' => 'value', <ide> public function testFormSecurityMultipleFields() <ide> */ <ide> public function testFormSecurityMultipleSubmitButtons() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', 'testKey')); <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', 'testKey')); <ide> <ide> $this->Form->create($this->article); <ide> $this->Form->text('Address.title'); <ide> public function testSecurityButtonNestedNamed() <ide> */ <ide> public function testSecuritySubmitNestedNamed() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', 'testKey')); <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', 'testKey')); <ide> <ide> $this->Form->create($this->article); <ide> $this->Form->submit('Test', ['type' => 'submit', 'name' => 'Address[button]']); <ide> public function testSecuritySubmitNestedNamed() <ide> */ <ide> public function testSecuritySubmitImageNoName() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', 'testKey')); <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', 'testKey')); <ide> <ide> $this->Form->create(); <ide> $result = $this->Form->submit('save.png'); <ide> public function testSecuritySubmitImageNoName() <ide> */ <ide> public function testSecuritySubmitImageName() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', 'testKey')); <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', 'testKey')); <ide> <ide> $this->Form->create(null); <ide> $result = $this->Form->submit('save.png', ['name' => 'test']); <ide> public function testSecuritySubmitImageName() <ide> */ <ide> public function testFormSecurityMultipleControlFields() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', 'testKey')); <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', 'testKey')); <ide> $this->Form->create(); <ide> <ide> $this->Form->hidden('Addresses.0.id', ['value' => '123456']); <ide> public function testFormSecurityMultipleControlFields() <ide> */ <ide> public function testFormSecurityArrayFields() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', 'testKey')); <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', 'testKey')); <ide> <ide> $this->Form->create(); <ide> $this->Form->text('Address.primary.1'); <ide> public function testFormSecurityArrayFields() <ide> */ <ide> public function testFormSecurityMultipleControlDisabledFields() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', [ <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', [ <ide> 'unlockedFields' => ['first_name', 'address'], <ide> ])); <ide> $this->Form->create(); <ide> public function testFormSecurityMultipleControlDisabledFields() <ide> */ <ide> public function testFormSecurityControlUnlockedFields() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', [ <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', [ <ide> 'unlockedFields' => ['first_name', 'address'], <ide> ])); <ide> $this->Form->create(); <ide> $this->assertEquals( <del> $this->View->getRequest()->getAttribute('_formToken'), <add> $this->View->getRequest()->getAttribute('formToken'), <ide> ['unlockedFields' => $this->Form->unlockField()] <ide> ); <ide> <ide> public function testFormSecurityControlUnlockedFields() <ide> */ <ide> public function testFormSecurityControlUnlockedFieldsDebugSecurityTrue() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', [ <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', [ <ide> 'unlockedFields' => ['first_name', 'address'], <ide> ])); <ide> $this->Form->create(); <ide> $this->assertEquals( <del> $this->View->getRequest()->getAttribute('_formToken'), <add> $this->View->getRequest()->getAttribute('formToken'), <ide> ['unlockedFields' => $this->Form->unlockField()] <ide> ); <ide> <ide> public function testFormSecurityControlUnlockedFieldsDebugSecurityTrue() <ide> */ <ide> public function testFormSecurityControlUnlockedFieldsDebugSecurityDebugFalse() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', [ <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', [ <ide> 'unlockedFields' => ['first_name', 'address'], <ide> ])); <ide> $this->Form->create(); <ide> $this->assertEquals( <del> $this->View->getRequest()->getAttribute('_formToken'), <add> $this->View->getRequest()->getAttribute('formToken'), <ide> ['unlockedFields' => $this->Form->unlockField()] <ide> ); <ide> <ide> public function testFormSecurityControlUnlockedFieldsDebugSecurityDebugFalse() <ide> */ <ide> public function testFormSecurityControlUnlockedFieldsDebugSecurityFalse() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', [ <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', [ <ide> 'unlockedFields' => ['first_name', 'address'], <ide> ])); <ide> $this->Form->create(); <ide> $this->assertEquals( <del> $this->View->getRequest()->getAttribute('_formToken'), <add> $this->View->getRequest()->getAttribute('formToken'), <ide> ['unlockedFields' => $this->Form->unlockField()] <ide> ); <ide> <ide> public function testFormSecurityControlUnlockedFieldsDebugSecurityFalse() <ide> */ <ide> public function testFormSecureWithCustomNameAttribute() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', 'testKey')); <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', 'testKey')); <ide> <ide> $this->Form->text('UserForm.published', ['name' => 'User[custom]']); <ide> $this->assertSame('User.custom', $this->Form->fields[0]); <ide> public function testFormSecureWithCustomNameAttribute() <ide> public function testFormSecuredControl() <ide> { <ide> $this->View->setRequest($this->View->getRequest() <del> ->withAttribute('_formToken', 'stuff') <add> ->withAttribute('formToken', 'stuff') <ide> ->withAttribute('csrfToken', 'testKey')); <ide> $this->article['schema'] = [ <ide> 'ratio' => ['type' => 'decimal', 'length' => 5, 'precision' => 6], <ide> public function testFormSecuredControl() <ide> */ <ide> public function testSecuredControlCustomName() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', 'testKey')); <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', 'testKey')); <ide> $this->assertEquals([], $this->Form->fields); <ide> <ide> $this->Form->text('text_input', [ <ide> public function testSecuredControlCustomName() <ide> */ <ide> public function testSecuredControlDuplicate() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', 'testKey')); <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', 'testKey')); <ide> $this->assertEquals([], $this->Form->fields); <ide> <ide> $this->Form->control('text_val', [ <ide> public function testFormSecuredMultipleSelect() <ide> */ <ide> public function testFormSecuredRadio() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', 'testKey')); <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', 'testKey')); <ide> <ide> $this->assertEquals([], $this->Form->fields); <ide> $options = ['1' => 'option1', '2' => 'option2']; <ide> public function testFormSecuredRadio() <ide> */ <ide> public function testFormSecuredAndDisabledNotAssoc() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', 'testKey')); <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', 'testKey')); <ide> <ide> $this->Form->select('Model.select', [1, 2], ['disabled']); <ide> $this->Form->checkbox('Model.checkbox', ['disabled']); <ide> public function testFormSecuredAndDisabledNotAssoc() <ide> */ <ide> public function testFormSecuredAndDisabled() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', 'testKey')); <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', 'testKey')); <ide> <ide> $this->Form->checkbox('Model.checkbox', ['disabled' => true]); <ide> $this->Form->text('Model.text', ['disabled' => true]); <ide> public function testFormSecuredAndDisabled() <ide> */ <ide> public function testDisableSecurityUsingForm() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', [ <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', [ <ide> 'disabledFields' => [], <ide> ])); <ide> $this->Form->create(); <ide> public function testDisableSecurityUsingForm() <ide> */ <ide> public function testUnlockFieldAddsToList() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', [ <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', [ <ide> 'unlockedFields' => [], <ide> ])); <ide> $this->Form->unlockField('Contact.name'); <ide> public function testUnlockFieldAddsToList() <ide> */ <ide> public function testUnlockFieldRemovingFromFields() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', [ <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', [ <ide> 'unlockedFields' => [], <ide> ])); <ide> $this->Form->create($this->article); <ide> public function testUnlockFieldRemovingFromFields() <ide> */ <ide> public function testResetUnlockFields() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', [ <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', [ <ide> 'key' => 'testKey', <ide> 'unlockedFields' => [], <ide> ])); <ide> public function testResetUnlockFields() <ide> */ <ide> public function testSecuredFormUrlIgnoresHost() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', ['key' => 'testKey'])); <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', ['key' => 'testKey'])); <ide> <ide> $expected = '2548654895b160d724042ed269a2a863fd9d66ee%3A'; <ide> $this->Form->create($this->article, [ <ide> public function testSecuredFormUrlIgnoresHost() <ide> */ <ide> public function testSecuredFormUrlHasHtmlAndIdentifier() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', 'testKey')); <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', 'testKey')); <ide> <ide> $expected = '0a913f45b887b4d9cc2650ef1edc50183896959c%3A'; <ide> $this->Form->create($this->article, [ <ide> public function testSelectMultipleCheckboxRequestData() <ide> */ <ide> public function testSelectMultipleCheckboxSecurity() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', 'testKey')); <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', 'testKey')); <ide> $this->assertEquals([], $this->Form->fields); <ide> <ide> $this->Form->select( <ide> public function testSelectMultipleSecureWithNoOptions() <ide> */ <ide> public function testSelectNoSecureWithNoOptions() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', 'testkey')); <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', 'testkey')); <ide> $this->assertEquals([], $this->Form->fields); <ide> <ide> $this->Form->select( <ide> public function testDateTime() <ide> public function testDateTimeSecured() <ide> { <ide> $this->View->setRequest( <del> $this->View->getRequest()->withAttribute('_formToken', ['unlockedFields' => []]) <add> $this->View->getRequest()->withAttribute('formToken', ['unlockedFields' => []]) <ide> ); <ide> $this->Form->dateTime('date'); <ide> $expected = ['date']; <ide> public function testDateTimeSecured() <ide> public function testDateTimeSecuredDisabled() <ide> { <ide> $this->View->setRequest( <del> $this->View->getRequest()->withAttribute('_formToken', ['unlockedFields' => []]) <add> $this->View->getRequest()->withAttribute('formToken', ['unlockedFields' => []]) <ide> ); <ide> $this->Form->dateTime('date', ['secure' => false]); <ide> $expected = []; <ide> public function testSecurePostButton() <ide> { <ide> $this->View->setRequest($this->View->getRequest() <ide> ->withAttribute('csrfToken', 'testkey') <del> ->withAttribute('_formToken', ['unlockedFields' => []])); <add> ->withAttribute('formToken', ['unlockedFields' => []])); <ide> <ide> $result = $this->Form->postButton('Delete', '/posts/delete/1'); <ide> $tokenDebug = urlencode(json_encode([ <ide> public function testPostLinkSecurityHash() <ide> { <ide> $hash = hash_hmac('sha1', '/posts/delete/1' . serialize(['id' => '1']) . session_id(), Security::getSalt()); <ide> $hash .= '%3Aid'; <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', ['key' => 'test'])); <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', ['key' => 'test'])); <ide> <ide> $result = $this->Form->postLink( <ide> 'Delete', <ide> public function testPostLinkSecurityHashBlockMode() <ide> { <ide> $hash = hash_hmac('sha1', '/posts/delete/1' . serialize([]) . session_id(), Security::getSalt()); <ide> $hash .= '%3A'; <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', ['key' => 'test'])); <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', ['key' => 'test'])); <ide> <ide> $this->Form->create(null, ['url' => ['action' => 'add']]); <ide> $this->Form->control('title'); <ide> public function testPostLinkSecurityHashNoDebugMode() <ide> $hash = hash_hmac('sha1', '/posts/delete/1' . serialize(['id' => '1']) . session_id(), Security::getSalt()); <ide> $hash .= '%3Aid'; <ide> $this->View->setRequest($this->View->getRequest() <del> ->withAttribute('_formToken', ['key' => 'test'])); <add> ->withAttribute('formToken', ['key' => 'test'])); <ide> <ide> $result = $this->Form->postLink( <ide> 'Delete', <ide> public function testPostLinkAfterGetForm() <ide> { <ide> $this->View->setRequest($this->View->getRequest() <ide> ->withAttribute('csrfToken', 'testkey') <del> ->withAttribute('_formToken', 'val')); <add> ->withAttribute('formToken', 'val')); <ide> <ide> $this->Form->create($this->article, ['type' => 'get']); <ide> $this->Form->end(); <ide> public function testSubmitImage() <ide> */ <ide> public function testSubmitUnlockedByDefault() <ide> { <del> $this->View->setRequest($this->View->getRequest()->withAttribute('_formToken', 'secured')); <add> $this->View->setRequest($this->View->getRequest()->withAttribute('formToken', 'secured')); <ide> $this->Form->submit('Go go'); <ide> $this->Form->submit('Save', ['name' => 'save']); <ide>
4
Text
Text
update flake8 command
4e8a0d924eafc3f15dff202980cf24f99221eeb3
<ide><path>CONTRIBUTING.md <ide> We want your work to be readable by others; therefore, we encourage you to note <ide> black . <ide> ``` <ide> <del>- All submissions will need to pass the test __flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics__ before they will be accepted so if possible, try this test locally on your Python file(s) before submitting your pull request. <add>- All submissions will need to pass the test __flake8 . --ignore=E203,W503 --max-line-length=88__ before they will be accepted so if possible, try this test locally on your Python file(s) before submitting your pull request. <ide> <ide> ```bash <ide> pip3 install flake8 # only required the first time <del> flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics <add> flake8 . --ignore=E203,W503 --max-line-length=88 --show-source <ide> ``` <ide> <ide> - Original code submission require docstrings or comments to describe your work. <ide><path>DIRECTORY.md <ide> * [Zellers Congruence](https://github.com/TheAlgorithms/Python/blob/master/maths/zellers_congruence.py) <ide> <ide> ## Matrix <add> * [Count Islands In Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/count_islands_in_matrix.py) <ide> * [Matrix Class](https://github.com/TheAlgorithms/Python/blob/master/matrix/matrix_class.py) <ide> * [Matrix Operation](https://github.com/TheAlgorithms/Python/blob/master/matrix/matrix_operation.py) <ide> * [Nth Fibonacci Using Matrix Exponentiation](https://github.com/TheAlgorithms/Python/blob/master/matrix/nth_fibonacci_using_matrix_exponentiation.py)
2
Python
Python
set version to v3.0.0.dev11
2d9604d39cbf30edf7c4170bb872045e36c7090f
<ide><path>spacy/about.py <ide> # fmt: off <ide> __title__ = "spacy" <del>__version__ = "3.0.0.dev10" <add>__version__ = "3.0.0.dev11" <ide> __release__ = True <ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download" <ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
1
Python
Python
add return_tensor parameter for feature extraction
35bd089a241788a43a43e27de1ef3f5cede7954b
<ide><path>src/transformers/pipelines/feature_extraction.py <ide> class FeatureExtractionPipeline(Pipeline): <ide> If no framework is specified, will default to the one currently installed. If no framework is specified and <ide> both frameworks are installed, will default to the framework of the `model`, or to PyTorch if no model is <ide> provided. <add> return_tensor (`bool`, *optional*): <add> If `True`, returns a tensor according to the specified framework, otherwise returns a list. <ide> task (`str`, defaults to `""`): <ide> A task-identifier for the pipeline. <ide> args_parser ([`~pipelines.ArgumentHandler`], *optional*): <ide> class FeatureExtractionPipeline(Pipeline): <ide> the associated CUDA device id. <ide> """ <ide> <del> def _sanitize_parameters(self, truncation=None, tokenize_kwargs=None, **kwargs): <add> def _sanitize_parameters(self, truncation=None, tokenize_kwargs=None, return_tensors=None, **kwargs): <ide> if tokenize_kwargs is None: <ide> tokenize_kwargs = {} <ide> <ide> def _sanitize_parameters(self, truncation=None, tokenize_kwargs=None, **kwargs): <ide> <ide> preprocess_params = tokenize_kwargs <ide> <del> return preprocess_params, {}, {} <add> postprocess_params = {} <add> if return_tensors is not None: <add> postprocess_params["return_tensors"] = return_tensors <add> <add> return preprocess_params, {}, postprocess_params <ide> <ide> def preprocess(self, inputs, **tokenize_kwargs) -> Dict[str, GenericTensor]: <ide> return_tensors = self.framework <ide> def _forward(self, model_inputs): <ide> model_outputs = self.model(**model_inputs) <ide> return model_outputs <ide> <del> def postprocess(self, model_outputs): <add> def postprocess(self, model_outputs, return_tensors=False): <ide> # [0] is the first available tensor, logits or last_hidden_state. <add> if return_tensors: <add> return model_outputs[0] <ide> if self.framework == "pt": <ide> return model_outputs[0].tolist() <ide> elif self.framework == "tf": <ide><path>tests/pipelines/test_pipelines_feature_extraction.py <ide> import unittest <ide> <ide> import numpy as np <add>import tensorflow as tf <add>import torch <ide> <ide> from transformers import ( <ide> FEATURE_EXTRACTOR_MAPPING, <ide> def test_tokenization_small_model_tf(self): <ide> tokenize_kwargs=tokenize_kwargs, <ide> ) <ide> <add> @require_torch <add> def test_return_tensors_pt(self): <add> feature_extractor = pipeline( <add> task="feature-extraction", model="hf-internal-testing/tiny-random-distilbert", framework="pt" <add> ) <add> outputs = feature_extractor("This is a test" * 100, return_tensors=True) <add> self.assertTrue(torch.is_tensor(outputs)) <add> <add> @require_tf <add> def test_return_tensors_tf(self): <add> feature_extractor = pipeline( <add> task="feature-extraction", model="hf-internal-testing/tiny-random-distilbert", framework="tf" <add> ) <add> outputs = feature_extractor("This is a test" * 100, return_tensors=True) <add> self.assertTrue(tf.is_tensor(outputs)) <add> <ide> def get_shape(self, input_, shape=None): <ide> if shape is None: <ide> shape = []
2
Javascript
Javascript
fix next info test during stable release
3d5a9bf5e7a44286254c8a5fd9f674537ba41d4f
<ide><path>test/integration/cli/test/index.test.js <ide> describe('CLI Usage', () => { <ide> stdout: true, <ide> stderr: true, <ide> }) <del> expect(info.stderr || '').toBe('') <add> <add> // when a stable release is done the non-latest canary <add> // warning will show so skip this check for the stable release <add> if (pkg.version.includes('-canary')) { <add> expect(info.stderr || '').toBe('') <add> } <ide> expect(info.stdout).toMatch( <ide> new RegExp(` <ide> Operating System:
1
Java
Java
add @donotstrip to remoteconnection methods
ecd8802c1faef183c8f6dcec4f42ae4e3011bd1d
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/Inspector.java <ide> private Page(int id, String title, String vm) { <ide> <ide> @DoNotStrip <ide> public interface RemoteConnection { <add> @DoNotStrip <ide> void onMessage(String message); <add> @DoNotStrip <ide> void onDisconnect(); <ide> } <ide>
1
Javascript
Javascript
improve feb translation
b308b60a07ab602a78afffa2a324520bd0957dcc
<ide><path>src/locale/ro.js <ide> //! locale : Romanian [ro] <ide> //! author : Vlad Gurdiga : https://github.com/gurdiga <ide> //! author : Valentin Agachi : https://github.com/avaly <add>//! author : Emanuel Cepoi : https://github.com/cepem <ide> <ide> import moment from '../moment'; <ide> <ide> function relativeTimeWithPlural(number, withoutSuffix, key) { <ide> <ide> export default moment.defineLocale('ro', { <ide> months : 'ianuarie_februarie_martie_aprilie_mai_iunie_iulie_august_septembrie_octombrie_noiembrie_decembrie'.split('_'), <del> monthsShort : 'ian._febr._mart._apr._mai_iun._iul._aug._sept._oct._nov._dec.'.split('_'), <add> monthsShort : 'ian._feb._mart._apr._mai_iun._iul._aug._sept._oct._nov._dec.'.split('_'), <ide> monthsParseExact: true, <ide> weekdays : 'duminică_luni_marți_miercuri_joi_vineri_sâmbătă'.split('_'), <ide> weekdaysShort : 'Dum_Lun_Mar_Mie_Joi_Vin_Sâm'.split('_'), <ide><path>src/test/locale/ro.js <ide> import moment from '../../moment'; <ide> localeModule('ro'); <ide> <ide> test('parse', function (assert) { <del> var tests = 'ianuarie ian._februarie febr._martie mart._aprilie apr._mai mai_iunie iun._iulie iul._august aug._septembrie sept._octombrie oct._noiembrie nov._decembrie dec.'.split('_'), i; <add> var tests = 'ianuarie ian._februarie feb._martie mart._aprilie apr._mai mai_iunie iun._iulie iul._august aug._septembrie sept._octombrie oct._noiembrie nov._decembrie dec.'.split('_'), i; <ide> function equalTest(input, mmm, i) { <ide> assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); <ide> } <ide> test('format', function (assert) { <ide> var a = [ <ide> ['dddd, MMMM Do YYYY, h:mm:ss A', 'duminică, februarie 14 2010, 3:25:50 PM'], <ide> ['ddd, hA', 'Dum, 3PM'], <del> ['M Mo MM MMMM MMM', '2 2 02 februarie febr.'], <add> ['M Mo MM MMMM MMM', '2 2 02 februarie feb.'], <ide> ['YYYY YY', '2010 10'], <ide> ['D Do DD', '14 14 14'], <ide> ['d do dddd ddd dd', '0 0 duminică Dum Du'], <ide> test('format', function (assert) { <ide> ['LLL', '14 februarie 2010 15:25'], <ide> ['LLLL', 'duminică, 14 februarie 2010 15:25'], <ide> ['l', '14.2.2010'], <del> ['ll', '14 febr. 2010'], <del> ['lll', '14 febr. 2010 15:25'], <del> ['llll', 'Dum, 14 febr. 2010 15:25'] <add> ['ll', '14 feb. 2010'], <add> ['lll', '14 feb. 2010 15:25'], <add> ['llll', 'Dum, 14 feb. 2010 15:25'] <ide> ], <ide> b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), <ide> i; <ide> test('format ordinal', function (assert) { <ide> }); <ide> <ide> test('format month', function (assert) { <del> var expected = 'ianuarie ian._februarie febr._martie mart._aprilie apr._mai mai_iunie iun._iulie iul._august aug._septembrie sept._octombrie oct._noiembrie nov._decembrie dec.'.split('_'), i; <add> var expected = 'ianuarie ian._februarie feb._martie mart._aprilie apr._mai mai_iunie iun._iulie iul._august aug._septembrie sept._octombrie oct._noiembrie nov._decembrie dec.'.split('_'), i; <ide> for (i = 0; i < expected.length; i++) { <ide> assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); <ide> }
2
Python
Python
fix a typo in a comment in methodviewtype.__new__
6b9fd4a968dc314ec03c6e5c08c5939667f1634c
<ide><path>flask/views.py <ide> def __new__(cls, name, bases, d): <ide> methods.add(key.upper()) <ide> # If we have no method at all in there we don't want to <ide> # add a method list. (This is for instance the case for <del> # the baseclass or another subclass of a base method view <add> # the base class or another subclass of a base method view <ide> # that does not introduce new methods). <ide> if methods: <ide> rv.methods = sorted(methods)
1
Javascript
Javascript
use cached styles
8377b30b8d35283e325123ddd9047544d83ac11c
<ide><path>Libraries/Image/ImageBackground.js <ide> <ide> const Image = require('Image'); <ide> const React = require('React'); <add>const StyleSheet = require('StyleSheet'); <ide> const View = require('View'); <ide> <ide> /** <ide> class ImageBackground extends React.Component { <ide> <Image <ide> {...props} <ide> style={[ <add> StyleSheet.absoluteFill, <ide> { <del> position: 'absolute', <del> left: 0, <del> right: 0, <del> top: 0, <del> bottom: 0, <ide> // Temporary Workaround: <ide> // Current (imperfect yet) implementation of <Image> overwrites width and height styles <ide> // (which is not quite correct), and these styles conflict with explicitly set styles
1
Python
Python
add fac to spacy.explain (resolves )
559f4139e32b7de01dc0f97ec284b4d356413528
<ide><path>spacy/glossary.py <ide> def explain(term): <ide> 'PERSON': 'People, including fictional', <ide> 'NORP': 'Nationalities or religious or political groups', <ide> 'FACILITY': 'Buildings, airports, highways, bridges, etc.', <add> 'FAC': 'Buildings, airports, highways, bridges, etc.', <ide> 'ORG': 'Companies, agencies, institutions, etc.', <ide> 'GPE': 'Countries, cities, states', <ide> 'LOC': 'Non-GPE locations, mountain ranges, bodies of water',
1
PHP
PHP
add tests for datetimetype marshalling
8d633748b0a341b8540a9e18284ea0ff0c1e4f41
<ide><path>src/Database/Type/DateTimeType.php <ide> public function toPHP($value, Driver $driver) { <ide> return $value; <ide> } <ide> <add>/** <add> * Convert request data into a datetime object. <add> * <add> * @param mixed $value Request data <add> * @return \DateTime <add> */ <add> public function marshall($value) { <add> try { <add> if ($value === '' || $value === null || $value === false || $value === true) { <add> return $value; <add> } elseif (is_numeric($value)) { <add> $date = new DateTime('@' . $value); <add> } elseif (is_string($value)) { <add> $date = new DateTime($value); <add> } <add> if (isset($date)) { <add> return $date; <add> } <add> } catch (\Exception $e) { <add> return $value; <add> } <add> <add> $value += ['second' => 0]; <add> <add> $date = new DateTime(); <add> $date->setTime(0, 0, 0); <add> if (isset($value['year'], $value['month'], $value['day'])) { <add> $date->setDate($value['year'], $value['month'], $value['day']); <add> } <add> if (isset($value['hour'], $value['minute'])) { <add> if (isset($value['meridian'])) { <add> $value['hour'] = strtolower($value['meridian']) === 'am' ? $value['hour'] : $value['hour'] + 12; <add> } <add> $date->setTime($value['hour'], $value['minute'], $value['second']); <add> } <add> return $date; <add> } <add> <ide> } <ide><path>tests/TestCase/Database/Type/DateTimeTypeTest.php <ide> public function testToDatabase() { <ide> $this->assertEquals('2013-08-12 15:16:17', $result); <ide> } <ide> <add>/** <add> * Data provider for marshall() <add> * <add> * @return array <add> */ <add> public static function marshallProvider() { <add> return [ <add> // invalid types. <add> [null, null], <add> [false, false], <add> [true, true], <add> ['', ''], <add> ['derpy', 'derpy'], <add> ['2013-nope!', '2013-nope!'], <add> <add> // valid string types <add> ['1392387900', new \DateTime('@1392387900')], <add> [1392387900, new \DateTime('@1392387900')], <add> ['2014-02-14', new \DateTime('2014-02-14')], <add> ['2014-02-14 13:14:15', new \DateTime('2014-02-14 13:14:15')], <add> <add> // valid array types <add> [ <add> ['year' => 2014, 'month' => 2, 'day' => 14, 'hour' => 13, 'minute' => 14, 'second' => 15], <add> new \DateTime('2014-02-14 13:14:15') <add> ], <add> [ <add> [ <add> 'year' => 2014, 'month' => 2, 'day' => 14, <add> 'hour' => 1, 'minute' => 14, 'second' => 15, <add> 'meridian' => 'am' <add> ], <add> new \DateTime('2014-02-14 01:14:15') <add> ], <add> [ <add> [ <add> 'year' => 2014, 'month' => 2, 'day' => 14, <add> 'hour' => 1, 'minute' => 14, 'second' => 15, <add> 'meridian' => 'pm' <add> ], <add> new \DateTime('2014-02-14 13:14:15') <add> ], <add> ]; <add> } <add> <add>/** <add> * test marshalling data. <add> * <add> * @dataProvider marshallProvider <add> * @return void <add> */ <add> public function testMarshall($value, $expected) { <add> $result = $this->type->marshall($value); <add> $this->assertEquals($expected, $result); <add> } <add> <ide> }
2
Text
Text
add min/max to performance documentation
d5393003acb19164d6112e5c4745c37e6a9ee7be
<ide><path>docs/general/performance.md <ide> new Chart(ctx, { <ide> }); <ide> ``` <ide> <add>## Specify `min` and `max` for scales <add> <add>If you specify the `min` and `max`, the scale does not have to compute the range from the data. <add> <add>```javascript <add>new Chart(ctx, { <add> type: 'line', <add> data: data, <add> options: { <add> scales: { <add> x: { <add> type: 'time', <add> min: new Date('2019-01-01').valueOf(), <add> max: new Date('2019-12-31').valueOf() <add> }, <add> y: { <add> type: 'linear', <add> min: 0, <add> max: 100 <add> } <add> } <add> } <add>}); <add>``` <add> <ide> ## Data Decimation <ide> <ide> Decimating your data will achieve the best results. When there is a lot of data to display on the graph, it doesn't make sense to show tens of thousands of data points on a graph that is only a few hundred pixels wide.
1
Javascript
Javascript
get pages before entry function
0b9b902a89e0afbd167226c71ad31677dbea914b
<ide><path>server/build/webpack.js <ide> export default async function getBaseWebpackConfig (dir, {dev = false, isServer <ide> .split(process.platform === 'win32' ? ';' : ':') <ide> .filter((p) => !!p) <ide> <del> let totalPages <add> const pagesEntries = await getPages(dir, {dev, isServer, pageExtensions: config.pageExtensions.join('|')}) <add> const totalPages = Object.keys(pagesEntries).length <add> const clientEntries = !isServer ? { <add> 'main.js': [ <add> dev && !isServer && path.join(__dirname, '..', '..', 'client', 'webpack-hot-middleware-client'), <add> dev && !isServer && path.join(__dirname, '..', '..', 'client', 'on-demand-entries-client'), <add> require.resolve(`../../client/next${dev ? '-dev' : ''}`) <add> ].filter(Boolean) <add> } : {} <ide> <ide> let webpackConfig = { <ide> devtool: dev ? 'source-map' : false, <ide> export default async function getBaseWebpackConfig (dir, {dev = false, isServer <ide> target: isServer ? 'node' : 'web', <ide> externals: externalsConfig(dir, isServer), <ide> context: dir, <add> // Kept as function to be backwards compatible <ide> entry: async () => { <del> const pages = await getPages(dir, {dev, isServer, pageExtensions: config.pageExtensions.join('|')}) <del> totalPages = Object.keys(pages).length <del> const mainJS = require.resolve(`../../client/next${dev ? '-dev' : ''}`) <del> const clientConfig = !isServer ? { <del> 'main.js': [ <del> dev && !isServer && path.join(__dirname, '..', '..', 'client', 'webpack-hot-middleware-client'), <del> dev && !isServer && path.join(__dirname, '..', '..', 'client', 'on-demand-entries-client'), <del> mainJS <del> ].filter(Boolean) <del> } : {} <ide> return { <del> ...clientConfig, <del> ...pages <add> ...clientEntries, <add> // Only _error and _document when in development. The rest is handled by on-demand-entries <add> ...pagesEntries <ide> } <ide> }, <ide> output: {
1
Text
Text
fix max length on stream.md
1a5ec837ca56774f2a9ee54ee9a0f6cbfa01d4bc
<ide><path>doc/api/stream.md <ide> constructor and implement the `writable._write()` method. The <ide> changes: <ide> - version: REPLACEME <ide> pr-url: https://github.com/nodejs/node/pull/18438 <del> description: Add `emitClose` option to specify if `close` is emitted on destroy <add> description: > <add> Add `emitClose` option to specify if `close` is emitted on destroy <ide> --> <ide> <ide> * `options` {Object}
1
Javascript
Javascript
add missing semicolons in sea3dlegacy
476491aba1d81f20cd583d9a7c998a6f8fb1eff3
<ide><path>examples/js/loaders/sea3d/SEA3DLegacy.js <ide> THREE.SEA3D.prototype.readSkeleton = function( sea ) { <ide> <ide> for ( var i = 0; i < sea.joint.length; i ++ ) { <ide> <del> var bone = sea.joint[ i ] <add> var bone = sea.joint[ i ]; <ide> <ide> // get world inverse matrix <ide>
1
Mixed
Text
address feedback and expand documentation
308390ba5b7fe03e5ed899c70e49faa47044ace8
<ide><path>Library/Homebrew/livecheck.rb <ide> # also return the related instance variable when no argument is provided. <ide> # <ide> # This information is used by the `brew livecheck` command to control its <del># behavior. <add># behavior. Example `livecheck` blocks can be found in the <add># [`brew livecheck` documentation](https://docs.brew.sh/Brew-Livecheck). <ide> class Livecheck <ide> extend Forwardable <ide> <ide><path>Library/Homebrew/livecheck/strategy/sourceforge.rb <ide> module Strategy <ide> # pushed out of the feed (especially if it hasn't been updated recently). <ide> # <ide> # Usually we address this situation by adding a `livecheck` block to <del> # the formula that checks the page for the relevant directory in the <add> # the formula/cask that checks the page for the relevant directory in the <ide> # project instead. In this situation, it's necessary to use <ide> # `strategy :page_match` to prevent the {Sourceforge} stratgy from <ide> # being used. <ide><path>docs/Brew-Livecheck.md <del># Brew Livecheck <add># `brew livecheck` <ide> <del>**NOTE: This document is a work in progress and will be revised and expanded as time permits.** <add>The `brew livecheck` command finds the newest version of a formula or cask's software by checking upstream. Livecheck has [strategies](https://rubydoc.brew.sh/Homebrew/Livecheck/Strategy.html) to identify versions from various sources, such as Git repositories, websites, etc. <ide> <del>**NOTE: `livecheck` blocks are currently found in separate files in the [Homebrew/homebrew-livecheck](https://github.com/Homebrew/homebrew-livecheck) repository's `Livecheckables` folder. These will be migrated to their respective formulae in Homebrew/homebrew-core in the near future and this document is written as if this migration has already happened.** <add>## Behavior <ide> <del>The general purpose of the `brew livecheck` command is to find the newest version of a formula's software by checking an upstream source. Livecheck has [built-in strategies](#built-in-strategies) that can identify versions from some popular sources, such as Git repositories, certain websites, etc. <add>When livecheck isn't given instructions for how to check for upstream versions, it does the following by default: <ide> <del>## Default behavior <add>1. For formulae: Collect the `head`, `stable`, and `homepage` URLs, in that order. For casks: Collect the `url` and `homepage` URLs, in that order. <add>1. Determine if any strategies apply to the first URL. If not, try the next URL. <add>1. If a strategy can be applied, use it to check for new versions. <add>1. Return the newest version (or an error if versions could not be found at any available URLs). <ide> <del>When livecheck isn't given instructions for how to check for upstream versions of a formula's software, it does the following by default: <add>It's sometimes necessary to override this default behavior to create a working check for a formula/cask. If a source doesn't provide the newest version, we need to check a different one. If livecheck doesn't correctly match version text, we need to provide an appropriate regex. <ide> <del>1. Collect the `head`, `stable`, and `homepage` URLs from the formula, in that order. <del>2. Determine if any of the available strategies can be applied to the first URL. Move on to the next URL if no strategies apply. <del>3. If a strategy can be applied, use it to check for new versions. <del>4. Return the newest version (or an error if versions could not be found at any available URLs). <add>This can be accomplished by adding a `livecheck` block to the formula/cask. For more information on the available methods, please refer to the [`Livecheck` class documentation](https://rubydoc.brew.sh/Livecheck.html). <ide> <del>This approach works fine for a number of formulae without requiring any manual intervention. However, it's sometimes necessary to change livecheck's default behavior to create a working check for a formula. <add>## Creating a check <ide> <del>It may be that the source livecheck is using doesn't provide the newest version and we need to check a different one instead. In another case, livecheck may be matching a version it shouldn't and we need to provide a regex to only match what's appropriate. <add>1. **Use the debug output to understand the situation**. `brew livecheck --debug <formula>|<cask>` provides information about which URLs livecheck tries, any strategies that apply, matched versions, etc. <ide> <del>## The `livecheck` block <add>1. **Research available sources to select a URL**. Try removing the file name from `stable`/`url`, to see if this is a directory listing page. If that doesn't work, try to find a page that links to the file (e.g. a download page). If it's not possible to find the newest version on the website, try checking other sources from the formula/cask. When necessary, search for other sources outside of the formula/cask. <ide> <del>We can control livecheck's behavior by providing a `livecheck` block in the formula. Here is a simple example to check a "downloads" page for links containing a filename like `example-1.2.tar.gz`: <add>1. **Create a regex, if necessary**. If the check works without a regex and wouldn't benefit from having one, it's usually fine to omit it. More information on creating regexes can be found in the [regex guidelines](#regex-guidelines) section. <ide> <del>```ruby <del>livecheck do <del> url "https://www.example.com/downloads/" <del> regex(/href=.*?example[._-]v?(\d+(?:\.\d+)+)\.t/i) <del>end <del>``` <add>### General guidelines <ide> <del>At the moment, it's only necessary to create a `livecheck` block in a formula when the default check doesn't work properly. <add>* **Only use `strategy` when it's necessary**. For example, if livecheck is already using `Git` for a URL, it's not necessary to use `strategy :git`. However, if `Git` applies to a URL but we need to use `PageMatch`, it's necessary to use `strategy :page_match`. <ide> <del>## Creating a check <add>* **Only use the `GithubLatest` strategy when it's necessary and correct**. Github.com rate limits requests and we try to minimize our use of this strategy to avoid hitting the rate limit on CI or when using `brew livecheck --tap` on large taps (e.g. homebrew/core). The `Git` strategy is often sufficient and we only need to use `GithubLatest` when the "latest" release is different than the newest version from the tags. <ide> <del>1. **Use the debug output to understand the current situation**. Running `brew livecheck --debug <formula>` (where `<formula>` is the formula name) will provide more information about which URL livecheck is using and any strategy that applies. <add>### URL guidelines <ide> <del>2. **Research available sources**. It's generally preferable to check for a new version at the same source as the `stable` URL, when possible. With this in mind, it may be a good idea to start by removing the file name from the `stable` URL, to see if this is a directory listing page. If that doesn't work, the website may have a downloads page we can check for versions. If it's not possible to find the newest version at this source through any means, try checking other sources from the formula (e.g. an upstream Git repository or the homepage). It's also sometimes necessary to search for other sources outside of the formula. <add>* **A `url` is required in a `livecheck` block**. This can be a URL string (e.g. `"https://www.example.com/downloads/"`) or a formula/cask URL symbol (i.e. `:stable`, `:url`, `:head`, `:homepage`). The exception to this rule is a `livecheck` block that only uses `skip`. <ide> <del>3. **Compare available versions between sources**. If the latest version is available from the `stable` source, it's best to use that. Otherwise, check the other sources to identify where the latest version is available. <add>* **Check for versions in the same location as the stable archive, whenever possible**. <ide> <del>4. **Select a source**. After researching and comparing sources, decide which one is the best available option and use it as the `url` in the `livecheck` block. <add>* **Avoid checking paginated release pages, when possible**. For example, we generally avoid checking the `release` page for a GitHub project because the latest stable version can be pushed off the first page by pre-release versions. In this scenario, it's more reliable to use the `Git` strategy, which fetches all the tags in the repository. <ide> <del>5. **Create a regex, if necessary or beneficial**. If the check works fine without a regex and wouldn't benefit from having one, it's fine to omit it. However, when a default check isn't working properly and we need to create a `livecheck` block, a regex is almost always necessary as well. More information on creating regexes can be found in the [regex guidelines](#regex-guidelines) section. <add>### Regex guidelines <ide> <del>6. **Verify the check is working as intended**. Run `brew livecheck --debug <formula>` again to ensure livecheck is identifying all the versions it should and properly returning the newest version at the end. <add>The `livecheck` block regex restricts matches to a subset of the fetched content and uses a capture group around the version text. <ide> <del>### URL guidelines <add>* **Regexes should be made case insensitive, whenever possible**, by adding `i` at the end (e.g. `/.../i` or `%r{...}i`). This improves reliability, as the regex will handle changes in letter case without needing modifications. <ide> <del>* **A `url` is a required part of a `livecheck` block** and can either be a string containing a URL (e.g. `"https://www.example.com/downloads/"`) or a symbol referencing one of the supported formula URLs (i.e. `:stable`, `:homepage`, or `:head`). <add>* **Regexes should only use a capturing group around the version text**. For example, in `/href=.*?example-v?(\d+(?:\.\d+)+)(?:-src)?\.t/i`, we're only using a capturing group around the version test (matching a version like `1.2`, `1.2.3`, etc.) and we're using non-capturing groups elsewhere (e.g. `(?:-src)?`). <ide> <del>* **Use a symbol for a formula URL (i.e. `:homepage`, `:stable`, and `:head`) when appropriate**, to avoid duplicating formula URLs in the livecheckable. <add>* **Anchor the start/end of the regex, to restrict the scope**. For example, on HTML pages we often match file names or version directories in `href` attribute URLs (e.g. `/href=.*?example[._-]v?(\d+(?:\.\d+)+)\.zip/i`). The general idea is that limiting scope will help exclude unwanted matches. <ide> <del>* **It's generally preferable to check for versions in the same location as the stable archive, when possible**. This preference is stronger for first-party sources (websites, repositories, etc.) and becomes weaker for third-party sources (e.g. mirrors, another software package manager, etc.). <add>* **Avoid generic catch-alls like `.*` or `.+`** in favor of something non-greedy and/or contextually appropriate. For example, to match characters within the bounds of an HTML attribute, use `[^"' >]+?`. <ide> <del>### Regex guidelines <add>* **Use `[._-]` in place of a period/underscore/hyphen between the software name and version in a file name**. For a file named `example-1.2.3.tar.gz`, `example[._-]v?(\d+(?:\.\d+)+)\.t` will continue matching if the upstream file name format changes to `example_1.2.3.tar.gz` or `example.1.2.3.tar.gz`. <ide> <del>The regex in a `livecheck` block is used within a strategy to restrict matching to only relevant text (or strings) and to establish what part of the matched text is the version (using a capture group). <add>* **Use `\.t` in place of `\.tgz`, `\.tar\.gz`, etc.** There are a variety of different file extensions for tarballs (e.g. `.tar.bz2`, `tbz2`, `.tar.gz`, `.tgz`, `.tar.xz`, `.txz`, etc.) and the upstream source may switch from one compression format to another over time. `\.t` avoids this issue by matching current and future formats starting with `t`. Outside of tarballs, we use the full file extension in the regex like `\.zip`, `\.jar`, etc. <ide> <del>Creating a good regex is a balance between being too strict (breaking easily) and too loose (matching more than it should). <add>## Example `livecheck` blocks <ide> <del>* For technical reasons, **the `regex` call in the `livecheck` block should always use parentheses** (e.g. `regex(/example/)`). <add>The following examples cover a number of patterns that you may encounter. These are intended to be representative samples and can be easily adapted. <ide> <del>* **Regex literals should follow the established Homebrew style**, where the `/.../` syntax is the default and the `%r{...}` syntax is used when a forward slash (`/`) is present. <add>When in doubt, start with one of these examples instead of copy-pasting a `livecheck` block from a random formula/cask. <ide> <del>* **Regexes should adequately represent their intention.** This requires an understanding of basic regex syntax, so we avoid issues like using `.` (match any character) instead of `\.` when we only want to match a period. We also try to be careful about our use of generic catch-alls like `.*` or `.+`, as it's often better to use something non-greedy and contextually appropriate. For example, if we wanted to match a variety of characters while trying to stay within the bounds of an HTML attribute, we could use something like `[^"' >]*?`. <add>### File names <ide> <del>* **Try not to be too specific in some parts of the regex.** For example, if a file name uses a hyphen (`-`) between the software name and version (e.g. `example-1.2.3.tar.gz`), we may want to use something like `example[._-]v?(\d+(?:\.\d+)+)\.t` instead. This would allow the regex to continue matching if the upstream file name format changes to `example.1.2.3.tar.gz` or `example_1.2.3.tar.gz`. <add>```ruby <add> livecheck do <add> url "https://www.example.com/downloads/" <add> regex(/href=.*?example[._-]v?(\d+(?:\.\d+)+)\.t/i) <add> end <add>``` <ide> <del>* **Regexes should be case insensitive unless case sensitivity is explicitly required for matching to work properly**. Case insensitivity is enabled by adding the `i` flag at the end of the regex literal (e.g. `/.../i` or `%r{...}i`). This helps to improve reliability and reduce maintenance, as a case-insensitive regex doesn't need to be manually updated if there are any upstream changes in letter case. <add>When matching the version from a file name on an HTML page, we often restrict matching to `href` attributes. `href=.*?` will match the opening delimiter (`"`, `'`) as well as any part of the URL before the file name. <ide> <del>* **Regexes should only use a capturing group around the part of the matched text that corresponds to the version**. For example, in `/href=.*?example-v?(\d+(?:\.\d+)+)(?:-src)?\.t/i`, we're only using a capturing group around the version part (matching a version like `1.2`, `1.2.3`, etc.) and we're using non-capturing groups elsewhere (e.g. `(?:-src)?`). This allows livecheck to rely on the first capture group being the version string. <add>We sometimes make this more explicit to exclude unwanted matches. URLs with a preceding path can use `href=.*?/` and others can use `href=["']?`. For example, this is necessary when the page also contains unwanted files with a longer prefix (`another-example-1.2.tar.gz`). <ide> <del>* **Regexes should only match stable versions**. Regexes should be written to avoid prerelease versions like `1.2-alpha1`, `1.2-beta1`, `1.2-rc1`, etc. <add>### Version directories <ide> <del>* **Restrict matching to `href` attributes when targeting file names in an HTML page (or `url` attributes in an RSS feed)**. Using `href=.*?` (or `url=.*?`) at the start of the regex will take care of any opening delimiter for the attribute (`"`, `'`, or nothing) as well as any leading part of the URL. This helps to keep the regex from being overly specific, reducing the need for maintenance in the future. A regex like `href=.*?example-...` is often fine but sometimes it's necessary to have something explicit before the file name to limit matching to only what's appropriate (e.g. `href=.*?/example-...` or `href=["']?example-...`). Similarly, `["' >]` can be used to target the end of the attribute, when needed. <add>```ruby <add> livecheck do <add> url "https://www.example.com/releases/example/" <add> regex(%r{href=["']?v?(\d+(?:\.\d+)+)/?["' >]}i) <add> end <add>``` <ide> <del>* **Use `\.t` in place of `\.tgz`, `\.tar\.gz`, etc.** There are a number of different file extensions for tarballs (e.g. `.tar.bz2`, `tbz2`, `.tar.gz`, `.tgz`, `.tar.xz`, `.txz`, etc.) and the upstream source may switch from one compression format to another over time. `\.t` avoids this issue by matching current and future formats starting with `t`. Outside of tarballs, it's fine to use full file extensions in the regex like `\.zip`, `\.jar`, etc. <add>When checking a directory listing page, sometimes files are separated into version directories (e.g. `1.2.3/`). In this case, we must identify versions from the directory names. <ide> <del>* **When matching versions like `1.2`, `1.2.3`, `v1.2`, etc., use the standard snippet for this in the regex: `v?(\d+(?:\.\d+)+)`**. This is often copy-pasted into the regex but it can also be modified to suit the circumstances. For example, if the version uses underscores instead, the standard regex could be modified to something like `v?(\d+(?:[._]\d+)+)`. [The general idea behind this standard snippet is that it better represents our intention compared to older, looser snippets that we now avoid (e.g. `[0-9.]+`).] <add>### Git tags <ide> <del>* **Similarly, when matching Git tags with a version like `1.2`, `1.2.3`, `v1.2.3`, etc., start with the standard regex for this (`/^v?(\d+(?:\.\d+)+)$/i`) and modify it as needed**. Sometimes it's necessary to modify the regex to add a prefix, like `/^example-v?(\d+(?:\.\d+)+)$/i` for an `example-1.2.3` tag format. The general idea here is that Git tags are strings, so we can avoid unrelated software by restricting the start of the string (`^`) and unstable versions by restricting the end of the string (`$`). <add>```ruby <add> livecheck do <add> url :stable <add> regex(/^v?(\d+(?:\.\d+)+)$/i) <add> end <add>``` <ide> <del>## Built-in strategies <add>When the `stable` URL uses the `Git` strategy, the regex above will only match tags like `1.2`/`v1.2`, etc. <ide> <del>Livecheck's strategies are established methods for finding versions at either a specific source or a general type of source. The available strategies are as follows: <add>If tags include the software name as a prefix (e.g. `example-1.2.3`), it's easy to modify the regex accordingly: `/^example[._-]v?(\d+(?:\.\d+)+)$/i` <ide> <del>* `Apache` <del>* `Bitbucket` <del>* `Git` <del>* `Gnome` <del>* `Gnu` <del>* `Hackage` <del>* `Launchpad` <del>* `Npm` <del>* `PageMatch` <del>* `Pypi` <del>* `Sourceforge` <add>### `PageMatch` `strategy` block <add> <add>```ruby <add> livecheck do <add> url :homepage <add> regex(/href=.*?example[._-]v?(\d{4}-\d{2}-\d{2})\.t/i) <add> strategy :page_match do |page, regex| <add> page.scan(regex).map { |match| match&.first&.gsub(/\D/, "") } <add> end <add> end <add>``` <ide> <del>Each strategy has a `#match?(url)` method which determines whether the strategy can be applied to the provided URL. The `PageMatch` strategy is used as a fallback when a regex is provided and no other strategies apply. `PageMatch` simply uses the regex to match content on a page, so it's the desired strategy for URLs where a more-specific strategy doesn't apply. <add>When necessary, a `strategy` block allows us to have greater flexibility in how upstream version information is matched and processed. Currently, they're only used when the upstream version format needs to be manipulated to match the formula/cask format. In the example above, we're converting a date format like `2020-01-01` into `20200101`. <ide> <del>Some of the strategies generate a URL and regex internally. In these cases, the strategy often derives information from the provided URL and uses it to create the URL it will check and the regex used for matching. However, if a `regex` is provided in the `livecheck` block, it will be used instead of any generated regex. <add>The `PageMatch` `strategy` block style seen here also applies to any strategy that uses `PageMatch` internally. <ide> <del>Livecheck also has a simple numeric priority system, where 5 is the default unless a strategy has defined its own `PRIORITY` constant. Currently, the `Git` strategy has a higher priority (8) and the `PageMatch` strategy has a low priority (0). In practice, this means that when more than one strategy applies to a URL (usually a specific strategy and `PageMatch`), the higher priority strategy is the one that's used. <add>### `Git` `strategy` block <ide> <del>### Tap strategies <add>```ruby <add> livecheck do <add> url :stable <add> regex(/^(\d{4}-\d{2}-\d{2})$/i) <add> strategy :git do |tags, regex| <add> tags.map { |tag| tag[regex, 1]&.gsub(/\D/, "") }.compact <add> end <add> end <add>``` <ide> <del>Taps can add strategies to apply to their formulae by creating a `livecheck_strategy` folder in the root directory and placing strategy files within. At a minimum, strategies must provide a `#match?(url)` method and a `#find_versions(url, regex)` method. <add>A `strategy` block for `Git` is a bit different, as the block receives an array of tag strings instead of a page content string. Similar to the `PageMatch` example, this is converting tags with a date format like `2020-01-01` into `20200101`. <ide> <del>The `#match?(url)` method takes a URL string and returns `true` or `false` to indicate whether the strategy can be applied to the URL. <add>### Skip <ide> <del>`#find_versions(url, regex)` takes a URL and an optional regex and returns a `Hash` with a format like `{ :matches => {}, :regex => regex, :url => url }`. The `:matches` `Hash` uses version strings as the keys (e.g. `"1.2.3"`) and `Version` objects as the values. `:regex` is either the strategy-generated regex (if applicable), the regex provided as an argument, or `nil`. The `:url` is either the strategy-generated URL (if applicable) or the original URL provided. <add>```ruby <add> livecheck do <add> skip "No version information available" <add> end <add>``` <ide> <del>The built-in strategies in Homebrew's `livecheck_strategy` folder may serve as examples to follow when creating tap strategies. Many of the built-in strategies simply generate a URL and regex before using the `PageMatch` strategy to do the heavy lifting (e.g. `PageMatch.find_versions(page_url, regex)`). When a strategy is checking a text page of some sort (e.g. HTML, RSS, etc.), it may be able to do the same thing. If a strategy needs to do something more complex, the `Git` and `PageMatch` strategies can be referenced as standalone examples. <add>Livecheck automatically skips some formulae/casks for a number of reasons (deprecated, disabled, discontinued, etc.). However, on rare occasions we need to use a `livecheck` block to do a manual skip. The `skip` method takes a string containing a very brief reason for skipping. <ide><path>docs/Formula-Cookbook.md <ide> Instead of `git diff | pbcopy`, for some editors `git diff >> path/to/your/formu <ide> <ide> If anything isn’t clear, you can usually figure it out by `grep`ping the `$(brew --repo homebrew/core)` directory. Please submit a pull request to amend this document if you think it will help! <ide> <add>### `livecheck` blocks <add> <add>When `brew livecheck` is unable to identify versions for a formula, we can control its behavior using a `livecheck` block. Here is a simple example to check a page for links containing a filename like `example-1.2.tar.gz`: <add> <add>```ruby <add>livecheck do <add> url "https://www.example.com/downloads/" <add> regex(/href=.*?example[._-]v?(\d+(?:\.\d+)+)\.t/i) <add>end <add>``` <add> <add>For `url`/`regex` guidelines and additional `livecheck` block examples, refer to the [`brew livecheck` documentation](Brew-Livecheck.md). For more technical information on the methods used in a `livecheck` block, please refer to the [`Livecheck` class documentation](https://rubydoc.brew.sh/Livecheck.html). <add> <ide> ### Unstable versions (`head`) <ide> <ide> Formulae can specify an alternate download for the upstream project’s [`head`](https://rubydoc.brew.sh/Formula#head-class_method) (`master`/`trunk`). <ide><path>docs/README.md <ide> - [Deprecating, Disabling, and Removing Formulae](Deprecating-Disabling-and-Removing-Formulae.md) <ide> - [Node for Formula Authors](Node-for-Formula-Authors.md) <ide> - [Python for Formula Authors](Python-for-Formula-Authors.md) <del>- [Brew Livecheck](Brew-Livecheck.md) <add>- [`brew livecheck`](Brew-Livecheck.md) <ide> - [Migrating A Formula To A Tap](Migrating-A-Formula-To-A-Tap.md) <ide> - [Rename A Formula](Rename-A-Formula.md) <ide> - [Building Against Non-Homebrew Dependencies](Building-Against-Non-Homebrew-Dependencies.md)
5
Ruby
Ruby
use rails.env after loading environment
d8c5ea76bce3bdc810f3d06af7908c6e474b154c
<ide><path>railties/lib/rails/commands/console.rb <ide> def start <ide> end <ide> <ide> if options[:sandbox] <del> puts "Loading #{ENV['RAILS_ENV']} environment in sandbox (Rails #{Rails.version})" <add> puts "Loading #{Rails.env} environment in sandbox (Rails #{Rails.version})" <ide> puts "Any modifications you make will be rolled back on exit" <ide> else <del> puts "Loading #{ENV['RAILS_ENV']} environment (Rails #{Rails.version})" <add> puts "Loading #{Rails.env} environment (Rails #{Rails.version})" <ide> end <ide> IRB.start <ide> end
1
Mixed
Javascript
support all arraybufferview types
2ced07ccaf7682b9ec8fb3bcc3dc8d2bb2798c61
<ide><path>doc/api/zlib.md <ide> ignored by the decompression classes. <ide> * `level` {integer} (compression only) <ide> * `memLevel` {integer} (compression only) <ide> * `strategy` {integer} (compression only) <del>* `dictionary` {Buffer|Uint8Array} (deflate/inflate only, empty dictionary by <add>* `dictionary` {Buffer|TypedArray|DataView} (deflate/inflate only, empty dictionary by <ide> default) <ide> <ide> See the description of `deflateInit2` and `inflateInit2` at <ide> Returns a new [Unzip][] object with an [options][]. <ide> <ide> <!--type=misc--> <ide> <del>All of these take a [Buffer][], [Uint8Array][], or string as the first <del>argument, an optional second argument to supply options to the `zlib` classes <del>and will call the supplied callback with `callback(error, result)`. <add>All of these take a [`Buffer`][], [`TypedArray`][], [`DataView`][], or string as <add>the first argument, an optional second argument to supply options to the `zlib` <add>classes and will call the supplied callback with `callback(error, result)`. <ide> <ide> Every method has a `*Sync` counterpart, which accept the same arguments, but <ide> without a callback. <ide> without a callback. <ide> <!-- YAML <ide> added: v0.6.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: REPLACEME <add> description: The `buffer` parameter can be any TypedArray or DataView now. <ide> - version: REPLACEME <ide> pr-url: https://github.com/nodejs/node/pull/12001 <ide> description: The `buffer` parameter can be an Uint8Array now. <ide> changes: <ide> <!-- YAML <ide> added: v0.11.12 <ide> changes: <add> - version: REPLACEME <add> pr-url: REPLACEME <add> description: The `buffer` parameter can be any TypedArray or DataView now. <ide> - version: REPLACEME <ide> pr-url: https://github.com/nodejs/node/pull/12001 <ide> description: The `buffer` parameter can be an Uint8Array now. <ide> --> <ide> <del>- `buffer` {Buffer|Uint8Array|string} <add>- `buffer` {Buffer|TypedArray|DataView|string} <ide> <ide> Compress a chunk of data with [Deflate][]. <ide> <ide> ### zlib.deflateRaw(buffer[, options], callback) <ide> <!-- YAML <ide> added: v0.6.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: REPLACEME <add> description: The `buffer` parameter can be any TypedArray or DataView now. <ide> - version: REPLACEME <ide> pr-url: https://github.com/nodejs/node/pull/12001 <ide> description: The `buffer` parameter can be an Uint8Array now. <ide> changes: <ide> <!-- YAML <ide> added: v0.11.12 <ide> changes: <add> - version: REPLACEME <add> pr-url: REPLACEME <add> description: The `buffer` parameter can be any TypedArray or DataView now. <ide> - version: REPLACEME <ide> pr-url: https://github.com/nodejs/node/pull/12001 <ide> description: The `buffer` parameter can be an Uint8Array now. <ide> --> <ide> <del>- `buffer` {Buffer|Uint8Array|string} <add>- `buffer` {Buffer|TypedArray|DataView|string} <ide> <ide> Compress a chunk of data with [DeflateRaw][]. <ide> <ide> ### zlib.gunzip(buffer[, options], callback) <ide> <!-- YAML <ide> added: v0.6.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: REPLACEME <add> description: The `buffer` parameter can be any TypedArray or DataView now. <ide> - version: REPLACEME <ide> pr-url: https://github.com/nodejs/node/pull/12001 <ide> description: The `buffer` parameter can be an Uint8Array now. <ide> changes: <ide> <!-- YAML <ide> added: v0.11.12 <ide> changes: <add> - version: REPLACEME <add> pr-url: REPLACEME <add> description: The `buffer` parameter can be any TypedArray or DataView now. <ide> - version: REPLACEME <ide> pr-url: https://github.com/nodejs/node/pull/12001 <ide> description: The `buffer` parameter can be an Uint8Array now. <ide> --> <ide> <del>- `buffer` {Buffer|Uint8Array|string} <add>- `buffer` {Buffer|TypedArray|DataView|string} <ide> <ide> Decompress a chunk of data with [Gunzip][]. <ide> <ide> ### zlib.gzip(buffer[, options], callback) <ide> <!-- YAML <ide> added: v0.6.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: REPLACEME <add> description: The `buffer` parameter can be any TypedArray or DataView now. <ide> - version: REPLACEME <ide> pr-url: https://github.com/nodejs/node/pull/12001 <ide> description: The `buffer` parameter can be an Uint8Array now. <ide> changes: <ide> <!-- YAML <ide> added: v0.11.12 <ide> changes: <add> - version: REPLACEME <add> pr-url: REPLACEME <add> description: The `buffer` parameter can be any TypedArray or DataView now. <ide> - version: REPLACEME <ide> pr-url: https://github.com/nodejs/node/pull/12001 <ide> description: The `buffer` parameter can be an Uint8Array now. <ide> --> <ide> <del>- `buffer` {Buffer|Uint8Array|string} <add>- `buffer` {Buffer|TypedArray|DataView|string} <ide> <ide> Compress a chunk of data with [Gzip][]. <ide> <ide> ### zlib.inflate(buffer[, options], callback) <ide> <!-- YAML <ide> added: v0.6.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: REPLACEME <add> description: The `buffer` parameter can be any TypedArray or DataView now. <ide> - version: REPLACEME <ide> pr-url: https://github.com/nodejs/node/pull/12001 <ide> description: The `buffer` parameter can be an Uint8Array now. <ide> changes: <ide> <!-- YAML <ide> added: v0.11.12 <ide> changes: <add> - version: REPLACEME <add> pr-url: REPLACEME <add> description: The `buffer` parameter can be any TypedArray or DataView now. <ide> - version: REPLACEME <ide> pr-url: https://github.com/nodejs/node/pull/12001 <ide> description: The `buffer` parameter can be an Uint8Array now. <ide> --> <ide> <del>- `buffer` {Buffer|Uint8Array|string} <add>- `buffer` {Buffer|TypedArray|DataView|string} <ide> <ide> Decompress a chunk of data with [Inflate][]. <ide> <ide> ### zlib.inflateRaw(buffer[, options], callback) <ide> <!-- YAML <ide> added: v0.6.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: REPLACEME <add> description: The `buffer` parameter can be any TypedArray or DataView now. <ide> - version: REPLACEME <ide> pr-url: https://github.com/nodejs/node/pull/12001 <ide> description: The `buffer` parameter can be an Uint8Array now. <ide> changes: <ide> <!-- YAML <ide> added: v0.11.12 <ide> changes: <add> - version: REPLACEME <add> pr-url: REPLACEME <add> description: The `buffer` parameter can be any TypedArray or DataView now. <ide> - version: REPLACEME <ide> pr-url: https://github.com/nodejs/node/pull/12001 <ide> description: The `buffer` parameter can be an Uint8Array now. <ide> --> <ide> <del>- `buffer` {Buffer|Uint8Array|string} <add>- `buffer` {Buffer|TypedArray|DataView|string} <ide> <ide> Decompress a chunk of data with [InflateRaw][]. <ide> <ide> ### zlib.unzip(buffer[, options], callback) <ide> <!-- YAML <ide> added: v0.6.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: REPLACEME <add> description: The `buffer` parameter can be any TypedArray or DataView now. <ide> - version: REPLACEME <ide> pr-url: https://github.com/nodejs/node/pull/12001 <ide> description: The `buffer` parameter can be an Uint8Array now. <ide> changes: <ide> <!-- YAML <ide> added: v0.11.12 <ide> changes: <add> - version: REPLACEME <add> pr-url: REPLACEME <add> description: The `buffer` parameter can be any TypedArray or DataView now. <ide> - version: REPLACEME <ide> pr-url: https://github.com/nodejs/node/pull/12001 <ide> description: The `buffer` parameter can be an Uint8Array now. <ide> --> <ide> <del>- `buffer` {Buffer|Uint8Array|string} <add>- `buffer` {Buffer|TypedArray|DataView|string} <ide> <ide> Decompress a chunk of data with [Unzip][]. <ide> <ide> Decompress a chunk of data with [Unzip][]. <ide> [InflateRaw]: #zlib_class_zlib_inflateraw <ide> [Unzip]: #zlib_class_zlib_unzip <ide> [`.flush()`]: #zlib_zlib_flush_kind_callback <del>[Buffer]: buffer.html <del>[Uint8Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array <add>[`Buffer`]: buffer.html#buffer_class_buffer <add>[`DataView`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView <add>[`TypedArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray <ide><path>lib/zlib.js <ide> const Buffer = require('buffer').Buffer; <ide> const internalUtil = require('internal/util'); <ide> const Transform = require('_stream_transform'); <del>const { isUint8Array } = process.binding('util'); <ide> const binding = process.binding('zlib'); <ide> const assert = require('assert').ok; <ide> const kMaxLength = require('buffer').kMaxLength; <ide> function isInvalidStrategy(strategy) { <ide> } <ide> <ide> function zlibBuffer(engine, buffer, callback) { <del> // Streams do not support non-Buffer Uint8Arrays yet. Convert it to a <add> // Streams do not support non-Buffer ArrayBufferViews yet. Convert it to a <ide> // Buffer without copying. <del> if (isUint8Array(buffer) && <add> if (ArrayBuffer.isView(buffer) && <ide> Object.getPrototypeOf(buffer) !== Buffer.prototype) { <ide> buffer = Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength); <ide> } <ide> function zlibBuffer(engine, buffer, callback) { <ide> var chunk; <ide> while (null !== (chunk = engine.read())) { <ide> buffers.push(chunk); <del> nread += chunk.length; <add> nread += chunk.byteLength; <ide> } <ide> engine.once('readable', flow); <ide> } <ide> function zlibBuffer(engine, buffer, callback) { <ide> function zlibBufferSync(engine, buffer) { <ide> if (typeof buffer === 'string') <ide> buffer = Buffer.from(buffer); <del> else if (!isUint8Array(buffer)) <del> throw new TypeError('"buffer" argument must be a string, Buffer, or ' + <del> 'Uint8Array'); <add> else if (!ArrayBuffer.isView(buffer)) <add> throw new TypeError('"buffer" argument must be a string, Buffer, ' + <add> 'TypedArray, or DataView'); <ide> <ide> var flushFlag = engine._finishFlushFlag; <ide> <ide> class Zlib extends Transform { <ide> throw new TypeError('Invalid strategy: ' + opts.strategy); <ide> <ide> if (opts.dictionary) { <del> if (!isUint8Array(opts.dictionary)) { <add> if (!ArrayBuffer.isView(opts.dictionary)) { <ide> throw new TypeError( <del> 'Invalid dictionary: it should be a Buffer or an Uint8Array'); <add> 'Invalid dictionary: it should be a Buffer, TypedArray, or DataView'); <ide> } <ide> } <ide> <ide> class Zlib extends Transform { <ide> var flushFlag; <ide> var ws = this._writableState; <ide> var ending = ws.ending || ws.ended; <del> var last = ending && (!chunk || ws.length === chunk.length); <add> var last = ending && (!chunk || ws.length === chunk.byteLength); <ide> <del> if (chunk !== null && !isUint8Array(chunk)) <add> if (chunk !== null && !ArrayBuffer.isView(chunk)) <ide> return cb(new TypeError('invalid input')); <ide> <ide> if (!this._handle) <ide> class Zlib extends Transform { <ide> flushFlag = this._flushFlag; <ide> // once we've flushed the last of the queue, stop flushing and <ide> // go back to the normal behavior. <del> if (chunk.length >= ws.length) { <add> if (chunk.byteLength >= ws.length) { <ide> this._flushFlag = this._opts.flush || constants.Z_NO_FLUSH; <ide> } <ide> } <ide> class Zlib extends Transform { <ide> } <ide> <ide> _processChunk(chunk, flushFlag, cb) { <del> var availInBefore = chunk && chunk.length; <add> var availInBefore = chunk && chunk.byteLength; <ide> var availOutBefore = this._chunkSize - this._offset; <ide> var inOff = 0; <ide> <ide> class Zlib extends Transform { <ide> self.push(out); <ide> } else { <ide> buffers.push(out); <del> nread += out.length; <add> nread += out.byteLength; <ide> } <ide> } <ide> <ide><path>test/parallel/test-zlib-convenience-methods.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const zlib = require('zlib'); <ide> <del>const expectStr = 'blahblahblahblahblahblah'; <add>// Must be a multiple of 4 characters in total to test all ArrayBufferView <add>// types. <add>const expectStr = 'blah'.repeat(8); <ide> const expectBuf = Buffer.from(expectStr); <del>const expectUint8Array = new Uint8Array(expectBuf); <add> <ide> const opts = { <ide> level: 9, <ide> chunkSize: 1024, <ide> }; <ide> <del>for (const method of [ <del> ['gzip', 'gunzip'], <del> ['gzip', 'unzip'], <del> ['deflate', 'inflate'], <del> ['deflateRaw', 'inflateRaw'], <add>for (const [type, expect] of [ <add> ['string', expectStr], <add> ['Buffer', expectBuf], <add> ...common.getArrayBufferViews(expectBuf).map((obj) => <add> [obj[Symbol.toStringTag], obj] <add> ) <ide> ]) { <del> for (const [type, expect] of [ <del> ['string', expectStr], <del> ['Buffer', expectBuf], <del> ['Uint8Array', expectUint8Array] <add> for (const method of [ <add> ['gzip', 'gunzip'], <add> ['gzip', 'unzip'], <add> ['deflate', 'inflate'], <add> ['deflateRaw', 'inflateRaw'], <ide> ]) { <ide> zlib[method[0]](expect, opts, common.mustCall((err, result) => { <ide> zlib[method[1]](result, opts, common.mustCall((err, result) => { <ide><path>test/parallel/test-zlib-deflate-constructors.js <ide> assert.throws( <ide> // Throws if opts.dictionary is not a Buffer <ide> assert.throws( <ide> () => { new zlib.Deflate({dictionary: 'not a buffer'}); }, <del> /^TypeError: Invalid dictionary: it should be a Buffer or an Uint8Array$/ <add> new RegExp('^TypeError: Invalid dictionary: it should be a Buffer, ' + <add> 'TypedArray, or DataView$') <ide> ); <ide><path>test/parallel/test-zlib-dictionary.js <ide> const spdyDict = Buffer.from([ <ide> 'ation/xhtmltext/plainpublicmax-agecharset=iso-8859-1utf-8gzipdeflateHTTP/1', <ide> '.1statusversionurl\0' <ide> ].join('')); <del>const spdyDictUint8Array = new Uint8Array(spdyDict); <ide> <ide> const input = [ <ide> 'HTTP/1.1 200 Ok', <ide> function deflateRawResetDictionaryTest(spdyDict) { <ide> }); <ide> } <ide> <del>for (const dict of [spdyDict, spdyDictUint8Array]) { <add>for (const dict of [spdyDict, ...common.getArrayBufferViews(spdyDict)]) { <ide> basicDictionaryTest(dict); <ide> deflateResetDictionaryTest(dict); <ide> rawDictionaryTest(dict); <ide><path>test/parallel/test-zlib-not-string-or-buffer.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const zlib = require('zlib'); <ide> <del>const expected = <del> /^TypeError: "buffer" argument must be a string, Buffer, or Uint8Array$/; <add>const expected = new RegExp('^TypeError: "buffer" argument must be a string, ' + <add> 'Buffer, TypedArray, or DataView$'); <ide> <ide> assert.throws(() => { zlib.deflateSync(undefined); }, expected); <ide> assert.throws(() => { zlib.deflateSync(null); }, expected);
6
Javascript
Javascript
move benchmark-dgram to sequential
d0943bcb693dc8a0cf0b903c04918c4ac6e694ea
<add><path>test/sequential/test-benchmark-dgram.js <del><path>test/parallel/test-benchmark-dgram.js <ide> require('../common'); <ide> <ide> const runBenchmark = require('../common/benchmark'); <ide> <add>// Because the dgram benchmarks use hardcoded ports, this should be in <add>// sequential rather than parallel to make sure it does not conflict with <add>// tests that choose random available ports. <add> <ide> runBenchmark('dgram', ['address=true', <ide> 'chunks=2', <ide> 'dur=0.1',
1
Ruby
Ruby
add rdocs to map.resources
a27ccf176564db7293fba115a7d05087611ae84b
<ide><path>actionpack/lib/action_controller/resources.rb <ide> def add_default_action(collection, method, action) <ide> end <ide> end <ide> <add> # Creates named routes for implementing verb-oriented controllers. This is <add> # useful for implementing REST API's, where a single resource has different <add> # behavior based on the HTTP verb (method) used to access it. <add> # <add> # Because browsers don't yet support any verbs except GET and POST, you can send <add> # a parameter named "_method" and the plugin will use that as the request method. <add> # <add> # example: <add> # <add> # map.resources :messages <add> # <add> # class MessagesController < ActionController::Base <add> # # GET messages_url <add> # def index <add> # # return all messages <add> # end <add> # <add> # # GET new_message_url <add> # def new <add> # # return an HTML form for describing a new message <add> # end <add> # <add> # # POST messages_url <add> # def create <add> # # create a new message <add> # end <add> # <add> # # GET message_url(:id => 1) <add> # def show <add> # # find and return a specific message <add> # end <add> # <add> # # GET edit_message_url(:id => 1) <add> # def edit <add> # # return an HTML form for editing a specific message <add> # end <add> # <add> # # PUT message_url(:id => 1) <add> # def update <add> # # find and update a specific message <add> # end <add> # <add> # # DELETE message_url(:id => 1) <add> # def destroy <add> # # delete a specific message <add> # end <add> # end <add> # <add> # The #resource method accepts various options, too, to customize the resulting <add> # routes: <add> # * <tt>:controller</tt> -- specify the controller name for the routes. <add> # * <tt>:singular</tt> -- specify the singular name used in the member routes. <add> # * <tt>:path_prefix</tt> -- set a prefix to the routes with required route variables. <add> # Weblog comments usually belong to a post, so you might use a resource like: <add> # <add> # map.resources :comments, :path_prefix => '/articles/:article_id' <add> # <add> # You can nest resource calls to set this automatically: <add> # <add> # map.resources :posts do |post| <add> # map.resources :comments <add> # end <add> # <add> # * <tt>:name_prefix</tt> -- define a prefix for all generated routes, usually ending in an underscore. <add> # Use this if you have named routes that may clash. <add> # <add> # map.resources :tags, :path_prefix => '/books/:book_id', :name_prefix => 'book_' <add> # map.resources :tags, :path_prefix => '/toys/:toy_id', :name_prefix => 'toy_' <add> # <add> # * <tt>:collection</tt> -- add named routes for other actions that operate on the collection. <add> # Takes a hash of <tt>#{action} => #{method}</tt>, where method is <tt>:get</tt>/<tt>:post</tt>/<tt>:put</tt>/<tt>:delete</tt> <add> # or <tt>:any</tt> if the method does not matter. These routes map to a URL like /messages;rss, with a route of rss_messages_url. <add> # * <tt>:member</tt> -- same as :collection, but for actions that operate on a specific member. <add> # * <tt>:new</tt> -- same as :collection, but for actions that operate on the new resource action. <add> # <add> # If <tt>map.resources</tt> is called with multiple resources, they all get the same options applied. <add> # <add> # Examples: <add> # <add> # map.resources :messages, :path_prefix => "/thread/:thread_id" <add> # # --> GET /thread/7/messages/1 <add> # <add> # map.resources :messages, :collection => { :rss => :get } <add> # # --> GET /messages;rss (maps to the #rss action) <add> # # also adds a url named "rss_messages" <add> # <add> # map.resources :messages, :member => { :mark => :post } <add> # # --> POST /messages/1;mark (maps to the #mark action) <add> # # also adds a url named "mark_message" <add> # <add> # map.resources :messages, :new => { :preview => :post } <add> # # --> POST /messages/new;preview (maps to the #preview action) <add> # # also adds a url named "preview_new_message" <add> # <add> # map.resources :messages, :new => { :new => :any, :preview => :post } <add> # # --> POST /messages/new;preview (maps to the #preview action) <add> # # also adds a url named "preview_new_message" <add> # # --> /messages/new can be invoked via any request method <add> # <add> # map.resources :messages, :controller => "categories", <add> # :path_prefix => "/category/:category_id", <add> # :name_prefix => "category_" <add> # # --> GET /categories/7/messages/1 <add> # # has named route "category_message" <ide> def resources(*entities, &block) <ide> options = entities.last.is_a?(Hash) ? entities.pop : { } <ide> entities.each { |entity| map_resource entity, options.dup, &block }
1
Python
Python
remove import from non-existing module
a4a37a783efcfd1cbb21acc29077c8096a0a0198
<ide><path>spacy/lang/pl/__init__.py <ide> # coding: utf8 <ide> from __future__ import unicode_literals <ide> <del>from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS <ide> from .stop_words import STOP_WORDS <ide> <ide> from ..tokenizer_exceptions import BASE_EXCEPTIONS
1
PHP
PHP
use getconnection in tests
3195338ab72ef6eaace61b98751b37c485930577
<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', 'connection']) <add> ->setMethods(['_connect', 'getConnection']) <ide> ->setConstructorArgs([$config]) <ide> ->getMock(); <ide> $dsn = 'sqlsrv:Server=foo;Database=bar;MultipleActiveResultSets=false'; <ide> public function testConnectionConfigCustom() <ide> $driver->expects($this->once())->method('_connect') <ide> ->with($dsn, $expected); <ide> <del> $driver->expects($this->any())->method('connection') <add> $driver->expects($this->any())->method('getConnection') <ide> ->will($this->returnValue($connection)); <ide> <ide> $driver->connect();
1
PHP
PHP
add aggregate example
bd5783b5e9db18b353fe10f5ed8bd6f7ca7b8c6e
<ide><path>config/logging.php <ide> */ <ide> <ide> 'channels' => [ <add> 'aggregate' => [ <add> 'driver' => 'aggregate', <add> 'channels' => ['single', 'daily'], <add> ], <add> <ide> 'single' => [ <ide> 'driver' => 'single', <ide> 'path' => storage_path('logs/laravel.log'),
1
Javascript
Javascript
add tls clientcertengine tests
829d8f1cd0351d9fc3ee0ff9ce63c6f6c34da373
<ide><path>test/parallel/test-tls-clientcertengine-invalid-arg-type.js <add>'use strict'; <add>const common = require('../common'); <add> <add>if (!common.hasCrypto) <add> common.skip('missing crypto'); <add> <add>const assert = require('assert'); <add>const tls = require('tls'); <add> <add>{ <add> assert.throws( <add> () => { tls.createSecureContext({ clientCertEngine: 0 }); }, <add> common.expectsError({ code: 'ERR_INVALID_ARG_TYPE', <add> message: / Received type number$/ })); <add>} <ide><path>test/parallel/test-tls-clientcertengine-unsupported.js <add>'use strict'; <add>const common = require('../common'); <add> <add>if (!common.hasCrypto) <add> common.skip('missing crypto'); <add> <add>// Monkey-patch SecureContext <add>const binding = process.binding('crypto'); <add>const NativeSecureContext = binding.SecureContext; <add> <add>binding.SecureContext = function() { <add> const rv = new NativeSecureContext(); <add> rv.setClientCertEngine = undefined; <add> return rv; <add>}; <add> <add>const assert = require('assert'); <add>const tls = require('tls'); <add> <add>{ <add> assert.throws( <add> () => { tls.createSecureContext({ clientCertEngine: 'Cannonmouth' }); }, <add> common.expectsError({ <add> code: 'ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED', <add> message: 'Custom engines not supported by this OpenSSL' <add> }) <add> ); <add>} <ide><path>test/parallel/test-tls-server-setoptions-clientcertengine.js <add>'use strict'; <add>const common = require('../common'); <add> <add>if (!common.hasCrypto) <add> common.skip('missing crypto'); <add> <add>const assert = require('assert'); <add>const tls = require('tls'); <add> <add>{ <add> const server = tls.createServer(); <add> assert.strictEqual(server.clientCertEngine, undefined); <add> server.setOptions({ clientCertEngine: 'Cannonmouth' }); <add> assert.strictEqual(server.clientCertEngine, 'Cannonmouth'); <add>}
3
PHP
PHP
consolidate event names
0423841897babfcc136a95f7278a7f5b4669a22f
<ide><path>src/Controller/Component.php <ide> * cycle. The available callbacks are: <ide> * <ide> * - `beforeFilter(EventInterface $event)` <del> * Called before the controller's beforeFilter method by default. <add> * Called before Controller::beforeFilter() method by default. <ide> * - `startup(EventInterface $event)` <del> * Called after the controller's beforeFilter method, and before the <add> * Called after Controller::beforeFilter() method, and before the <ide> * controller action is called. <ide> * - `beforeRender(EventInterface $event)` <del> * Called before the Controller beforeRender, and before the view class is loaded. <del> * - `shutdown(EventInterface $event)` <add> * Called before Controller::beforeRender(), and before the view class is loaded. <add> * - `afterFilter(EventInterface $event)` <ide> * Called after the action is complete and the view has been rendered but <ide> * before Controller::afterFilter(). <ide> * - `beforeRedirect(EventInterface $event $url, Response $response)` <ide> public function implementedEvents(): array <ide> 'Controller.startup' => 'startup', <ide> 'Controller.beforeRender' => 'beforeRender', <ide> 'Controller.beforeRedirect' => 'beforeRedirect', <del> 'Controller.shutdown' => 'shutdown', <add> 'Controller.shutdown' => 'afterFilter', <ide> ]; <ide> $events = []; <ide> foreach ($eventMap as $event => $method) { <ide> public function implementedEvents(): array <ide> } <ide> } <ide> <add> if (!isset($events['Controller.shutdown']) && method_exists($this, 'shutdown')) { <add> deprecationWarning('`Controller.shutdown` event callback is now `afterFilter()` instead of `shutdown()`.'); <add> $events[$event] = 'shutdown'; <add> } <add> <ide> return $events; <ide> } <ide> <ide><path>tests/TestCase/Controller/ComponentTest.php <ide> use TestApp\Controller\Component\ConfiguredComponent; <ide> use TestApp\Controller\Component\OrangeComponent; <ide> use TestApp\Controller\Component\SomethingWithFlashComponent; <add>use TestApp\Controller\Component\TestShutdownComponent; <ide> use TestApp\Controller\ComponentTestController; <ide> <ide> /** <ide> public function testNoEventsInnerComponent(): void <ide> $this->assertInstanceOf(AppleComponent::class, $Component->Apple, 'class is wrong'); <ide> } <ide> <add> /** <add> * Tests deprecated shutdown callback <add> */ <add> public function testEventShutdown(): void <add> { <add> $Collection = new ComponentRegistry(); <add> <add> $this->deprecated(function () use ($Collection): void { <add> $Component = new TestShutdownComponent($Collection); <add> $result = $Component->__debugInfo(); <add> <add> $expected = [ <add> 'components' => [], <add> 'implementedEvents' => [ <add> 'Controller.shutdown' => 'shutdown', <add> ], <add> '_config' => [], <add> ]; <add> $this->assertEquals($expected, $result); <add> }); <add> } <add> <ide> /** <ide> * Test that calling getController() without setting a controller throws exception <ide> */ <ide><path>tests/test_app/TestApp/Controller/Component/TestShutdownComponent.php <add><?php <add>declare(strict_types=1); <add> <add>namespace TestApp\Controller\Component; <add> <add>use Cake\Controller\Component; <add>use Cake\Event\EventInterface; <add> <add>/** <add> * Tests deprecated shutdown callback <add> */ <add>class TestShutdownComponent extends Component <add>{ <add> /** <add> * @param \Cake\Event\EventInterface $event <add> * @return void <add> */ <add> public function shutdown(EventInterface $event): void <add> { <add> } <add>}
3
PHP
PHP
clear command
54f198fd9d54ad492eb22a9add5ca15c24208002
<ide><path>src/Illuminate/Foundation/Console/RouteCacheCommand.php <ide> use Illuminate\Filesystem\Filesystem; <ide> use Symfony\Component\Console\Input\InputOption; <ide> use Symfony\Component\Console\Input\InputArgument; <del>use Illuminate\Routing\Generators\ControllerGenerator; <ide> <ide> class RouteCacheCommand extends Command { <ide> <ide> class RouteCacheCommand extends Command { <ide> * Create a new route command instance. <ide> * <ide> * @param \Illuminate\Routing\Router $router <add> * @param \Illuminate\Filesystem\Filesystem $files <ide> * @return void <ide> */ <ide> public function __construct(Router $router, Filesystem $files) <ide><path>src/Illuminate/Foundation/Console/RouteClearCommand.php <add><?php namespace Illuminate\Foundation\Console; <add> <add>use Illuminate\Routing\Router; <add>use Illuminate\Console\Command; <add>use Illuminate\Filesystem\Filesystem; <add>use Symfony\Component\Console\Input\InputOption; <add>use Symfony\Component\Console\Input\InputArgument; <add> <add>class RouteClearCommand extends Command { <add> <add> /** <add> * The console command name. <add> * <add> * @var string <add> */ <add> protected $name = 'route:clear'; <add> <add> /** <add> * The console command description. <add> * <add> * @var string <add> */ <add> protected $description = 'Remove the route cache file.'; <add> <add> /** <add> * The filesystem instance. <add> * <add> * @var \Illuminate\Filesystem\Filesystem <add> */ <add> protected $files; <add> <add> /** <add> * Create a new route command instance. <add> * <add> * @param \Illuminate\Filesystem\Filesystem $files <add> * @return void <add> */ <add> public function __construct(Filesystem $files) <add> { <add> parent::__construct(); <add> <add> $this->files = $files; <add> } <add> <add> /** <add> * Execute the console command. <add> * <add> * @return void <add> */ <add> public function fire() <add> { <add> $this->files->delete($this->laravel['path'].'/routing/cache.php'); <add> <add> $this->info('Route cache cleared!'); <add> } <add> <add>} <ide>\ No newline at end of file <ide><path>src/Illuminate/Foundation/Providers/RouteCacheServiceProvider.php <ide> <ide> use Illuminate\Support\ServiceProvider; <ide> use Illuminate\Foundation\Console\RouteCacheCommand; <add>use Illuminate\Foundation\Console\RouteClearCommand; <ide> <ide> class RouteCacheServiceProvider extends ServiceProvider { <ide> <ide> public function register() <ide> return new RouteCacheCommand($app['router'], $app['files']); <ide> }); <ide> <del> $this->commands('command.route.cache'); <add> $this->app->bindShared('command.route.clear', function($app) <add> { <add> return new RouteClearCommand($app['files']); <add> }); <add> <add> $this->commands('command.route.cache', 'command.route.clear'); <ide> } <ide> <ide> /** <ide> public function register() <ide> */ <ide> public function provides() <ide> { <del> return array('command.route.cache'); <add> return array('command.route.cache', 'command.route.clear'); <ide> } <ide> <ide> }
3
Python
Python
add testcases for default field values
9f9cb97d6538e320a0740749b200d418d9d52040
<ide><path>rest_framework/fields.py <ide> class URLField(CharField): <ide> type_name = 'URLField' <ide> <ide> def __init__(self, **kwargs): <del> kwargs['max_length'] = kwargs.get('max_length', 200) <ide> kwargs['validators'] = [validators.URLValidator()] <ide> super(URLField, self).__init__(**kwargs) <ide> <ide> class SlugField(CharField): <ide> type_name = 'SlugField' <ide> <ide> def __init__(self, *args, **kwargs): <del> kwargs['max_length'] = kwargs.get('max_length', 50) <ide> super(SlugField, self).__init__(*args, **kwargs) <ide> <ide> <ide><path>rest_framework/tests/fields.py <ide> def test_choices_not_required(self): <ide> self.assertEqual(f.choices, models.fields.BLANK_CHOICE_DASH + self.SAMPLE_CHOICES) <ide> <ide> <add>class EmailFieldTests(TestCase): <add> """ <add> Tests for EmailField attribute values <add> """ <add> <add> class EmailFieldModel(RESTFrameworkModel): <add> email_field = models.EmailField(blank=True) <add> <add> class EmailFieldWithGivenMaxLengthModel(RESTFrameworkModel): <add> email_field = models.EmailField(max_length=150, blank=True) <add> <add> def test_default_model_value(self): <add> class EmailFieldSerializer(serializers.ModelSerializer): <add> class Meta: <add> model = self.EmailFieldModel <add> <add> serializer = EmailFieldSerializer(data={}) <add> self.assertEqual(serializer.is_valid(), True) <add> self.assertEqual(getattr(serializer.fields['email_field'], 'max_length'), 75) <add> <add> def test_given_model_value(self): <add> class EmailFieldSerializer(serializers.ModelSerializer): <add> class Meta: <add> model = self.EmailFieldWithGivenMaxLengthModel <add> <add> serializer = EmailFieldSerializer(data={}) <add> self.assertEqual(serializer.is_valid(), True) <add> self.assertEqual(getattr(serializer.fields['email_field'], 'max_length'), 150) <add> <add> def test_given_serializer_value(self): <add> class EmailFieldSerializer(serializers.ModelSerializer): <add> email_field = serializers.EmailField(source='email_field', max_length=20, required=False) <add> <add> class Meta: <add> model = self.EmailFieldModel <add> <add> serializer = EmailFieldSerializer(data={}) <add> self.assertEqual(serializer.is_valid(), True) <add> self.assertEqual(getattr(serializer.fields['email_field'], 'max_length'), 20) <add> <add> <ide> class SlugFieldTests(TestCase): <ide> """ <ide> Tests for SlugField attribute values <ide> """ <ide> <del> def test_default_value(self): <del> class SlugFieldModel(RESTFrameworkModel): <del> slug_field = models.SlugField(blank=True) <add> class SlugFieldModel(RESTFrameworkModel): <add> slug_field = models.SlugField(blank=True) <add> <add> class SlugFieldWithGivenMaxLengthModel(RESTFrameworkModel): <add> slug_field = models.SlugField(max_length=84, blank=True) <ide> <add> def test_default_model_value(self): <ide> class SlugFieldSerializer(serializers.ModelSerializer): <ide> class Meta: <del> model = SlugFieldModel <add> model = self.SlugFieldModel <ide> <ide> serializer = SlugFieldSerializer(data={}) <ide> self.assertEqual(serializer.is_valid(), True) <ide> self.assertEqual(getattr(serializer.fields['slug_field'], 'max_length'), 50) <ide> <del> def test_given_value(self): <del> class SlugFieldModel(RESTFrameworkModel): <del> slug_field = models.SlugField(max_length=84, blank=True) <del> <add> def test_given_model_value(self): <ide> class SlugFieldSerializer(serializers.ModelSerializer): <ide> class Meta: <del> model = SlugFieldModel <add> model = self.SlugFieldWithGivenMaxLengthModel <ide> <ide> serializer = SlugFieldSerializer(data={}) <ide> self.assertEqual(serializer.is_valid(), True) <ide> self.assertEqual(getattr(serializer.fields['slug_field'], 'max_length'), 84) <ide> <add> def test_given_serializer_value(self): <add> class SlugFieldSerializer(serializers.ModelSerializer): <add> slug_field = serializers.SlugField(source='slug_field', max_length=20, required=False) <add> <add> class Meta: <add> model = self.SlugFieldModel <add> <add> serializer = SlugFieldSerializer(data={}) <add> self.assertEqual(serializer.is_valid(), True) <add> self.assertEqual(getattr(serializer.fields['slug_field'], 'max_length'), 20) <add> <ide> <ide> class URLFieldTests(TestCase): <ide> """ <ide> Tests for URLField attribute values <ide> """ <ide> <del> def test_default_value(self): <del> class URLFieldModel(RESTFrameworkModel): <del> url_field = models.URLField(blank=True) <add> class URLFieldModel(RESTFrameworkModel): <add> url_field = models.URLField(blank=True) <add> <add> class URLFieldWithGivenMaxLengthModel(RESTFrameworkModel): <add> url_field = models.URLField(max_length=128, blank=True) <ide> <add> def test_default_model_value(self): <ide> class URLFieldSerializer(serializers.ModelSerializer): <ide> class Meta: <del> model = URLFieldModel <add> model = self.URLFieldModel <ide> <ide> serializer = URLFieldSerializer(data={}) <ide> self.assertEqual(serializer.is_valid(), True) <ide> self.assertEqual(getattr(serializer.fields['url_field'], 'max_length'), 200) <ide> <del> def test_given_value(self): <del> class URLFieldModel(RESTFrameworkModel): <del> url_field = models.URLField(max_length=128, blank=True) <add> def test_given_model_value(self): <add> class URLFieldSerializer(serializers.ModelSerializer): <add> class Meta: <add> model = self.URLFieldWithGivenMaxLengthModel <add> <add> serializer = URLFieldSerializer(data={}) <add> self.assertEqual(serializer.is_valid(), True) <add> self.assertEqual(getattr(serializer.fields['url_field'], 'max_length'), 128) <ide> <add> def test_given_serializer_value(self): <ide> class URLFieldSerializer(serializers.ModelSerializer): <add> url_field = serializers.URLField(source='url_field', max_length=20, required=False) <add> <ide> class Meta: <del> model = URLFieldModel <add> model = self.URLFieldWithGivenMaxLengthModel <ide> <ide> serializer = URLFieldSerializer(data={}) <ide> self.assertEqual(serializer.is_valid(), True) <del> self.assertEqual(getattr(serializer.fields['url_field'], 'max_length'), 128) <ide>\ No newline at end of file <add> self.assertEqual(getattr(serializer.fields['url_field'], 'max_length'), 20) <ide>\ No newline at end of file
2
Ruby
Ruby
remove errant pkg-config libdir
980db9d3fb6671c7562f97dfa3dd4f22fd74083f
<ide><path>Library/Homebrew/extend/ENV/super.rb <ide> def determine_pkg_config_path <ide> <ide> def determine_pkg_config_libdir <ide> PATH.new( <del> "/usr/lib/pkgconfig", <ide> homebrew_extra_pkg_config_paths, <ide> ).existing <ide> end
1
Ruby
Ruby
example bracket error
342f84ad45f632485f3faa94623132d8f82676a9
<ide><path>actionpack/lib/action_controller/metal/http_authentication.rb <ide> module HttpAuthentication <ide> # class PostsController < ApplicationController <ide> # REALM = "SuperSecret" <ide> # USERS = {"dhh" => "secret", #plain text password <del> # "dap" => Digest::MD5.hexdigest(["dap",REALM,"secret"].join(":")) #ha1 digest password <add> # "dap" => Digest::MD5.hexdigest(["dap",REALM,"secret"].join(":"))} #ha1 digest password <ide> # <ide> # before_filter :authenticate, :except => [:index] <ide> #
1
Go
Go
improve workdir test to cover more edge cases
c1f492755b8774005b3627da8ee001ee0b2df4eb
<ide><path>integration/buildfile_test.go <ide> func TestBuildRelativeWorkdir(t *testing.T) { <ide> img, err := buildImage(testContextTemplate{` <ide> FROM {IMAGE} <ide> RUN [ "$PWD" = '/' ] <del> WORKDIR /test1 <add> WORKDIR test1 <ide> RUN [ "$PWD" = '/test1' ] <del> WORKDIR test2 <del> RUN [ "$PWD" = '/test1/test2' ] <add> WORKDIR /test2 <add> RUN [ "$PWD" = '/test2' ] <add> WORKDIR test3 <add> RUN [ "$PWD" = '/test2/test3' ] <ide> `, nil, nil}, t, nil, true) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <del> if img.Config.WorkingDir != "/test1/test2" { <del> t.Fail() <add> if img.Config.WorkingDir != "/test2/test3" { <add> t.Fatalf("Expected workdir to be '/test2/test3', received '%s'", img.Config.WorkingDir) <ide> } <ide> } <ide>
1
Python
Python
add option mentioned in #940
70c10caa06d9feda3f446d0a82655f56cd2afdab
<ide><path>examples/run_glue.py <ide> def evaluate(args, model, tokenizer, prefix=""): <ide> <ide> <ide> def load_and_cache_examples(args, task, tokenizer, evaluate=False): <add> if args.local_rank not in [-1, 0]: <add> torch.distributed.barrier() # Make sure only the first process in distributed training process the dataset, and the others will use the cache <add> <ide> processor = processors[task]() <ide> output_mode = output_modes[task] <ide> # Load data features from cache or dataset file <ide> def load_and_cache_examples(args, task, tokenizer, evaluate=False): <ide> logger.info("Saving features into cached file %s", cached_features_file) <ide> torch.save(features, cached_features_file) <ide> <add> if args.local_rank == 0: <add> torch.distributed.barrier() # Make sure only the first process in distributed training process the dataset, and the others will use the cache <add> <ide> # Convert to Tensors and build dataset <ide> all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long) <ide> all_input_mask = torch.tensor([f.input_mask for f in features], dtype=torch.long) <ide><path>examples/run_squad.py <ide> def evaluate(args, model, tokenizer, prefix=""): <ide> <ide> <ide> def load_and_cache_examples(args, tokenizer, evaluate=False, output_examples=False): <add> if args.local_rank not in [-1, 0]: <add> torch.distributed.barrier() # Make sure only the first process in distributed training process the dataset, and the others will use the cache <add> <ide> # Load data features from cache or dataset file <ide> input_file = args.predict_file if evaluate else args.train_file <ide> cached_features_file = os.path.join(os.path.dirname(input_file), 'cached_{}_{}_{}'.format( <ide> def load_and_cache_examples(args, tokenizer, evaluate=False, output_examples=Fal <ide> logger.info("Saving features into cached file %s", cached_features_file) <ide> torch.save(features, cached_features_file) <ide> <add> if args.local_rank == 0: <add> torch.distributed.barrier() # Make sure only the first process in distributed training process the dataset, and the others will use the cache <add> <ide> # Convert to Tensors and build dataset <ide> all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long) <ide> all_input_mask = torch.tensor([f.input_mask for f in features], dtype=torch.long)
2
PHP
PHP
add "copy" command
01c4d3dd9c2b623fbde0de76e1fdf7485cf96d85
<ide><path>src/Shell/PluginAssetsShell.php <ide> class PluginAssetsShell extends Shell { <ide> <ide> /** <ide> * Attempt to symlink plugin assets to app's webroot. If symlinking fails it <del> * fallback to copying the assets. For vendor namespaced plugin, parent folder <add> * fallbacks to copying the assets. For vendor namespaced plugin, parent folder <ide> * for vendor name are created if required. <ide> * <ide> * @param string|string $name Name of plugin for which to symlink assets. <ide> public function symlink($name = null) { <ide> $this->_process($this->_list($name)); <ide> } <ide> <add>/** <add> * Copying plugin assets to app's webroot. For vendor namespaced plugin, <add> * parent folder for vendor name are created if required. <add> * <add> * @param string|string $name Name of plugin for which to symlink assets. <add> * If null all plugins will be processed. <add> * @return void <add> */ <add> public function copy($name = null) { <add> $this->_process($this->_list($name), true); <add> } <add> <ide> /** <ide> * Get list of plugins to process. Plugins without a webroot directory are skipped. <ide> * <ide> protected function _list($name = null) { <ide> * Process plugins <ide> * <ide> * @param array $plugins List of plugins to process <add> * @param bool $copy Force copy mode. Default false. <ide> * @return void <ide> */ <del> protected function _process($plugins) { <add> protected function _process($plugins, $copy = false) { <ide> foreach ($plugins as $plugin => $config) { <ide> $path = Plugin::path($plugin) . 'webroot'; <ide> <ide> protected function _process($plugins) { <ide> continue; <ide> } <ide> <del> $result = $this->_createSymlink( <del> $config['srcPath'], <del> $config['destDir'] . $config['link'] <del> ); <del> if ($result) { <del> continue; <add> if (!$copy) { <add> $result = $this->_createSymlink( <add> $config['srcPath'], <add> $config['destDir'] . $config['link'] <add> ); <add> if ($result) { <add> continue; <add> } <ide> } <ide> <ide> $this->_copyDirectory( <ide> public function getOptionParser() { <ide> $parser = parent::getOptionParser(); <ide> <ide> $parser->addSubcommand('symlink', [ <del> 'help' => 'Symlink / copy assets to app\'s webroot.' <add> 'help' => 'Symlink (copy as fallback) plugin assets to app\'s webroot.' <add> ])->addSubcommand('copy', [ <add> 'help' => 'Copy plugin assets to app\'s webroot.' <ide> ])->addArgument('name', [ <ide> 'help' => 'A specific plugin you want to symlink assets for.', <ide> 'optional' => true, <ide><path>tests/TestCase/Shell/PluginAssetsShellTest.php <ide> public function testSymlinkingSpecifiedPlugin() { <ide> $path = WWW_ROOT . 'test_plugin'; <ide> $link = new \SplFileInfo($path); <ide> $this->assertTrue(file_exists($path . DS . 'root.js')); <add> unlink($path); <ide> <ide> $path = WWW_ROOT . 'company' . DS . 'test_plugin_three'; <ide> $link = new \SplFileInfo($path); <ide> $this->assertFalse($link->isDir()); <ide> $this->assertFalse($link->isLink()); <ide> } <ide> <add>/** <add> * testCopy <add> * <add> * @return void <add> */ <add> public function testCopy() { <add> Plugin::load('TestPlugin'); <add> Plugin::load('Company/TestPluginThree'); <add> <add> $this->shell->copy(); <add> <add> $path = WWW_ROOT . 'test_plugin'; <add> $dir = new \SplFileInfo($path); <add> $this->assertTrue($dir->isDir()); <add> $this->assertTrue(file_exists($path . DS . 'root.js')); <add> <add> $folder = new Folder($path); <add> $folder->delete(); <add> <add> $path = WWW_ROOT . 'company' . DS . 'test_plugin_three'; <add> $link = new \SplFileInfo($path); <add> $this->assertTrue($link->isDir()); <add> $this->assertTrue(file_exists($path . DS . 'css' . DS . 'company.css')); <add> <add> $folder = new Folder(WWW_ROOT . 'company'); <add> $folder->delete(); <add> } <add> <ide> }
2
Python
Python
remove unused import
d2c94474ac11da442dff4548c0fe325eeecc5561
<ide><path>keras/applications/densenet.py <ide> from ..layers import Concatenate <ide> from ..layers import Conv2D <ide> from ..layers import Dense <del>from ..layers import Flatten <ide> from ..layers import GlobalAveragePooling2D <ide> from ..layers import Input <ide> from ..layers import MaxPooling2D
1
Text
Text
fix tiny typo
503aba577f9b272352e316e652c5868a0a11e8be
<ide><path>docs/tutorials/fundamentals/part-5-ui-and-react.md <ide> export default Header <ide> <ide> Our components can now read state from the store, and dispatch actions to the store. However, we're still missing something. Where and how are the React-Redux hooks finding the right Redux store? A hook is a JS function, so it can't automatically import a store from `store.js` by itself. <ide> <del>Instead, we have to specifically tell React-Redux what store we want to use in our components. We do this by **rendering a `<Provider>` component around our entire `<App>`, and passing the Redux store as a prop to `<Provider>`**. After we do this once, every component in the application will be able to access the Redux store if needs to. <add>Instead, we have to specifically tell React-Redux what store we want to use in our components. We do this by **rendering a `<Provider>` component around our entire `<App>`, and passing the Redux store as a prop to `<Provider>`**. After we do this once, every component in the application will be able to access the Redux store if it needs to. <ide> <ide> Let's add that to our main `index.js` file: <ide>
1
Javascript
Javascript
fix argument order in assertion
1dcba68534b810fb2af676121a8dc7a16285a79c
<ide><path>test/parallel/test-http2-pipe-named-pipe.js <ide> server.on('stream', common.mustCall((stream) => { <ide> })); <ide> <ide> dest.on('finish', common.mustCall(() => { <del> assert.strictEqual(fs.readFileSync(loc).length, <del> fs.readFileSync(fn).length); <add> assert.strictEqual(fs.readFileSync(fn).length, <add> fs.readFileSync(loc).length); <ide> })); <ide> })); <ide>
1
Javascript
Javascript
add tests for synaxtreescopedescriptor
ad41476cbe6fa4ef9a74a341b9e75178aee0339a
<ide><path>spec/text-editor-spec.js <ide> const {clipboard} = require('electron') <ide> const TextEditor = require('../src/text-editor') <ide> const TextBuffer = require('text-buffer') <ide> const TextMateLanguageMode = require('../src/text-mate-language-mode') <add>const TreeSitterLanguageMode = require('../src/tree-sitter-language-mode') <ide> <ide> describe('TextEditor', () => { <ide> let buffer, editor, lineLengths <ide> describe('TextEditor', () => { <ide> }) <ide> }) <ide> <add> describe('.syntaxTreeScopeDescriptorForBufferPosition(position)', () => { <add> it('returns the result of scopeDescriptorForBufferPosition() when textmate language mode is used', async () => { <add> atom.config.set('core.useTreeSitterParsers', false) <add> editor = await atom.workspace.open('sample.js', {autoIndent: false}) <add> await atom.packages.activatePackage('language-javascript') <add> <add> let buffer = editor.getBuffer() <add> <add> let languageMode = new TextMateLanguageMode({ <add> buffer, <add> grammar: atom.grammars.grammarForScopeName('source.js') <add> }) <add> <add> buffer.setLanguageMode(languageMode) <add> <add> languageMode.startTokenizing() <add> while (languageMode.firstInvalidRow() != null) { <add> advanceClock() <add> } <add> <add> const syntaxTreeeScopeDescriptor = editor.syntaxTreeScopeDescriptorForBufferPosition([4, 17]) <add> expect(syntaxTreeeScopeDescriptor.getScopesArray()).toEqual([ <add> 'source.js', <add> 'support.variable.property.js' <add> ]) <add> }) <add> <add> it('returns the result of syntaxTreeScopeDescriptorForBufferPosition() when tree-sitter language mode is used', async () => { <add> editor = await atom.workspace.open('sample.js', {autoIndent: false}) <add> await atom.packages.activatePackage('language-javascript') <add> <add> let buffer = editor.getBuffer() <add> <add> buffer.setLanguageMode(new TreeSitterLanguageMode({ <add> buffer, <add> grammar: atom.grammars.grammarForScopeName('source.js') <add> })) <add> <add> const syntaxTreeeScopeDescriptor = editor.syntaxTreeScopeDescriptorForBufferPosition([4, 17]) <add> expect(syntaxTreeeScopeDescriptor.getScopesArray()).toEqual([ <add> 'source.js', <add> 'program', <add> 'variable_declaration', <add> 'variable_declarator', <add> 'function', <add> 'statement_block', <add> 'variable_declaration', <add> 'variable_declarator', <add> 'function', <add> 'statement_block', <add> 'while_statement', <add> 'parenthesized_expression', <add> 'binary_expression', <add> 'member_expression', <add> 'property_identifier' <add> ]) <add> }) <add> }) <add> <ide> describe('.shouldPromptToSave()', () => { <ide> beforeEach(async () => { <ide> editor = await atom.workspace.open('sample.js') <ide><path>spec/tree-sitter-language-mode-spec.js <ide> describe('TreeSitterLanguageMode', () => { <ide> }) <ide> }) <ide> <add> describe('.syntaxTreeScopeDescriptorForPosition', () => { <add> it('returns a scope descriptor representing the given position in the syntax tree', async () => { <add> const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, { <add> scopeName: 'source.js', <add> parser: 'tree-sitter-javascript' <add> }) <add> <add> buffer.setText('foo({bar: baz});') <add> <add> buffer.setLanguageMode(new TreeSitterLanguageMode({buffer, grammar})) <add> expect(editor.syntaxTreeScopeDescriptorForBufferPosition([0, 6]).getScopesArray()).toEqual([ <add> 'source.js', <add> 'program', <add> 'expression_statement', <add> 'call_expression', <add> 'arguments', <add> 'object', <add> 'pair', <add> 'property_identifier' <add> ]) <add> }) <add> <add> it('includes nodes in injected syntax trees', async () => { <add> const jsGrammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, { <add> scopeName: 'source.js', <add> parser: 'tree-sitter-javascript', <add> scopes: {}, <add> injectionRegExp: 'javascript', <add> injectionPoints: [HTML_TEMPLATE_LITERAL_INJECTION_POINT] <add> }) <add> <add> const htmlGrammar = new TreeSitterGrammar(atom.grammars, htmlGrammarPath, { <add> scopeName: 'text.html', <add> parser: 'tree-sitter-html', <add> scopes: {}, <add> injectionRegExp: 'html', <add> injectionPoints: [SCRIPT_TAG_INJECTION_POINT] <add> }) <add> <add> atom.grammars.addGrammar(jsGrammar) <add> atom.grammars.addGrammar(htmlGrammar) <add> <add> buffer.setText(` <add> <div> <add> <script> <add> html \` <add> <span>\${person.name}</span> <add> \` <add> </script> <add> </div> <add> `) <add> <add> const languageMode = new TreeSitterLanguageMode({buffer, grammar: htmlGrammar, grammars: atom.grammars}) <add> buffer.setLanguageMode(languageMode) <add> <add> const position = buffer.findSync('name').start <add> expect(editor.syntaxTreeScopeDescriptorForBufferPosition(position).getScopesArray()).toEqual([ <add> 'text.html', <add> 'fragment', <add> 'element', <add> 'raw_element', <add> 'raw_text', <add> 'program', <add> 'expression_statement', <add> 'call_expression', <add> 'template_string', <add> 'fragment', <add> 'element', <add> 'template_substitution', <add> 'member_expression', <add> 'property_identifier' <add> ]) <add> }) <add> }) <add> <ide> describe('.bufferRangeForScopeAtPosition(selector?, position)', () => { <ide> describe('when selector = null', () => { <ide> it('returns the range of the smallest node at position', async () => {
2
Ruby
Ruby
materialize subqueries by adding `distinct`
4794a9a6c18439657a2f888d394a85ae93368190
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb <ide> def subquery_for(key, select) <ide> <ide> subselect = Arel::SelectManager.new(select.engine) <ide> subselect.project Arel.sql(key.name) <del> subselect.from subsubselect.as('__active_record_temp') <add> # Materialized subquery by adding distinct <add> # to work with MySQL 5.7.6 which sets optimizer_switch='derived_merge=on' <add> subselect.from subsubselect.distinct.as('__active_record_temp') <ide> end <ide> <ide> def add_index_length(option_strings, column_names, options = {})
1
Javascript
Javascript
expose `hasscheduledtimers` on `ember.run`
9fa99447d769b02db0437461f6217ba8ec6d22f2
<ide><path>packages/ember/lib/index.js <ide> Ember.run.bind = metal.bind; <ide> Ember.run.cancel = metal.cancel; <ide> Ember.run.debounce = metal.debounce; <ide> Ember.run.end = metal.end; <add>Ember.run.hasScheduledTimers = metal.hasScheduledTimers; <ide> Ember.run.join = metal.join; <ide> Ember.run.later = metal.later; <ide> Ember.run.next = metal.next; <ide><path>packages/ember/tests/reexports_test.js <ide> let allExports =[ <ide> ['run.cancel', 'ember-metal', 'cancel'], <ide> ['run.debounce', 'ember-metal', 'debounce'], <ide> ['run.end', 'ember-metal', 'end'], <add> ['run.hasScheduledTimers', 'ember-metal', 'hasScheduledTimers'], <ide> ['run.join', 'ember-metal', 'join'], <ide> ['run.later', 'ember-metal', 'later'], <ide> ['run.next', 'ember-metal', 'next'],
2
PHP
PHP
remove persistent cache
283bcd028d12433d57f743d6f59710e1d29db3bd
<ide><path>src/View/Helper/StringTemplateTrait.php <ide> public function formatTemplate($name, $data) { <ide> public function templater() { <ide> if (empty($this->_templater)) { <ide> $class = $this->config('templateClass') ?: 'Cake\View\StringTemplate'; <del> $this->_templater = new $class([], str_replace('\\', '_', __CLASS__)); <add> $this->_templater = new $class(); <ide> <ide> $templates = $this->config('templates'); <ide> if ($templates) { <ide> public function templater() { <ide> } else { <ide> $this->_templater->add($templates); <ide> } <del> $this->_templater->writeCache(); <ide> } <ide> } <del> <ide> return $this->_templater; <ide> } <ide> <ide><path>src/View/StringTemplate.php <ide> */ <ide> namespace Cake\View; <ide> <del>use Cake\Cache\Cache; <ide> use Cake\Configure\Engine\PhpConfig; <ide> use Cake\Core\InstanceConfigTrait; <ide> <ide> class StringTemplate { <ide> */ <ide> protected $_compiled = []; <ide> <del>/** <del> * The persistent cache key for templates. <del> * <del> * @var string <del> */ <del> protected $_cacheKey; <del> <ide> /** <ide> * Constructor. <ide> * <ide> * @param array $config A set of templates to add. <del> * @param string $cacheKey The cache key to load templates from <ide> */ <del> public function __construct(array $config = [], $key = null) { <del> if ($key) { <del> $this->_cacheKey = $key; <del> $this->loadCache(); <del> } <add> public function __construct(array $config = []) { <ide> $this->add($config); <ide> } <ide> <del>/** <del> * Loads templates and compiled results from the persistent cache. <del> * <del> * @return void <del> */ <del> public function loadCache() { <del> if (!$this->_cacheKey) { <del> return; <del> } <del> $results = Cache::read($this->_cacheKey, '_cake_core_'); <del> if (!$results) { <del> return; <del> } <del> $this->_templates = $results['templates']; <del> $this->_compiled = $results['compiled']; <del> } <del> <del>/** <del> * Save templates to the persistent cache. <del> * <del> * @return void <del> */ <del> public function writeCache() { <del> if (empty($this->_cacheKey)) { <del> return; <del> } <del> $data = [ <del> 'templates' => $this->_config, <del> 'compiled' => $this->_compiled <del> ]; <del> Cache::write($this->_cacheKey, '_cake_core_'); <del> } <del> <ide> /** <ide> * Push the current templates into the template stack. <ide> *
2
Javascript
Javascript
remove string literal from assertion
d12e2f6fcf128cab969cb0dda72d332df62a83e6
<ide><path>test/parallel/test-dns-lookup.js <ide> dns.lookup('example.com', common.mustCall((error, result, addressType) => { <ide> assert.strictEqual(tickValue, 1); <ide> assert.strictEqual(error.code, 'ENOENT'); <ide> const descriptor = Object.getOwnPropertyDescriptor(error, 'message'); <del> assert.strictEqual(descriptor.enumerable, <del> false, 'The error message should be non-enumerable'); <add> // The error message should be non-enumerable. <add> assert.strictEqual(descriptor.enumerable, false); <ide> })); <ide> <ide> // Make sure that the error callback is called
1
Python
Python
set version to v2.2.0.dev16
aedfba867a483060a88a24be883c91e64c8aba42
<ide><path>spacy/about.py <ide> # fmt: off <ide> __title__ = "spacy" <del>__version__ = "2.2.0" <add>__version__ = "2.2.0.dev16" <ide> __release__ = True <ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download" <ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
1
Text
Text
add jobrapido to inthewild.md
35efb1d554121007ff096086e8d8678c8b67598a
<ide><path>INTHEWILD.md <ide> Currently **officially** using Airflow: <ide> 1. [Jampp](https://github.com/jampp) <ide> 1. [Jeitto](https://www.jeitto.com.br) [[@BrennerPablo](https://github.com/BrennerPablo) & [@ds-mauri](https://github.com/ds-mauri)] <ide> 1. [Jetlore](http://www.jetlore.com/) [[@bderose](https://github.com/bderose)] <add>1. [Jobrapido](https://www.jobrapido.com/) [[@mattiagiupponi](https://github.com/mattiagiupponi)] <ide> 1. [JobTeaser](https://www.jobteaser.com) [[@stefani75](https://github.com/stefani75) & [@knil-sama](https://github.com/knil-sama)] <ide> 1. [JULO](https://www.julo.co.id/) [[@sepam](https://github.com/sepam) & [@tenapril](https://github.com/tenapril) & [@verzqy](https://github.com/verzqy)] <ide> 1. [Kalibrr](https://www.kalibrr.com/) [[@charlesverdad](https://github.com/charlesverdad)]
1