content_type stringclasses 8 values | main_lang stringclasses 7 values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Javascript | Javascript | add code example for emberarray isany | bc31e34d9c492941ba369b2424df419cf98b3a4c | <ide><path>packages/@ember/-internals/runtime/lib/mixins/array.js
<ide> const ArrayMixin = Mixin.create(Enumerable, {
<ide> argument for any item in the array. This method is often simpler/faster
<ide> than using a callback.
<ide>
<add> Example usage:
<add>
<add> ```javascript
<add> const food = [
<add> { food: 'apple', isFruit: true},
<add> { food: 'bread', isFruit: false },
<add> { food: 'banana', isFruit: true }
<add> ];
<add> food.isAny('isFruit'); // true
<add>
<add> ```
<add>
<ide> @method isAny
<ide> @param {String} key the property to test
<ide> @param {String} [value] optional value to test against. Defaults to `true` | 1 |
PHP | PHP | add class argument | 0443f1c42c20f6a30d0d81050bc43e94c9c51145 | <ide><path>src/Illuminate/Database/Console/Seeds/SeedCommand.php
<ide> use Illuminate\Console\ConfirmableTrait;
<ide> use Illuminate\Database\ConnectionResolverInterface as Resolver;
<ide> use Illuminate\Database\Eloquent\Model;
<add>use Symfony\Component\Console\Input\InputArgument;
<ide> use Symfony\Component\Console\Input\InputOption;
<ide>
<ide> class SeedCommand extends Command
<ide> public function handle()
<ide> */
<ide> protected function getSeeder()
<ide> {
<del> $class = $this->input->getOption('class');
<add> $class = $this->input->getArgument('class') ?? $this->input->getOption('class');
<ide>
<ide> if (strpos($class, '\\') === false) {
<ide> $class = 'Database\\Seeders\\'.$class;
<ide> protected function getDatabase()
<ide> return $database ?: $this->laravel['config']['database.default'];
<ide> }
<ide>
<add> /**
<add> * Get the console command arguments.
<add> *
<add> * @return array
<add> */
<add> protected function getArguments()
<add> {
<add> return [
<add> ['class', InputArgument::OPTIONAL, 'The class name of the root seeder', null],
<add> ];
<add> }
<add>
<ide> /**
<ide> * Get the console command options.
<ide> * | 1 |
Javascript | Javascript | resolve refs in the order of the children | 83cbc3e5fb700f45c48214c3785d8b44ab5ebdce | <ide><path>src/renderers/shared/stack/reconciler/ReactChildReconciler.js
<ide> var ReactChildReconciler = {
<ide> updateChildren: function(
<ide> prevChildren,
<ide> nextChildren,
<add> mountImages,
<ide> removedNodes,
<ide> transaction,
<add> hostParent,
<add> hostContainerInfo,
<ide> context) {
<ide> // We currently don't have a way to track moves here but if we use iterators
<ide> // instead of for..in we can zip the iterators and check if an item has
<ide> var ReactChildReconciler = {
<ide> // The child must be instantiated before it's mounted.
<ide> var nextChildInstance = instantiateReactComponent(nextElement);
<ide> nextChildren[name] = nextChildInstance;
<add> // Creating mount image now ensures refs are resolved in right order
<add> // (see https://github.com/facebook/react/pull/7101 for explanation).
<add> var nextChildMountImage = ReactReconciler.mountComponent(
<add> nextChildInstance,
<add> transaction,
<add> hostParent,
<add> hostContainerInfo,
<add> context
<add> );
<add> mountImages.push(nextChildMountImage);
<ide> }
<ide> }
<ide> // Unmount children that are no longer present.
<ide><path>src/renderers/shared/stack/reconciler/ReactMultiChild.js
<ide> var ReactMultiChild = {
<ide> _reconcilerUpdateChildren: function(
<ide> prevChildren,
<ide> nextNestedChildrenElements,
<add> mountImages,
<ide> removedNodes,
<ide> transaction,
<ide> context
<ide> var ReactMultiChild = {
<ide> ReactCurrentOwner.current = null;
<ide> }
<ide> ReactChildReconciler.updateChildren(
<del> prevChildren, nextChildren, removedNodes, transaction, context
<add> prevChildren,
<add> nextChildren,
<add> mountImages,
<add> removedNodes,
<add> transaction,
<add> this,
<add> this._hostContainerInfo,
<add> context
<ide> );
<ide> return nextChildren;
<ide> }
<ide> }
<ide> nextChildren = flattenChildren(nextNestedChildrenElements);
<ide> ReactChildReconciler.updateChildren(
<del> prevChildren, nextChildren, removedNodes, transaction, context
<add> prevChildren,
<add> nextChildren,
<add> mountImages,
<add> removedNodes,
<add> transaction,
<add> this,
<add> this._hostContainerInfo,
<add> context
<ide> );
<ide> return nextChildren;
<ide> },
<ide> var ReactMultiChild = {
<ide> _updateChildren: function(nextNestedChildrenElements, transaction, context) {
<ide> var prevChildren = this._renderedChildren;
<ide> var removedNodes = {};
<add> var mountImages = [];
<ide> var nextChildren = this._reconcilerUpdateChildren(
<ide> prevChildren,
<ide> nextNestedChildrenElements,
<add> mountImages,
<ide> removedNodes,
<ide> transaction,
<ide> context
<ide> var ReactMultiChild = {
<ide> var name;
<ide> // `nextIndex` will increment for each child in `nextChildren`, but
<ide> // `lastIndex` will be the last index visited in `prevChildren`.
<del> var lastIndex = 0;
<ide> var nextIndex = 0;
<add> var lastIndex = 0;
<add> // `nextMountIndex` will increment for each newly mounted child.
<add> var nextMountIndex = 0;
<ide> var lastPlacedNode = null;
<ide> for (name in nextChildren) {
<ide> if (!nextChildren.hasOwnProperty(name)) {
<ide> var ReactMultiChild = {
<ide> updates,
<ide> this._mountChildAtIndex(
<ide> nextChild,
<add> mountImages[nextMountIndex],
<ide> lastPlacedNode,
<ide> nextIndex,
<ide> transaction,
<ide> context
<ide> )
<ide> );
<add> nextMountIndex++;
<ide> }
<ide> nextIndex++;
<ide> lastPlacedNode = ReactReconciler.getHostNode(nextChild);
<ide> var ReactMultiChild = {
<ide> */
<ide> _mountChildAtIndex: function(
<ide> child,
<add> mountImage,
<ide> afterNode,
<ide> index,
<ide> transaction,
<ide> context) {
<del> var mountImage = ReactReconciler.mountComponent(
<del> child,
<del> transaction,
<del> this,
<del> this._hostContainerInfo,
<del> context
<del> );
<ide> child._mountIndex = index;
<ide> return this.createChild(child, afterNode, mountImage);
<ide> },
<ide><path>src/renderers/shared/stack/reconciler/__tests__/ReactMultiChildReconcile-test.js
<ide> var StatusDisplay = React.createClass({
<ide> return this.state.internalState;
<ide> },
<ide>
<add> componentDidMount: function() {
<add> this.props.onFlush();
<add> },
<add>
<add> componentDidUpdate: function() {
<add> this.props.onFlush();
<add> },
<add>
<ide> render: function() {
<ide> return (
<ide> <div>
<ide> var StatusDisplay = React.createClass({
<ide> */
<ide> var FriendsStatusDisplay = React.createClass({
<ide> /**
<del> * Retrieves the rendered children in a nice format for comparing to the input
<del> * `this.props.usernameToStatus`. Gets the order directly from each rendered
<del> * child's `index` field. Refs are not maintained in the rendered order, and
<del> * neither is `this._renderedChildren` (surprisingly).
<del> */
<del> getStatusDisplays: function() {
<del> var name;
<del> var orderOfUsernames = [];
<add> * Gets the order directly from each rendered child's `index` field.
<add> * Refs are not maintained in the rendered order, and neither is
<add> * `this._renderedChildren` (surprisingly).
<add> */
<add> getOriginalKeys: function() {
<add> var originalKeys = [];
<ide> // TODO: Update this to a better test that doesn't rely so much on internal
<ide> // implementation details.
<ide> var statusDisplays =
<ide> ReactInstanceMap.get(this)
<ide> ._renderedComponent
<ide> ._renderedChildren;
<add> var name;
<ide> for (name in statusDisplays) {
<ide> var child = statusDisplays[name];
<ide> var isPresent = !!child;
<ide> if (isPresent) {
<del> orderOfUsernames[child._mountIndex] = getOriginalKey(name);
<add> originalKeys[child._mountIndex] = getOriginalKey(name);
<ide> }
<ide> }
<add> return originalKeys;
<add> },
<add> /**
<add> * Retrieves the rendered children in a nice format for comparing to the input
<add> * `this.props.usernameToStatus`.
<add> */
<add> getStatusDisplays: function() {
<ide> var res = {};
<ide> var i;
<del> for (i = 0; i < orderOfUsernames.length; i++) {
<del> var key = orderOfUsernames[i];
<add> var originalKeys = this.getOriginalKeys();
<add> for (i = 0; i < originalKeys.length; i++) {
<add> var key = originalKeys[i];
<ide> res[key] = this.refs[key];
<ide> }
<ide> return res;
<ide> },
<add> /**
<add> * Verifies that by the time a child is flushed, the refs that appeared
<add> * earlier have already been resolved.
<add> * TODO: This assumption will likely break with incremental reconciler
<add> * but our internal layer API depends on this assumption. We need to change
<add> * it to be more declarative before making ref resolution indeterministic.
<add> */
<add> verifyPreviousRefsResolved: function(flushedKey) {
<add> var i;
<add> var originalKeys = this.getOriginalKeys();
<add> for (i = 0; i < originalKeys.length; i++) {
<add> var key = originalKeys[i];
<add> if (key === flushedKey) {
<add> // We are only interested in children up to the current key.
<add> return;
<add> }
<add> expect(this.refs[key]).toBeTruthy();
<add> }
<add> },
<ide> render: function() {
<ide> var children = [];
<ide> var key;
<ide> for (key in this.props.usernameToStatus) {
<ide> var status = this.props.usernameToStatus[key];
<ide> children.push(
<ide> !status ? null :
<del> <StatusDisplay key={key} ref={key} status={status} />
<add> <StatusDisplay
<add> key={key}
<add> ref={key}
<add> onFlush={this.verifyPreviousRefsResolved.bind(this, key)}
<add> status={status}
<add> />
<ide> );
<ide> }
<ide> return ( | 3 |
Mixed | Javascript | convert androiddialogpicker to js view configs | 121141c86b75b46fe9cbd5ec36853d75cd33615b | <ide><path>Libraries/Components/Picker/AndroidDialogPickerNativeComponent.js
<ide> * LICENSE file in the root directory of this source tree.
<ide> *
<ide> * @format
<del> * @flow strict-local
<add> * @flow
<ide> */
<ide>
<ide> 'use strict';
<ide> import * as React from 'react';
<ide>
<ide> import codegenNativeCommands from '../../Utilities/codegenNativeCommands';
<ide> import requireNativeComponent from '../../ReactNative/requireNativeComponent';
<add>import registerGeneratedViewConfig from '../../Utilities/registerGeneratedViewConfig';
<add>import AndroidDialogPickerViewConfig from './AndroidDialogPickerViewConfig';
<ide>
<ide> import type {
<ide> DirectEventHandler,
<ide> export const Commands: NativeCommands = codegenNativeCommands<NativeCommands>({
<ide> supportedCommands: ['setNativeSelectedPosition'],
<ide> });
<ide>
<del>export default (requireNativeComponent<NativeProps>(
<del> 'AndroidDialogPicker',
<del>): NativeType);
<add>let AndroidDialogPickerNativeComponent;
<add>if (global.RN$Bridgeless) {
<add> registerGeneratedViewConfig(
<add> 'AndroidDialogPicker',
<add> AndroidDialogPickerViewConfig,
<add> );
<add> AndroidDialogPickerNativeComponent = 'AndroidDialogPicker';
<add>} else {
<add> AndroidDialogPickerNativeComponent = requireNativeComponent<NativeProps>(
<add> 'AndroidDialogPicker',
<add> );
<add>}
<add>
<add>export default ((AndroidDialogPickerNativeComponent: any): NativeType);
<ide><path>Libraries/Components/Picker/AndroidDialogPickerViewConfig.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow strict-local
<add> * @format
<add> */
<add>
<add>'use strict';
<add>
<add>import type {GeneratedViewConfig} from '../../Utilities/registerGeneratedViewConfig';
<add>
<add>const AndroidDialogPickerViewConfig = {
<add> uiViewClassName: 'AndroidDialogPicker',
<add> bubblingEventTypes: {},
<add> directEventTypes: {},
<add> validAttributes: {
<add> color: {process: require('../../StyleSheet/processColor')},
<add> backgroundColor: {process: require('../../StyleSheet/processColor')},
<add> enabled: true,
<add> items: true,
<add> prompt: true,
<add> selected: true,
<add> onSelect: true,
<add> },
<add>};
<add>
<add>module.exports = (AndroidDialogPickerViewConfig: GeneratedViewConfig);
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactPickerManager.java
<ide> import com.facebook.react.bridge.ReadableArray;
<ide> import com.facebook.react.uimanager.SimpleViewManager;
<ide> import com.facebook.react.uimanager.ThemedReactContext;
<del>import com.facebook.react.uimanager.UIManagerModule;
<add>import com.facebook.react.uimanager.UIManagerHelper;
<ide> import com.facebook.react.uimanager.ViewProps;
<ide> import com.facebook.react.uimanager.annotations.ReactProp;
<ide> import com.facebook.react.uimanager.events.EventDispatcher;
<ide> protected void onAfterUpdateTransaction(ReactPicker view) {
<ide>
<ide> @Override
<ide> protected void addEventEmitters(final ThemedReactContext reactContext, final ReactPicker picker) {
<del> UIManagerModule uiManager = reactContext.getNativeModule(UIManagerModule.class);
<del>
<del> if (uiManager == null) {
<del> return;
<del> }
<del>
<del> picker.setOnSelectListener(new PickerEventEmitter(picker, uiManager.getEventDispatcher()));
<add> picker.setOnSelectListener(
<add> new PickerEventEmitter(
<add> picker, UIManagerHelper.getEventDispatcherForReactTag(reactContext, picker.getId())));
<ide> }
<ide>
<ide> @Override | 3 |
Go | Go | fix an error about arguments missing | af053ccf6b3179978e087defd0062664152697ef | <ide><path>daemon/monitor.go
<ide> import (
<ide> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/daemon/execdriver"
<ide> "github.com/docker/docker/runconfig"
<add> "github.com/docker/docker/utils"
<ide> )
<ide>
<ide> const defaultTimeIncrement = 100
<ide>
<ide> // containerMonitor monitors the execution of a container's main process.
<del>// If a restart policy is specified for the cotnainer the monitor will ensure that the
<add>// If a restart policy is specified for the container the monitor will ensure that the
<ide> // process is restarted based on the rules of the policy. When the container is finally stopped
<ide> // the monitor will reset and cleanup any of the container resources such as networking allocations
<ide> // and the rootfs
<ide> func (m *containerMonitor) shouldRestart(exitCode int) bool {
<ide> case "on-failure":
<ide> // the default value of 0 for MaximumRetryCount means that we will not enforce a maximum count
<ide> if max := m.restartPolicy.MaximumRetryCount; max != 0 && m.failureCount >= max {
<del> log.Debugf("stopping restart of container %s because maximum failure could of %d has been reached", max)
<add> log.Debugf("stopping restart of container %s because maximum failure could of %d has been reached",
<add> utils.TruncateID(m.container.ID), max)
<ide> return false
<ide> }
<ide> | 1 |
Text | Text | correct variable name | 5b2abbed25ef41c4cc1b3806037c6bd7631db327 | <ide><path>docs/api-guide/format-suffixes.md
<ide> Also note that `format_suffix_patterns` does not support descending into `includ
<ide>
<ide> If using the `i18n_patterns` function provided by Django, as well as `format_suffix_patterns` you should make sure that the `i18n_patterns` function is applied as the final, or outermost function. For example:
<ide>
<del> url patterns = [
<add> urlpatterns = [
<ide> …
<ide> ]
<ide> | 1 |
Python | Python | remove unused import | 2df62145f147d93378c50a7b2593c00e3d1129e0 | <ide><path>numpy/core/tests/test_ufunc.py
<ide> from numpy.testing import (
<ide> assert_, assert_equal, assert_raises, assert_array_equal,
<ide> assert_almost_equal, assert_array_almost_equal, assert_no_warnings,
<del> assert_allclose, assert_array_almost_equal_nulp
<add> assert_allclose,
<ide> )
<ide> from numpy.compat import pickle
<ide> | 1 |
Python | Python | take advantage of the cache when running tests | b670c2668426326aeffe626aabac7ee2dff3c7c2 | <ide><path>templates/adding_a_new_model/tests/modeling_tf_xxx_test.py
<ide> from __future__ import print_function
<ide>
<ide> import unittest
<del>import shutil
<ide> import sys
<ide>
<ide> from .modeling_tf_common_test import (TFCommonTestCases, ids_tensor)
<ide> from .configuration_common_test import ConfigTester
<del>from .utils import require_tf, slow
<add>from .utils import CACHE_DIR, require_tf, slow
<ide>
<ide> from transformers import XxxConfig, is_tf_available
<ide>
<ide> def test_for_token_classification(self):
<ide>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<del> cache_dir = "/tmp/transformers_test/"
<ide> for model_name in ['xxx-base-uncased']:
<del> model = TFXxxModel.from_pretrained(model_name, cache_dir=cache_dir)
<del> shutil.rmtree(cache_dir)
<add> model = TFXxxModel.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> self.assertIsNotNone(model)
<ide>
<ide> if __name__ == "__main__":
<ide><path>templates/adding_a_new_model/tests/modeling_xxx_test.py
<ide> from __future__ import print_function
<ide>
<ide> import unittest
<del>import shutil
<ide>
<ide> from transformers import is_torch_available
<ide>
<ide> from .modeling_common_test import (CommonTestCases, ids_tensor)
<ide> from .configuration_common_test import ConfigTester
<del>from .utils import require_torch, slow, torch_device
<add>from .utils import CACHE_DIR, require_torch, slow, torch_device
<ide>
<ide> if is_torch_available():
<ide> from transformers import (XxxConfig, XxxModel, XxxForMaskedLM,
<ide> def test_for_token_classification(self):
<ide>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<del> cache_dir = "/tmp/transformers_test/"
<ide> for model_name in list(XXX_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<del> model = XxxModel.from_pretrained(model_name, cache_dir=cache_dir)
<del> shutil.rmtree(cache_dir)
<add> model = XxxModel.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> self.assertIsNotNone(model)
<ide>
<ide> if __name__ == "__main__":
<ide><path>transformers/tests/modeling_albert_test.py
<ide> from __future__ import print_function
<ide>
<ide> import unittest
<del>import shutil
<ide>
<ide> from transformers import is_torch_available
<ide>
<ide> from .modeling_common_test import (CommonTestCases, ids_tensor)
<ide> from .configuration_common_test import ConfigTester
<del>from .utils import require_torch, slow, torch_device
<add>from .utils import CACHE_DIR, require_torch, slow, torch_device
<ide>
<ide> if is_torch_available():
<ide> from transformers import (AlbertConfig, AlbertModel, AlbertForMaskedLM,
<ide> def test_for_sequence_classification(self):
<ide>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<del> cache_dir = "/tmp/transformers_test/"
<ide> for model_name in list(ALBERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<del> model = AlbertModel.from_pretrained(model_name, cache_dir=cache_dir)
<del> shutil.rmtree(cache_dir)
<add> model = AlbertModel.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> self.assertIsNotNone(model)
<ide>
<ide> if __name__ == "__main__":
<ide><path>transformers/tests/modeling_bert_test.py
<ide> from __future__ import print_function
<ide>
<ide> import unittest
<del>import shutil
<ide>
<ide> from transformers import is_torch_available
<ide>
<ide> from .modeling_common_test import (CommonTestCases, ids_tensor, floats_tensor)
<ide> from .configuration_common_test import ConfigTester
<del>from .utils import require_torch, slow, torch_device
<add>from .utils import CACHE_DIR, require_torch, slow, torch_device
<ide>
<ide> if is_torch_available():
<ide> from transformers import (BertConfig, BertModel, BertForMaskedLM,
<ide> def test_for_token_classification(self):
<ide>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<del> cache_dir = "/tmp/transformers_test/"
<ide> for model_name in list(BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<del> model = BertModel.from_pretrained(model_name, cache_dir=cache_dir)
<del> shutil.rmtree(cache_dir)
<add> model = BertModel.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> self.assertIsNotNone(model)
<ide>
<ide>
<ide><path>transformers/tests/modeling_common_test.py
<ide>
<ide> from transformers import is_torch_available
<ide>
<del>from .utils import require_torch, slow, torch_device
<add>from .utils import CACHE_DIR, require_torch, slow, torch_device
<ide>
<ide> if is_torch_available():
<ide> import torch
<ide> def create_and_check_double_heads(self, config, input_ids, token_type_ids, posit
<ide> [[], []])
<ide>
<ide> def create_and_check_model_from_pretrained(self):
<del> cache_dir = "/tmp/transformers_test/"
<ide> for model_name in list(self.base_model_class.pretrained_model_archive_map.keys())[:1]:
<del> model = self.base_model_class.from_pretrained(model_name, cache_dir=cache_dir)
<del> shutil.rmtree(cache_dir)
<add> model = self.base_model_class.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> self.parent.assertIsNotNone(model)
<ide>
<ide> def prepare_config_and_inputs_for_common(self):
<ide><path>transformers/tests/modeling_ctrl_test.py
<ide> from __future__ import print_function
<ide>
<ide> import unittest
<del>import shutil
<ide> import pdb
<ide>
<ide> from transformers import is_torch_available
<ide>
<ide> from .modeling_common_test import (CommonTestCases, ids_tensor)
<ide> from .configuration_common_test import ConfigTester
<del>from .utils import require_torch, slow, torch_device
<add>from .utils import CACHE_DIR, require_torch, slow, torch_device
<ide>
<ide>
<ide> @require_torch
<ide> def test_ctrl_lm_head_model(self):
<ide>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<del> cache_dir = "/tmp/transformers_test/"
<ide> for model_name in list(CTRL_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<del> model = CTRLModel.from_pretrained(model_name, cache_dir=cache_dir)
<del> shutil.rmtree(cache_dir)
<add> model = CTRLModel.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> self.assertIsNotNone(model)
<ide>
<ide>
<ide><path>transformers/tests/modeling_distilbert_test.py
<ide>
<ide> from .modeling_common_test import (CommonTestCases, ids_tensor)
<ide> from .configuration_common_test import ConfigTester
<del>from .utils import require_torch, slow, torch_device
<add>from .utils import CACHE_DIR, require_torch, slow, torch_device
<ide>
<ide>
<ide> @require_torch
<ide> def test_for_token_classification(self):
<ide>
<ide> # @slow
<ide> # def test_model_from_pretrained(self):
<del> # cache_dir = "/tmp/transformers_test/"
<ide> # for model_name in list(DISTILBERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<del> # model = DistilBertModel.from_pretrained(model_name, cache_dir=cache_dir)
<del> # shutil.rmtree(cache_dir)
<add> # model = DistilBertModel.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> # self.assertIsNotNone(model)
<ide>
<ide> if __name__ == "__main__":
<ide><path>transformers/tests/modeling_gpt2_test.py
<ide> from __future__ import print_function
<ide>
<ide> import unittest
<del>import shutil
<ide>
<ide> from transformers import is_torch_available
<ide>
<ide>
<ide> from .modeling_common_test import (CommonTestCases, ids_tensor)
<ide> from .configuration_common_test import ConfigTester
<del>from .utils import require_torch, slow, torch_device
<add>from .utils import CACHE_DIR, require_torch, slow, torch_device
<ide>
<ide>
<ide> @require_torch
<ide> def test_gpt2_double_lm_head_model(self):
<ide>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<del> cache_dir = "/tmp/transformers_test/"
<ide> for model_name in list(GPT2_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<del> model = GPT2Model.from_pretrained(model_name, cache_dir=cache_dir)
<del> shutil.rmtree(cache_dir)
<add> model = GPT2Model.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> self.assertIsNotNone(model)
<ide>
<ide>
<ide><path>transformers/tests/modeling_openai_test.py
<ide> from __future__ import print_function
<ide>
<ide> import unittest
<del>import shutil
<ide>
<ide> from transformers import is_torch_available
<ide>
<ide>
<ide> from .modeling_common_test import (CommonTestCases, ids_tensor)
<ide> from .configuration_common_test import ConfigTester
<del>from .utils import require_torch, slow, torch_device
<add>from .utils import CACHE_DIR, require_torch, slow, torch_device
<ide>
<ide>
<ide> @require_torch
<ide> def test_openai_gpt_double_lm_head_model(self):
<ide>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<del> cache_dir = "/tmp/transformers_test/"
<ide> for model_name in list(OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<del> model = OpenAIGPTModel.from_pretrained(model_name, cache_dir=cache_dir)
<del> shutil.rmtree(cache_dir)
<add> model = OpenAIGPTModel.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> self.assertIsNotNone(model)
<ide>
<ide>
<ide><path>transformers/tests/modeling_roberta_test.py
<ide> from __future__ import print_function
<ide>
<ide> import unittest
<del>import shutil
<ide>
<ide> from transformers import is_torch_available
<ide>
<ide>
<ide> from .modeling_common_test import (CommonTestCases, ids_tensor)
<ide> from .configuration_common_test import ConfigTester
<del>from .utils import require_torch, slow, torch_device
<add>from .utils import CACHE_DIR, require_torch, slow, torch_device
<ide>
<ide>
<ide> @require_torch
<ide> def test_for_masked_lm(self):
<ide>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<del> cache_dir = "/tmp/transformers_test/"
<ide> for model_name in list(ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<del> model = RobertaModel.from_pretrained(model_name, cache_dir=cache_dir)
<del> shutil.rmtree(cache_dir)
<add> model = RobertaModel.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> self.assertIsNotNone(model)
<ide>
<ide>
<ide><path>transformers/tests/modeling_t5_test.py
<ide> from __future__ import print_function
<ide>
<ide> import unittest
<del>import shutil
<ide>
<ide> from transformers import is_torch_available
<ide>
<ide> from .modeling_common_test import (CommonTestCases, ids_tensor, floats_tensor)
<ide> from .configuration_common_test import ConfigTester
<del>from .utils import require_torch, slow, torch_device
<add>from .utils import CACHE_DIR, require_torch, slow, torch_device
<ide>
<ide> if is_torch_available():
<ide> from transformers import (T5Config, T5Model, T5WithLMHeadModel)
<ide> def test_with_lm_head(self):
<ide>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<del> cache_dir = "/tmp/transformers_test/"
<ide> for model_name in list(T5_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<del> model = T5Model.from_pretrained(model_name, cache_dir=cache_dir)
<del> shutil.rmtree(cache_dir)
<add> model = T5Model.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> self.assertIsNotNone(model)
<ide>
<ide> if __name__ == "__main__":
<ide><path>transformers/tests/modeling_tf_albert_test.py
<ide> from __future__ import print_function
<ide>
<ide> import unittest
<del>import shutil
<ide> import sys
<ide>
<ide> from .modeling_tf_common_test import (TFCommonTestCases, ids_tensor)
<ide> from .configuration_common_test import ConfigTester
<del>from .utils import require_tf, slow
<add>from .utils import CACHE_DIR, require_tf, slow
<ide>
<ide> from transformers import AlbertConfig, is_tf_available
<ide>
<ide> def test_for_sequence_classification(self):
<ide>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<del> cache_dir = "/tmp/transformers_test/"
<ide> # for model_name in list(TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<ide> for model_name in ['albert-base-uncased']:
<del> model = TFAlbertModel.from_pretrained(
<del> model_name, cache_dir=cache_dir)
<del> shutil.rmtree(cache_dir)
<add> model = TFAlbertModel.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> self.assertIsNotNone(model)
<ide>
<ide>
<ide><path>transformers/tests/modeling_tf_auto_test.py
<ide> def test_model_from_pretrained(self):
<ide> logging.basicConfig(level=logging.INFO)
<ide> # for model_name in list(TF_BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<ide> for model_name in ['bert-base-uncased']:
<del> config = AutoConfig.from_pretrained(model_name, force_download=True)
<add> config = AutoConfig.from_pretrained(model_name)
<ide> self.assertIsNotNone(config)
<ide> self.assertIsInstance(config, BertConfig)
<ide>
<del> model = TFAutoModel.from_pretrained(model_name, force_download=True)
<add> model = TFAutoModel.from_pretrained(model_name)
<ide> self.assertIsNotNone(model)
<ide> self.assertIsInstance(model, TFBertModel)
<ide>
<ide> def test_lmhead_model_from_pretrained(self):
<ide> logging.basicConfig(level=logging.INFO)
<ide> # for model_name in list(TF_BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<ide> for model_name in ['bert-base-uncased']:
<del> config = AutoConfig.from_pretrained(model_name, force_download=True)
<add> config = AutoConfig.from_pretrained(model_name)
<ide> self.assertIsNotNone(config)
<ide> self.assertIsInstance(config, BertConfig)
<ide>
<del> model = TFAutoModelWithLMHead.from_pretrained(model_name, force_download=True)
<add> model = TFAutoModelWithLMHead.from_pretrained(model_name)
<ide> self.assertIsNotNone(model)
<ide> self.assertIsInstance(model, TFBertForMaskedLM)
<ide>
<ide> def test_sequence_classification_model_from_pretrained(self):
<ide> logging.basicConfig(level=logging.INFO)
<ide> # for model_name in list(TF_BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<ide> for model_name in ['bert-base-uncased']:
<del> config = AutoConfig.from_pretrained(model_name, force_download=True)
<add> config = AutoConfig.from_pretrained(model_name)
<ide> self.assertIsNotNone(config)
<ide> self.assertIsInstance(config, BertConfig)
<ide>
<del> model = TFAutoModelForSequenceClassification.from_pretrained(model_name, force_download=True)
<add> model = TFAutoModelForSequenceClassification.from_pretrained(model_name)
<ide> self.assertIsNotNone(model)
<ide> self.assertIsInstance(model, TFBertForSequenceClassification)
<ide>
<ide> def test_question_answering_model_from_pretrained(self):
<ide> logging.basicConfig(level=logging.INFO)
<ide> # for model_name in list(TF_BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<ide> for model_name in ['bert-base-uncased']:
<del> config = AutoConfig.from_pretrained(model_name, force_download=True)
<add> config = AutoConfig.from_pretrained(model_name)
<ide> self.assertIsNotNone(config)
<ide> self.assertIsInstance(config, BertConfig)
<ide>
<del> model = TFAutoModelForQuestionAnswering.from_pretrained(model_name, force_download=True)
<add> model = TFAutoModelForQuestionAnswering.from_pretrained(model_name)
<ide> self.assertIsNotNone(model)
<ide> self.assertIsInstance(model, TFBertForQuestionAnswering)
<ide>
<ide> def test_from_pretrained_identifier(self):
<ide> logging.basicConfig(level=logging.INFO)
<del> model = TFAutoModelWithLMHead.from_pretrained(SMALL_MODEL_IDENTIFIER, force_download=True)
<add> model = TFAutoModelWithLMHead.from_pretrained(SMALL_MODEL_IDENTIFIER)
<ide> self.assertIsInstance(model, TFBertForMaskedLM)
<ide>
<ide>
<ide><path>transformers/tests/modeling_tf_bert_test.py
<ide> from __future__ import print_function
<ide>
<ide> import unittest
<del>import shutil
<ide> import sys
<ide>
<ide> from .modeling_tf_common_test import (TFCommonTestCases, ids_tensor)
<ide> from .configuration_common_test import ConfigTester
<del>from .utils import require_tf, slow
<add>from .utils import CACHE_DIR, require_tf, slow
<ide>
<ide> from transformers import BertConfig, is_tf_available
<ide>
<ide> def test_for_token_classification(self):
<ide>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<del> cache_dir = "/tmp/transformers_test/"
<ide> # for model_name in list(TF_BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<ide> for model_name in ['bert-base-uncased']:
<del> model = TFBertModel.from_pretrained(model_name, cache_dir=cache_dir)
<del> shutil.rmtree(cache_dir)
<add> model = TFBertModel.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> self.assertIsNotNone(model)
<ide>
<ide> if __name__ == "__main__":
<ide><path>transformers/tests/modeling_tf_ctrl_test.py
<ide> from __future__ import print_function
<ide>
<ide> import unittest
<del>import shutil
<ide> import sys
<ide>
<ide> from .modeling_tf_common_test import (TFCommonTestCases, ids_tensor)
<ide> from .configuration_common_test import ConfigTester
<del>from .utils import require_tf, slow
<add>from .utils import CACHE_DIR, require_tf, slow
<ide>
<ide> from transformers import CTRLConfig, is_tf_available
<ide>
<ide> def test_ctrl_lm_head(self):
<ide>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<del> cache_dir = "/tmp/transformers_test/"
<ide> for model_name in list(TF_CTRL_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<del> model = TFCTRLModel.from_pretrained(model_name, cache_dir=cache_dir)
<del> shutil.rmtree(cache_dir)
<add> model = TFCTRLModel.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> self.assertIsNotNone(model)
<ide>
<ide> if __name__ == "__main__":
<ide><path>transformers/tests/modeling_tf_distilbert_test.py
<ide>
<ide> from .modeling_tf_common_test import (TFCommonTestCases, ids_tensor)
<ide> from .configuration_common_test import ConfigTester
<del>from .utils import require_tf, slow
<add>from .utils import CACHE_DIR, require_tf, slow
<ide>
<ide> from transformers import DistilBertConfig, is_tf_available
<ide>
<ide> def test_for_sequence_classification(self):
<ide>
<ide> # @slow
<ide> # def test_model_from_pretrained(self):
<del> # cache_dir = "/tmp/transformers_test/"
<ide> # for model_name in list(DISTILBERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<del> # model = DistilBertModel.from_pretrained(model_name, cache_dir=cache_dir)
<del> # shutil.rmtree(cache_dir)
<add> # model = DistilBertModel.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> # self.assertIsNotNone(model)
<ide>
<ide> if __name__ == "__main__":
<ide><path>transformers/tests/modeling_tf_gpt2_test.py
<ide> from __future__ import print_function
<ide>
<ide> import unittest
<del>import shutil
<ide> import sys
<ide>
<ide> from .modeling_tf_common_test import (TFCommonTestCases, ids_tensor)
<ide> from .configuration_common_test import ConfigTester
<del>from .utils import require_tf, slow
<add>from .utils import CACHE_DIR, require_tf, slow
<ide>
<ide> from transformers import GPT2Config, is_tf_available
<ide>
<ide> def test_gpt2_double_head(self):
<ide>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<del> cache_dir = "/tmp/transformers_test/"
<ide> for model_name in list(TF_GPT2_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<del> model = TFGPT2Model.from_pretrained(model_name, cache_dir=cache_dir)
<del> shutil.rmtree(cache_dir)
<add> model = TFGPT2Model.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> self.assertIsNotNone(model)
<ide>
<ide> if __name__ == "__main__":
<ide><path>transformers/tests/modeling_tf_openai_gpt_test.py
<ide> from __future__ import print_function
<ide>
<ide> import unittest
<del>import shutil
<ide> import sys
<ide>
<ide> from .modeling_tf_common_test import (TFCommonTestCases, ids_tensor)
<ide> from .configuration_common_test import ConfigTester
<del>from .utils import require_tf, slow
<add>from .utils import CACHE_DIR, require_tf, slow
<ide>
<ide> from transformers import OpenAIGPTConfig, is_tf_available
<ide>
<ide> def test_openai_gpt_double_head(self):
<ide>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<del> cache_dir = "/tmp/transformers_test/"
<ide> for model_name in list(TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<del> model = TFOpenAIGPTModel.from_pretrained(model_name, cache_dir=cache_dir)
<del> shutil.rmtree(cache_dir)
<add> model = TFOpenAIGPTModel.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> self.assertIsNotNone(model)
<ide>
<ide> if __name__ == "__main__":
<ide><path>transformers/tests/modeling_tf_roberta_test.py
<ide> from __future__ import print_function
<ide>
<ide> import unittest
<del>import shutil
<ide>
<ide> from .modeling_tf_common_test import (TFCommonTestCases, ids_tensor)
<ide> from .configuration_common_test import ConfigTester
<del>from .utils import require_tf, slow
<add>from .utils import CACHE_DIR, require_tf, slow
<ide>
<ide> from transformers import RobertaConfig, is_tf_available
<ide>
<ide> def test_for_masked_lm(self):
<ide>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<del> cache_dir = "/tmp/transformers_test/"
<ide> for model_name in list(TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<del> model = TFRobertaModel.from_pretrained(model_name, cache_dir=cache_dir)
<del> shutil.rmtree(cache_dir)
<add> model = TFRobertaModel.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> self.assertIsNotNone(model)
<ide>
<ide>
<ide><path>transformers/tests/modeling_tf_t5_test.py
<ide> from __future__ import print_function
<ide>
<ide> import unittest
<del>import shutil
<ide> import sys
<ide>
<ide> from .modeling_tf_common_test import (TFCommonTestCases, ids_tensor)
<ide> from .configuration_common_test import ConfigTester
<del>from .utils import require_tf, slow
<add>from .utils import CACHE_DIR, require_tf, slow
<ide>
<ide> from transformers import T5Config, is_tf_available
<ide>
<ide> def test_with_lm_head(self):
<ide>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<del> cache_dir = "/tmp/transformers_test/"
<ide> for model_name in ['t5-small']:
<del> model = TFT5Model.from_pretrained(model_name, cache_dir=cache_dir)
<del> shutil.rmtree(cache_dir)
<add> model = TFT5Model.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> self.assertIsNotNone(model)
<ide>
<ide> if __name__ == "__main__":
<ide><path>transformers/tests/modeling_tf_transfo_xl_test.py
<ide>
<ide> import unittest
<ide> import random
<del>import shutil
<ide>
<ide> from .modeling_tf_common_test import (TFCommonTestCases, ids_tensor)
<ide> from .configuration_common_test import ConfigTester
<del>from .utils import require_tf, slow
<add>from .utils import CACHE_DIR, require_tf, slow
<ide>
<ide> from transformers import TransfoXLConfig, is_tf_available
<ide>
<ide> def test_transfo_xl_lm_head(self):
<ide>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<del> cache_dir = "/tmp/transformers_test/"
<ide> for model_name in list(TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<del> model = TFTransfoXLModel.from_pretrained(model_name, cache_dir=cache_dir)
<del> shutil.rmtree(cache_dir)
<add> model = TFTransfoXLModel.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> self.assertIsNotNone(model)
<ide>
<ide>
<ide><path>transformers/tests/modeling_tf_xlm_test.py
<ide> from __future__ import print_function
<ide>
<ide> import unittest
<del>import shutil
<ide>
<ide> from transformers import is_tf_available
<ide>
<ide>
<ide> from .modeling_tf_common_test import (TFCommonTestCases, ids_tensor)
<ide> from .configuration_common_test import ConfigTester
<del>from .utils import require_tf, slow
<add>from .utils import CACHE_DIR, require_tf, slow
<ide>
<ide>
<ide> @require_tf
<ide> def test_xlm_sequence_classif(self):
<ide>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<del> cache_dir = "/tmp/transformers_test/"
<ide> for model_name in list(TF_XLM_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<del> model = XLMModel.from_pretrained(model_name, cache_dir=cache_dir)
<del> shutil.rmtree(cache_dir)
<add> model = XLMModel.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> self.assertIsNotNone(model)
<ide>
<ide>
<ide><path>transformers/tests/modeling_tf_xlnet_test.py
<ide> import unittest
<ide> import json
<ide> import random
<del>import shutil
<ide>
<ide> from transformers import XLNetConfig, is_tf_available
<ide>
<ide>
<ide> from .modeling_tf_common_test import (TFCommonTestCases, ids_tensor)
<ide> from .configuration_common_test import ConfigTester
<del>from .utils import require_tf, slow
<add>from .utils import CACHE_DIR, require_tf, slow
<ide>
<ide>
<ide> @require_tf
<ide> def test_xlnet_qa(self):
<ide>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<del> cache_dir = "/tmp/transformers_test/"
<ide> for model_name in list(TF_XLNET_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<del> model = TFXLNetModel.from_pretrained(model_name, cache_dir=cache_dir)
<del> shutil.rmtree(cache_dir)
<add> model = TFXLNetModel.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> self.assertIsNotNone(model)
<ide>
<ide>
<ide><path>transformers/tests/modeling_transfo_xl_test.py
<ide>
<ide> import unittest
<ide> import random
<del>import shutil
<ide>
<ide> from transformers import is_torch_available
<ide>
<ide>
<ide> from .modeling_common_test import (CommonTestCases, ids_tensor)
<ide> from .configuration_common_test import ConfigTester
<del>from .utils import require_torch, slow, torch_device
<add>from .utils import CACHE_DIR, require_torch, slow, torch_device
<ide>
<ide>
<ide> @require_torch
<ide> def test_transfo_xl_lm_head(self):
<ide>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<del> cache_dir = "/tmp/transformers_test/"
<ide> for model_name in list(TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<del> model = TransfoXLModel.from_pretrained(model_name, cache_dir=cache_dir)
<del> shutil.rmtree(cache_dir)
<add> model = TransfoXLModel.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> self.assertIsNotNone(model)
<ide>
<ide>
<ide><path>transformers/tests/modeling_xlm_test.py
<ide> from __future__ import print_function
<ide>
<ide> import unittest
<del>import shutil
<ide>
<ide> from transformers import is_torch_available
<ide>
<ide>
<ide> from .modeling_common_test import (CommonTestCases, ids_tensor)
<ide> from .configuration_common_test import ConfigTester
<del>from .utils import require_torch, slow, torch_device
<add>from .utils import CACHE_DIR, require_torch, slow, torch_device
<ide>
<ide>
<ide> @require_torch
<ide> def test_xlm_sequence_classif(self):
<ide>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<del> cache_dir = "/tmp/transformers_test/"
<ide> for model_name in list(XLM_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<del> model = XLMModel.from_pretrained(model_name, cache_dir=cache_dir)
<del> shutil.rmtree(cache_dir)
<add> model = XLMModel.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> self.assertIsNotNone(model)
<ide>
<ide>
<ide><path>transformers/tests/modeling_xlnet_test.py
<ide> import unittest
<ide> import json
<ide> import random
<del>import shutil
<ide>
<ide> from transformers import is_torch_available
<ide>
<ide>
<ide> from .modeling_common_test import (CommonTestCases, ids_tensor)
<ide> from .configuration_common_test import ConfigTester
<del>from .utils import require_torch, slow, torch_device
<add>from .utils import CACHE_DIR, require_torch, slow, torch_device
<ide>
<ide>
<ide> @require_torch
<ide> def test_xlnet_qa(self):
<ide>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<del> cache_dir = "/tmp/transformers_test/"
<ide> for model_name in list(XLNET_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<del> model = XLNetModel.from_pretrained(model_name, cache_dir=cache_dir)
<del> shutil.rmtree(cache_dir)
<add> model = XLNetModel.from_pretrained(model_name, cache_dir=CACHE_DIR)
<ide> self.assertIsNotNone(model)
<ide>
<ide>
<ide><path>transformers/tests/utils.py
<ide> import os
<ide> import unittest
<add>import tempfile
<ide>
<ide> from distutils.util import strtobool
<ide>
<ide> from transformers.file_utils import _tf_available, _torch_available
<ide>
<ide>
<add>CACHE_DIR = os.path.join(tempfile.gettempdir(), "transformers_test")
<add>
<ide> SMALL_MODEL_IDENTIFIER = "julien-c/bert-xsmall-dummy"
<ide>
<ide> | 27 |
Text | Text | add details about undoing require() image sizing | edf30065ea3544611af66c5319f47e46ee31b721 | <ide><path>docs/Images.md
<ide> var icon = this.props.active ? require('./my-icon-active.png') : require('./my-i
<ide> <Image source={icon} />
<ide> ```
<ide>
<add>Note that image sources required this way include size (width, height) info for the Image. If you need to scale the image dynamically (i.e. via flex), you may need to manually set { width: undefined, height: undefined } on the style attribute.
<add>
<ide> **Available React Native 0.14+**. If you've generated your project with 0.13 or earlier, read this. The new asset system relies on build hooks for [Xcode](https://github.com/facebook/react-native/pull/3523) and [Gradle](https://github.com/facebook/react-native/commit/9dc036d2b99e6233297c55a3490bfc308e34e75f) that are included in new projects generated with `react-native init`. If you generated your projects before that, you'll have to manually add them to your projects to use the new images asset system. See [Upgrading](/react-native/docs/upgrading.html) for instructions on how to do this.
<ide>
<ide> ## Images From Hybrid App's Resources | 1 |
Javascript | Javascript | remove obsolete domain test | 186ce7e837bde20bd2726d662721a93c95ba24a6 | <ide><path>test/parallel/test-microtask-queue-run-domain.js
<del>// Copyright Joyent, Inc. and other Node contributors.
<del>//
<del>// Permission is hereby granted, free of charge, to any person obtaining a
<del>// copy of this software and associated documentation files (the
<del>// "Software"), to deal in the Software without restriction, including
<del>// without limitation the rights to use, copy, modify, merge, publish,
<del>// distribute, sublicense, and/or sell copies of the Software, and to permit
<del>// persons to whom the Software is furnished to do so, subject to the
<del>// following conditions:
<del>//
<del>// The above copyright notice and this permission notice shall be included
<del>// in all copies or substantial portions of the Software.
<del>//
<del>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<del>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<del>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<del>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<del>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<del>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<del>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<del>
<del>'use strict';
<del>require('../common');
<del>const assert = require('assert');
<del>
<del>// Requiring the domain module here changes the function that is used by node to
<del>// call process.nextTick's callbacks to a variant that specifically handles
<del>// domains. We want to test this specific variant in this test, and so even if
<del>// the domain module is not used, this require call is needed and must not be
<del>// removed.
<del>require('domain');
<del>
<del>function enqueueMicrotask(fn) {
<del> Promise.resolve().then(fn);
<del>}
<del>
<del>let done = 0;
<del>
<del>process.on('exit', function() {
<del> assert.strictEqual(done, 2);
<del>});
<del>
<del>// no nextTick, microtask
<del>setTimeout(function() {
<del> enqueueMicrotask(function() {
<del> done++;
<del> });
<del>}, 0);
<del>
<del>
<del>// no nextTick, microtask with nextTick
<del>setTimeout(function() {
<del> let called = false;
<del>
<del> enqueueMicrotask(function() {
<del> process.nextTick(function() {
<del> called = true;
<del> });
<del> });
<del>
<del> setTimeout(function() {
<del> if (called)
<del> done++;
<del> }, 0);
<del>
<del>}, 0); | 1 |
Go | Go | add note to copytocontainer documentation | 1c3071e487db96ba8274ac2388eca0002e9cee77 | <ide><path>client/container_copy.go
<ide> func (cli *Client) ContainerStatPath(ctx context.Context, containerID, path stri
<ide> }
<ide>
<ide> // CopyToContainer copies content into the container filesystem.
<add>// Note that `content` must be a Reader for a TAR
<ide> func (cli *Client) CopyToContainer(ctx context.Context, container, path string, content io.Reader, options types.CopyToContainerOptions) error {
<ide> query := url.Values{}
<ide> query.Set("path", filepath.ToSlash(path)) // Normalize the paths used in the API. | 1 |
Ruby | Ruby | use march=native for generic module | d0f1fa668ce2a943f1613080f8b517decdeab215 | <ide><path>Library/Homebrew/hardware.rb
<ide> class << self
<ide> penryn: "-march=core2 -msse4.1",
<ide> core2: "-march=core2",
<ide> core: "-march=prescott",
<del> dunno: "",
<add> dunno: "-march=native",
<ide> }.freeze
<ide>
<ide> def optimization_flags | 1 |
PHP | PHP | fix import order | 64a5753870f82586463ef6bad55e149fa2ac9448 | <ide><path>tests/TestCase/Http/Middleware/CsrfProtectionMiddlewareTest.php
<ide> use Cake\TestSuite\TestCase;
<ide> use Psr\Http\Message\ServerRequestInterface;
<ide> use TestApp\Http\TestRequestHandler;
<del>use Zend\Diactoros\Response\RedirectResponse;
<ide> use Zend\Diactoros\Response as DiactorosResponse;
<add>use Zend\Diactoros\Response\RedirectResponse;
<ide>
<ide> /**
<ide> * Test for CsrfProtection | 1 |
PHP | PHP | allow whitespace before tags when checking html | b717f319172f8caa7d1203e0eafcc1535265c749 | <ide><path>src/TestSuite/TestCase.php
<ide> public function assertHtml($expected, $string, $fullDebug = false)
<ide> $tags = $matches[1];
<ide> $type = 'Regex matches';
<ide> } else {
<del> $tags = preg_quote($tags, '/');
<add> $tags = '\s*' . preg_quote($tags, '/');
<ide> $type = 'Text equals';
<ide> }
<ide> $regex[] = [
<ide><path>tests/TestCase/TestSuite/AssertHtmlTest.php
<ide> */
<ide> class AssertHtmlTest extends TestCase
<ide> {
<del> public function testAssertHtmlWhitespace()
<add> /**
<add> * Test whitespace after HTML tags
<add> *
<add> * @return
<add> */
<add> public function testAssertHtmlWhitespaceAfter()
<ide> {
<ide> $input = <<<HTML
<ide> <div class="wrapper">
<ide> public function testAssertHtmlWhitespace()
<ide> ];
<ide> $this->assertHtml($pattern, $input);
<ide> }
<add>
<add> /**
<add> * Test whitespace inside HTML tags
<add> *
<add> * @return void
<add> */
<add> public function testAssertHtmlInnerWhitespace()
<add> {
<add> $input = <<<HTML
<add><div class="widget">
<add> <div class="widget-content">
<add> A custom widget
<add> </div>
<add></div>
<add>HTML;
<add> $expected = [
<add> ['div' => ['class' => 'widget']],
<add> ['div' => ['class' => 'widget-content']],
<add> 'A custom widget',
<add> '/div',
<add> '/div',
<add> ];
<add> $this->assertHtml($expected, $input);
<add> }
<add>
<ide> /**
<ide> * test assertHtml works with single and double quotes
<ide> * | 2 |
Javascript | Javascript | improve error messaging in handlebars helper | 9f2caece30bcf6ffab4a39dd8cd510b6081d749e | <ide><path>packages/sproutcore-handlebars/lib/helpers/binding.js
<ide> require('sproutcore-handlebars/ext');
<ide> require('sproutcore-handlebars/views/bindable_span');
<ide>
<del>var get = SC.get, getPath = SC.getPath;
<add>var get = SC.get, getPath = SC.getPath, fmt = SC.String.fmt;
<ide>
<ide> (function() {
<ide> // Binds a property into the DOM. This will create a hook in DOM that the
<ide> var get = SC.get, getPath = SC.getPath;
<ide> DOM. Note that if you need to support IE7 and IE8 you must modify the
<ide> model objects properties using SC.get() and SC.set() for this to work as
<ide> it relies on SC's KVO system. For all other browsers this will be handled
<del> for you automatically.
<add> for you automatically.
<ide>
<add> @private
<ide> @name Handlebars.helpers.bind
<ide> @param {String} property Property to bind
<ide> @param {Function} fn Context to provide for rendering
<ide> @returns {String} HTML string
<ide> */
<ide> Handlebars.registerHelper('bind', function(property, fn) {
<add> sc_assert("You cannot pass more than one argument to the bind helper", arguments.length <= 2);
<add>
<ide> return bind.call(this, property, fn, false, function(result) {
<ide> return !SC.none(result);
<ide> });
<ide> var get = SC.get, getPath = SC.getPath;
<ide> {{content.title}}
<ide> {{/boundIf}}
<ide>
<add> @private
<ide> @name Handlebars.helpers.boundIf
<ide> @param {String} property Property to bind
<ide> @param {Function} fn Context to provide for rendering
<ide> @returns {String} HTML string
<ide> */
<ide> Handlebars.registerHelper('boundIf', function(property, fn) {
<del> if(fn) {
<del> return bind.call(this, property, fn, true, function(result) {
<del> if (SC.typeOf(result) === 'array') {
<del> return get(result, 'length') !== 0;
<del> } else {
<del> return !!result;
<del> }
<del> } );
<del> } else {
<del> throw new SC.Error("Cannot use boundIf helper without a block.");
<del> }
<add> return bind.call(this, property, fn, true, function(result) {
<add> if (SC.typeOf(result) === 'array') {
<add> return get(result, 'length') !== 0;
<add> } else {
<add> return !!result;
<add> }
<add> } );
<ide> });
<ide> })();
<ide>
<ide> var get = SC.get, getPath = SC.getPath;
<ide> @returns {String} HTML string
<ide> */
<ide> Handlebars.registerHelper('with', function(context, options) {
<add> sc_assert("You must pass exactly one argument to the with helper", arguments.length == 2);
<add> sc_assert("You must pass a block to the with helper", options.fn && options.fn !== Handlebars.VM.noop);
<add>
<ide> return Handlebars.helpers.bind.call(options.contexts[0], context, options);
<ide> });
<ide>
<ide> Handlebars.registerHelper('with', function(context, options) {
<ide> @returns {String} HTML string
<ide> */
<ide> Handlebars.registerHelper('if', function(context, options) {
<add> sc_assert("You must pass exactly one argument to the if helper", arguments.length == 2);
<add> sc_assert("You must pass a block to the if helper", options.fn && options.fn !== Handlebars.VM.noop);
<add>
<ide> return Handlebars.helpers.boundIf.call(options.contexts[0], context, options);
<ide> });
<ide>
<ide> Handlebars.registerHelper('if', function(context, options) {
<ide> @returns {String} HTML string
<ide> */
<ide> Handlebars.registerHelper('unless', function(context, options) {
<add> sc_assert("You must pass exactly one argument to the unless helper", arguments.length == 2);
<add> sc_assert("You must pass a block to the unless helper", options.fn && options.fn !== Handlebars.VM.noop);
<add>
<ide> var fn = options.fn, inverse = options.inverse;
<ide>
<ide> options.fn = inverse;
<ide> Handlebars.registerHelper('unless', function(context, options) {
<ide> Handlebars.registerHelper('bindAttr', function(options) {
<ide>
<ide> var attrs = options.hash;
<add>
<add> sc_assert("You must specify at least one hash argument to bindAttr", !!SC.keys(attrs).length);
<add>
<ide> var view = options.data.view;
<ide> var ret = [];
<ide> var ctx = this;
<ide> Handlebars.registerHelper('bindAttr', function(options) {
<ide> // current value of the property as an attribute.
<ide> attrKeys.forEach(function(attr) {
<ide> var property = attrs[attr];
<add>
<add> sc_assert(fmt("You must provide a String for a bound attribute, not %@", [property]), typeof property === 'string');
<add>
<ide> var value = getPath(ctx, property);
<ide>
<add> sc_assert(fmt("Attributes must be numbers, strings or booleans, not %@", [value]), value == null || typeof value === 'number' || typeof value === 'string' || typeof value === 'boolean');
<add>
<ide> var observer, invoker;
<ide>
<ide> observer = function observer() {
<ide> var result = getPath(ctx, property);
<add>
<add> sc_assert(fmt("Attributes must be numbers, strings or booleans, not %@", [result]), result == null || typeof result === 'number' || typeof result === 'string' || typeof result === 'boolean');
<add>
<ide> var elem = view.$("[data-handlebars-id='" + dataId + "']");
<ide>
<ide> // If we aren't able to find the element, it means the element
<ide> Handlebars.registerHelper('bindAttr', function(options) {
<ide>
<ide> // A false result will remove the attribute from the element. This is
<ide> // to support attributes such as disabled, whose presence is meaningful.
<del> if (result === NO && currentValue) {
<add> if (result === false && currentValue) {
<ide> elem.removeAttr(attr);
<ide>
<ide> // Likewise, a true result will set the attribute's name as the value.
<del> } else if (result === YES && currentValue !== attr) {
<add> } else if (result === true && currentValue !== attr) {
<ide> elem.attr(attr, attr);
<ide>
<ide> } else if (currentValue !== result) {
<ide> Handlebars.registerHelper('bindAttr', function(options) {
<ide> SC.addObserver(ctx, property, invoker);
<ide>
<ide> // Use the attribute's name as the value when it is YES
<del> if (value === YES) {
<add> if (value === true) {
<ide> value = attr;
<ide> }
<ide>
<ide> // Do not add the attribute when the value is false
<del> if (value !== NO) {
<add> if (value !== false) {
<ide> // Return the current value, in the form src="foo.jpg"
<ide> ret.push(attr + '="' + value + '"');
<ide> }
<ide><path>packages/sproutcore-handlebars/lib/helpers/view.js
<ide> var get = SC.get, set = SC.set;
<ide>
<ide> /** @private */
<ide> SC.Handlebars.ViewHelper = SC.Object.create({
<del>
<add>
<ide> viewClassFromHTMLOptions: function(viewClass, options) {
<ide> var extensions = {},
<ide> classes = options['class'],
<ide> SC.Handlebars.ViewHelper = SC.Object.create({
<ide>
<ide> if ('string' === typeof path) {
<ide> newView = SC.getPath(thisContext, path);
<del> if (!newView) {
<del> throw new SC.Error("Unable to find view at path '" + path + "'");
<del> }
<add> sc_assert("Unable to find view at path '" + path + "'", !!newView);
<ide> } else {
<del> sc_assert('You must pass a string or a view class to the #view helper', SC.View.detect(path));
<ide> newView = path;
<ide> }
<ide>
<del> sc_assert("Null or undefined object was passed to the #view helper. Did you mean to pass a property path string?", !!newView);
<add> sc_assert(SC.String.fmt('You must pass a view class to the #view helper, not %@ (%@)', [path, newView]), SC.View.detect(newView));
<ide>
<ide> newView = this.viewClassFromHTMLOptions(newView, hash);
<ide> var currentView = data.view;
<ide> var viewOptions = {};
<del> if (fn) { viewOptions.template = fn; }
<add>
<add> if (fn) {
<add> sc_assert("You cannot provide a template block if you also specified a templateName", !get(viewOptions, 'templateName') && !newView.PrototypeMixin.keys().indexOf('templateName') >= 0);
<add> viewOptions.template = fn;
<add> }
<ide>
<ide> currentView.appendChild(newView, viewOptions);
<ide> }
<ide> SC.Handlebars.ViewHelper = SC.Object.create({
<ide> @returns {String} HTML string
<ide> */
<ide> Handlebars.registerHelper('view', function(path, options) {
<add> sc_assert("The view helper only takes a single argument", arguments.length <= 2);
<add>
<ide> // If no path is provided, treat path param as options.
<ide> if (path && path.data && path.data.isRenderData) {
<ide> options = path;
<ide><path>packages/sproutcore-handlebars/tests/handlebars_test.js
<ide> test("should be able to bind element attributes using {{bindAttr}}", function()
<ide> equals(view.$('img').attr('alt'), "The SproutCore Logo", "updates alt attribute when content object is a hash");
<ide>
<ide> SC.run(function() {
<del> set(view, 'content', {
<add> set(view, 'content', SC.Object.create({
<ide> url: "http://www.sproutcore.com/assets/images/logo.png",
<del> title: function() {
<add> title: SC.computed(function() {
<ide> return "Nanananana SproutCore!";
<del> }
<del> });
<add> })
<add> }));
<ide> });
<ide>
<ide> equals(view.$('img').attr('alt'), "Nanananana SproutCore!", "updates alt attribute when title property is computed"); | 3 |
Javascript | Javascript | add user password test | 2b510239389f166470df571c9005ad66711f49b9 | <ide><path>tests/models/User_spec.js
<ide> var User = require('../../models/User');
<ide>
<ide> var mocha = require('mocha')
<ide> , chai = require('chai')
<add> , should = chai.should()
<ide> , expect = chai.expect
<ide> , mongoose = require('mongoose');
<ide>
<ide> describe('User attributes', function() {
<ide> });
<ide>
<ide> it('_id is a mongoDB ObjectId', function() {
<del> expect( user._id ).to.be.an.instanceOf(mongoose.Types.ObjectId);
<add> user._id.should.be.an.instanceOf(mongoose.Types.ObjectId);
<ide> });
<ide>
<ide> it('email should be a string', function() {
<del> expect( user.email ).to.be.a( 'string' );
<add> user.email.should.be.a( 'string' );
<add> });
<add>
<add> it('password should be a string', function() {
<add> expect( user.password ).to.be.a( 'string' );
<ide> });
<ide> })
<ide> | 1 |
Javascript | Javascript | reorganize $parse tests | aef3ef7b0380701323edac83b79f66fc44e382e3 | <ide><path>test/ng/parseSpec.js
<ide> describe('parser', function() {
<ide> expect(bCalled).toBe(true);
<ide> });
<ide>
<del> it('should not invoke filters unless the input/arguments change', function() {
<del> var filterCalled = false;
<del> $filterProvider.register('foo', valueFn(function(input) {
<del> filterCalled = true;
<del> return input;
<del> }));
<add> describe('filters', function() {
<add>
<add> it('should not be invoked unless the input/arguments change', function() {
<add> var filterCalled = false;
<add> $filterProvider.register('foo', valueFn(function(input) {
<add> filterCalled = true;
<add> return input;
<add> }));
<add>
<add> scope.$watch('a | foo:b:1');
<add> scope.a = 0;
<add> scope.$digest();
<add> expect(filterCalled).toBe(true);
<add>
<add> filterCalled = false;
<add> scope.$digest();
<add> expect(filterCalled).toBe(false);
<add>
<add> scope.a++;
<add> scope.$digest();
<add> expect(filterCalled).toBe(true);
<add> });
<ide>
<del> scope.$watch('a | foo:b:1');
<del> scope.a = 0;
<del> scope.$digest();
<del> expect(filterCalled).toBe(true);
<add> it('should always be invoked if they are marked as having $stateful', function() {
<add> var filterCalled = false;
<add> $filterProvider.register('foo', valueFn(extend(function(input) {
<add> filterCalled = true;
<add> return input;
<add> }, {$stateful: true})));
<add>
<add> scope.$watch('a | foo:b:1');
<add> scope.a = 0;
<add> scope.$digest();
<add> expect(filterCalled).toBe(true);
<add>
<add> filterCalled = false;
<add> scope.$digest();
<add> expect(filterCalled).toBe(true);
<add> });
<ide>
<del> filterCalled = false;
<del> scope.$digest();
<del> expect(filterCalled).toBe(false);
<add> it('should be treated as constant when input are constant', inject(function($parse) {
<add> var filterCalls = 0;
<add> $filterProvider.register('foo', valueFn(function(input) {
<add> filterCalls++;
<add> return input;
<add> }));
<ide>
<del> scope.a++;
<del> scope.$digest();
<del> expect(filterCalled).toBe(true);
<del> });
<add> var parsed = $parse('{x: 1} | foo:1');
<ide>
<del> it('should invoke filters if they are marked as having $stateful', function() {
<del> var filterCalled = false;
<del> $filterProvider.register('foo', valueFn(extend(function(input) {
<del> filterCalled = true;
<del> return input;
<del> }, {$stateful: true})));
<add> expect(parsed.constant).toBe(true);
<ide>
<del> scope.$watch('a | foo:b:1');
<del> scope.a = 0;
<del> scope.$digest();
<del> expect(filterCalled).toBe(true);
<add> var watcherCalls = 0;
<add> scope.$watch(parsed, function(input) {
<add> expect(input).toEqual({x:1});
<add> watcherCalls++;
<add> });
<ide>
<del> filterCalled = false;
<del> scope.$digest();
<del> expect(filterCalled).toBe(true);
<del> });
<add> scope.$digest();
<add> expect(filterCalls).toBe(1);
<add> expect(watcherCalls).toBe(1);
<ide>
<del> it('should not invoke interceptorFns unless the input changes', inject(function($parse) {
<del> var called = false;
<del> function interceptor(v) {
<del> called = true;
<del> return v;
<del> }
<del> scope.$watch($parse('a', interceptor));
<del> scope.$watch($parse('a + b', interceptor));
<del> scope.a = scope.b = 0;
<del> scope.$digest();
<del> expect(called).toBe(true);
<add> scope.$digest();
<add> expect(filterCalls).toBe(1);
<add> expect(watcherCalls).toBe(1);
<add> }));
<ide>
<del> called = false;
<del> scope.$digest();
<del> expect(called).toBe(false);
<add> describe('with non-primitive input', function() {
<ide>
<del> scope.a++;
<del> scope.$digest();
<del> expect(called).toBe(true);
<del> }));
<add> describe('that does NOT support valueOf()', function() {
<ide>
<del> it('should not invoke interceptorFns unless the input.valueOf changes even if the instance changes', inject(function($parse) {
<del> var called = false;
<del> function interceptor(v) {
<del> called = true;
<del> return v;
<del> }
<del> scope.$watch($parse('a', interceptor));
<del> scope.a = new Date();
<del> scope.$digest();
<del> expect(called).toBe(true);
<add> it('should always be reevaluated', inject(function($parse) {
<add> var filterCalls = 0;
<add> $filterProvider.register('foo', valueFn(function(input) {
<add> filterCalls++;
<add> return input;
<add> }));
<ide>
<del> called = false;
<del> scope.a = new Date(scope.a.valueOf());
<del> scope.$digest();
<del> expect(called).toBe(false);
<del> }));
<add> var parsed = $parse('obj | foo');
<add> var obj = scope.obj = {};
<ide>
<del> it('should invoke interceptorFns if input.valueOf changes even if the instance does not', inject(function($parse) {
<del> var called = false;
<del> function interceptor(v) {
<del> called = true;
<del> return v;
<del> }
<del> scope.$watch($parse('a', interceptor));
<del> scope.a = new Date();
<del> scope.$digest();
<del> expect(called).toBe(true);
<add> var watcherCalls = 0;
<add> scope.$watch(parsed, function(input) {
<add> expect(input).toBe(obj);
<add> watcherCalls++;
<add> });
<ide>
<del> called = false;
<del> scope.a.setTime(scope.a.getTime() + 1);
<del> scope.$digest();
<del> expect(called).toBe(true);
<del> }));
<add> scope.$digest();
<add> expect(filterCalls).toBe(2);
<add> expect(watcherCalls).toBe(1);
<ide>
<del> it('should invoke interceptors when the expression is `undefined`', inject(function($parse) {
<del> var called = false;
<del> function interceptor(v) {
<del> called = true;
<del> return v;
<del> }
<del> scope.$watch($parse(undefined, interceptor));
<del> scope.$digest();
<del> expect(called).toBe(true);
<del> }));
<add> scope.$digest();
<add> expect(filterCalls).toBe(3);
<add> expect(watcherCalls).toBe(1);
<add> }));
<ide>
<del> it('should treat filters with constant input as constants', inject(function($parse) {
<del> var filterCalls = 0;
<del> $filterProvider.register('foo', valueFn(function(input) {
<del> filterCalls++;
<del> return input;
<del> }));
<add> it('should always be reevaluated in literals', inject(function($parse) {
<add> $filterProvider.register('foo', valueFn(function(input) {
<add> return input.b > 0;
<add> }));
<ide>
<del> var parsed = $parse('{x: 1} | foo:1');
<add> scope.$watch('[(a | foo)]', function() {});
<ide>
<del> expect(parsed.constant).toBe(true);
<add> // Would be great if filter-output was checked for changes and this didn't throw...
<add> expect(function() { scope.$apply('a = {b: 1}'); }).toThrowMinErr('$rootScope', 'infdig');
<add> }));
<ide>
<del> var watcherCalls = 0;
<del> scope.$watch(parsed, function(input) {
<del> expect(input).toEqual({x:1});
<del> watcherCalls++;
<del> });
<add> it('should always be reevaluated when passed literals', inject(function($parse) {
<add> scope.$watch('[a] | filter', function() {});
<ide>
<del> scope.$digest();
<del> expect(filterCalls).toBe(1);
<del> expect(watcherCalls).toBe(1);
<add> scope.$apply('a = 1');
<ide>
<del> scope.$digest();
<del> expect(filterCalls).toBe(1);
<del> expect(watcherCalls).toBe(1);
<del> }));
<add> // Would be great if filter-output was checked for changes and this didn't throw...
<add> expect(function() { scope.$apply('a = {}'); }).toThrowMinErr('$rootScope', 'infdig');
<add> }));
<add> });
<ide>
<del> it('should always reevaluate filters with non-primitive input that doesn\'t support valueOf()',
<del> inject(function($parse) {
<del> var filterCalls = 0;
<del> $filterProvider.register('foo', valueFn(function(input) {
<del> filterCalls++;
<del> return input;
<del> }));
<add> describe('that does support valueOf()', function() {
<add>
<add> it('should not be reevaluated',
<add> inject(function($parse) {
<add> var filterCalls = 0;
<add> $filterProvider.register('foo', valueFn(function(input) {
<add> filterCalls++;
<add> expect(input instanceof Date).toBe(true);
<add> return input;
<add> }));
<add>
<add> var parsed = $parse('date | foo:a');
<add> var date = scope.date = new Date();
<add>
<add> var watcherCalls = 0;
<add> scope.$watch(parsed, function(input) {
<add> expect(input).toBe(date);
<add> watcherCalls++;
<add> });
<add>
<add> scope.$digest();
<add> expect(filterCalls).toBe(1);
<add> expect(watcherCalls).toBe(1);
<add>
<add> scope.$digest();
<add> expect(filterCalls).toBe(1);
<add> expect(watcherCalls).toBe(1);
<add> }));
<ide>
<del> var parsed = $parse('obj | foo');
<del> var obj = scope.obj = {};
<add> it('should not be reevaluated in literals', inject(function($parse) {
<add> var filterCalls = 0;
<add> $filterProvider.register('foo', valueFn(function(input) {
<add> filterCalls++;
<add> return input;
<add> }));
<ide>
<del> var watcherCalls = 0;
<del> scope.$watch(parsed, function(input) {
<del> expect(input).toBe(obj);
<del> watcherCalls++;
<del> });
<add> scope.date = new Date(1234567890123);
<ide>
<del> scope.$digest();
<del> expect(filterCalls).toBe(2);
<del> expect(watcherCalls).toBe(1);
<add> var watcherCalls = 0;
<add> scope.$watch('[(date | foo)]', function(input) {
<add> watcherCalls++;
<add> });
<ide>
<del> scope.$digest();
<del> expect(filterCalls).toBe(3);
<del> expect(watcherCalls).toBe(1);
<del> }));
<add> scope.$digest();
<add> expect(filterCalls).toBe(1);
<add> expect(watcherCalls).toBe(1);
<ide>
<del> it('should not reevaluate filters in literals with non-primitive input that does support valueOf()',
<del> inject(function($parse) {
<del> var filterCalls = 0;
<del> $filterProvider.register('foo', valueFn(function(input) {
<del> filterCalls++;
<del> return input;
<del> }));
<add> scope.$digest();
<add> expect(filterCalls).toBe(1);
<add> expect(watcherCalls).toBe(1);
<add> }));
<ide>
<del> scope.date = new Date(1234567890123);
<add> it('should be reevaluated when valueOf() changes', inject(function($parse) {
<add> var filterCalls = 0;
<add> $filterProvider.register('foo', valueFn(function(input) {
<add> filterCalls++;
<add> expect(input instanceof Date).toBe(true);
<add> return input;
<add> }));
<ide>
<del> var watcherCalls = 0;
<del> scope.$watch('[(date | foo)]', function(input) {
<del> watcherCalls++;
<del> });
<add> var parsed = $parse('date | foo:a');
<add> var date = scope.date = new Date();
<ide>
<del> scope.$digest();
<del> expect(filterCalls).toBe(1);
<del> expect(watcherCalls).toBe(1);
<add> var watcherCalls = 0;
<add> scope.$watch(parsed, function(input) {
<add> expect(input).toBe(date);
<add> watcherCalls++;
<add> });
<ide>
<del> scope.$digest();
<del> expect(filterCalls).toBe(1);
<del> expect(watcherCalls).toBe(1);
<del> }));
<add> scope.$digest();
<add> expect(filterCalls).toBe(1);
<add> expect(watcherCalls).toBe(1);
<ide>
<del> it('should reevaluate filters in literals with non-primitive input that does support valueOf() when' +
<del> ' valueOf() value changes',
<del> inject(function($parse) {
<del> var filterCalls = 0;
<del> $filterProvider.register('foo', valueFn(function(input) {
<del> filterCalls++;
<del> return input;
<del> }));
<add> date.setYear(1901);
<ide>
<del> scope.date = new Date(1234567890123);
<add> scope.$digest();
<add> expect(filterCalls).toBe(2);
<add> expect(watcherCalls).toBe(1);
<add> }));
<ide>
<del> var watcherCalls = 0;
<del> scope.$watch('[(date | foo)]', function(input) {
<del> watcherCalls++;
<del> });
<add> it('should be reevaluated in literals when valueOf() changes', inject(function($parse) {
<add> var filterCalls = 0;
<add> $filterProvider.register('foo', valueFn(function(input) {
<add> filterCalls++;
<add> return input;
<add> }));
<ide>
<del> scope.$digest();
<del> expect(filterCalls).toBe(1);
<del> expect(watcherCalls).toBe(1);
<add> scope.date = new Date(1234567890123);
<ide>
<del> scope.date.setTime(1234567890);
<add> var watcherCalls = 0;
<add> scope.$watch('[(date | foo)]', function(input) {
<add> watcherCalls++;
<add> });
<ide>
<del> scope.$digest();
<del> expect(filterCalls).toBe(2);
<del> expect(watcherCalls).toBe(2);
<del> }));
<add> scope.$digest();
<add> expect(filterCalls).toBe(1);
<add> expect(watcherCalls).toBe(1);
<ide>
<del> it('should not reevaluate literals containing filters with non-primitive input that does support valueOf()' +
<del> ' when the instance changes but valueOf() does not', inject(function($parse) {
<del> var filterCalls = 0;
<del> $filterProvider.register('foo', valueFn(function(input) {
<del> filterCalls++;
<del> return input;
<del> }));
<add> scope.date.setTime(1234567890);
<ide>
<del> scope.date = new Date(1234567890123);
<add> scope.$digest();
<add> expect(filterCalls).toBe(2);
<add> expect(watcherCalls).toBe(2);
<add> }));
<ide>
<del> var watcherCalls = 0;
<del> scope.$watch($parse('[(date | foo)]'), function(input) {
<del> watcherCalls++;
<del> });
<add> it('should not be reevaluated when the instance changes but valueOf() does not', inject(function($parse) {
<add> var filterCalls = 0;
<add> $filterProvider.register('foo', valueFn(function(input) {
<add> filterCalls++;
<add> return input;
<add> }));
<ide>
<del> scope.$digest();
<del> expect(watcherCalls).toBe(1);
<del> expect(filterCalls).toBe(1);
<add> scope.date = new Date(1234567890123);
<ide>
<del> scope.date = new Date(1234567890123);
<del> scope.$digest();
<del> expect(watcherCalls).toBe(1);
<del> expect(filterCalls).toBe(1);
<del> }));
<add> var watcherCalls = 0;
<add> scope.$watch($parse('[(date | foo)]'), function(input) {
<add> watcherCalls++;
<add> });
<ide>
<del> it('should not reevaluate filters with literal input containing primitives', inject(function($parse) {
<del> var filterCalls = 0;
<del> $filterProvider.register('foo', valueFn(function(input) {
<del> filterCalls++;
<del> return input;
<del> }));
<add> scope.$digest();
<add> expect(watcherCalls).toBe(1);
<add> expect(filterCalls).toBe(1);
<ide>
<del> var watcherCalls = 0;
<del> scope.$watch('[a] | foo', function(input) {
<del> watcherCalls++;
<del> });
<add> scope.date = new Date(1234567890123);
<add> scope.$digest();
<add> expect(watcherCalls).toBe(1);
<add> expect(filterCalls).toBe(1);
<add> }));
<add> });
<ide>
<del> scope.$apply('a = 1');
<del> expect(filterCalls).toBe(1);
<del> expect(watcherCalls).toBe(1);
<add> it('should not be reevaluated when input is simplified via unary operators', inject(function($parse) {
<add> var filterCalls = 0;
<add> $filterProvider.register('foo', valueFn(function(input) {
<add> filterCalls++;
<add> return input;
<add> }));
<ide>
<del> scope.$apply('a = 2');
<del> expect(filterCalls).toBe(2);
<del> expect(watcherCalls).toBe(2);
<del> }));
<add> scope.obj = {};
<ide>
<del> it('should not reevaluate filters within literals with primitive inputs', inject(function($parse) {
<del> var filterCalls = 0;
<del> $filterProvider.register('foo', valueFn(function(input) {
<del> filterCalls++;
<del> return input;
<del> }));
<add> var watcherCalls = 0;
<add> scope.$watch('!obj | foo:!obj', function(input) {
<add> watcherCalls++;
<add> });
<ide>
<del> scope.prim = 1234567890123;
<add> scope.$digest();
<add> expect(filterCalls).toBe(1);
<add> expect(watcherCalls).toBe(1);
<ide>
<del> var watcherCalls = 0;
<del> scope.$watch('[(prim | foo)]', function(input) {
<del> watcherCalls++;
<del> });
<add> scope.$digest();
<add> expect(filterCalls).toBe(1);
<add> expect(watcherCalls).toBe(1);
<add> }));
<ide>
<del> scope.$digest();
<del> expect(filterCalls).toBe(1);
<del> expect(watcherCalls).toBe(1);
<add> it('should not be reevaluated when input is simplified via non-plus/concat binary operators', inject(function($parse) {
<add> var filterCalls = 0;
<add> $filterProvider.register('foo', valueFn(function(input) {
<add> filterCalls++;
<add> return input;
<add> }));
<ide>
<del> scope.$digest();
<del> expect(filterCalls).toBe(1);
<del> expect(watcherCalls).toBe(1);
<del> }));
<add> scope.obj = {};
<ide>
<del> it('should always reevaluate filters with non-primitive inputs within literals',
<del> inject(function($parse) {
<del> $filterProvider.register('foo', valueFn(function(input) {
<del> return input.b > 0;
<del> }));
<add> var watcherCalls = 0;
<add> scope.$watch('1 - obj | foo:(1 * obj)', function(input) {
<add> watcherCalls++;
<add> });
<ide>
<del> scope.$watch('[(a | foo)]', function() {});
<add> scope.$digest();
<add> expect(filterCalls).toBe(1);
<add> expect(watcherCalls).toBe(1);
<ide>
<del> // Would be great if filter-output was checked for changes and this didn't throw...
<del> expect(function() { scope.$apply('a = {b: 1}'); }).toThrowMinErr('$rootScope', 'infdig');
<del> }));
<add> scope.$digest();
<add> expect(filterCalls).toBe(1);
<add> expect(watcherCalls).toBe(1);
<add> }));
<ide>
<del> it('should always reevaluate filters with literal input containing non-primitives',
<del> inject(function($parse) {
<del> scope.$watch('[a] | filter', function() {});
<add> it('should be reevaluated when input is simplified via plus/concat', inject(function($parse) {
<add> var filterCalls = 0;
<add> $filterProvider.register('foo', valueFn(function(input) {
<add> filterCalls++;
<add> return input;
<add> }));
<ide>
<del> scope.$apply('a = 1');
<add> scope.obj = {};
<ide>
<del> // Would be great if filter-output was checked for changes and this didn't throw...
<del> expect(function() { scope.$apply('a = {}'); }).toThrowMinErr('$rootScope', 'infdig');
<del> }));
<add> var watcherCalls = 0;
<add> scope.$watch('1 + obj | foo', function(input) {
<add> watcherCalls++;
<add> });
<ide>
<del> it('should not reevaluate filters with non-primitive input that gets simplified via unary operators',
<del> inject(function($parse) {
<del> var filterCalls = 0;
<del> $filterProvider.register('foo', valueFn(function(input) {
<del> filterCalls++;
<del> return input;
<del> }));
<add> scope.$digest();
<add> expect(filterCalls).toBe(2);
<add> expect(watcherCalls).toBe(1);
<ide>
<del> scope.obj = {};
<add> scope.$digest();
<add> expect(filterCalls).toBe(3);
<add> expect(watcherCalls).toBe(1);
<add> }));
<ide>
<del> var watcherCalls = 0;
<del> scope.$watch('!obj | foo:!obj', function(input) {
<del> watcherCalls++;
<del> });
<add> it('should reevaluate computed member expressions', inject(function($parse) {
<add> var toStringCalls = 0;
<ide>
<del> scope.$digest();
<del> expect(filterCalls).toBe(1);
<del> expect(watcherCalls).toBe(1);
<add> scope.obj = {};
<add> scope.key = {
<add> toString: function() {
<add> toStringCalls++;
<add> return 'foo';
<add> }
<add> };
<add>
<add> var watcherCalls = 0;
<add> scope.$watch('obj[key]', function(input) {
<add> watcherCalls++;
<add> });
<add>
<add> scope.$digest();
<add> expect(toStringCalls).toBe(2);
<add> expect(watcherCalls).toBe(1);
<add>
<add> scope.$digest();
<add> expect(toStringCalls).toBe(3);
<add> expect(watcherCalls).toBe(1);
<add> }));
<add>
<add> it('should be reevaluated with input created with null prototype', inject(function($parse) {
<add> var filterCalls = 0;
<add> $filterProvider.register('foo', valueFn(function(input) {
<add> filterCalls++;
<add> return input;
<add> }));
<ide>
<del> scope.$digest();
<del> expect(filterCalls).toBe(1);
<del> expect(watcherCalls).toBe(1);
<del> }));
<add> var parsed = $parse('obj | foo');
<add> var obj = scope.obj = Object.create(null);
<ide>
<del> it('should not reevaluate filters with non-primitive input that gets simplified via non plus/concat binary operators',
<del> inject(function($parse) {
<del> var filterCalls = 0;
<del> $filterProvider.register('foo', valueFn(function(input) {
<del> filterCalls++;
<del> return input;
<del> }));
<add> var watcherCalls = 0;
<add> scope.$watch(parsed, function(input) {
<add> expect(input).toBe(obj);
<add> watcherCalls++;
<add> });
<ide>
<del> scope.obj = {};
<add> scope.$digest();
<add> expect(filterCalls).toBe(2);
<add> expect(watcherCalls).toBe(1);
<ide>
<del> var watcherCalls = 0;
<del> scope.$watch('1 - obj | foo:(1 * obj)', function(input) {
<del> watcherCalls++;
<add> scope.$digest();
<add> expect(filterCalls).toBe(3);
<add> expect(watcherCalls).toBe(1);
<add> }));
<ide> });
<ide>
<del> scope.$digest();
<del> expect(filterCalls).toBe(1);
<del> expect(watcherCalls).toBe(1);
<add> describe('with primitive input', function() {
<ide>
<del> scope.$digest();
<del> expect(filterCalls).toBe(1);
<del> expect(watcherCalls).toBe(1);
<del> }));
<add> it('should not be reevaluated when passed literals', inject(function($parse) {
<add> var filterCalls = 0;
<add> $filterProvider.register('foo', valueFn(function(input) {
<add> filterCalls++;
<add> return input;
<add> }));
<ide>
<del> it('should reevaluate filters with non-primitive input that gets simplified via plus/concat', inject(function($parse) {
<del> var filterCalls = 0;
<del> $filterProvider.register('foo', valueFn(function(input) {
<del> filterCalls++;
<del> return input;
<del> }));
<add> var watcherCalls = 0;
<add> scope.$watch('[a] | foo', function(input) {
<add> watcherCalls++;
<add> });
<add>
<add> scope.$apply('a = 1');
<add> expect(filterCalls).toBe(1);
<add> expect(watcherCalls).toBe(1);
<add>
<add> scope.$apply('a = 2');
<add> expect(filterCalls).toBe(2);
<add> expect(watcherCalls).toBe(2);
<add> }));
<add>
<add> it('should not be reevaluated in literals', inject(function($parse) {
<add> var filterCalls = 0;
<add> $filterProvider.register('foo', valueFn(function(input) {
<add> filterCalls++;
<add> return input;
<add> }));
<ide>
<del> scope.obj = {};
<add> scope.prim = 1234567890123;
<ide>
<del> var watcherCalls = 0;
<del> scope.$watch('1 + obj | foo', function(input) {
<del> watcherCalls++;
<del> });
<add> var watcherCalls = 0;
<add> scope.$watch('[(prim | foo)]', function(input) {
<add> watcherCalls++;
<add> });
<ide>
<del> scope.$digest();
<del> expect(filterCalls).toBe(2);
<del> expect(watcherCalls).toBe(1);
<add> scope.$digest();
<add> expect(filterCalls).toBe(1);
<add> expect(watcherCalls).toBe(1);
<ide>
<del> scope.$digest();
<del> expect(filterCalls).toBe(3);
<del> expect(watcherCalls).toBe(1);
<del> }));
<add> scope.$digest();
<add> expect(filterCalls).toBe(1);
<add> expect(watcherCalls).toBe(1);
<add> }));
<add> });
<add> });
<ide>
<del> it('should reevaluate computed member expressions with non-primitive input', inject(function($parse) {
<del> var toStringCalls = 0;
<add> describe('interceptorFns', function() {
<ide>
<del> scope.obj = {};
<del> scope.key = {
<del> toString: function() {
<del> toStringCalls++;
<del> return 'foo';
<add> it('should always be invoked if they are flagged as having $stateful',
<add> inject(function($parse) {
<add> var called = false;
<add> function interceptor() {
<add> called = true;
<ide> }
<del> };
<add> interceptor.$stateful = true;
<ide>
<del> var watcherCalls = 0;
<del> scope.$watch('obj[key]', function(input) {
<del> watcherCalls++;
<del> });
<add> scope.$watch($parse('a', interceptor));
<add> scope.a = 0;
<add> scope.$digest();
<add> expect(called).toBe(true);
<ide>
<del> scope.$digest();
<del> expect(toStringCalls).toBe(2);
<del> expect(watcherCalls).toBe(1);
<add> called = false;
<add> scope.$digest();
<add> expect(called).toBe(true);
<ide>
<del> scope.$digest();
<del> expect(toStringCalls).toBe(3);
<del> expect(watcherCalls).toBe(1);
<del> }));
<add> scope.a++;
<add> called = false;
<add> scope.$digest();
<add> expect(called).toBe(true);
<add> }));
<ide>
<del> it('should always reevaluate filters with non-primitive input created with null prototype',
<del> inject(function($parse) {
<del> var filterCalls = 0;
<del> $filterProvider.register('foo', valueFn(function(input) {
<del> filterCalls++;
<del> return input;
<add> it('should not be invoked unless the input changes', inject(function($parse) {
<add> var called = false;
<add> function interceptor(v) {
<add> called = true;
<add> return v;
<add> }
<add> scope.$watch($parse('a', interceptor));
<add> scope.$watch($parse('a + b', interceptor));
<add> scope.a = scope.b = 0;
<add> scope.$digest();
<add> expect(called).toBe(true);
<add>
<add> called = false;
<add> scope.$digest();
<add> expect(called).toBe(false);
<add>
<add> scope.a++;
<add> scope.$digest();
<add> expect(called).toBe(true);
<ide> }));
<ide>
<del> var parsed = $parse('obj | foo');
<del> var obj = scope.obj = Object.create(null);
<add> it('should not be invoked unless the input.valueOf() changes even if the instance changes', inject(function($parse) {
<add> var called = false;
<add> function interceptor(v) {
<add> called = true;
<add> return v;
<add> }
<add> scope.$watch($parse('a', interceptor));
<add> scope.a = new Date();
<add> scope.$digest();
<add> expect(called).toBe(true);
<add>
<add> called = false;
<add> scope.a = new Date(scope.a.valueOf());
<add> scope.$digest();
<add> expect(called).toBe(false);
<add> }));
<ide>
<del> var watcherCalls = 0;
<del> scope.$watch(parsed, function(input) {
<del> expect(input).toBe(obj);
<del> watcherCalls++;
<del> });
<add> it('should be invoked if input.valueOf() changes even if the instance does not', inject(function($parse) {
<add> var called = false;
<add> function interceptor(v) {
<add> called = true;
<add> return v;
<add> }
<add> scope.$watch($parse('a', interceptor));
<add> scope.a = new Date();
<add> scope.$digest();
<add> expect(called).toBe(true);
<add>
<add> called = false;
<add> scope.a.setTime(scope.a.getTime() + 1);
<add> scope.$digest();
<add> expect(called).toBe(true);
<add> }));
<ide>
<del> scope.$digest();
<del> expect(filterCalls).toBe(2);
<del> expect(watcherCalls).toBe(1);
<add> it('should be invoked when the expression is `undefined`', inject(function($parse) {
<add> var called = false;
<add> function interceptor(v) {
<add> called = true;
<add> return v;
<add> }
<add> scope.$watch($parse(undefined, interceptor));
<add> scope.$digest();
<add> expect(called).toBe(true);
<add> }));
<add> });
<ide>
<del> scope.$digest();
<del> expect(filterCalls).toBe(3);
<del> expect(watcherCalls).toBe(1);
<del> }));
<add> describe('literals', function() {
<ide>
<del> it('should not reevaluate filters with non-primitive input that does support valueOf()',
<del> inject(function($parse) {
<del> var filterCalls = 0;
<del> $filterProvider.register('foo', valueFn(function(input) {
<del> filterCalls++;
<del> expect(input instanceof Date).toBe(true);
<del> return input;
<del> }));
<add> it('should support watching', inject(function($parse) {
<add> var lastVal = NaN;
<add> var callCount = 0;
<add> var listener = function(val) { callCount++; lastVal = val; };
<ide>
<del> var parsed = $parse('date | foo:a');
<del> var date = scope.date = new Date();
<add> scope.$watch('{val: val}', listener);
<ide>
<del> var watcherCalls = 0;
<del> scope.$watch(parsed, function(input) {
<del> expect(input).toBe(date);
<del> watcherCalls++;
<del> });
<add> scope.$apply('val = 1');
<add> expect(callCount).toBe(1);
<add> expect(lastVal).toEqual({val: 1});
<ide>
<del> scope.$digest();
<del> expect(filterCalls).toBe(1);
<del> expect(watcherCalls).toBe(1);
<add> scope.$apply('val = []');
<add> expect(callCount).toBe(2);
<add> expect(lastVal).toEqual({val: []});
<ide>
<del> scope.$digest();
<del> expect(filterCalls).toBe(1);
<del> expect(watcherCalls).toBe(1);
<del> }));
<add> scope.$apply('val = []');
<add> expect(callCount).toBe(3);
<add> expect(lastVal).toEqual({val: []});
<ide>
<del> it('should reevaluate filters with non-primitive input that does support valueOf() when' +
<del> ' valueOf() value changes', inject(function($parse) {
<del> var filterCalls = 0;
<del> $filterProvider.register('foo', valueFn(function(input) {
<del> filterCalls++;
<del> expect(input instanceof Date).toBe(true);
<del> return input;
<add> scope.$apply('val = {}');
<add> expect(callCount).toBe(4);
<add> expect(lastVal).toEqual({val: {}});
<ide> }));
<ide>
<del> var parsed = $parse('date | foo:a');
<del> var date = scope.date = new Date();
<add> it('should only watch the direct inputs', inject(function($parse) {
<add> var lastVal = NaN;
<add> var callCount = 0;
<add> var listener = function(val) { callCount++; lastVal = val; };
<ide>
<del> var watcherCalls = 0;
<del> scope.$watch(parsed, function(input) {
<del> expect(input).toBe(date);
<del> watcherCalls++;
<del> });
<add> scope.$watch('{val: val}', listener);
<ide>
<del> scope.$digest();
<del> expect(filterCalls).toBe(1);
<del> expect(watcherCalls).toBe(1);
<add> scope.$apply('val = 1');
<add> expect(callCount).toBe(1);
<add> expect(lastVal).toEqual({val: 1});
<ide>
<del> date.setYear(1901);
<add> scope.$apply('val = [2]');
<add> expect(callCount).toBe(2);
<add> expect(lastVal).toEqual({val: [2]});
<ide>
<del> scope.$digest();
<del> expect(filterCalls).toBe(2);
<del> expect(watcherCalls).toBe(1);
<del> }));
<add> scope.$apply('val.push(3)');
<add> expect(callCount).toBe(2);
<ide>
<del> it('should always invoke interceptorFns if they are flagged as having $stateful',
<del> inject(function($parse) {
<del> var called = false;
<del> function interceptor() {
<del> called = true;
<del> }
<del> interceptor.$stateful = true;
<add> scope.$apply('val.length = 0');
<add> expect(callCount).toBe(2);
<add> }));
<ide>
<del> scope.$watch($parse('a', interceptor));
<del> scope.a = 0;
<del> scope.$digest();
<del> expect(called).toBe(true);
<add> it('should only watch the direct inputs when nested', inject(function($parse) {
<add> var lastVal = NaN;
<add> var callCount = 0;
<add> var listener = function(val) { callCount++; lastVal = val; };
<ide>
<del> called = false;
<del> scope.$digest();
<del> expect(called).toBe(true);
<add> scope.$watch('[{val: [val]}]', listener);
<ide>
<del> scope.a++;
<del> called = false;
<del> scope.$digest();
<del> expect(called).toBe(true);
<del> }));
<add> scope.$apply('val = 1');
<add> expect(callCount).toBe(1);
<add> expect(lastVal).toEqual([{val: [1]}]);
<ide>
<del> it('should not reevaluate literals with non-primitive input', inject(function($parse) {
<del> var obj = scope.obj = {};
<add> scope.$apply('val = [2]');
<add> expect(callCount).toBe(2);
<add> expect(lastVal).toEqual([{val: [[2]]}]);
<ide>
<del> var parsed = $parse('[obj]');
<del> var watcherCalls = 0;
<del> scope.$watch(parsed, function(input) {
<del> expect(input[0]).toBe(obj);
<del> watcherCalls++;
<del> });
<add> scope.$apply('val.push(3)');
<add> expect(callCount).toBe(2);
<ide>
<del> scope.$digest();
<del> expect(watcherCalls).toBe(1);
<add> scope.$apply('val.length = 0');
<add> expect(callCount).toBe(2);
<add> }));
<ide>
<del> scope.$digest();
<del> expect(watcherCalls).toBe(1);
<del> }));
<add> describe('with non-primative input', function() {
<ide>
<del> it('should not reevaluate literals with non-primitive input that does support valueOf()',
<del> inject(function($parse) {
<add> describe('that does NOT support valueOf()', function() {
<add> it('should not be reevaluated', inject(function($parse) {
<add> var obj = scope.obj = {};
<ide>
<del> var date = scope.date = new Date();
<add> var parsed = $parse('[obj]');
<add> var watcherCalls = 0;
<add> scope.$watch(parsed, function(input) {
<add> expect(input[0]).toBe(obj);
<add> watcherCalls++;
<add> });
<ide>
<del> var parsed = $parse('[date]');
<del> var watcherCalls = 0;
<del> scope.$watch(parsed, function(input) {
<del> expect(input[0]).toBe(date);
<del> watcherCalls++;
<del> });
<add> scope.$digest();
<add> expect(watcherCalls).toBe(1);
<ide>
<del> scope.$digest();
<del> expect(watcherCalls).toBe(1);
<add> scope.$digest();
<add> expect(watcherCalls).toBe(1);
<add> }));
<add> });
<ide>
<del> scope.$digest();
<del> expect(watcherCalls).toBe(1);
<del> }));
<add> describe('that does support valueOf()', function() {
<add> it('should not be reevaluated', inject(function($parse) {
<add> var date = scope.date = new Date();
<ide>
<del> it('should reevaluate literals with non-primitive input when valueOf() changes', inject(function($parse) {
<del> var date = scope.date = new Date();
<add> var parsed = $parse('[date]');
<add> var watcherCalls = 0;
<add> scope.$watch(parsed, function(input) {
<add> expect(input[0]).toBe(date);
<add> watcherCalls++;
<add> });
<ide>
<del> var parsed = $parse('[date]');
<del> var watcherCalls = 0;
<del> scope.$watch(parsed, function(input) {
<del> expect(input[0]).toBe(date);
<del> watcherCalls++;
<del> });
<add> scope.$digest();
<add> expect(watcherCalls).toBe(1);
<ide>
<del> scope.$digest();
<del> expect(watcherCalls).toBe(1);
<add> scope.$digest();
<add> expect(watcherCalls).toBe(1);
<add> }));
<ide>
<del> date.setYear(1901);
<add> it('should be reevaluated even when valueOf() changes', inject(function($parse) {
<add> var date = scope.date = new Date();
<ide>
<del> scope.$digest();
<del> expect(watcherCalls).toBe(2);
<del> }));
<add> var parsed = $parse('[date]');
<add> var watcherCalls = 0;
<add> scope.$watch(parsed, function(input) {
<add> expect(input[0]).toBe(date);
<add> watcherCalls++;
<add> });
<ide>
<del> it('should not reevaluate literals with non-primitive input that does support valueOf()' +
<del> ' when the instance changes but valueOf() does not', inject(function($parse) {
<add> scope.$digest();
<add> expect(watcherCalls).toBe(1);
<ide>
<del> scope.date = new Date(1234567890123);
<add> date.setYear(1901);
<ide>
<del> var parsed = $parse('[date]');
<del> var watcherCalls = 0;
<del> scope.$watch(parsed, function(input) {
<del> watcherCalls++;
<del> });
<add> scope.$digest();
<add> expect(watcherCalls).toBe(2);
<add> }));
<ide>
<del> scope.$digest();
<del> expect(watcherCalls).toBe(1);
<add> it('should not be reevaluated when the instance changes but valueOf() does not', inject(function($parse) {
<add> scope.date = new Date(1234567890123);
<ide>
<del> scope.date = new Date(1234567890123);
<del> scope.$digest();
<del> expect(watcherCalls).toBe(1);
<del> }));
<add> var parsed = $parse('[date]');
<add> var watcherCalls = 0;
<add> scope.$watch(parsed, function(input) {
<add> watcherCalls++;
<add> });
<ide>
<del> it('should reevaluate literals with non-primitive input that does support valueOf()' +
<del> ' when the instance does not change but valueOf() does', inject(function($parse) {
<add> scope.$digest();
<add> expect(watcherCalls).toBe(1);
<ide>
<del> scope.date = new Date(1234567890123);
<add> scope.date = new Date(1234567890123);
<add> scope.$digest();
<add> expect(watcherCalls).toBe(1);
<add> }));
<ide>
<del> var parsed = $parse('[date]');
<del> var watcherCalls = 0;
<del> scope.$watch(parsed, function(input) {
<del> watcherCalls++;
<del> });
<add> it('should be reevaluated when the instance does not change but valueOf() does', inject(function($parse) {
<ide>
<del> scope.$digest();
<del> expect(watcherCalls).toBe(1);
<add> scope.date = new Date(1234567890123);
<ide>
<del> scope.date.setTime(scope.date.getTime() + 1);
<del> scope.$digest();
<del> expect(watcherCalls).toBe(2);
<del> }));
<add> var parsed = $parse('[date]');
<add> var watcherCalls = 0;
<add> scope.$watch(parsed, function(input) {
<add> watcherCalls++;
<add> });
<add>
<add> scope.$digest();
<add> expect(watcherCalls).toBe(1);
<add>
<add> scope.date.setTime(scope.date.getTime() + 1);
<add> scope.$digest();
<add> expect(watcherCalls).toBe(2);
<add> }));
<add> });
<add> });
<add> });
<ide>
<ide> it('should continue with the evaluation of the expression without invoking computed parts',
<ide> inject(function($parse) {
<ide> describe('parser', function() {
<ide> expect(count).toBe(4);
<ide> expect(values[3]).toEqual({'undefined': true});
<ide> });
<del>
<del> it('should support watching literals', inject(function($parse) {
<del> var lastVal = NaN;
<del> var callCount = 0;
<del> var listener = function(val) { callCount++; lastVal = val; };
<del>
<del> scope.$watch('{val: val}', listener);
<del>
<del> scope.$apply('val = 1');
<del> expect(callCount).toBe(1);
<del> expect(lastVal).toEqual({val: 1});
<del>
<del> scope.$apply('val = []');
<del> expect(callCount).toBe(2);
<del> expect(lastVal).toEqual({val: []});
<del>
<del> scope.$apply('val = []');
<del> expect(callCount).toBe(3);
<del> expect(lastVal).toEqual({val: []});
<del>
<del> scope.$apply('val = {}');
<del> expect(callCount).toBe(4);
<del> expect(lastVal).toEqual({val: {}});
<del> }));
<del>
<del> it('should only watch the direct inputs to literals', inject(function($parse) {
<del> var lastVal = NaN;
<del> var callCount = 0;
<del> var listener = function(val) { callCount++; lastVal = val; };
<del>
<del> scope.$watch('{val: val}', listener);
<del>
<del> scope.$apply('val = 1');
<del> expect(callCount).toBe(1);
<del> expect(lastVal).toEqual({val: 1});
<del>
<del> scope.$apply('val = [2]');
<del> expect(callCount).toBe(2);
<del> expect(lastVal).toEqual({val: [2]});
<del>
<del> scope.$apply('val.push(3)');
<del> expect(callCount).toBe(2);
<del>
<del> scope.$apply('val.length = 0');
<del> expect(callCount).toBe(2);
<del> }));
<del>
<del> it('should only watch the direct inputs to nested literals', inject(function($parse) {
<del> var lastVal = NaN;
<del> var callCount = 0;
<del> var listener = function(val) { callCount++; lastVal = val; };
<del>
<del> scope.$watch('[{val: [val]}]', listener);
<del>
<del> scope.$apply('val = 1');
<del> expect(callCount).toBe(1);
<del> expect(lastVal).toEqual([{val: [1]}]);
<del>
<del> scope.$apply('val = [2]');
<del> expect(callCount).toBe(2);
<del> expect(lastVal).toEqual([{val: [[2]]}]);
<del>
<del> scope.$apply('val.push(3)');
<del> expect(callCount).toBe(2);
<del>
<del> scope.$apply('val.length = 0');
<del> expect(callCount).toBe(2);
<del> }));
<ide> });
<ide>
<ide> describe('locals', function() { | 1 |
PHP | PHP | add unique method to message bag | 2bb3fae85458b0bc94554969d9e22bdf0c221152 | <ide><path>src/Illuminate/Support/MessageBag.php
<ide> public function all($format = null)
<ide> return $all;
<ide> }
<ide>
<add> /**
<add> * Get all of the unique messages for every key in the bag.
<add> *
<add> * @param string $format
<add> * @return array
<add> */
<add> public function unique($format = null)
<add> {
<add> return array_unique($this->all($format));
<add> }
<add>
<ide> /**
<ide> * Format an array of messages.
<ide> * | 1 |
Text | Text | remove empty list item | c87ae5f62ead51c58185b1b6663da064e19e8b89 | <ide><path>docs/focus/2018-04-16.md
<ide>
<ide> - Atom core
<ide> - Separated keyboard enablement from "readOnly" TextEditor state in [atom/atom#17124](https://github.com/atom/atom/pull/17124).
<del>- Atom IDE
<ide> - GitHub Package
<ide> - Completed, merged, and shipped "Create pull request" [atom/github#1376](https://github.com/atom/github/pull/1376), which I used to open this pull request :wink:
<ide> - Updated to Enzyme 3 [atom/github#1386](https://github.com/atom/github/pull/1386) which paves the way for us to upgrade React. | 1 |
Python | Python | remove unittest dependencies in numpy/ma/tests | d51030ad61fe449752e4330eadf6cb25fbee2f2a | <ide><path>numpy/ma/tests/test_core.py
<ide> import numpy.core.fromnumeric as fromnumeric
<ide> import numpy.core.umath as umath
<ide> from numpy.testing import (
<del> TestCase, run_module_suite, assert_raises, assert_warns, suppress_warnings
<add> run_module_suite, assert_raises, assert_warns, suppress_warnings
<ide> )
<ide> from numpy import ndarray
<ide> from numpy.compat import asbytes, asbytes_nested
<ide> "setting an item on a masked array which has a shared mask will not copy")
<ide>
<ide>
<del>class TestMaskedArray(TestCase):
<add>class TestMaskedArray(object):
<ide> # Base test class for MaskedArrays.
<ide>
<del> def setUp(self):
<add> def setup(self):
<ide> # Base data definition.
<ide> x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
<ide> y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
<ide> def test_basic0d(self):
<ide> x = masked_array(0, mask=False)
<ide> assert_equal(str(x), '0')
<ide> x = array(0, mask=1)
<del> self.assertTrue(x.filled().dtype is x._data.dtype)
<add> assert_(x.filled().dtype is x._data.dtype)
<ide>
<ide> def test_basic1d(self):
<ide> # Test of basic array creation and properties in 1 dimension.
<ide> (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
<del> self.assertTrue(not isMaskedArray(x))
<del> self.assertTrue(isMaskedArray(xm))
<del> self.assertTrue((xm - ym).filled(0).any())
<add> assert_(not isMaskedArray(x))
<add> assert_(isMaskedArray(xm))
<add> assert_((xm - ym).filled(0).any())
<ide> fail_if_equal(xm.mask.astype(int), ym.mask.astype(int))
<ide> s = x.shape
<ide> assert_equal(np.shape(xm), s)
<ide> def test_basic2d(self):
<ide> ym.shape = s
<ide> xf.shape = s
<ide>
<del> self.assertTrue(not isMaskedArray(x))
<del> self.assertTrue(isMaskedArray(xm))
<add> assert_(not isMaskedArray(x))
<add> assert_(isMaskedArray(xm))
<ide> assert_equal(shape(xm), s)
<ide> assert_equal(xm.shape, s)
<ide> assert_equal(xm.size, reduce(lambda x, y:x * y, s))
<ide> def test_creation_with_list_of_maskedarrays(self):
<ide> x.mask = nomask
<ide> data = array((x, x[::-1]))
<ide> assert_equal(data, [[0, 1, 2, 3, 4], [4, 3, 2, 1, 0]])
<del> self.assertTrue(data.mask is nomask)
<add> assert_(data.mask is nomask)
<ide>
<ide> def test_creation_from_ndarray_with_padding(self):
<ide> x = np.array([('A', 0)], dtype={'names':['f0','f1'],
<ide> def test_asarray(self):
<ide> def test_asarray_default_order(self):
<ide> # See Issue #6646
<ide> m = np.eye(3).T
<del> self.assertFalse(m.flags.c_contiguous)
<add> assert_(not m.flags.c_contiguous)
<ide>
<ide> new_m = asarray(m)
<del> self.assertTrue(new_m.flags.c_contiguous)
<add> assert_(new_m.flags.c_contiguous)
<ide>
<ide> def test_asarray_enforce_order(self):
<ide> # See Issue #6646
<ide> m = np.eye(3).T
<del> self.assertFalse(m.flags.c_contiguous)
<add> assert_(not m.flags.c_contiguous)
<ide>
<ide> new_m = asarray(m, order='C')
<del> self.assertTrue(new_m.flags.c_contiguous)
<add> assert_(new_m.flags.c_contiguous)
<ide>
<ide> def test_fix_invalid(self):
<ide> # Checks fix_invalid.
<ide> def test_maskedelement(self):
<ide> # Test of masked element
<ide> x = arange(6)
<ide> x[1] = masked
<del> self.assertTrue(str(masked) == '--')
<del> self.assertTrue(x[1] is masked)
<add> assert_(str(masked) == '--')
<add> assert_(x[1] is masked)
<ide> assert_equal(filled(x[1], 0), 0)
<ide>
<ide> def test_set_element_as_object(self):
<ide> def test_set_element_as_object(self):
<ide> x = (1, 2, 3, 4, 5)
<ide> a[0] = x
<ide> assert_equal(a[0], x)
<del> self.assertTrue(a[0] is x)
<add> assert_(a[0] is x)
<ide>
<ide> import datetime
<ide> dt = datetime.datetime.now()
<ide> a[0] = dt
<del> self.assertTrue(a[0] is dt)
<add> assert_(a[0] is dt)
<ide>
<ide> def test_indexing(self):
<ide> # Tests conversions and indexing
<ide> def test_copy(self):
<ide> n = [0, 0, 1, 0, 0]
<ide> m = make_mask(n)
<ide> m2 = make_mask(m)
<del> self.assertTrue(m is m2)
<add> assert_(m is m2)
<ide> m3 = make_mask(m, copy=1)
<del> self.assertTrue(m is not m3)
<add> assert_(m is not m3)
<ide>
<ide> x1 = np.arange(5)
<ide> y1 = array(x1, mask=m)
<ide> assert_equal(y1._data.__array_interface__, x1.__array_interface__)
<del> self.assertTrue(allequal(x1, y1.data))
<add> assert_(allequal(x1, y1.data))
<ide> assert_equal(y1._mask.__array_interface__, m.__array_interface__)
<ide>
<ide> y1a = array(y1)
<del> self.assertTrue(y1a._data.__array_interface__ ==
<add> assert_(y1a._data.__array_interface__ ==
<ide> y1._data.__array_interface__)
<del> self.assertTrue(y1a.mask is y1.mask)
<add> assert_(y1a.mask is y1.mask)
<ide>
<ide> y2 = array(x1, mask=m3)
<del> self.assertTrue(y2._data.__array_interface__ == x1.__array_interface__)
<del> self.assertTrue(y2._mask.__array_interface__ == m3.__array_interface__)
<del> self.assertTrue(y2[2] is masked)
<add> assert_(y2._data.__array_interface__ == x1.__array_interface__)
<add> assert_(y2._mask.__array_interface__ == m3.__array_interface__)
<add> assert_(y2[2] is masked)
<ide> y2[2] = 9
<del> self.assertTrue(y2[2] is not masked)
<del> self.assertTrue(y2._mask.__array_interface__ == m3.__array_interface__)
<del> self.assertTrue(allequal(y2.mask, 0))
<add> assert_(y2[2] is not masked)
<add> assert_(y2._mask.__array_interface__ == m3.__array_interface__)
<add> assert_(allequal(y2.mask, 0))
<ide>
<ide> y2a = array(x1, mask=m, copy=1)
<del> self.assertTrue(y2a._data.__array_interface__ != x1.__array_interface__)
<del> #self.assertTrue( y2a.mask is not m)
<del> self.assertTrue(y2a._mask.__array_interface__ != m.__array_interface__)
<del> self.assertTrue(y2a[2] is masked)
<add> assert_(y2a._data.__array_interface__ != x1.__array_interface__)
<add> #assert_( y2a.mask is not m)
<add> assert_(y2a._mask.__array_interface__ != m.__array_interface__)
<add> assert_(y2a[2] is masked)
<ide> y2a[2] = 9
<del> self.assertTrue(y2a[2] is not masked)
<del> #self.assertTrue( y2a.mask is not m)
<del> self.assertTrue(y2a._mask.__array_interface__ != m.__array_interface__)
<del> self.assertTrue(allequal(y2a.mask, 0))
<add> assert_(y2a[2] is not masked)
<add> #assert_( y2a.mask is not m)
<add> assert_(y2a._mask.__array_interface__ != m.__array_interface__)
<add> assert_(allequal(y2a.mask, 0))
<ide>
<ide> y3 = array(x1 * 1.0, mask=m)
<del> self.assertTrue(filled(y3).dtype is (x1 * 1.0).dtype)
<add> assert_(filled(y3).dtype is (x1 * 1.0).dtype)
<ide>
<ide> x4 = arange(4)
<ide> x4[2] = masked
<ide> def test_copy(self):
<ide>
<ide> def test_copy_on_python_builtins(self):
<ide> # Tests copy works on python builtins (issue#8019)
<del> self.assertTrue(isMaskedArray(np.ma.copy([1,2,3])))
<del> self.assertTrue(isMaskedArray(np.ma.copy((1,2,3))))
<add> assert_(isMaskedArray(np.ma.copy([1,2,3])))
<add> assert_(isMaskedArray(np.ma.copy((1,2,3))))
<ide>
<ide> def test_copy_immutable(self):
<ide> # Tests that the copy method is immutable, GitHub issue #5247
<ide> def test_pickling_subbaseclass(self):
<ide> a_pickled = pickle.loads(a.dumps())
<ide> assert_equal(a_pickled._mask, a._mask)
<ide> assert_equal(a_pickled, a)
<del> self.assertTrue(isinstance(a_pickled._data, np.matrix))
<add> assert_(isinstance(a_pickled._data, np.matrix))
<ide>
<ide> def test_pickling_maskedconstant(self):
<ide> # Test pickling MaskedConstant
<ide> def test_topython(self):
<ide> assert_equal(1.0, float(array(1)))
<ide> assert_equal(1, int(array([[[1]]])))
<ide> assert_equal(1.0, float(array([[1]])))
<del> self.assertRaises(TypeError, float, array([1, 1]))
<add> assert_raises(TypeError, float, array([1, 1]))
<ide>
<ide> with suppress_warnings() as sup:
<ide> sup.filter(UserWarning, 'Warning: converting a masked element')
<ide> assert_(np.isnan(float(array([1], mask=[1]))))
<ide>
<ide> a = array([1, 2, 3], mask=[1, 0, 0])
<del> self.assertRaises(TypeError, lambda: float(a))
<add> assert_raises(TypeError, lambda: float(a))
<ide> assert_equal(float(a[-1]), 3.)
<del> self.assertTrue(np.isnan(float(a[0])))
<del> self.assertRaises(TypeError, int, a)
<add> assert_(np.isnan(float(a[0])))
<add> assert_raises(TypeError, int, a)
<ide> assert_equal(int(a[-1]), 3)
<del> self.assertRaises(MAError, lambda:int(a[0]))
<add> assert_raises(MAError, lambda:int(a[0]))
<ide>
<ide> def test_oddfeatures_1(self):
<ide> # Test of other odd features
<ide> def test_filled_with_f_order(self):
<ide> a = array(np.array([(0, 1, 2), (4, 5, 6)], order='F'),
<ide> mask=np.array([(0, 0, 1), (1, 0, 0)], order='F'),
<ide> order='F') # this is currently ignored
<del> self.assertTrue(a.flags['F_CONTIGUOUS'])
<del> self.assertTrue(a.filled(0).flags['F_CONTIGUOUS'])
<add> assert_(a.flags['F_CONTIGUOUS'])
<add> assert_(a.filled(0).flags['F_CONTIGUOUS'])
<ide>
<ide> def test_optinfo_propagation(self):
<ide> # Checks that _optinfo dictionary isn't back-propagated
<ide> def test_mvoid_getitem(self):
<ide> dtype=ndtype)
<ide> # w/o mask
<ide> f = a[0]
<del> self.assertTrue(isinstance(f, mvoid))
<add> assert_(isinstance(f, mvoid))
<ide> assert_equal((f[0], f['a']), (1, 1))
<ide> assert_equal(f['b'], 2)
<ide> # w/ mask
<ide> f = a[1]
<del> self.assertTrue(isinstance(f, mvoid))
<del> self.assertTrue(f[0] is masked)
<del> self.assertTrue(f['a'] is masked)
<add> assert_(isinstance(f, mvoid))
<add> assert_(f[0] is masked)
<add> assert_(f['a'] is masked)
<ide> assert_equal(f[1], 4)
<ide>
<ide> # exotic dtype
<ide> def test_object_with_array(self):
<ide> assert_(mx2[0] == 0.)
<ide>
<ide>
<del>class TestMaskedArrayArithmetic(TestCase):
<add>class TestMaskedArrayArithmetic(object):
<ide> # Base test class for MaskedArrays.
<ide>
<del> def setUp(self):
<add> def setup(self):
<ide> # Base data definition.
<ide> x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
<ide> y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
<ide> def setUp(self):
<ide> self.err_status = np.geterr()
<ide> np.seterr(divide='ignore', invalid='ignore')
<ide>
<del> def tearDown(self):
<add> def teardown(self):
<ide> np.seterr(**self.err_status)
<ide>
<ide> def test_basic_arithmetic(self):
<ide> def test_mixed_arithmetic(self):
<ide> # Tests mixed arithmetics.
<ide> na = np.array([1])
<ide> ma = array([1])
<del> self.assertTrue(isinstance(na + ma, MaskedArray))
<del> self.assertTrue(isinstance(ma + na, MaskedArray))
<add> assert_(isinstance(na + ma, MaskedArray))
<add> assert_(isinstance(ma + na, MaskedArray))
<ide>
<ide> def test_limits_arithmetic(self):
<ide> tiny = np.finfo(float).tiny
<ide> def test_masked_singleton_arithmetic(self):
<ide> # Tests some scalar arithmetics on MaskedArrays.
<ide> # Masked singleton should remain masked no matter what
<ide> xm = array(0, mask=1)
<del> self.assertTrue((1 / array(0)).mask)
<del> self.assertTrue((1 + xm).mask)
<del> self.assertTrue((-xm).mask)
<del> self.assertTrue(maximum(xm, xm).mask)
<del> self.assertTrue(minimum(xm, xm).mask)
<add> assert_((1 / array(0)).mask)
<add> assert_((1 + xm).mask)
<add> assert_((-xm).mask)
<add> assert_(maximum(xm, xm).mask)
<add> assert_(minimum(xm, xm).mask)
<ide>
<ide> def test_masked_singleton_equality(self):
<ide> # Tests (in)equality on masked singleton
<ide> def test_count_func(self):
<ide>
<ide> ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0])
<ide> res = count(ott)
<del> self.assertTrue(res.dtype.type is np.intp)
<add> assert_(res.dtype.type is np.intp)
<ide> assert_equal(3, res)
<ide>
<ide> ott = ott.reshape((2, 2))
<ide> def test_minmax_func(self):
<ide> def test_minimummaximum_func(self):
<ide> a = np.ones((2, 2))
<ide> aminimum = minimum(a, a)
<del> self.assertTrue(isinstance(aminimum, MaskedArray))
<add> assert_(isinstance(aminimum, MaskedArray))
<ide> assert_equal(aminimum, np.minimum(a, a))
<ide>
<ide> aminimum = minimum.outer(a, a)
<del> self.assertTrue(isinstance(aminimum, MaskedArray))
<add> assert_(isinstance(aminimum, MaskedArray))
<ide> assert_equal(aminimum, np.minimum.outer(a, a))
<ide>
<ide> amaximum = maximum(a, a)
<del> self.assertTrue(isinstance(amaximum, MaskedArray))
<add> assert_(isinstance(amaximum, MaskedArray))
<ide> assert_equal(amaximum, np.maximum(a, a))
<ide>
<ide> amaximum = maximum.outer(a, a)
<del> self.assertTrue(isinstance(amaximum, MaskedArray))
<add> assert_(isinstance(amaximum, MaskedArray))
<ide> assert_equal(amaximum, np.maximum.outer(a, a))
<ide>
<ide> def test_minmax_reduce(self):
<ide> def test_minmax_funcs_with_output(self):
<ide> pass
<ide> nout = np.empty((4,), dtype=float)
<ide> result = npfunc(xm, axis=0, out=nout)
<del> self.assertTrue(result is nout)
<add> assert_(result is nout)
<ide> # Use the ma version
<ide> nout.fill(-999)
<ide> result = mafunc(xm, axis=0, out=nout)
<del> self.assertTrue(result is nout)
<add> assert_(result is nout)
<ide>
<ide> def test_minmax_methods(self):
<ide> # Additional tests on max/min
<ide> (_, _, _, _, _, xm, _, _, _, _) = self.d
<ide> xm.shape = (xm.size,)
<ide> assert_equal(xm.max(), 10)
<del> self.assertTrue(xm[0].max() is masked)
<del> self.assertTrue(xm[0].max(0) is masked)
<del> self.assertTrue(xm[0].max(-1) is masked)
<add> assert_(xm[0].max() is masked)
<add> assert_(xm[0].max(0) is masked)
<add> assert_(xm[0].max(-1) is masked)
<ide> assert_equal(xm.min(), -10.)
<del> self.assertTrue(xm[0].min() is masked)
<del> self.assertTrue(xm[0].min(0) is masked)
<del> self.assertTrue(xm[0].min(-1) is masked)
<add> assert_(xm[0].min() is masked)
<add> assert_(xm[0].min(0) is masked)
<add> assert_(xm[0].min(-1) is masked)
<ide> assert_equal(xm.ptp(), 20.)
<del> self.assertTrue(xm[0].ptp() is masked)
<del> self.assertTrue(xm[0].ptp(0) is masked)
<del> self.assertTrue(xm[0].ptp(-1) is masked)
<add> assert_(xm[0].ptp() is masked)
<add> assert_(xm[0].ptp(0) is masked)
<add> assert_(xm[0].ptp(-1) is masked)
<ide>
<ide> x = array([1, 2, 3], mask=True)
<del> self.assertTrue(x.min() is masked)
<del> self.assertTrue(x.max() is masked)
<del> self.assertTrue(x.ptp() is masked)
<add> assert_(x.min() is masked)
<add> assert_(x.max() is masked)
<add> assert_(x.ptp() is masked)
<ide>
<ide> def test_addsumprod(self):
<ide> # Tests add, sum, product.
<ide> def test_numpyarithmetics(self):
<ide> assert_equal(a.mask, [0, 0, 0, 0, 1])
<ide>
<ide>
<del>class TestMaskedArrayAttributes(TestCase):
<add>class TestMaskedArrayAttributes(object):
<ide>
<ide> def test_keepmask(self):
<ide> # Tests the keep mask flag
<ide> def test_hardmask(self):
<ide> assert_equal(xh._data, [0, 10, 2, 3, 4])
<ide> assert_equal(xs._data, [0, 10, 2, 3, 40])
<ide> assert_equal(xs.mask, [0, 0, 0, 1, 0])
<del> self.assertTrue(xh._hardmask)
<del> self.assertTrue(not xs._hardmask)
<add> assert_(xh._hardmask)
<add> assert_(not xs._hardmask)
<ide> xh[1:4] = [10, 20, 30]
<ide> xs[1:4] = [10, 20, 30]
<ide> assert_equal(xh._data, [0, 10, 20, 3, 4])
<ide> def test_flat(self):
<ide> test = masked_array(np.matrix([[1, 2, 3]]), mask=[0, 0, 1])
<ide> assert_equal(test.flat[1], 2)
<ide> assert_equal(test.flat[2], masked)
<del> self.assertTrue(np.all(test.flat[0:2] == test[0, 0:2]))
<add> assert_(np.all(test.flat[0:2] == test[0, 0:2]))
<ide> # Test flat on masked_matrices
<ide> test = masked_array(np.matrix([[1, 2, 3]]), mask=[0, 0, 1])
<ide> test.flat = masked_array([3, 2, 1], mask=[1, 0, 0])
<ide> def assign():
<ide> assert_equal(m._mask, np.ma.nomask)
<ide>
<ide>
<del>class TestFillingValues(TestCase):
<add>class TestFillingValues(object):
<ide>
<ide> def test_check_on_scalar(self):
<ide> # Test _check_fill_value set to valid and invalid values
<ide> def test_check_on_scalar(self):
<ide> assert_equal(fval, b"0")
<ide> fval = _check_fill_value(None, "|S3")
<ide> assert_equal(fval, default_fill_value(b"camelot!"))
<del> self.assertRaises(TypeError, _check_fill_value, 1e+20, int)
<del> self.assertRaises(TypeError, _check_fill_value, 'stuff', int)
<add> assert_raises(TypeError, _check_fill_value, 1e+20, int)
<add> assert_raises(TypeError, _check_fill_value, 'stuff', int)
<ide>
<ide> def test_check_on_fields(self):
<ide> # Tests _check_fill_value with records
<ide> _check_fill_value = np.ma.core._check_fill_value
<ide> ndtype = [('a', int), ('b', float), ('c', "|S3")]
<ide> # A check on a list should return a single record
<ide> fval = _check_fill_value([-999, -12345678.9, "???"], ndtype)
<del> self.assertTrue(isinstance(fval, ndarray))
<add> assert_(isinstance(fval, ndarray))
<ide> assert_equal(fval.item(), [-999, -12345678.9, b"???"])
<ide> # A check on None should output the defaults
<ide> fval = _check_fill_value(None, ndtype)
<del> self.assertTrue(isinstance(fval, ndarray))
<add> assert_(isinstance(fval, ndarray))
<ide> assert_equal(fval.item(), [default_fill_value(0),
<ide> default_fill_value(0.),
<ide> asbytes(default_fill_value("0"))])
<ide> #.....Using a structured type as fill_value should work
<ide> fill_val = np.array((-999, -12345678.9, "???"), dtype=ndtype)
<ide> fval = _check_fill_value(fill_val, ndtype)
<del> self.assertTrue(isinstance(fval, ndarray))
<add> assert_(isinstance(fval, ndarray))
<ide> assert_equal(fval.item(), [-999, -12345678.9, b"???"])
<ide>
<ide> #.....Using a flexible type w/ a different type shouldn't matter
<ide> def test_check_on_fields(self):
<ide> # suppress deprecation warning in 1.12 (remove in 1.13)
<ide> with assert_warns(FutureWarning):
<ide> fval = _check_fill_value(fill_val, ndtype)
<del> self.assertTrue(isinstance(fval, ndarray))
<add> assert_(isinstance(fval, ndarray))
<ide> assert_equal(fval.item(), [-999, -12345678.9, b"???"])
<ide>
<ide> #.....Using an object-array shouldn't matter either
<ide> fill_val = np.ndarray(shape=(1,), dtype=object)
<ide> fill_val[0] = (-999, -12345678.9, b"???")
<ide> fval = _check_fill_value(fill_val, object)
<del> self.assertTrue(isinstance(fval, ndarray))
<add> assert_(isinstance(fval, ndarray))
<ide> assert_equal(fval.item(), [-999, -12345678.9, b"???"])
<ide> # NOTE: This test was never run properly as "fill_value" rather than
<ide> # "fill_val" was assigned. Written properly, it fails.
<ide> #fill_val = np.array((-999, -12345678.9, "???"))
<ide> #fval = _check_fill_value(fill_val, ndtype)
<del> #self.assertTrue(isinstance(fval, ndarray))
<add> #assert_(isinstance(fval, ndarray))
<ide> #assert_equal(fval.item(), [-999, -12345678.9, b"???"])
<ide> #.....One-field-only flexible type should work as well
<ide> ndtype = [("a", int)]
<ide> fval = _check_fill_value(-999999999, ndtype)
<del> self.assertTrue(isinstance(fval, ndarray))
<add> assert_(isinstance(fval, ndarray))
<ide> assert_equal(fval.item(), (-999999999,))
<ide>
<ide> def test_fillvalue_conversion(self):
<ide> def test_fillvalue_bytes_or_str(self):
<ide> assert_equal(a["f1"].fill_value, default_fill_value("eggs"))
<ide>
<ide>
<del>class TestUfuncs(TestCase):
<add>class TestUfuncs(object):
<ide> # Test class for the application of ufuncs on MaskedArrays.
<ide>
<del> def setUp(self):
<add> def setup(self):
<ide> # Base data definition.
<ide> self.d = (array([1.0, 0, -1, pi / 2] * 2, mask=[0, 1] + [0] * 6),
<ide> array([1.0, 0, -1, pi / 2] * 2, mask=[1, 0] + [0] * 6),)
<ide> self.err_status = np.geterr()
<ide> np.seterr(divide='ignore', invalid='ignore')
<ide>
<del> def tearDown(self):
<add> def teardown(self):
<ide> np.seterr(**self.err_status)
<ide>
<ide> def test_testUfuncRegression(self):
<ide> def test_testUfuncRegression(self):
<ide> def test_reduce(self):
<ide> # Tests reduce on MaskedArrays.
<ide> a = self.d[0]
<del> self.assertTrue(not alltrue(a, axis=0))
<del> self.assertTrue(sometrue(a, axis=0))
<add> assert_(not alltrue(a, axis=0))
<add> assert_(sometrue(a, axis=0))
<ide> assert_equal(sum(a[:3], axis=0), 0)
<ide> assert_equal(product(a, axis=0), 0)
<ide> assert_equal(add.reduce(a), pi)
<ide> def test_minmax(self):
<ide> assert_equal(amask.min(), 5)
<ide> assert_equal(amask.max(0), a.max(0))
<ide> assert_equal(amask.min(0), [5, 6, 7, 8])
<del> self.assertTrue(amask.max(1)[0].mask)
<del> self.assertTrue(amask.min(1)[0].mask)
<add> assert_(amask.max(1)[0].mask)
<add> assert_(amask.min(1)[0].mask)
<ide>
<ide> def test_ndarray_mask(self):
<ide> # Check that the mask of the result is a ndarray (not a MaskedArray...)
<ide> def test_ndarray_mask(self):
<ide> mask=[1, 0, 0, 0, 1])
<ide> assert_equal(test, control)
<ide> assert_equal(test.mask, control.mask)
<del> self.assertTrue(not isinstance(test.mask, MaskedArray))
<add> assert_(not isinstance(test.mask, MaskedArray))
<ide>
<ide> def test_treatment_of_NotImplemented(self):
<ide> # Check that NotImplemented is returned at appropriate places
<ide>
<ide> a = masked_array([1., 2.], mask=[1, 0])
<del> self.assertRaises(TypeError, operator.mul, a, "abc")
<del> self.assertRaises(TypeError, operator.truediv, a, "abc")
<add> assert_raises(TypeError, operator.mul, a, "abc")
<add> assert_raises(TypeError, operator.truediv, a, "abc")
<ide>
<ide> class MyClass(object):
<ide> __array_priority__ = a.__array_priority__ + 1
<ide> def test_no_masked_nan_warnings(self):
<ide> # also check that allclose uses ma ufuncs, to avoid warning
<ide> allclose(m, 0.5)
<ide>
<del>class TestMaskedArrayInPlaceArithmetics(TestCase):
<add>class TestMaskedArrayInPlaceArithmetics(object):
<ide> # Test MaskedArray Arithmetics
<ide>
<del> def setUp(self):
<add> def setup(self):
<ide> x = arange(10)
<ide> y = arange(10)
<ide> xm = arange(10)
<ide> def test_inplace_pow_type(self):
<ide> assert_equal(len(w), 0, "Failed on type=%s." % t)
<ide>
<ide>
<del>class TestMaskedArrayMethods(TestCase):
<add>class TestMaskedArrayMethods(object):
<ide> # Test class for miscellaneous MaskedArrays methods.
<del> def setUp(self):
<add> def setup(self):
<ide> # Base data definition.
<ide> x = np.array([8.375, 7.545, 8.828, 8.5, 1.757, 5.928,
<ide> 8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
<ide> def test_allclose(self):
<ide> # Tests allclose on arrays
<ide> a = np.random.rand(10)
<ide> b = a + np.random.rand(10) * 1e-8
<del> self.assertTrue(allclose(a, b))
<add> assert_(allclose(a, b))
<ide> # Test allclose w/ infs
<ide> a[0] = np.inf
<del> self.assertTrue(not allclose(a, b))
<add> assert_(not allclose(a, b))
<ide> b[0] = np.inf
<del> self.assertTrue(allclose(a, b))
<add> assert_(allclose(a, b))
<ide> # Test allclose w/ masked
<ide> a = masked_array(a)
<ide> a[-1] = masked
<del> self.assertTrue(allclose(a, b, masked_equal=True))
<del> self.assertTrue(not allclose(a, b, masked_equal=False))
<add> assert_(allclose(a, b, masked_equal=True))
<add> assert_(not allclose(a, b, masked_equal=False))
<ide> # Test comparison w/ scalar
<ide> a *= 1e-8
<ide> a[0] = 0
<del> self.assertTrue(allclose(a, 0, masked_equal=True))
<add> assert_(allclose(a, 0, masked_equal=True))
<ide>
<ide> # Test that the function works for MIN_INT integer typed arrays
<ide> a = masked_array([np.iinfo(np.int_).min], dtype=np.int_)
<del> self.assertTrue(allclose(a, a))
<add> assert_(allclose(a, a))
<ide>
<ide> def test_allany(self):
<ide> # Checks the any/all methods/functions.
<ide> def test_allany(self):
<ide> mxbig = (mx > 0.5)
<ide> mxsmall = (mx < 0.5)
<ide>
<del> self.assertFalse(mxbig.all())
<del> self.assertTrue(mxbig.any())
<add> assert_(not mxbig.all())
<add> assert_(mxbig.any())
<ide> assert_equal(mxbig.all(0), [False, False, True])
<ide> assert_equal(mxbig.all(1), [False, False, True])
<ide> assert_equal(mxbig.any(0), [False, False, True])
<ide> assert_equal(mxbig.any(1), [True, True, True])
<ide>
<del> self.assertFalse(mxsmall.all())
<del> self.assertTrue(mxsmall.any())
<add> assert_(not mxsmall.all())
<add> assert_(mxsmall.any())
<ide> assert_equal(mxsmall.all(0), [True, True, False])
<ide> assert_equal(mxsmall.all(1), [False, False, False])
<ide> assert_equal(mxsmall.any(0), [True, True, False])
<ide> def test_allany_onmatrices(self):
<ide> mXbig = (mX > 0.5)
<ide> mXsmall = (mX < 0.5)
<ide>
<del> self.assertFalse(mXbig.all())
<del> self.assertTrue(mXbig.any())
<add> assert_(not mXbig.all())
<add> assert_(mXbig.any())
<ide> assert_equal(mXbig.all(0), np.matrix([False, False, True]))
<ide> assert_equal(mXbig.all(1), np.matrix([False, False, True]).T)
<ide> assert_equal(mXbig.any(0), np.matrix([False, False, True]))
<ide> assert_equal(mXbig.any(1), np.matrix([True, True, True]).T)
<ide>
<del> self.assertFalse(mXsmall.all())
<del> self.assertTrue(mXsmall.any())
<add> assert_(not mXsmall.all())
<add> assert_(mXsmall.any())
<ide> assert_equal(mXsmall.all(0), np.matrix([True, True, False]))
<ide> assert_equal(mXsmall.all(1), np.matrix([False, False, False]).T)
<ide> assert_equal(mXsmall.any(0), np.matrix([True, True, False]))
<ide> def test_allany_oddities(self):
<ide> store = empty((), dtype=bool)
<ide> full = array([1, 2, 3], mask=True)
<ide>
<del> self.assertTrue(full.all() is masked)
<add> assert_(full.all() is masked)
<ide> full.all(out=store)
<del> self.assertTrue(store)
<del> self.assertTrue(store._mask, True)
<del> self.assertTrue(store is not masked)
<add> assert_(store)
<add> assert_(store._mask, True)
<add> assert_(store is not masked)
<ide>
<ide> store = empty((), dtype=bool)
<del> self.assertTrue(full.any() is masked)
<add> assert_(full.any() is masked)
<ide> full.any(out=store)
<del> self.assertTrue(not store)
<del> self.assertTrue(store._mask, True)
<del> self.assertTrue(store is not masked)
<add> assert_(not store)
<add> assert_(store._mask, True)
<add> assert_(store is not masked)
<ide>
<ide> def test_argmax_argmin(self):
<ide> # Tests argmin & argmax on MaskedArrays.
<ide> def test_compressed(self):
<ide> a = array(np.matrix([1, 2, 3, 4]), mask=[0, 0, 0, 0])
<ide> b = a.compressed()
<ide> assert_equal(b, a)
<del> self.assertTrue(isinstance(b, np.matrix))
<add> assert_(isinstance(b, np.matrix))
<ide> a[0, 0] = masked
<ide> b = a.compressed()
<ide> assert_equal(b, [[2, 3, 4]])
<ide> def test_put(self):
<ide> n = [0, 0, 0, 1, 1]
<ide> m = make_mask(n)
<ide> x = array(d, mask=m)
<del> self.assertTrue(x[3] is masked)
<del> self.assertTrue(x[4] is masked)
<add> assert_(x[3] is masked)
<add> assert_(x[4] is masked)
<ide> x[[1, 4]] = [10, 40]
<del> self.assertTrue(x[3] is masked)
<del> self.assertTrue(x[4] is not masked)
<add> assert_(x[3] is masked)
<add> assert_(x[4] is not masked)
<ide> assert_equal(x, [0, 10, 2, -1, 40])
<ide>
<ide> x = masked_array(arange(10), mask=[1, 0, 0, 0, 0] * 2)
<ide> def test_put_nomask(self):
<ide> z = array([3., -1.], mask=[False, True])
<ide>
<ide> x.put([1, 2], z)
<del> self.assertTrue(x[0] is not masked)
<add> assert_(x[0] is not masked)
<ide> assert_equal(x[0], 0)
<del> self.assertTrue(x[1] is not masked)
<add> assert_(x[1] is not masked)
<ide> assert_equal(x[1], 3)
<del> self.assertTrue(x[2] is masked)
<del> self.assertTrue(x[3] is not masked)
<add> assert_(x[2] is masked)
<add> assert_(x[3] is not masked)
<ide> assert_equal(x[3], 0)
<ide>
<ide> def test_put_hardmask(self):
<ide> def test_sort(self):
<ide>
<ide> x = [1, 4, 2, 3]
<ide> sortedx = sort(x)
<del> self.assertTrue(not isinstance(sorted, MaskedArray))
<add> assert_(not isinstance(sorted, MaskedArray))
<ide>
<ide> x = array([0, 1, -1, -2, 2], mask=nomask, dtype=np.int8)
<ide> sortedx = sort(x, endwith=False)
<ide> def test_squeeze(self):
<ide> assert_equal(data.squeeze(), [1, 2, 3])
<ide> assert_equal(data.squeeze()._mask, [1, 1, 1])
<ide> data = masked_array([[1]], mask=True)
<del> self.assertTrue(data.squeeze() is masked)
<add> assert_(data.squeeze() is masked)
<ide>
<ide> def test_swapaxes(self):
<ide> # Tests swapaxes on MaskedArrays.
<ide> def test_take(self):
<ide> masked_array([[10, 20], [10, 20]], [[0, 1], [0, 1]]))
<ide>
<ide> # assert_equal crashes when passed np.ma.mask
<del> self.assertIs(x[1], np.ma.masked)
<del> self.assertIs(x.take(1), np.ma.masked)
<add> assert_(x[1] is np.ma.masked)
<add> assert_(x.take(1) is np.ma.masked)
<ide>
<ide> x = array([[10, 20, 30], [40, 50, 60]], mask=[[0, 0, 1], [1, 0, 0, ]])
<ide> assert_equal(x.take([0, 2], axis=1),
<ide> def test_tolist(self):
<ide> x = array(np.arange(12))
<ide> x[[1, -2]] = masked
<ide> xlist = x.tolist()
<del> self.assertTrue(xlist[1] is None)
<del> self.assertTrue(xlist[-2] is None)
<add> assert_(xlist[1] is None)
<add> assert_(xlist[-2] is None)
<ide> # ... on 2D
<ide> x.shape = (3, 4)
<ide> xlist = x.tolist()
<ide> def test_arraymethod(self):
<ide> assert_equal(MaskedArray.cumsum(marray.T, 0), control.cumsum(0))
<ide>
<ide>
<del>class TestMaskedArrayMathMethods(TestCase):
<add>class TestMaskedArrayMathMethods(object):
<ide>
<del> def setUp(self):
<add> def setup(self):
<ide> # Base data definition.
<ide> x = np.array([8.375, 7.545, 8.828, 8.5, 1.757, 5.928,
<ide> 8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
<ide> def test_cumsumprod_with_output(self):
<ide> output.fill(-9999)
<ide> result = npfunc(xm, axis=0, out=output)
<ide> # ... the result should be the given output
<del> self.assertTrue(result is output)
<add> assert_(result is output)
<ide> assert_equal(result, xmmeth(axis=0, out=output))
<ide>
<ide> output = empty((3, 4), dtype=int)
<ide> result = xmmeth(axis=0, out=output)
<del> self.assertTrue(result is output)
<add> assert_(result is output)
<ide>
<ide> def test_ptp(self):
<ide> # Tests ptp on MaskedArrays.
<ide> def test_varstd_specialcases(self):
<ide> x = array(arange(10), mask=True)
<ide> for methodname in ('var', 'std'):
<ide> method = getattr(x, methodname)
<del> self.assertTrue(method() is masked)
<del> self.assertTrue(method(0) is masked)
<del> self.assertTrue(method(-1) is masked)
<add> assert_(method() is masked)
<add> assert_(method(0) is masked)
<add> assert_(method(-1) is masked)
<ide> # Using a masked array as explicit output
<ide> method(out=mout)
<del> self.assertTrue(mout is not masked)
<add> assert_(mout is not masked)
<ide> assert_equal(mout.mask, True)
<ide> # Using a ndarray as explicit output
<ide> method(out=nout)
<del> self.assertTrue(np.isnan(nout))
<add> assert_(np.isnan(nout))
<ide>
<ide> x = array(arange(10), mask=True)
<ide> x[-1] = 9
<ide> for methodname in ('var', 'std'):
<ide> method = getattr(x, methodname)
<del> self.assertTrue(method(ddof=1) is masked)
<del> self.assertTrue(method(0, ddof=1) is masked)
<del> self.assertTrue(method(-1, ddof=1) is masked)
<add> assert_(method(ddof=1) is masked)
<add> assert_(method(0, ddof=1) is masked)
<add> assert_(method(-1, ddof=1) is masked)
<ide> # Using a masked array as explicit output
<ide> method(out=mout, ddof=1)
<del> self.assertTrue(mout is not masked)
<add> assert_(mout is not masked)
<ide> assert_equal(mout.mask, True)
<ide> # Using a ndarray as explicit output
<ide> method(out=nout, ddof=1)
<del> self.assertTrue(np.isnan(nout))
<add> assert_(np.isnan(nout))
<ide>
<ide> def test_varstd_ddof(self):
<ide> a = array([[1, 1, 0], [1, 1, 0]], mask=[[0, 0, 1], [0, 0, 1]])
<ide> def test_axis_methods_nomask(self):
<ide> assert_equal(a.max(1), [3, 6])
<ide>
<ide>
<del>class TestMaskedArrayMathMethodsComplex(TestCase):
<add>class TestMaskedArrayMathMethodsComplex(object):
<ide> # Test class for miscellaneous MaskedArrays methods.
<del> def setUp(self):
<add> def setup(self):
<ide> # Base data definition.
<ide> x = np.array([8.375j, 7.545j, 8.828j, 8.5j, 1.757j, 5.928,
<ide> 8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
<ide> def test_varstd(self):
<ide> mX[:, k].compressed().std())
<ide>
<ide>
<del>class TestMaskedArrayFunctions(TestCase):
<add>class TestMaskedArrayFunctions(object):
<ide> # Test class for miscellaneous functions.
<ide>
<del> def setUp(self):
<add> def setup(self):
<ide> x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
<ide> y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
<ide> m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
<ide> def test_round_with_output(self):
<ide> output.fill(-9999)
<ide> result = np.round(xm, decimals=2, out=output)
<ide> # ... the result should be the given output
<del> self.assertTrue(result is output)
<add> assert_(result is output)
<ide> assert_equal(result, xm.round(decimals=2, out=output))
<ide>
<ide> output = empty((3, 4), dtype=float)
<ide> result = xm.round(decimals=2, out=output)
<del> self.assertTrue(result is output)
<add> assert_(result is output)
<ide>
<ide> def test_round_with_scalar(self):
<ide> # Testing round with scalar/zero dimension input
<ide> def test_round_with_scalar(self):
<ide>
<ide> def test_identity(self):
<ide> a = identity(5)
<del> self.assertTrue(isinstance(a, MaskedArray))
<add> assert_(isinstance(a, MaskedArray))
<ide> assert_equal(a, np.identity(5))
<ide>
<ide> def test_power(self):
<ide> x = -1.1
<ide> assert_almost_equal(power(x, 2.), 1.21)
<del> self.assertTrue(power(x, masked) is masked)
<add> assert_(power(x, masked) is masked)
<ide> x = array([-1.1, -1.1, 1.1, 1.1, 0.])
<ide> b = array([0.5, 2., 0.5, 2., -1.], mask=[0, 0, 0, 0, 1])
<ide> y = power(x, b)
<ide> def test_choose_with_out(self):
<ide> store = empty(4, dtype=int)
<ide> chosen = choose([2, 3, 1, 0], choices, out=store)
<ide> assert_equal(store, array([20, 31, 12, 3]))
<del> self.assertTrue(store is chosen)
<add> assert_(store is chosen)
<ide> # Check with some masked indices + out
<ide> store = empty(4, dtype=int)
<ide> indices_ = array([2, 3, 1, 0], mask=[1, 0, 0, 1])
<ide> def test_reshape(self):
<ide> # Try the default
<ide> b = a.reshape((5, 2))
<ide> assert_equal(b.shape, (5, 2))
<del> self.assertTrue(b.flags['C'])
<add> assert_(b.flags['C'])
<ide> # Try w/ arguments as list instead of tuple
<ide> b = a.reshape(5, 2)
<ide> assert_equal(b.shape, (5, 2))
<del> self.assertTrue(b.flags['C'])
<add> assert_(b.flags['C'])
<ide> # Try w/ order
<ide> b = a.reshape((5, 2), order='F')
<ide> assert_equal(b.shape, (5, 2))
<del> self.assertTrue(b.flags['F'])
<add> assert_(b.flags['F'])
<ide> # Try w/ order
<ide> b = a.reshape(5, 2, order='F')
<ide> assert_equal(b.shape, (5, 2))
<del> self.assertTrue(b.flags['F'])
<add> assert_(b.flags['F'])
<ide>
<ide> c = np.reshape(a, (2, 5))
<del> self.assertTrue(isinstance(c, MaskedArray))
<add> assert_(isinstance(c, MaskedArray))
<ide> assert_equal(c.shape, (2, 5))
<del> self.assertTrue(c[0, 0] is masked)
<del> self.assertTrue(c.flags['C'])
<add> assert_(c[0, 0] is masked)
<add> assert_(c.flags['C'])
<ide>
<ide> def test_make_mask_descr(self):
<ide> # Flexible
<ide> def test_convolve(self):
<ide> assert_equal(test, masked_equal([-1, -1, -1, -1, -1], -1))
<ide>
<ide>
<del>class TestMaskedFields(TestCase):
<add>class TestMaskedFields(object):
<ide>
<del> def setUp(self):
<add> def setup(self):
<ide> ilist = [1, 2, 3, 4, 5]
<ide> flist = [1.1, 2.2, 3.3, 4.4, 5.5]
<ide> slist = ['one', 'two', 'three', 'four', 'five']
<ide> def test_view(self):
<ide>
<ide> test = a.view((float, 2), np.matrix)
<ide> assert_equal(test, data)
<del> self.assertTrue(isinstance(test, np.matrix))
<add> assert_(isinstance(test, np.matrix))
<ide>
<ide> def test_getitem(self):
<ide> ndtype = [('a', float), ('b', float)]
<ide> def test_element_len(self):
<ide> assert_equal(len(rec), len(self.data['ddtype']))
<ide>
<ide>
<del>class TestMaskedObjectArray(TestCase):
<add>class TestMaskedObjectArray(object):
<ide>
<ide> def test_getitem(self):
<ide> arr = np.ma.array([None, None])
<ide> def test_nested_ma(self):
<ide> assert_(arr[0] is np.ma.masked)
<ide>
<ide>
<del>class TestMaskedView(TestCase):
<add>class TestMaskedView(object):
<ide>
<del> def setUp(self):
<add> def setup(self):
<ide> iterator = list(zip(np.arange(10), np.random.rand(10)))
<ide> data = np.array(iterator)
<ide> a = array(iterator, dtype=[('a', float), ('b', float)])
<ide> def setUp(self):
<ide> def test_view_to_nothing(self):
<ide> (data, a, controlmask) = self.data
<ide> test = a.view()
<del> self.assertTrue(isinstance(test, MaskedArray))
<add> assert_(isinstance(test, MaskedArray))
<ide> assert_equal(test._data, a._data)
<ide> assert_equal(test._mask, a._mask)
<ide>
<ide> def test_view_to_type(self):
<ide> (data, a, controlmask) = self.data
<ide> test = a.view(np.ndarray)
<del> self.assertTrue(not isinstance(test, MaskedArray))
<add> assert_(not isinstance(test, MaskedArray))
<ide> assert_equal(test, a._data)
<ide> assert_equal_records(test, data.view(a.dtype).squeeze())
<ide>
<ide> def test_view_to_simple_dtype(self):
<ide> (data, a, controlmask) = self.data
<ide> # View globally
<ide> test = a.view(float)
<del> self.assertTrue(isinstance(test, MaskedArray))
<add> assert_(isinstance(test, MaskedArray))
<ide> assert_equal(test, data.ravel())
<ide> assert_equal(test.mask, controlmask)
<ide>
<ide> def test_view_to_flexible_dtype(self):
<ide> assert_equal(test['B'], a['b'])
<ide>
<ide> test = a[0].view([('A', float), ('B', float)])
<del> self.assertTrue(isinstance(test, MaskedArray))
<add> assert_(isinstance(test, MaskedArray))
<ide> assert_equal(test.mask.dtype.names, ('A', 'B'))
<ide> assert_equal(test['A'], a['a'][0])
<ide> assert_equal(test['B'], a['b'][0])
<ide>
<ide> test = a[-1].view([('A', float), ('B', float)])
<del> self.assertTrue(isinstance(test, MaskedArray))
<add> assert_(isinstance(test, MaskedArray))
<ide> assert_equal(test.dtype.names, ('A', 'B'))
<ide> assert_equal(test['A'], a['a'][-1])
<ide> assert_equal(test['B'], a['b'][-1])
<ide> def test_view_to_subdtype(self):
<ide> (data, a, controlmask) = self.data
<ide> # View globally
<ide> test = a.view((float, 2))
<del> self.assertTrue(isinstance(test, MaskedArray))
<add> assert_(isinstance(test, MaskedArray))
<ide> assert_equal(test, data)
<ide> assert_equal(test.mask, controlmask.reshape(-1, 2))
<ide> # View on 1 masked element
<ide> test = a[0].view((float, 2))
<del> self.assertTrue(isinstance(test, MaskedArray))
<add> assert_(isinstance(test, MaskedArray))
<ide> assert_equal(test, data[0])
<ide> assert_equal(test.mask, (1, 0))
<ide> # View on 1 unmasked element
<ide> test = a[-1].view((float, 2))
<del> self.assertTrue(isinstance(test, MaskedArray))
<add> assert_(isinstance(test, MaskedArray))
<ide> assert_equal(test, data[-1])
<ide>
<ide> def test_view_to_dtype_and_type(self):
<ide> (data, a, controlmask) = self.data
<ide>
<ide> test = a.view((float, 2), np.matrix)
<ide> assert_equal(test, data)
<del> self.assertTrue(isinstance(test, np.matrix))
<del> self.assertTrue(not isinstance(test, MaskedArray))
<add> assert_(isinstance(test, np.matrix))
<add> assert_(not isinstance(test, MaskedArray))
<ide>
<del>class TestOptionalArgs(TestCase):
<add>class TestOptionalArgs(object):
<ide> def test_ndarrayfuncs(self):
<ide> # test axis arg behaves the same as ndarray (including multiple axes)
<ide>
<ide> def test_count(self):
<ide> assert_raises(np.AxisError, count, np.ma.array(1), axis=1)
<ide>
<ide>
<del>class TestMaskedConstant(TestCase):
<add>class TestMaskedConstant(object):
<ide> def _do_add_test(self, add):
<ide> # sanity check
<del> self.assertIs(add(np.ma.masked, 1), np.ma.masked)
<add> assert_(add(np.ma.masked, 1) is np.ma.masked)
<ide>
<ide> # now try with a vector
<ide> vector = np.array([1, 2, 3])
<ide><path>numpy/ma/tests/test_deprecations.py
<ide> from __future__ import division, absolute_import, print_function
<ide>
<ide> import numpy as np
<del>from numpy.testing import TestCase, run_module_suite, assert_warns
<add>from numpy.testing import run_module_suite, assert_warns
<ide> from numpy.ma.testutils import assert_equal
<ide> from numpy.ma.core import MaskedArrayFutureWarning
<ide>
<del>class TestArgsort(TestCase):
<add>class TestArgsort(object):
<ide> """ gh-8701 """
<ide> def _test_base(self, argsort, cls):
<ide> arr_0d = np.array(1).view(cls)
<ide> def test_method(self):
<ide> return self._test_base(np.ma.MaskedArray.argsort, np.ma.MaskedArray)
<ide>
<ide>
<del>class TestMinimumMaximum(TestCase):
<add>class TestMinimumMaximum(object):
<ide> def test_minimum(self):
<ide> assert_warns(DeprecationWarning, np.ma.minimum, np.ma.array([1, 2]))
<ide>
<ide><path>numpy/ma/tests/test_extras.py
<ide>
<ide> import numpy as np
<ide> from numpy.testing import (
<del> TestCase, run_module_suite, assert_warns, suppress_warnings,
<del> assert_raises
<add> run_module_suite, assert_warns, suppress_warnings, assert_raises,
<ide> )
<ide> from numpy.ma.testutils import (
<ide> assert_, assert_array_equal, assert_equal, assert_almost_equal
<ide> import numpy.ma.extras as mae
<ide>
<ide>
<del>class TestGeneric(TestCase):
<add>class TestGeneric(object):
<ide> #
<ide> def test_masked_all(self):
<ide> # Tests masked_all
<ide> def test_flatnotmasked_contiguous(self):
<ide> assert_equal(test, None)
<ide>
<ide>
<del>class TestAverage(TestCase):
<add>class TestAverage(object):
<ide> # Several tests of average. Why so many ? Good point...
<ide> def test_testAverage1(self):
<ide> # Test of average.
<ide> def test_testAverage1(self):
<ide> assert_equal(2.0, average(ott, weights=[1., 1., 2., 1.]))
<ide> result, wts = average(ott, weights=[1., 1., 2., 1.], returned=1)
<ide> assert_equal(2.0, result)
<del> self.assertTrue(wts == 4.0)
<add> assert_(wts == 4.0)
<ide> ott[:] = masked
<ide> assert_equal(average(ott, axis=0).mask, [True])
<ide> ott = array([0., 1., 2., 3.], mask=[True, False, False, False])
<ide> def test_complex(self):
<ide> assert_almost_equal(wav1.imag, expected1.imag)
<ide>
<ide>
<del>class TestConcatenator(TestCase):
<add>class TestConcatenator(object):
<ide> # Tests for mr_, the equivalent of r_ for masked arrays.
<ide>
<ide> def test_1d(self):
<ide> def test_1d(self):
<ide> m = [1, 0, 0, 0, 0]
<ide> d = masked_array(b, mask=m)
<ide> c = mr_[d, 0, 0, d]
<del> self.assertTrue(isinstance(c, MaskedArray))
<add> assert_(isinstance(c, MaskedArray))
<ide> assert_array_equal(c, [1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1])
<ide> assert_array_equal(c.mask, mr_[m, 0, 0, m])
<ide>
<ide> def test_2d(self):
<ide> b_2 = masked_array(a_2, mask=m_2)
<ide> # append columns
<ide> d = mr_['1', b_1, b_2]
<del> self.assertTrue(d.shape == (5, 10))
<add> assert_(d.shape == (5, 10))
<ide> assert_array_equal(d[:, :5], b_1)
<ide> assert_array_equal(d[:, 5:], b_2)
<ide> assert_array_equal(d.mask, np.r_['1', m_1, m_2])
<ide> d = mr_[b_1, b_2]
<del> self.assertTrue(d.shape == (10, 5))
<add> assert_(d.shape == (10, 5))
<ide> assert_array_equal(d[:5,:], b_1)
<ide> assert_array_equal(d[5:,:], b_2)
<ide> assert_array_equal(d.mask, np.r_[m_1, m_2])
<ide> def test_matrix(self):
<ide> assert_equal(type(actual.data), type(expected.data))
<ide>
<ide>
<del>class TestNotMasked(TestCase):
<add>class TestNotMasked(object):
<ide> # Tests notmasked_edges and notmasked_contiguous.
<ide>
<ide> def test_edges(self):
<ide> def test_contiguous(self):
<ide> assert_equal(tmp[-3], slice(0, 4, None))
<ide> #
<ide> tmp = notmasked_contiguous(a, 0)
<del> self.assertTrue(len(tmp[-1]) == 1)
<del> self.assertTrue(tmp[-2] is None)
<add> assert_(len(tmp[-1]) == 1)
<add> assert_(tmp[-2] is None)
<ide> assert_equal(tmp[-3], tmp[-1])
<del> self.assertTrue(len(tmp[0]) == 2)
<add> assert_(len(tmp[0]) == 2)
<ide> #
<ide> tmp = notmasked_contiguous(a, 1)
<ide> assert_equal(tmp[0][-1], slice(0, 4, None))
<del> self.assertTrue(tmp[1] is None)
<add> assert_(tmp[1] is None)
<ide> assert_equal(tmp[2][-1], slice(7, 8, None))
<ide> assert_equal(tmp[2][-2], slice(0, 6, None))
<ide>
<ide>
<del>class TestCompressFunctions(TestCase):
<add>class TestCompressFunctions(object):
<ide>
<ide> def test_compress_nd(self):
<ide> # Tests compress_nd
<ide> def test_mask_rowcols(self):
<ide> assert_equal(mask_rowcols(x, 1,).mask,
<ide> [[1, 1, 0], [1, 1, 0], [1, 1, 0]])
<ide> x = array(x._data, mask=[[1, 0, 0], [0, 1, 0], [0, 0, 1]])
<del> self.assertTrue(mask_rowcols(x).all() is masked)
<del> self.assertTrue(mask_rowcols(x, 0).all() is masked)
<del> self.assertTrue(mask_rowcols(x, 1).all() is masked)
<del> self.assertTrue(mask_rowcols(x).mask.all())
<del> self.assertTrue(mask_rowcols(x, 0).mask.all())
<del> self.assertTrue(mask_rowcols(x, 1).mask.all())
<add> assert_(mask_rowcols(x).all() is masked)
<add> assert_(mask_rowcols(x, 0).all() is masked)
<add> assert_(mask_rowcols(x, 1).all() is masked)
<add> assert_(mask_rowcols(x).mask.all())
<add> assert_(mask_rowcols(x, 0).mask.all())
<add> assert_(mask_rowcols(x, 1).mask.all())
<ide>
<ide> def test_dot(self):
<ide> # Tests dot product
<ide> def test_dot_out(self):
<ide> assert_equal(a, res)
<ide>
<ide>
<del>class TestApplyAlongAxis(TestCase):
<add>class TestApplyAlongAxis(object):
<ide> # Tests 2D functions
<ide> def test_3d(self):
<ide> a = arange(12.).reshape(2, 2, 3)
<ide> def myfunc(b, offset=0):
<ide> assert_equal(xa, [[2, 5], [8, 11]])
<ide>
<ide>
<del>class TestApplyOverAxes(TestCase):
<add>class TestApplyOverAxes(object):
<ide> # Tests apply_over_axes
<ide> def test_basic(self):
<ide> a = arange(24).reshape(2, 3, 4)
<ide> def test_basic(self):
<ide> assert_equal(test, ctrl)
<ide>
<ide>
<del>class TestMedian(TestCase):
<add>class TestMedian(object):
<ide> def test_pytype(self):
<ide> r = np.ma.median([[np.inf, np.inf], [np.inf, np.inf]], axis=-1)
<ide> assert_equal(r, np.inf)
<ide> def test_object(self):
<ide> assert_(type(np.ma.median(o.astype(object))), float)
<ide>
<ide>
<del>class TestCov(TestCase):
<add>class TestCov(object):
<ide>
<del> def setUp(self):
<add> def setup(self):
<ide> self.data = array(np.random.rand(12))
<ide>
<ide> def test_1d_without_missing(self):
<ide> def test_2d_with_missing(self):
<ide> x.shape[0] / frac))
<ide>
<ide>
<del>class TestCorrcoef(TestCase):
<add>class TestCorrcoef(object):
<ide>
<del> def setUp(self):
<add> def setup(self):
<ide> self.data = array(np.random.rand(12))
<ide> self.data2 = array(np.random.rand(12))
<ide>
<ide> def test_2d_with_missing(self):
<ide> control[:-1, :-1])
<ide>
<ide>
<del>class TestPolynomial(TestCase):
<add>class TestPolynomial(object):
<ide> #
<ide> def test_polyfit(self):
<ide> # Tests polyfit
<ide> def test_polyfit_with_masked_NaNs(self):
<ide> assert_almost_equal(a, a_)
<ide>
<ide>
<del>class TestArraySetOps(TestCase):
<add>class TestArraySetOps(object):
<ide>
<ide> def test_unique_onlist(self):
<ide> # Test unique on list
<ide> data = [1, 1, 1, 2, 2, 3]
<ide> test = unique(data, return_index=True, return_inverse=True)
<del> self.assertTrue(isinstance(test[0], MaskedArray))
<add> assert_(isinstance(test[0], MaskedArray))
<ide> assert_equal(test[0], masked_array([1, 2, 3], mask=[0, 0, 0]))
<ide> assert_equal(test[1], [0, 3, 5])
<ide> assert_equal(test[2], [0, 0, 0, 1, 1, 2])
<ide> def test_ediff1d_ndarray(self):
<ide> test = ediff1d(x)
<ide> control = array([1, 1, 1, 1], mask=[0, 0, 0, 0])
<ide> assert_equal(test, control)
<del> self.assertTrue(isinstance(test, MaskedArray))
<add> assert_(isinstance(test, MaskedArray))
<ide> assert_equal(test.filled(0), control.filled(0))
<ide> assert_equal(test.mask, control.mask)
<ide> #
<ide> test = ediff1d(x, to_end=masked, to_begin=masked)
<ide> control = array([0, 1, 1, 1, 1, 0], mask=[1, 0, 0, 0, 0, 1])
<del> self.assertTrue(isinstance(test, MaskedArray))
<add> assert_(isinstance(test, MaskedArray))
<ide> assert_equal(test.filled(0), control.filled(0))
<ide> assert_equal(test.mask, control.mask)
<ide>
<ide> def test_setdiff1d_char_array(self):
<ide> assert_array_equal(setdiff1d(a, b), np.array(['c']))
<ide>
<ide>
<del>class TestShapeBase(TestCase):
<add>class TestShapeBase(object):
<ide>
<ide> def test_atleast_2d(self):
<ide> # Test atleast_2d
<ide><path>numpy/ma/tests/test_mrecords.py
<ide> import numpy.ma as ma
<ide> from numpy import recarray
<ide> from numpy.ma import masked, nomask
<del>from numpy.testing import TestCase, run_module_suite, temppath
<add>from numpy.testing import run_module_suite, temppath
<ide> from numpy.core.records import (
<ide> fromrecords as recfromrecords, fromarrays as recfromarrays
<ide> )
<ide> )
<ide>
<ide>
<del>class TestMRecords(TestCase):
<del> # Base test class for MaskedArrays.
<del> def __init__(self, *args, **kwds):
<del> TestCase.__init__(self, *args, **kwds)
<del> self.setup()
<add>class TestMRecords(object):
<ide>
<del> def setup(self):
<del> # Generic setup
<del> ilist = [1, 2, 3, 4, 5]
<del> flist = [1.1, 2.2, 3.3, 4.4, 5.5]
<del> slist = [b'one', b'two', b'three', b'four', b'five']
<del> ddtype = [('a', int), ('b', float), ('c', '|S8')]
<del> mask = [0, 1, 0, 0, 1]
<del> self.base = ma.array(list(zip(ilist, flist, slist)),
<del> mask=mask, dtype=ddtype)
<add> ilist = [1, 2, 3, 4, 5]
<add> flist = [1.1, 2.2, 3.3, 4.4, 5.5]
<add> slist = [b'one', b'two', b'three', b'four', b'five']
<add> ddtype = [('a', int), ('b', float), ('c', '|S8')]
<add> mask = [0, 1, 0, 0, 1]
<add> base = ma.array(list(zip(ilist, flist, slist)), mask=mask, dtype=ddtype)
<ide>
<ide> def test_byview(self):
<ide> # Test creation by view
<ide> def test_hardmask(self):
<ide> base = self.base.copy()
<ide> mbase = base.view(mrecarray)
<ide> mbase.harden_mask()
<del> self.assertTrue(mbase._hardmask)
<add> assert_(mbase._hardmask)
<ide> mbase.mask = nomask
<ide> assert_equal_records(mbase._mask, base._mask)
<ide> mbase.soften_mask()
<del> self.assertTrue(not mbase._hardmask)
<add> assert_(not mbase._hardmask)
<ide> mbase.mask = nomask
<ide> # So, the mask of a field is no longer set to nomask...
<ide> assert_equal_records(mbase._mask,
<ide> ma.make_mask_none(base.shape, base.dtype))
<del> self.assertTrue(ma.make_mask(mbase['b']._mask) is nomask)
<add> assert_(ma.make_mask(mbase['b']._mask) is nomask)
<ide> assert_equal(mbase['a']._mask, mbase['b']._mask)
<ide>
<ide> def test_pickling(self):
<ide> def test_exotic_formats(self):
<ide> dtype=mult.dtype))
<ide>
<ide>
<del>class TestView(TestCase):
<add>class TestView(object):
<ide>
<del> def setUp(self):
<add> def setup(self):
<ide> (a, b) = (np.arange(10), np.random.rand(10))
<ide> ndtype = [('a', np.float), ('b', np.float)]
<ide> arr = np.array(list(zip(a, b)), dtype=ndtype)
<ide> def setUp(self):
<ide> def test_view_by_itself(self):
<ide> (mrec, a, b, arr) = self.data
<ide> test = mrec.view()
<del> self.assertTrue(isinstance(test, MaskedRecords))
<add> assert_(isinstance(test, MaskedRecords))
<ide> assert_equal_records(test, mrec)
<ide> assert_equal_records(test._mask, mrec._mask)
<ide>
<ide> def test_view_simple_dtype(self):
<ide> (mrec, a, b, arr) = self.data
<ide> ntype = (np.float, 2)
<ide> test = mrec.view(ntype)
<del> self.assertTrue(isinstance(test, ma.MaskedArray))
<add> assert_(isinstance(test, ma.MaskedArray))
<ide> assert_equal(test, np.array(list(zip(a, b)), dtype=np.float))
<del> self.assertTrue(test[3, 1] is ma.masked)
<add> assert_(test[3, 1] is ma.masked)
<ide>
<ide> def test_view_flexible_type(self):
<ide> (mrec, a, b, arr) = self.data
<ide> alttype = [('A', np.float), ('B', np.float)]
<ide> test = mrec.view(alttype)
<del> self.assertTrue(isinstance(test, MaskedRecords))
<add> assert_(isinstance(test, MaskedRecords))
<ide> assert_equal_records(test, arr.view(alttype))
<del> self.assertTrue(test['B'][3] is masked)
<add> assert_(test['B'][3] is masked)
<ide> assert_equal(test.dtype, np.dtype(alttype))
<del> self.assertTrue(test._fill_value is None)
<add> assert_(test._fill_value is None)
<ide>
<ide>
<ide> ##############################################################################
<del>class TestMRecordsImport(TestCase):
<del> # Base test class for MaskedArrays.
<del> def __init__(self, *args, **kwds):
<del> TestCase.__init__(self, *args, **kwds)
<del> self.setup()
<del>
<del> def setup(self):
<del> # Generic setup
<del> _a = ma.array([1, 2, 3], mask=[0, 0, 1], dtype=int)
<del> _b = ma.array([1.1, 2.2, 3.3], mask=[0, 0, 1], dtype=float)
<del> _c = ma.array([b'one', b'two', b'three'],
<del> mask=[0, 0, 1], dtype='|S8')
<del> ddtype = [('a', int), ('b', float), ('c', '|S8')]
<del> mrec = fromarrays([_a, _b, _c], dtype=ddtype,
<del> fill_value=(b'99999', b'99999.',
<del> b'N/A'))
<del> nrec = recfromarrays((_a._data, _b._data, _c._data), dtype=ddtype)
<del> self.data = (mrec, nrec, ddtype)
<add>class TestMRecordsImport(object):
<add>
<add> _a = ma.array([1, 2, 3], mask=[0, 0, 1], dtype=int)
<add> _b = ma.array([1.1, 2.2, 3.3], mask=[0, 0, 1], dtype=float)
<add> _c = ma.array([b'one', b'two', b'three'],
<add> mask=[0, 0, 1], dtype='|S8')
<add> ddtype = [('a', int), ('b', float), ('c', '|S8')]
<add> mrec = fromarrays([_a, _b, _c], dtype=ddtype,
<add> fill_value=(b'99999', b'99999.',
<add> b'N/A'))
<add> nrec = recfromarrays((_a._data, _b._data, _c._data), dtype=ddtype)
<add> data = (mrec, nrec, ddtype)
<ide>
<ide> def test_fromarrays(self):
<ide> _a = ma.array([1, 2, 3], mask=[0, 0, 1], dtype=int)
<ide> def test_fromtextfile(self):
<ide> with open(path, 'w') as f:
<ide> f.write(fcontent)
<ide> mrectxt = fromtextfile(path, delimitor=',', varnames='ABCDEFG')
<del> self.assertTrue(isinstance(mrectxt, MaskedRecords))
<add> assert_(isinstance(mrectxt, MaskedRecords))
<ide> assert_equal(mrectxt.F, [1, 1, 1, 1])
<ide> assert_equal(mrectxt.E._mask, [1, 1, 1, 1])
<ide> assert_equal(mrectxt.C, [1, 2, 3.e+5, -1e-10])
<ide><path>numpy/ma/tests/test_old_ma.py
<ide> import numpy as np
<ide> import numpy.core.umath as umath
<ide> import numpy.core.fromnumeric as fromnumeric
<del>from numpy.testing import TestCase, run_module_suite, assert_
<add>from numpy.testing import (
<add> run_module_suite, assert_, assert_raises, assert_equal,
<add> )
<ide> from numpy.ma.testutils import assert_array_equal
<ide> from numpy.ma import (
<ide> MaskType, MaskedArray, absolute, add, all, allclose, allequal, alltrue,
<ide> def eq(v, w, msg=''):
<ide> return result
<ide>
<ide>
<del>class TestMa(TestCase):
<add>class TestMa(object):
<ide>
<del> def setUp(self):
<add> def setup(self):
<ide> x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
<ide> y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
<ide> a10 = 10.
<ide> def setUp(self):
<ide> def test_testBasic1d(self):
<ide> # Test of basic array creation and properties in 1 dimension.
<ide> (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
<del> self.assertFalse(isMaskedArray(x))
<del> self.assertTrue(isMaskedArray(xm))
<del> self.assertEqual(shape(xm), s)
<del> self.assertEqual(xm.shape, s)
<del> self.assertEqual(xm.dtype, x.dtype)
<del> self.assertEqual(xm.size, reduce(lambda x, y:x * y, s))
<del> self.assertEqual(count(xm), len(m1) - reduce(lambda x, y:x + y, m1))
<del> self.assertTrue(eq(xm, xf))
<del> self.assertTrue(eq(filled(xm, 1.e20), xf))
<del> self.assertTrue(eq(x, xm))
<add> assert_(not isMaskedArray(x))
<add> assert_(isMaskedArray(xm))
<add> assert_equal(shape(xm), s)
<add> assert_equal(xm.shape, s)
<add> assert_equal(xm.dtype, x.dtype)
<add> assert_equal(xm.size, reduce(lambda x, y:x * y, s))
<add> assert_equal(count(xm), len(m1) - reduce(lambda x, y:x + y, m1))
<add> assert_(eq(xm, xf))
<add> assert_(eq(filled(xm, 1.e20), xf))
<add> assert_(eq(x, xm))
<ide>
<ide> def test_testBasic2d(self):
<ide> # Test of basic array creation and properties in 2 dimensions.
<ide> def test_testBasic2d(self):
<ide> ym.shape = s
<ide> xf.shape = s
<ide>
<del> self.assertFalse(isMaskedArray(x))
<del> self.assertTrue(isMaskedArray(xm))
<del> self.assertEqual(shape(xm), s)
<del> self.assertEqual(xm.shape, s)
<del> self.assertEqual(xm.size, reduce(lambda x, y:x * y, s))
<del> self.assertEqual(count(xm),
<add> assert_(not isMaskedArray(x))
<add> assert_(isMaskedArray(xm))
<add> assert_equal(shape(xm), s)
<add> assert_equal(xm.shape, s)
<add> assert_equal(xm.size, reduce(lambda x, y:x * y, s))
<add> assert_equal(count(xm),
<ide> len(m1) - reduce(lambda x, y:x + y, m1))
<del> self.assertTrue(eq(xm, xf))
<del> self.assertTrue(eq(filled(xm, 1.e20), xf))
<del> self.assertTrue(eq(x, xm))
<del> self.setUp()
<add> assert_(eq(xm, xf))
<add> assert_(eq(filled(xm, 1.e20), xf))
<add> assert_(eq(x, xm))
<add> self.setup()
<ide>
<ide> def test_testArithmetic(self):
<ide> # Test of basic arithmetic.
<ide> (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
<ide> a2d = array([[1, 2], [0, 4]])
<ide> a2dm = masked_array(a2d, [[0, 0], [1, 0]])
<del> self.assertTrue(eq(a2d * a2d, a2d * a2dm))
<del> self.assertTrue(eq(a2d + a2d, a2d + a2dm))
<del> self.assertTrue(eq(a2d - a2d, a2d - a2dm))
<add> assert_(eq(a2d * a2d, a2d * a2dm))
<add> assert_(eq(a2d + a2d, a2d + a2dm))
<add> assert_(eq(a2d - a2d, a2d - a2dm))
<ide> for s in [(12,), (4, 3), (2, 6)]:
<ide> x = x.reshape(s)
<ide> y = y.reshape(s)
<ide> xm = xm.reshape(s)
<ide> ym = ym.reshape(s)
<ide> xf = xf.reshape(s)
<del> self.assertTrue(eq(-x, -xm))
<del> self.assertTrue(eq(x + y, xm + ym))
<del> self.assertTrue(eq(x - y, xm - ym))
<del> self.assertTrue(eq(x * y, xm * ym))
<add> assert_(eq(-x, -xm))
<add> assert_(eq(x + y, xm + ym))
<add> assert_(eq(x - y, xm - ym))
<add> assert_(eq(x * y, xm * ym))
<ide> with np.errstate(divide='ignore', invalid='ignore'):
<del> self.assertTrue(eq(x / y, xm / ym))
<del> self.assertTrue(eq(a10 + y, a10 + ym))
<del> self.assertTrue(eq(a10 - y, a10 - ym))
<del> self.assertTrue(eq(a10 * y, a10 * ym))
<add> assert_(eq(x / y, xm / ym))
<add> assert_(eq(a10 + y, a10 + ym))
<add> assert_(eq(a10 - y, a10 - ym))
<add> assert_(eq(a10 * y, a10 * ym))
<ide> with np.errstate(divide='ignore', invalid='ignore'):
<del> self.assertTrue(eq(a10 / y, a10 / ym))
<del> self.assertTrue(eq(x + a10, xm + a10))
<del> self.assertTrue(eq(x - a10, xm - a10))
<del> self.assertTrue(eq(x * a10, xm * a10))
<del> self.assertTrue(eq(x / a10, xm / a10))
<del> self.assertTrue(eq(x ** 2, xm ** 2))
<del> self.assertTrue(eq(abs(x) ** 2.5, abs(xm) ** 2.5))
<del> self.assertTrue(eq(x ** y, xm ** ym))
<del> self.assertTrue(eq(np.add(x, y), add(xm, ym)))
<del> self.assertTrue(eq(np.subtract(x, y), subtract(xm, ym)))
<del> self.assertTrue(eq(np.multiply(x, y), multiply(xm, ym)))
<add> assert_(eq(a10 / y, a10 / ym))
<add> assert_(eq(x + a10, xm + a10))
<add> assert_(eq(x - a10, xm - a10))
<add> assert_(eq(x * a10, xm * a10))
<add> assert_(eq(x / a10, xm / a10))
<add> assert_(eq(x ** 2, xm ** 2))
<add> assert_(eq(abs(x) ** 2.5, abs(xm) ** 2.5))
<add> assert_(eq(x ** y, xm ** ym))
<add> assert_(eq(np.add(x, y), add(xm, ym)))
<add> assert_(eq(np.subtract(x, y), subtract(xm, ym)))
<add> assert_(eq(np.multiply(x, y), multiply(xm, ym)))
<ide> with np.errstate(divide='ignore', invalid='ignore'):
<del> self.assertTrue(eq(np.divide(x, y), divide(xm, ym)))
<add> assert_(eq(np.divide(x, y), divide(xm, ym)))
<ide>
<ide> def test_testMixedArithmetic(self):
<ide> na = np.array([1])
<ide> ma = array([1])
<del> self.assertTrue(isinstance(na + ma, MaskedArray))
<del> self.assertTrue(isinstance(ma + na, MaskedArray))
<add> assert_(isinstance(na + ma, MaskedArray))
<add> assert_(isinstance(ma + na, MaskedArray))
<ide>
<ide> def test_testUfuncs1(self):
<ide> # Test various functions such as sin, cos.
<ide> (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
<del> self.assertTrue(eq(np.cos(x), cos(xm)))
<del> self.assertTrue(eq(np.cosh(x), cosh(xm)))
<del> self.assertTrue(eq(np.sin(x), sin(xm)))
<del> self.assertTrue(eq(np.sinh(x), sinh(xm)))
<del> self.assertTrue(eq(np.tan(x), tan(xm)))
<del> self.assertTrue(eq(np.tanh(x), tanh(xm)))
<add> assert_(eq(np.cos(x), cos(xm)))
<add> assert_(eq(np.cosh(x), cosh(xm)))
<add> assert_(eq(np.sin(x), sin(xm)))
<add> assert_(eq(np.sinh(x), sinh(xm)))
<add> assert_(eq(np.tan(x), tan(xm)))
<add> assert_(eq(np.tanh(x), tanh(xm)))
<ide> with np.errstate(divide='ignore', invalid='ignore'):
<del> self.assertTrue(eq(np.sqrt(abs(x)), sqrt(xm)))
<del> self.assertTrue(eq(np.log(abs(x)), log(xm)))
<del> self.assertTrue(eq(np.log10(abs(x)), log10(xm)))
<del> self.assertTrue(eq(np.exp(x), exp(xm)))
<del> self.assertTrue(eq(np.arcsin(z), arcsin(zm)))
<del> self.assertTrue(eq(np.arccos(z), arccos(zm)))
<del> self.assertTrue(eq(np.arctan(z), arctan(zm)))
<del> self.assertTrue(eq(np.arctan2(x, y), arctan2(xm, ym)))
<del> self.assertTrue(eq(np.absolute(x), absolute(xm)))
<del> self.assertTrue(eq(np.equal(x, y), equal(xm, ym)))
<del> self.assertTrue(eq(np.not_equal(x, y), not_equal(xm, ym)))
<del> self.assertTrue(eq(np.less(x, y), less(xm, ym)))
<del> self.assertTrue(eq(np.greater(x, y), greater(xm, ym)))
<del> self.assertTrue(eq(np.less_equal(x, y), less_equal(xm, ym)))
<del> self.assertTrue(eq(np.greater_equal(x, y), greater_equal(xm, ym)))
<del> self.assertTrue(eq(np.conjugate(x), conjugate(xm)))
<del> self.assertTrue(eq(np.concatenate((x, y)), concatenate((xm, ym))))
<del> self.assertTrue(eq(np.concatenate((x, y)), concatenate((x, y))))
<del> self.assertTrue(eq(np.concatenate((x, y)), concatenate((xm, y))))
<del> self.assertTrue(eq(np.concatenate((x, y, x)), concatenate((x, ym, x))))
<add> assert_(eq(np.sqrt(abs(x)), sqrt(xm)))
<add> assert_(eq(np.log(abs(x)), log(xm)))
<add> assert_(eq(np.log10(abs(x)), log10(xm)))
<add> assert_(eq(np.exp(x), exp(xm)))
<add> assert_(eq(np.arcsin(z), arcsin(zm)))
<add> assert_(eq(np.arccos(z), arccos(zm)))
<add> assert_(eq(np.arctan(z), arctan(zm)))
<add> assert_(eq(np.arctan2(x, y), arctan2(xm, ym)))
<add> assert_(eq(np.absolute(x), absolute(xm)))
<add> assert_(eq(np.equal(x, y), equal(xm, ym)))
<add> assert_(eq(np.not_equal(x, y), not_equal(xm, ym)))
<add> assert_(eq(np.less(x, y), less(xm, ym)))
<add> assert_(eq(np.greater(x, y), greater(xm, ym)))
<add> assert_(eq(np.less_equal(x, y), less_equal(xm, ym)))
<add> assert_(eq(np.greater_equal(x, y), greater_equal(xm, ym)))
<add> assert_(eq(np.conjugate(x), conjugate(xm)))
<add> assert_(eq(np.concatenate((x, y)), concatenate((xm, ym))))
<add> assert_(eq(np.concatenate((x, y)), concatenate((x, y))))
<add> assert_(eq(np.concatenate((x, y)), concatenate((xm, y))))
<add> assert_(eq(np.concatenate((x, y, x)), concatenate((x, ym, x))))
<ide>
<ide> def test_xtestCount(self):
<ide> # Test count
<ide> ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0])
<del> self.assertTrue(count(ott).dtype.type is np.intp)
<del> self.assertEqual(3, count(ott))
<del> self.assertEqual(1, count(1))
<del> self.assertTrue(eq(0, array(1, mask=[1])))
<add> assert_(count(ott).dtype.type is np.intp)
<add> assert_equal(3, count(ott))
<add> assert_equal(1, count(1))
<add> assert_(eq(0, array(1, mask=[1])))
<ide> ott = ott.reshape((2, 2))
<del> self.assertTrue(count(ott).dtype.type is np.intp)
<add> assert_(count(ott).dtype.type is np.intp)
<ide> assert_(isinstance(count(ott, 0), np.ndarray))
<del> self.assertTrue(count(ott).dtype.type is np.intp)
<del> self.assertTrue(eq(3, count(ott)))
<add> assert_(count(ott).dtype.type is np.intp)
<add> assert_(eq(3, count(ott)))
<ide> assert_(getmask(count(ott, 0)) is nomask)
<del> self.assertTrue(eq([1, 2], count(ott, 0)))
<add> assert_(eq([1, 2], count(ott, 0)))
<ide>
<ide> def test_testMinMax(self):
<ide> # Test minimum and maximum.
<ide> def test_testMinMax(self):
<ide> xmr = ravel(xm)
<ide>
<ide> # true because of careful selection of data
<del> self.assertTrue(eq(max(xr), maximum.reduce(xmr)))
<del> self.assertTrue(eq(min(xr), minimum.reduce(xmr)))
<add> assert_(eq(max(xr), maximum.reduce(xmr)))
<add> assert_(eq(min(xr), minimum.reduce(xmr)))
<ide>
<ide> def test_testAddSumProd(self):
<ide> # Test add, sum, product.
<ide> (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
<del> self.assertTrue(eq(np.add.reduce(x), add.reduce(x)))
<del> self.assertTrue(eq(np.add.accumulate(x), add.accumulate(x)))
<del> self.assertTrue(eq(4, sum(array(4), axis=0)))
<del> self.assertTrue(eq(4, sum(array(4), axis=0)))
<del> self.assertTrue(eq(np.sum(x, axis=0), sum(x, axis=0)))
<del> self.assertTrue(eq(np.sum(filled(xm, 0), axis=0), sum(xm, axis=0)))
<del> self.assertTrue(eq(np.sum(x, 0), sum(x, 0)))
<del> self.assertTrue(eq(np.product(x, axis=0), product(x, axis=0)))
<del> self.assertTrue(eq(np.product(x, 0), product(x, 0)))
<del> self.assertTrue(eq(np.product(filled(xm, 1), axis=0),
<add> assert_(eq(np.add.reduce(x), add.reduce(x)))
<add> assert_(eq(np.add.accumulate(x), add.accumulate(x)))
<add> assert_(eq(4, sum(array(4), axis=0)))
<add> assert_(eq(4, sum(array(4), axis=0)))
<add> assert_(eq(np.sum(x, axis=0), sum(x, axis=0)))
<add> assert_(eq(np.sum(filled(xm, 0), axis=0), sum(xm, axis=0)))
<add> assert_(eq(np.sum(x, 0), sum(x, 0)))
<add> assert_(eq(np.product(x, axis=0), product(x, axis=0)))
<add> assert_(eq(np.product(x, 0), product(x, 0)))
<add> assert_(eq(np.product(filled(xm, 1), axis=0),
<ide> product(xm, axis=0)))
<ide> if len(s) > 1:
<del> self.assertTrue(eq(np.concatenate((x, y), 1),
<add> assert_(eq(np.concatenate((x, y), 1),
<ide> concatenate((xm, ym), 1)))
<del> self.assertTrue(eq(np.add.reduce(x, 1), add.reduce(x, 1)))
<del> self.assertTrue(eq(np.sum(x, 1), sum(x, 1)))
<del> self.assertTrue(eq(np.product(x, 1), product(x, 1)))
<add> assert_(eq(np.add.reduce(x, 1), add.reduce(x, 1)))
<add> assert_(eq(np.sum(x, 1), sum(x, 1)))
<add> assert_(eq(np.product(x, 1), product(x, 1)))
<ide>
<ide> def test_testCI(self):
<ide> # Test of conversions and indexing
<ide> def test_testCI(self):
<ide> x2 = np.array([1, 'hello', 2, 3], object)
<ide> s1 = x1[1]
<ide> s2 = x2[1]
<del> self.assertEqual(type(s2), str)
<del> self.assertEqual(type(s1), str)
<del> self.assertEqual(s1, s2)
<add> assert_equal(type(s2), str)
<add> assert_equal(type(s1), str)
<add> assert_equal(s1, s2)
<ide> assert_(x1[1:1].shape == (0,))
<ide>
<ide> def test_testCopySize(self):
<ide> # Tests of some subtle points of copying and sizing.
<ide> n = [0, 0, 1, 0, 0]
<ide> m = make_mask(n)
<ide> m2 = make_mask(m)
<del> self.assertTrue(m is m2)
<add> assert_(m is m2)
<ide> m3 = make_mask(m, copy=1)
<del> self.assertTrue(m is not m3)
<add> assert_(m is not m3)
<ide>
<ide> x1 = np.arange(5)
<ide> y1 = array(x1, mask=m)
<del> self.assertTrue(y1._data is not x1)
<del> self.assertTrue(allequal(x1, y1._data))
<del> self.assertTrue(y1.mask is m)
<add> assert_(y1._data is not x1)
<add> assert_(allequal(x1, y1._data))
<add> assert_(y1.mask is m)
<ide>
<ide> y1a = array(y1, copy=0)
<del> self.assertTrue(y1a.mask is y1.mask)
<add> assert_(y1a.mask is y1.mask)
<ide>
<ide> y2 = array(x1, mask=m3, copy=0)
<del> self.assertTrue(y2.mask is m3)
<del> self.assertTrue(y2[2] is masked)
<add> assert_(y2.mask is m3)
<add> assert_(y2[2] is masked)
<ide> y2[2] = 9
<del> self.assertTrue(y2[2] is not masked)
<del> self.assertTrue(y2.mask is m3)
<del> self.assertTrue(allequal(y2.mask, 0))
<add> assert_(y2[2] is not masked)
<add> assert_(y2.mask is m3)
<add> assert_(allequal(y2.mask, 0))
<ide>
<ide> y2a = array(x1, mask=m, copy=1)
<del> self.assertTrue(y2a.mask is not m)
<del> self.assertTrue(y2a[2] is masked)
<add> assert_(y2a.mask is not m)
<add> assert_(y2a[2] is masked)
<ide> y2a[2] = 9
<del> self.assertTrue(y2a[2] is not masked)
<del> self.assertTrue(y2a.mask is not m)
<del> self.assertTrue(allequal(y2a.mask, 0))
<add> assert_(y2a[2] is not masked)
<add> assert_(y2a.mask is not m)
<add> assert_(allequal(y2a.mask, 0))
<ide>
<ide> y3 = array(x1 * 1.0, mask=m)
<del> self.assertTrue(filled(y3).dtype is (x1 * 1.0).dtype)
<add> assert_(filled(y3).dtype is (x1 * 1.0).dtype)
<ide>
<ide> x4 = arange(4)
<ide> x4[2] = masked
<ide> y4 = resize(x4, (8,))
<del> self.assertTrue(eq(concatenate([x4, x4]), y4))
<del> self.assertTrue(eq(getmask(y4), [0, 0, 1, 0, 0, 0, 1, 0]))
<add> assert_(eq(concatenate([x4, x4]), y4))
<add> assert_(eq(getmask(y4), [0, 0, 1, 0, 0, 0, 1, 0]))
<ide> y5 = repeat(x4, (2, 2, 2, 2), axis=0)
<del> self.assertTrue(eq(y5, [0, 0, 1, 1, 2, 2, 3, 3]))
<add> assert_(eq(y5, [0, 0, 1, 1, 2, 2, 3, 3]))
<ide> y6 = repeat(x4, 2, axis=0)
<del> self.assertTrue(eq(y5, y6))
<add> assert_(eq(y5, y6))
<ide>
<ide> def test_testPut(self):
<ide> # Test of put
<ide> def test_testPut(self):
<ide> m = make_mask(n)
<ide> m2 = m.copy()
<ide> x = array(d, mask=m)
<del> self.assertTrue(x[3] is masked)
<del> self.assertTrue(x[4] is masked)
<add> assert_(x[3] is masked)
<add> assert_(x[4] is masked)
<ide> x[[1, 4]] = [10, 40]
<del> self.assertTrue(x.mask is m)
<del> self.assertTrue(x[3] is masked)
<del> self.assertTrue(x[4] is not masked)
<del> self.assertTrue(eq(x, [0, 10, 2, -1, 40]))
<add> assert_(x.mask is m)
<add> assert_(x[3] is masked)
<add> assert_(x[4] is not masked)
<add> assert_(eq(x, [0, 10, 2, -1, 40]))
<ide>
<ide> x = array(d, mask=m2, copy=True)
<ide> x.put([0, 1, 2], [-1, 100, 200])
<del> self.assertTrue(x.mask is not m2)
<del> self.assertTrue(x[3] is masked)
<del> self.assertTrue(x[4] is masked)
<del> self.assertTrue(eq(x, [-1, 100, 200, 0, 0]))
<add> assert_(x.mask is not m2)
<add> assert_(x[3] is masked)
<add> assert_(x[4] is masked)
<add> assert_(eq(x, [-1, 100, 200, 0, 0]))
<ide>
<ide> def test_testPut2(self):
<ide> # Test of put
<ide> d = arange(5)
<ide> x = array(d, mask=[0, 0, 0, 0, 0])
<ide> z = array([10, 40], mask=[1, 0])
<del> self.assertTrue(x[2] is not masked)
<del> self.assertTrue(x[3] is not masked)
<add> assert_(x[2] is not masked)
<add> assert_(x[3] is not masked)
<ide> x[2:4] = z
<del> self.assertTrue(x[2] is masked)
<del> self.assertTrue(x[3] is not masked)
<del> self.assertTrue(eq(x, [0, 1, 10, 40, 4]))
<add> assert_(x[2] is masked)
<add> assert_(x[3] is not masked)
<add> assert_(eq(x, [0, 1, 10, 40, 4]))
<ide>
<ide> d = arange(5)
<ide> x = array(d, mask=[0, 0, 0, 0, 0])
<ide> y = x[2:4]
<ide> z = array([10, 40], mask=[1, 0])
<del> self.assertTrue(x[2] is not masked)
<del> self.assertTrue(x[3] is not masked)
<add> assert_(x[2] is not masked)
<add> assert_(x[3] is not masked)
<ide> y[:] = z
<del> self.assertTrue(y[0] is masked)
<del> self.assertTrue(y[1] is not masked)
<del> self.assertTrue(eq(y, [10, 40]))
<del> self.assertTrue(x[2] is masked)
<del> self.assertTrue(x[3] is not masked)
<del> self.assertTrue(eq(x, [0, 1, 10, 40, 4]))
<add> assert_(y[0] is masked)
<add> assert_(y[1] is not masked)
<add> assert_(eq(y, [10, 40]))
<add> assert_(x[2] is masked)
<add> assert_(x[3] is not masked)
<add> assert_(eq(x, [0, 1, 10, 40, 4]))
<ide>
<ide> def test_testMaPut(self):
<ide> (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
<ide> def test_testMasked(self):
<ide> # Test of masked element
<ide> xx = arange(6)
<ide> xx[1] = masked
<del> self.assertTrue(str(masked) == '--')
<del> self.assertTrue(xx[1] is masked)
<del> self.assertEqual(filled(xx[1], 0), 0)
<add> assert_(str(masked) == '--')
<add> assert_(xx[1] is masked)
<add> assert_equal(filled(xx[1], 0), 0)
<ide>
<ide> def test_testAverage1(self):
<ide> # Test of average.
<ide> ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0])
<del> self.assertTrue(eq(2.0, average(ott, axis=0)))
<del> self.assertTrue(eq(2.0, average(ott, weights=[1., 1., 2., 1.])))
<add> assert_(eq(2.0, average(ott, axis=0)))
<add> assert_(eq(2.0, average(ott, weights=[1., 1., 2., 1.])))
<ide> result, wts = average(ott, weights=[1., 1., 2., 1.], returned=1)
<del> self.assertTrue(eq(2.0, result))
<del> self.assertTrue(wts == 4.0)
<add> assert_(eq(2.0, result))
<add> assert_(wts == 4.0)
<ide> ott[:] = masked
<del> self.assertTrue(average(ott, axis=0) is masked)
<add> assert_(average(ott, axis=0) is masked)
<ide> ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0])
<ide> ott = ott.reshape(2, 2)
<ide> ott[:, 1] = masked
<del> self.assertTrue(eq(average(ott, axis=0), [2.0, 0.0]))
<del> self.assertTrue(average(ott, axis=1)[0] is masked)
<del> self.assertTrue(eq([2., 0.], average(ott, axis=0)))
<add> assert_(eq(average(ott, axis=0), [2.0, 0.0]))
<add> assert_(average(ott, axis=1)[0] is masked)
<add> assert_(eq([2., 0.], average(ott, axis=0)))
<ide> result, wts = average(ott, axis=0, returned=1)
<del> self.assertTrue(eq(wts, [1., 0.]))
<add> assert_(eq(wts, [1., 0.]))
<ide>
<ide> def test_testAverage2(self):
<ide> # More tests of average.
<ide> w1 = [0, 1, 1, 1, 1, 0]
<ide> w2 = [[0, 1, 1, 1, 1, 0], [1, 0, 0, 0, 0, 1]]
<ide> x = arange(6)
<del> self.assertTrue(allclose(average(x, axis=0), 2.5))
<del> self.assertTrue(allclose(average(x, axis=0, weights=w1), 2.5))
<add> assert_(allclose(average(x, axis=0), 2.5))
<add> assert_(allclose(average(x, axis=0, weights=w1), 2.5))
<ide> y = array([arange(6), 2.0 * arange(6)])
<del> self.assertTrue(allclose(average(y, None),
<add> assert_(allclose(average(y, None),
<ide> np.add.reduce(np.arange(6)) * 3. / 12.))
<del> self.assertTrue(allclose(average(y, axis=0), np.arange(6) * 3. / 2.))
<del> self.assertTrue(allclose(average(y, axis=1),
<add> assert_(allclose(average(y, axis=0), np.arange(6) * 3. / 2.))
<add> assert_(allclose(average(y, axis=1),
<ide> [average(x, axis=0), average(x, axis=0)*2.0]))
<del> self.assertTrue(allclose(average(y, None, weights=w2), 20. / 6.))
<del> self.assertTrue(allclose(average(y, axis=0, weights=w2),
<add> assert_(allclose(average(y, None, weights=w2), 20. / 6.))
<add> assert_(allclose(average(y, axis=0, weights=w2),
<ide> [0., 1., 2., 3., 4., 10.]))
<del> self.assertTrue(allclose(average(y, axis=1),
<add> assert_(allclose(average(y, axis=1),
<ide> [average(x, axis=0), average(x, axis=0)*2.0]))
<ide> m1 = zeros(6)
<ide> m2 = [0, 0, 1, 1, 0, 0]
<ide> m3 = [[0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0]]
<ide> m4 = ones(6)
<ide> m5 = [0, 1, 1, 1, 1, 1]
<del> self.assertTrue(allclose(average(masked_array(x, m1), axis=0), 2.5))
<del> self.assertTrue(allclose(average(masked_array(x, m2), axis=0), 2.5))
<del> self.assertTrue(average(masked_array(x, m4), axis=0) is masked)
<del> self.assertEqual(average(masked_array(x, m5), axis=0), 0.0)
<del> self.assertEqual(count(average(masked_array(x, m4), axis=0)), 0)
<add> assert_(allclose(average(masked_array(x, m1), axis=0), 2.5))
<add> assert_(allclose(average(masked_array(x, m2), axis=0), 2.5))
<add> assert_(average(masked_array(x, m4), axis=0) is masked)
<add> assert_equal(average(masked_array(x, m5), axis=0), 0.0)
<add> assert_equal(count(average(masked_array(x, m4), axis=0)), 0)
<ide> z = masked_array(y, m3)
<del> self.assertTrue(allclose(average(z, None), 20. / 6.))
<del> self.assertTrue(allclose(average(z, axis=0),
<add> assert_(allclose(average(z, None), 20. / 6.))
<add> assert_(allclose(average(z, axis=0),
<ide> [0., 1., 99., 99., 4.0, 7.5]))
<del> self.assertTrue(allclose(average(z, axis=1), [2.5, 5.0]))
<del> self.assertTrue(allclose(average(z, axis=0, weights=w2),
<add> assert_(allclose(average(z, axis=1), [2.5, 5.0]))
<add> assert_(allclose(average(z, axis=0, weights=w2),
<ide> [0., 1., 99., 99., 4.0, 10.0]))
<ide>
<ide> a = arange(6)
<ide> b = arange(6) * 3
<ide> r1, w1 = average([[a, b], [b, a]], axis=1, returned=1)
<del> self.assertEqual(shape(r1), shape(w1))
<del> self.assertEqual(r1.shape, w1.shape)
<add> assert_equal(shape(r1), shape(w1))
<add> assert_equal(r1.shape, w1.shape)
<ide> r2, w2 = average(ones((2, 2, 3)), axis=0, weights=[3, 1], returned=1)
<del> self.assertEqual(shape(w2), shape(r2))
<add> assert_equal(shape(w2), shape(r2))
<ide> r2, w2 = average(ones((2, 2, 3)), returned=1)
<del> self.assertEqual(shape(w2), shape(r2))
<add> assert_equal(shape(w2), shape(r2))
<ide> r2, w2 = average(ones((2, 2, 3)), weights=ones((2, 2, 3)), returned=1)
<del> self.assertTrue(shape(w2) == shape(r2))
<add> assert_(shape(w2) == shape(r2))
<ide> a2d = array([[1, 2], [0, 4]], float)
<ide> a2dm = masked_array(a2d, [[0, 0], [1, 0]])
<ide> a2da = average(a2d, axis=0)
<del> self.assertTrue(eq(a2da, [0.5, 3.0]))
<add> assert_(eq(a2da, [0.5, 3.0]))
<ide> a2dma = average(a2dm, axis=0)
<del> self.assertTrue(eq(a2dma, [1.0, 3.0]))
<add> assert_(eq(a2dma, [1.0, 3.0]))
<ide> a2dma = average(a2dm, axis=None)
<del> self.assertTrue(eq(a2dma, 7. / 3.))
<add> assert_(eq(a2dma, 7. / 3.))
<ide> a2dma = average(a2dm, axis=1)
<del> self.assertTrue(eq(a2dma, [1.5, 4.0]))
<add> assert_(eq(a2dma, [1.5, 4.0]))
<ide>
<ide> def test_testToPython(self):
<del> self.assertEqual(1, int(array(1)))
<del> self.assertEqual(1.0, float(array(1)))
<del> self.assertEqual(1, int(array([[[1]]])))
<del> self.assertEqual(1.0, float(array([[1]])))
<del> self.assertRaises(TypeError, float, array([1, 1]))
<del> self.assertRaises(ValueError, bool, array([0, 1]))
<del> self.assertRaises(ValueError, bool, array([0, 0], mask=[0, 1]))
<add> assert_equal(1, int(array(1)))
<add> assert_equal(1.0, float(array(1)))
<add> assert_equal(1, int(array([[[1]]])))
<add> assert_equal(1.0, float(array([[1]])))
<add> assert_raises(TypeError, float, array([1, 1]))
<add> assert_raises(ValueError, bool, array([0, 1]))
<add> assert_raises(ValueError, bool, array([0, 0], mask=[0, 1]))
<ide>
<ide> def test_testScalarArithmetic(self):
<ide> xm = array(0, mask=1)
<ide> #TODO FIXME: Find out what the following raises a warning in r8247
<ide> with np.errstate(divide='ignore'):
<del> self.assertTrue((1 / array(0)).mask)
<del> self.assertTrue((1 + xm).mask)
<del> self.assertTrue((-xm).mask)
<del> self.assertTrue((-xm).mask)
<del> self.assertTrue(maximum(xm, xm).mask)
<del> self.assertTrue(minimum(xm, xm).mask)
<del> self.assertTrue(xm.filled().dtype is xm._data.dtype)
<add> assert_((1 / array(0)).mask)
<add> assert_((1 + xm).mask)
<add> assert_((-xm).mask)
<add> assert_((-xm).mask)
<add> assert_(maximum(xm, xm).mask)
<add> assert_(minimum(xm, xm).mask)
<add> assert_(xm.filled().dtype is xm._data.dtype)
<ide> x = array(0, mask=0)
<del> self.assertTrue(x.filled() == x._data)
<del> self.assertEqual(str(xm), str(masked_print_option))
<add> assert_(x.filled() == x._data)
<add> assert_equal(str(xm), str(masked_print_option))
<ide>
<ide> def test_testArrayMethods(self):
<ide> a = array([1, 3, 2])
<del> self.assertTrue(eq(a.any(), a._data.any()))
<del> self.assertTrue(eq(a.all(), a._data.all()))
<del> self.assertTrue(eq(a.argmax(), a._data.argmax()))
<del> self.assertTrue(eq(a.argmin(), a._data.argmin()))
<del> self.assertTrue(eq(a.choose(0, 1, 2, 3, 4),
<add> assert_(eq(a.any(), a._data.any()))
<add> assert_(eq(a.all(), a._data.all()))
<add> assert_(eq(a.argmax(), a._data.argmax()))
<add> assert_(eq(a.argmin(), a._data.argmin()))
<add> assert_(eq(a.choose(0, 1, 2, 3, 4),
<ide> a._data.choose(0, 1, 2, 3, 4)))
<del> self.assertTrue(eq(a.compress([1, 0, 1]), a._data.compress([1, 0, 1])))
<del> self.assertTrue(eq(a.conj(), a._data.conj()))
<del> self.assertTrue(eq(a.conjugate(), a._data.conjugate()))
<add> assert_(eq(a.compress([1, 0, 1]), a._data.compress([1, 0, 1])))
<add> assert_(eq(a.conj(), a._data.conj()))
<add> assert_(eq(a.conjugate(), a._data.conjugate()))
<ide> m = array([[1, 2], [3, 4]])
<del> self.assertTrue(eq(m.diagonal(), m._data.diagonal()))
<del> self.assertTrue(eq(a.sum(), a._data.sum()))
<del> self.assertTrue(eq(a.take([1, 2]), a._data.take([1, 2])))
<del> self.assertTrue(eq(m.transpose(), m._data.transpose()))
<add> assert_(eq(m.diagonal(), m._data.diagonal()))
<add> assert_(eq(a.sum(), a._data.sum()))
<add> assert_(eq(a.take([1, 2]), a._data.take([1, 2])))
<add> assert_(eq(m.transpose(), m._data.transpose()))
<ide>
<ide> def test_testArrayAttributes(self):
<ide> a = array([1, 3, 2])
<del> self.assertEqual(a.ndim, 1)
<add> assert_equal(a.ndim, 1)
<ide>
<ide> def test_testAPI(self):
<del> self.assertFalse([m for m in dir(np.ndarray)
<del> if m not in dir(MaskedArray) and
<del> not m.startswith('_')])
<add> assert_(not [m for m in dir(np.ndarray)
<add> if m not in dir(MaskedArray) and
<add> not m.startswith('_')])
<ide>
<ide> def test_testSingleElementSubscript(self):
<ide> a = array([1, 3, 2])
<ide> b = array([1, 3, 2], mask=[1, 0, 1])
<del> self.assertEqual(a[0].shape, ())
<del> self.assertEqual(b[0].shape, ())
<del> self.assertEqual(b[1].shape, ())
<add> assert_equal(a[0].shape, ())
<add> assert_equal(b[0].shape, ())
<add> assert_equal(b[1].shape, ())
<ide>
<ide>
<del>class TestUfuncs(TestCase):
<del> def setUp(self):
<add>class TestUfuncs(object):
<add> def setup(self):
<ide> self.d = (array([1.0, 0, -1, pi / 2] * 2, mask=[0, 1] + [0] * 6),
<ide> array([1.0, 0, -1, pi / 2] * 2, mask=[1, 0] + [0] * 6),)
<ide>
<ide> def test_testUfuncRegression(self):
<ide> np.seterr(divide='ignore')
<ide> ur = uf(*args)
<ide> mr = mf(*args)
<del> self.assertTrue(eq(ur.filled(0), mr.filled(0), f))
<del> self.assertTrue(eqmask(ur.mask, mr.mask))
<add> assert_(eq(ur.filled(0), mr.filled(0), f))
<add> assert_(eqmask(ur.mask, mr.mask))
<ide>
<ide> def test_reduce(self):
<ide> a = self.d[0]
<del> self.assertFalse(alltrue(a, axis=0))
<del> self.assertTrue(sometrue(a, axis=0))
<del> self.assertEqual(sum(a[:3], axis=0), 0)
<del> self.assertEqual(product(a, axis=0), 0)
<add> assert_(not alltrue(a, axis=0))
<add> assert_(sometrue(a, axis=0))
<add> assert_equal(sum(a[:3], axis=0), 0)
<add> assert_equal(product(a, axis=0), 0)
<ide>
<ide> def test_minmax(self):
<ide> a = arange(1, 13).reshape(3, 4)
<ide> amask = masked_where(a < 5, a)
<del> self.assertEqual(amask.max(), a.max())
<del> self.assertEqual(amask.min(), 5)
<del> self.assertTrue((amask.max(0) == a.max(0)).all())
<del> self.assertTrue((amask.min(0) == [5, 6, 7, 8]).all())
<del> self.assertTrue(amask.max(1)[0].mask)
<del> self.assertTrue(amask.min(1)[0].mask)
<add> assert_equal(amask.max(), a.max())
<add> assert_equal(amask.min(), 5)
<add> assert_((amask.max(0) == a.max(0)).all())
<add> assert_((amask.min(0) == [5, 6, 7, 8]).all())
<add> assert_(amask.max(1)[0].mask)
<add> assert_(amask.min(1)[0].mask)
<ide>
<ide> def test_nonzero(self):
<ide> for t in "?bhilqpBHILQPfdgFDGO":
<ide> x = array([1, 0, 2, 0], mask=[0, 0, 1, 1])
<del> self.assertTrue(eq(nonzero(x), [0]))
<add> assert_(eq(nonzero(x), [0]))
<ide>
<ide>
<del>class TestArrayMethods(TestCase):
<add>class TestArrayMethods(object):
<ide>
<del> def setUp(self):
<add> def setup(self):
<ide> x = np.array([8.375, 7.545, 8.828, 8.5, 1.757, 5.928,
<ide> 8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
<ide> 3.012, 6.022, 5.095, 3.116, 5.238, 3.957,
<ide> def setUp(self):
<ide> def test_trace(self):
<ide> (x, X, XX, m, mx, mX, mXX,) = self.d
<ide> mXdiag = mX.diagonal()
<del> self.assertEqual(mX.trace(), mX.diagonal().compressed().sum())
<del> self.assertTrue(eq(mX.trace(),
<add> assert_equal(mX.trace(), mX.diagonal().compressed().sum())
<add> assert_(eq(mX.trace(),
<ide> X.trace() - sum(mXdiag.mask * X.diagonal(),
<ide> axis=0)))
<ide>
<ide> def test_clip(self):
<ide> (x, X, XX, m, mx, mX, mXX,) = self.d
<ide> clipped = mx.clip(2, 8)
<del> self.assertTrue(eq(clipped.mask, mx.mask))
<del> self.assertTrue(eq(clipped._data, x.clip(2, 8)))
<del> self.assertTrue(eq(clipped._data, mx._data.clip(2, 8)))
<add> assert_(eq(clipped.mask, mx.mask))
<add> assert_(eq(clipped._data, x.clip(2, 8)))
<add> assert_(eq(clipped._data, mx._data.clip(2, 8)))
<ide>
<ide> def test_ptp(self):
<ide> (x, X, XX, m, mx, mX, mXX,) = self.d
<ide> (n, m) = X.shape
<del> self.assertEqual(mx.ptp(), mx.compressed().ptp())
<add> assert_equal(mx.ptp(), mx.compressed().ptp())
<ide> rows = np.zeros(n, np.float_)
<ide> cols = np.zeros(m, np.float_)
<ide> for k in range(m):
<ide> cols[k] = mX[:, k].compressed().ptp()
<ide> for k in range(n):
<ide> rows[k] = mX[k].compressed().ptp()
<del> self.assertTrue(eq(mX.ptp(0), cols))
<del> self.assertTrue(eq(mX.ptp(1), rows))
<add> assert_(eq(mX.ptp(0), cols))
<add> assert_(eq(mX.ptp(1), rows))
<ide>
<ide> def test_swapaxes(self):
<ide> (x, X, XX, m, mx, mX, mXX,) = self.d
<ide> mXswapped = mX.swapaxes(0, 1)
<del> self.assertTrue(eq(mXswapped[-1], mX[:, -1]))
<add> assert_(eq(mXswapped[-1], mX[:, -1]))
<ide> mXXswapped = mXX.swapaxes(0, 2)
<del> self.assertEqual(mXXswapped.shape, (2, 2, 3, 3))
<add> assert_equal(mXXswapped.shape, (2, 2, 3, 3))
<ide>
<ide> def test_cumprod(self):
<ide> (x, X, XX, m, mx, mX, mXX,) = self.d
<ide> mXcp = mX.cumprod(0)
<del> self.assertTrue(eq(mXcp._data, mX.filled(1).cumprod(0)))
<add> assert_(eq(mXcp._data, mX.filled(1).cumprod(0)))
<ide> mXcp = mX.cumprod(1)
<del> self.assertTrue(eq(mXcp._data, mX.filled(1).cumprod(1)))
<add> assert_(eq(mXcp._data, mX.filled(1).cumprod(1)))
<ide>
<ide> def test_cumsum(self):
<ide> (x, X, XX, m, mx, mX, mXX,) = self.d
<ide> mXcp = mX.cumsum(0)
<del> self.assertTrue(eq(mXcp._data, mX.filled(0).cumsum(0)))
<add> assert_(eq(mXcp._data, mX.filled(0).cumsum(0)))
<ide> mXcp = mX.cumsum(1)
<del> self.assertTrue(eq(mXcp._data, mX.filled(0).cumsum(1)))
<add> assert_(eq(mXcp._data, mX.filled(0).cumsum(1)))
<ide>
<ide> def test_varstd(self):
<ide> (x, X, XX, m, mx, mX, mXX,) = self.d
<del> self.assertTrue(eq(mX.var(axis=None), mX.compressed().var()))
<del> self.assertTrue(eq(mX.std(axis=None), mX.compressed().std()))
<del> self.assertTrue(eq(mXX.var(axis=3).shape, XX.var(axis=3).shape))
<del> self.assertTrue(eq(mX.var().shape, X.var().shape))
<add> assert_(eq(mX.var(axis=None), mX.compressed().var()))
<add> assert_(eq(mX.std(axis=None), mX.compressed().std()))
<add> assert_(eq(mXX.var(axis=3).shape, XX.var(axis=3).shape))
<add> assert_(eq(mX.var().shape, X.var().shape))
<ide> (mXvar0, mXvar1) = (mX.var(axis=0), mX.var(axis=1))
<ide> for k in range(6):
<del> self.assertTrue(eq(mXvar1[k], mX[k].compressed().var()))
<del> self.assertTrue(eq(mXvar0[k], mX[:, k].compressed().var()))
<del> self.assertTrue(eq(np.sqrt(mXvar0[k]),
<add> assert_(eq(mXvar1[k], mX[k].compressed().var()))
<add> assert_(eq(mXvar0[k], mX[:, k].compressed().var()))
<add> assert_(eq(np.sqrt(mXvar0[k]),
<ide> mX[:, k].compressed().std()))
<ide>
<ide>
<ide><path>numpy/ma/tests/test_regression.py
<ide> import warnings
<ide>
<ide> import numpy as np
<del>from numpy.testing import (assert_, TestCase, assert_array_equal,
<del> assert_allclose, run_module_suite,
<del> suppress_warnings)
<add>from numpy.testing import (
<add> assert_, assert_array_equal, assert_allclose, run_module_suite,
<add> suppress_warnings
<add> )
<ide>
<ide> rlevel = 1
<ide>
<ide>
<del>class TestRegression(TestCase):
<add>class TestRegression(object):
<ide> def test_masked_array_create(self,level=rlevel):
<ide> # Ticket #17
<ide> x = np.ma.masked_array([0, 1, 2, 3, 0, 4, 5, 6],
<ide><path>numpy/ma/tests/test_subclassing.py
<ide> from __future__ import division, absolute_import, print_function
<ide>
<ide> import numpy as np
<del>from numpy.testing import TestCase, run_module_suite, assert_raises, dec
<add>from numpy.testing import run_module_suite, assert_, assert_raises, dec
<ide> from numpy.ma.testutils import assert_equal
<ide> from numpy.ma.core import (
<ide> array, arange, masked, MaskedArray, masked_array, log, add, hypot,
<ide> def __array_wrap__(self, obj, context=None):
<ide> return obj
<ide>
<ide>
<del>class TestSubclassing(TestCase):
<add>class TestSubclassing(object):
<ide> # Test suite for masked subclasses of ndarray.
<ide>
<del> def setUp(self):
<add> def setup(self):
<ide> x = np.arange(5, dtype='float')
<ide> mx = mmatrix(x, mask=[0, 1, 0, 0, 0])
<ide> self.data = (x, mx)
<ide> def test_data_subclassing(self):
<ide> m = [0, 0, 1, 0, 0]
<ide> xsub = SubArray(x)
<ide> xmsub = masked_array(xsub, mask=m)
<del> self.assertTrue(isinstance(xmsub, MaskedArray))
<add> assert_(isinstance(xmsub, MaskedArray))
<ide> assert_equal(xmsub._data, xsub)
<del> self.assertTrue(isinstance(xmsub._data, SubArray))
<add> assert_(isinstance(xmsub._data, SubArray))
<ide>
<ide> def test_maskedarray_subclassing(self):
<ide> # Tests subclassing MaskedArray
<ide> (x, mx) = self.data
<del> self.assertTrue(isinstance(mx._data, np.matrix))
<add> assert_(isinstance(mx._data, np.matrix))
<ide>
<ide> def test_masked_unary_operations(self):
<ide> # Tests masked_unary_operation
<ide> (x, mx) = self.data
<ide> with np.errstate(divide='ignore'):
<del> self.assertTrue(isinstance(log(mx), mmatrix))
<add> assert_(isinstance(log(mx), mmatrix))
<ide> assert_equal(log(x), np.log(x))
<ide>
<ide> def test_masked_binary_operations(self):
<ide> # Tests masked_binary_operation
<ide> (x, mx) = self.data
<ide> # Result should be a mmatrix
<del> self.assertTrue(isinstance(add(mx, mx), mmatrix))
<del> self.assertTrue(isinstance(add(mx, x), mmatrix))
<add> assert_(isinstance(add(mx, mx), mmatrix))
<add> assert_(isinstance(add(mx, x), mmatrix))
<ide> # Result should work
<ide> assert_equal(add(mx, x), mx+x)
<del> self.assertTrue(isinstance(add(mx, mx)._data, np.matrix))
<del> self.assertTrue(isinstance(add.outer(mx, mx), mmatrix))
<del> self.assertTrue(isinstance(hypot(mx, mx), mmatrix))
<del> self.assertTrue(isinstance(hypot(mx, x), mmatrix))
<add> assert_(isinstance(add(mx, mx)._data, np.matrix))
<add> assert_(isinstance(add.outer(mx, mx), mmatrix))
<add> assert_(isinstance(hypot(mx, mx), mmatrix))
<add> assert_(isinstance(hypot(mx, x), mmatrix))
<ide>
<ide> def test_masked_binary_operations2(self):
<ide> # Tests domained_masked_binary_operation
<ide> (x, mx) = self.data
<ide> xmx = masked_array(mx.data.__array__(), mask=mx.mask)
<del> self.assertTrue(isinstance(divide(mx, mx), mmatrix))
<del> self.assertTrue(isinstance(divide(mx, x), mmatrix))
<add> assert_(isinstance(divide(mx, mx), mmatrix))
<add> assert_(isinstance(divide(mx, x), mmatrix))
<ide> assert_equal(divide(mx, mx), divide(xmx, xmx))
<ide>
<ide> def test_attributepropagation(self):
<ide> def test_attributepropagation(self):
<ide> ym = msubarray(x)
<ide> #
<ide> z = (my+1)
<del> self.assertTrue(isinstance(z, MaskedArray))
<del> self.assertTrue(not isinstance(z, MSubArray))
<del> self.assertTrue(isinstance(z._data, SubArray))
<add> assert_(isinstance(z, MaskedArray))
<add> assert_(not isinstance(z, MSubArray))
<add> assert_(isinstance(z._data, SubArray))
<ide> assert_equal(z._data.info, {})
<ide> #
<ide> z = (ym+1)
<del> self.assertTrue(isinstance(z, MaskedArray))
<del> self.assertTrue(isinstance(z, MSubArray))
<del> self.assertTrue(isinstance(z._data, SubArray))
<del> self.assertTrue(z._data.info['added'] > 0)
<add> assert_(isinstance(z, MaskedArray))
<add> assert_(isinstance(z, MSubArray))
<add> assert_(isinstance(z._data, SubArray))
<add> assert_(z._data.info['added'] > 0)
<ide> # Test that inplace methods from data get used (gh-4617)
<ide> ym += 1
<del> self.assertTrue(isinstance(ym, MaskedArray))
<del> self.assertTrue(isinstance(ym, MSubArray))
<del> self.assertTrue(isinstance(ym._data, SubArray))
<del> self.assertTrue(ym._data.info['iadded'] > 0)
<add> assert_(isinstance(ym, MaskedArray))
<add> assert_(isinstance(ym, MSubArray))
<add> assert_(isinstance(ym._data, SubArray))
<add> assert_(ym._data.info['iadded'] > 0)
<ide> #
<ide> ym._set_mask([1, 0, 0, 0, 1])
<ide> assert_equal(ym._mask, [1, 0, 0, 0, 1])
<ide> def test_attributepropagation(self):
<ide> #
<ide> xsub = subarray(x, info={'name':'x'})
<ide> mxsub = masked_array(xsub)
<del> self.assertTrue(hasattr(mxsub, 'info'))
<add> assert_(hasattr(mxsub, 'info'))
<ide> assert_equal(mxsub.info, xsub.info)
<ide>
<ide> def test_subclasspreservation(self):
<ide> def test_subclasspreservation(self):
<ide> xsub = MSubArray(x, mask=m, info={'xsub':xinfo})
<ide> #
<ide> mxsub = masked_array(xsub, subok=False)
<del> self.assertTrue(not isinstance(mxsub, MSubArray))
<del> self.assertTrue(isinstance(mxsub, MaskedArray))
<add> assert_(not isinstance(mxsub, MSubArray))
<add> assert_(isinstance(mxsub, MaskedArray))
<ide> assert_equal(mxsub._mask, m)
<ide> #
<ide> mxsub = asarray(xsub)
<del> self.assertTrue(not isinstance(mxsub, MSubArray))
<del> self.assertTrue(isinstance(mxsub, MaskedArray))
<add> assert_(not isinstance(mxsub, MSubArray))
<add> assert_(isinstance(mxsub, MaskedArray))
<ide> assert_equal(mxsub._mask, m)
<ide> #
<ide> mxsub = masked_array(xsub, subok=True)
<del> self.assertTrue(isinstance(mxsub, MSubArray))
<add> assert_(isinstance(mxsub, MSubArray))
<ide> assert_equal(mxsub.info, xsub.info)
<ide> assert_equal(mxsub._mask, xsub._mask)
<ide> #
<ide> mxsub = asanyarray(xsub)
<del> self.assertTrue(isinstance(mxsub, MSubArray))
<add> assert_(isinstance(mxsub, MSubArray))
<ide> assert_equal(mxsub.info, xsub.info)
<ide> assert_equal(mxsub._mask, m)
<ide>
<ide> def test_subclass_items(self):
<ide> mxcsub = masked_array(xcsub, mask=[True, False, True, False, False])
<ide> # getter should return a ComplicatedSubArray, even for single item
<ide> # first check we wrote ComplicatedSubArray correctly
<del> self.assertTrue(isinstance(xcsub[1], ComplicatedSubArray))
<del> self.assertTrue(isinstance(xcsub[1,...], ComplicatedSubArray))
<del> self.assertTrue(isinstance(xcsub[1:4], ComplicatedSubArray))
<add> assert_(isinstance(xcsub[1], ComplicatedSubArray))
<add> assert_(isinstance(xcsub[1,...], ComplicatedSubArray))
<add> assert_(isinstance(xcsub[1:4], ComplicatedSubArray))
<ide>
<ide> # now that it propagates inside the MaskedArray
<del> self.assertTrue(isinstance(mxcsub[1], ComplicatedSubArray))
<del> self.assertTrue(isinstance(mxcsub[1,...].data, ComplicatedSubArray))
<del> self.assertTrue(mxcsub[0] is masked)
<del> self.assertTrue(isinstance(mxcsub[0,...].data, ComplicatedSubArray))
<del> self.assertTrue(isinstance(mxcsub[1:4].data, ComplicatedSubArray))
<add> assert_(isinstance(mxcsub[1], ComplicatedSubArray))
<add> assert_(isinstance(mxcsub[1,...].data, ComplicatedSubArray))
<add> assert_(mxcsub[0] is masked)
<add> assert_(isinstance(mxcsub[0,...].data, ComplicatedSubArray))
<add> assert_(isinstance(mxcsub[1:4].data, ComplicatedSubArray))
<ide>
<ide> # also for flattened version (which goes via MaskedIterator)
<del> self.assertTrue(isinstance(mxcsub.flat[1].data, ComplicatedSubArray))
<del> self.assertTrue(mxcsub.flat[0] is masked)
<del> self.assertTrue(isinstance(mxcsub.flat[1:4].base, ComplicatedSubArray))
<add> assert_(isinstance(mxcsub.flat[1].data, ComplicatedSubArray))
<add> assert_(mxcsub.flat[0] is masked)
<add> assert_(isinstance(mxcsub.flat[1:4].base, ComplicatedSubArray))
<ide>
<ide> # setter should only work with ComplicatedSubArray input
<ide> # first check we wrote ComplicatedSubArray correctly
<ide> def test_subclass_nomask_items(self):
<ide> xcsub = ComplicatedSubArray(x)
<ide> mxcsub_nomask = masked_array(xcsub)
<ide>
<del> self.assertTrue(isinstance(mxcsub_nomask[1,...].data, ComplicatedSubArray))
<del> self.assertTrue(isinstance(mxcsub_nomask[0,...].data, ComplicatedSubArray))
<add> assert_(isinstance(mxcsub_nomask[1,...].data, ComplicatedSubArray))
<add> assert_(isinstance(mxcsub_nomask[0,...].data, ComplicatedSubArray))
<ide>
<del> self.assertTrue(isinstance(mxcsub_nomask[1], ComplicatedSubArray))
<del> self.assertTrue(isinstance(mxcsub_nomask[0], ComplicatedSubArray))
<add> assert_(isinstance(mxcsub_nomask[1], ComplicatedSubArray))
<add> assert_(isinstance(mxcsub_nomask[0], ComplicatedSubArray))
<ide>
<ide> def test_subclass_repr(self):
<ide> """test that repr uses the name of the subclass
<ide> and 'array' for np.ndarray"""
<ide> x = np.arange(5)
<ide> mx = masked_array(x, mask=[True, False, True, False, False])
<del> self.assertTrue(repr(mx).startswith('masked_array'))
<add> assert_(repr(mx).startswith('masked_array'))
<ide> xsub = SubArray(x)
<ide> mxsub = masked_array(xsub, mask=[True, False, True, False, False])
<del> self.assertTrue(repr(mxsub).startswith(
<add> assert_(repr(mxsub).startswith(
<ide> 'masked_{0}(data = [-- 1 -- 3 4]'.format(SubArray.__name__)))
<ide>
<ide> def test_subclass_str(self):
<ide> def test_subclass_str(self):
<ide> x = np.arange(5)
<ide> xsub = SubArray(x)
<ide> mxsub = masked_array(xsub, mask=[True, False, True, False, False])
<del> self.assertTrue(str(mxsub) == '[-- 1 -- 3 4]')
<add> assert_(str(mxsub) == '[-- 1 -- 3 4]')
<ide>
<ide> xcsub = ComplicatedSubArray(x)
<ide> assert_raises(ValueError, xcsub.__setitem__, 0,
<ide> np.ma.core.masked_print_option)
<ide> mxcsub = masked_array(xcsub, mask=[True, False, True, False, False])
<del> self.assertTrue(str(mxcsub) == 'myprefix [-- 1 -- 3 4] mypostfix')
<add> assert_(str(mxcsub) == 'myprefix [-- 1 -- 3 4] mypostfix')
<ide>
<ide> def test_pure_subclass_info_preservation(self):
<ide> # Test that ufuncs and methods conserve extra information consistently;
<ide> # see gh-7122.
<ide> arr1 = SubMaskedArray('test', data=[1,2,3,4,5,6])
<ide> arr2 = SubMaskedArray(data=[0,1,2,3,4,5])
<ide> diff1 = np.subtract(arr1, arr2)
<del> self.assertTrue('info' in diff1._optinfo)
<del> self.assertTrue(diff1._optinfo['info'] == 'test')
<add> assert_('info' in diff1._optinfo)
<add> assert_(diff1._optinfo['info'] == 'test')
<ide> diff2 = arr1 - arr2
<del> self.assertTrue('info' in diff2._optinfo)
<del> self.assertTrue(diff2._optinfo['info'] == 'test')
<add> assert_('info' in diff2._optinfo)
<add> assert_(diff2._optinfo['info'] == 'test')
<ide>
<ide>
<ide> ############################################################################### | 7 |
Python | Python | add missing license header | c7ba84fd744168a63ab34c29846e1680a2d384b7 | <ide><path>libcloud/test/compute/test_azure.py
<del>import libcloud
<add># Licensed to the Apache Software Foundation (ASF) under one or more
<add># contributor license agreements. See the NOTICE file distributed with
<add># this work for additional information regarding copyright ownership.
<add># The ASF licenses this file to You under the Apache License, Version 2.0
<add># (the "License"); you may not use this file except in compliance with
<add># the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.import libcloud
<add>
<ide> from libcloud.common.types import LibcloudError
<ide> from libcloud.compute.base import NodeAuthPassword, NodeImage, NodeSize
<ide> from libcloud.compute.drivers.azure import azure_service_management_host
<ide>
<del>__author__ = 'david'
<del>
<ide> import os
<ide> import sys
<ide> | 1 |
Java | Java | fix capitalization of componentfactory in rntester | 83116e34bc4858e69e774cc2ed640f6d305cd4f3 | <ide><path>packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterApplication.java
<ide> public JSIModuleType getJSIModuleType() {
<ide>
<ide> @Override
<ide> public JSIModuleProvider<UIManager> getJSIModuleProvider() {
<del> final ComponentFactory ComponentFactory = new ComponentFactory();
<del> CoreComponentsRegistry.register(ComponentFactory);
<add> final ComponentFactory componentFactory = new ComponentFactory();
<add> CoreComponentsRegistry.register(componentFactory);
<ide> final ReactInstanceManager reactInstanceManager = getReactInstanceManager();
<ide>
<ide> ViewManagerRegistry viewManagerRegistry =
<ide> public JSIModuleProvider<UIManager> getJSIModuleProvider() {
<ide>
<ide> return new FabricJSIModuleProvider(
<ide> reactApplicationContext,
<del> ComponentFactory,
<add> componentFactory,
<ide> // TODO: T71362667 add ReactNativeConfig's support in RNTester
<ide> new ReactNativeConfig() {
<ide> @Override | 1 |
PHP | PHP | fix failing test | 5a96ac2a1acb642d7ec9e4e0ab33000772c6718e | <ide><path>tests/Support/SupportArrTest.php
<ide> public function testHas()
<ide> {
<ide> $array = ['products.desk' => ['price' => 100]];
<ide> $this->assertTrue(Arr::has($array, 'products.desk'));
<del> $this->assertTrue(Arr::has($array, ['products.desk']));
<del> $this->assertFalse(Arr::has($array, ['products.desk', 'missing']));
<ide>
<ide> $array = ['products' => ['desk' => ['price' => 100]]];
<ide> $this->assertTrue(Arr::has($array, 'products.desk')); | 1 |
Go | Go | fix docker top a restarting container | 5566ccb7aa0747005573f6f4f04f46552b75a394 | <ide><path>daemon/exec.go
<ide> func (d *Daemon) getExecConfig(name string) (*exec.Config, error) {
<ide> return nil, derr.ErrorCodeExecPaused.WithArgs(container.ID)
<ide> }
<ide> if container.IsRestarting() {
<del> return nil, derr.ErrorCodeExecRestarting.WithArgs(container.ID)
<add> return nil, derr.ErrorCodeContainerRestarting.WithArgs(container.ID)
<ide> }
<ide> return ec, nil
<ide> }
<ide> func (d *Daemon) getActiveContainer(name string) (*container.Container, error) {
<ide> return nil, derr.ErrorCodeExecPaused.WithArgs(name)
<ide> }
<ide> if container.IsRestarting() {
<del> return nil, derr.ErrorCodeExecRestarting.WithArgs(name)
<add> return nil, derr.ErrorCodeContainerRestarting.WithArgs(name)
<ide> }
<ide> return container, nil
<ide> }
<ide><path>daemon/top_unix.go
<ide> func (daemon *Daemon) ContainerTop(name string, psArgs string) (*types.Container
<ide> return nil, derr.ErrorCodeNotRunning.WithArgs(name)
<ide> }
<ide>
<add> if container.IsRestarting() {
<add> return nil, derr.ErrorCodeContainerRestarting.WithArgs(name)
<add> }
<ide> pids, err := daemon.ExecutionDriver().GetPidsForContainer(container.ID)
<ide> if err != nil {
<ide> return nil, err
<ide><path>errors/daemon.go
<ide> var (
<ide> HTTPStatusCode: http.StatusConflict,
<ide> })
<ide>
<add> // ErrorCodeContainerRestarting is generated when an operation was made
<add> // on a restarting container.
<add> ErrorCodeContainerRestarting = errcode.Register(errGroup, errcode.ErrorDescriptor{
<add> Value: "CONTAINERRESTARTING",
<add> Message: "Container %s is restarting, wait until the container is running",
<add> Description: "An operation was made on a restarting container",
<add> HTTPStatusCode: http.StatusConflict,
<add> })
<add>
<ide> // ErrorCodeNoExecID is generated when we try to get the info
<ide> // on an exec but it can't be found.
<ide> ErrorCodeNoExecID = errcode.Register(errGroup, errcode.ErrorDescriptor{
<ide> var (
<ide> HTTPStatusCode: http.StatusConflict,
<ide> })
<ide>
<del> // ErrorCodeExecRestarting is generated when we try to start an exec
<del> // but the container is restarting.
<del> ErrorCodeExecRestarting = errcode.Register(errGroup, errcode.ErrorDescriptor{
<del> Value: "EXECRESTARTING",
<del> Message: "Container %s is restarting, wait until the container is running",
<del> Description: "An attempt to start an 'exec' was made, but the owning container is restarting",
<del> HTTPStatusCode: http.StatusConflict,
<del> })
<del>
<ide> // ErrorCodeExecRunning is generated when we try to start an exec
<ide> // but its already running.
<ide> ErrorCodeExecRunning = errcode.Register(errGroup, errcode.ErrorDescriptor{ | 3 |
Javascript | Javascript | reuse variables in shader | 9a768ede0ea7311653576d758dc75de03208eb7b | <ide><path>examples/jsm/csm/Shader.js
<ide> IncidentLight directLight;
<ide> directionalLightShadow = directionalLightShadows[ i ];
<ide> directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
<ide>
<del> bool shouldFadeLastCascade = i == CSM_CASCADES - 1 && linearDepth > ( csmx + csmy ) / 2.0;
<add> bool shouldFadeLastCascade = i == CSM_CASCADES - 1 && linearDepth > cascadeCenter;
<ide> directLight.color = mix( prevColor, directLight.color, shouldFadeLastCascade ? ratio : 1.0 );
<ide>
<ide> }
<ide>
<ide> ReflectedLight prevLight = reflectedLight;
<ide> RE_Direct( directLight, geometry, material, reflectedLight );
<ide>
<del> bool shouldBlend = i != CSM_CASCADES - 1 || i == CSM_CASCADES - 1 && linearDepth < ( csmx + csmy ) / 2.0;
<add> bool shouldBlend = i != CSM_CASCADES - 1 || i == CSM_CASCADES - 1 && linearDepth < cascadeCenter;
<ide> float blendRatio = shouldBlend ? ratio : 1.0;
<ide>
<ide> reflectedLight.directDiffuse = mix( prevLight.directDiffuse, reflectedLight.directDiffuse, blendRatio ); | 1 |
Python | Python | add tokeniser serialisation | 65cea92a66211e1116fe9faea774ca66b09461e7 | <ide><path>keras/preprocessing/text.py
<ide> one_hot = text.one_hot
<ide> hashing_trick = text.hashing_trick
<ide> Tokenizer = text.Tokenizer
<add>tokenizer_from_json = text.tokenizer_from_json | 1 |
Mixed | Python | fix egg fragments in direct download | 88909a9adbaf4f3710603db2697c39f9a7274357 | <ide><path>.github/contributors/adrienball.md
<add># spaCy contributor agreement
<add>
<add>This spaCy Contributor Agreement (**"SCA"**) is based on the
<add>[Oracle Contributor Agreement](http://www.oracle.com/technetwork/oca-405177.pdf).
<add>The SCA applies to any contribution that you make to any product or project
<add>managed by us (the **"project"**), and sets out the intellectual property rights
<add>you grant to us in the contributed materials. The term **"us"** shall mean
<add>[ExplosionAI UG (haftungsbeschränkt)](https://explosion.ai/legal). The term
<add>**"you"** shall mean the person or entity identified below.
<add>
<add>If you agree to be bound by these terms, fill in the information requested
<add>below and include the filled-in version with your first pull request, under the
<add>folder [`.github/contributors/`](/.github/contributors/). The name of the file
<add>should be your GitHub username, with the extension `.md`. For example, the user
<add>example_user would create the file `.github/contributors/example_user.md`.
<add>
<add>Read this agreement carefully before signing. These terms and conditions
<add>constitute a binding legal agreement.
<add>
<add>## Contributor Agreement
<add>
<add>1. The term "contribution" or "contributed materials" means any source code,
<add>object code, patch, tool, sample, graphic, specification, manual,
<add>documentation, or any other material posted or submitted by you to the project.
<add>
<add>2. With respect to any worldwide copyrights, or copyright applications and
<add>registrations, in your contribution:
<add>
<add> * you hereby assign to us joint ownership, and to the extent that such
<add> assignment is or becomes invalid, ineffective or unenforceable, you hereby
<add> grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge,
<add> royalty-free, unrestricted license to exercise all rights under those
<add> copyrights. This includes, at our option, the right to sublicense these same
<add> rights to third parties through multiple levels of sublicensees or other
<add> licensing arrangements;
<add>
<add> * you agree that each of us can do all things in relation to your
<add> contribution as if each of us were the sole owners, and if one of us makes
<add> a derivative work of your contribution, the one who makes the derivative
<add> work (or has it made will be the sole owner of that derivative work;
<add>
<add> * you agree that you will not assert any moral rights in your contribution
<add> against us, our licensees or transferees;
<add>
<add> * you agree that we may register a copyright in your contribution and
<add> exercise all ownership rights associated with it; and
<add>
<add> * you agree that neither of us has any duty to consult with, obtain the
<add> consent of, pay or render an accounting to the other for any use or
<add> distribution of your contribution.
<add>
<add>3. With respect to any patents you own, or that you can license without payment
<add>to any third party, you hereby grant to us a perpetual, irrevocable,
<add>non-exclusive, worldwide, no-charge, royalty-free license to:
<add>
<add> * make, have made, use, sell, offer to sell, import, and otherwise transfer
<add> your contribution in whole or in part, alone or in combination with or
<add> included in any product, work or materials arising out of the project to
<add> which your contribution was submitted, and
<add>
<add> * at our option, to sublicense these same rights to third parties through
<add> multiple levels of sublicensees or other licensing arrangements.
<add>
<add>4. Except as set out above, you keep all right, title, and interest in your
<add>contribution. The rights that you grant to us under these terms are effective
<add>on the date you first submitted a contribution to us, even if your submission
<add>took place before the date you sign these terms.
<add>
<add>5. You covenant, represent, warrant and agree that:
<add>
<add> * Each contribution that you submit is and shall be an original work of
<add> authorship and you can legally grant the rights set out in this SCA;
<add>
<add> * to the best of your knowledge, each contribution will not violate any
<add> third party's copyrights, trademarks, patents, or other intellectual
<add> property rights; and
<add>
<add> * each contribution shall be in compliance with U.S. export control laws and
<add> other applicable export and import laws. You agree to notify us if you
<add> become aware of any circumstance which would make any of the foregoing
<add> representations inaccurate in any respect. We may publicly disclose your
<add> participation in the project, including the fact that you have signed the SCA.
<add>
<add>6. This SCA is governed by the laws of the State of California and applicable
<add>U.S. Federal law. Any choice of law rules will not apply.
<add>
<add>7. Please place an “x” on one of the applicable statement below. Please do NOT
<add>mark both statements:
<add>
<add> * [x] I am signing on behalf of myself as an individual and no other person
<add> or entity, including my employer, has or will have rights with respect to my
<add> contributions.
<add>
<add> * [ ] I am signing on behalf of my employer or a legal entity and I have the
<add> actual authority to contractually bind that entity.
<add>
<add>## Contributor Details
<add>
<add>| Field | Entry |
<add>|------------------------------- | ------------------------------- |
<add>| Name | Adrien Ball |
<add>| Company name (if applicable) | |
<add>| Title or role (if applicable) | Machine Learning Engineer |
<add>| Date | 2019-03-07 |
<add>| GitHub username | adrienball |
<add>| Website (optional) | https://medium.com/@adrien_ball |
<ide>\ No newline at end of file
<ide><path>spacy/cli/download.py
<ide> def download(model, direct=False, *pip_args):
<ide> with version.
<ide> """
<ide> if direct:
<del> dl = download_model('{m}/{m}.tar.gz#egg={m}'.format(m=model), pip_args)
<add> components = model.split("-")
<add> model_name = "".join(components[:-1])
<add> version = components[-1]
<add> dl = download_model(
<add> '{m}-{v}/{m}-{v}.tar.gz#egg={m}=={v}'.format(
<add> m=model_name, v=version), pip_args)
<ide> else:
<ide> shortcuts = get_json(about.__shortcuts__, "available shortcuts")
<ide> model_name = shortcuts.get(model, model) | 2 |
Javascript | Javascript | change var to let compact.js | dba276dde9cabba1cda334e2c602e935d75a2c2c | <ide><path>lib/internal/http2/compat.js
<ide> class Http2ServerResponse extends Stream {
<ide> addTrailers(headers) {
<ide> const keys = ObjectKeys(headers);
<ide> let key = '';
<del> for (var i = 0; i < keys.length; i++) {
<add> for (let i = 0; i < keys.length; i++) {
<ide> key = keys[i];
<ide> this.setTrailer(key, headers[key]);
<ide> }
<ide> class Http2ServerResponse extends Stream {
<ide> if (headers === undefined && typeof statusMessage === 'object')
<ide> headers = statusMessage;
<ide>
<del> var i;
<add> let i;
<ide> if (Array.isArray(headers)) {
<ide> for (i = 0; i < headers.length; i++) {
<ide> const header = headers[i]; | 1 |
Python | Python | add options to train a quantization friendly model | 624872573df147d613af5c494a803cc950fc830f | <ide><path>official/nlp/modeling/layers/mobile_bert_layers.py
<ide> def call(self, feature):
<ide> return output
<ide>
<ide>
<add>@tf.keras.utils.register_keras_serializable(package='Text')
<add>class NoNormClipped(NoNorm):
<add> """Quantization friendly implementation for the NoNorm.
<add>
<add> The output of NoNorm layer is clipped to [-6.0, 6.0] to make it quantization
<add> friendly.
<add> """
<add>
<add> def __init__(self, name=None):
<add> super(NoNormClipped, self).__init__(name=name)
<add>
<add> def call(self, feature):
<add> output = feature * self.scale + self.bias
<add> clipped_output = tf.clip_by_value(output, -6.0, 6.0)
<add> return clipped_output
<add>
<add>
<ide> def _get_norm_layer(normalization_type='no_norm', name=None):
<ide> """Get normlization layer.
<ide>
<ide> def _get_norm_layer(normalization_type='no_norm', name=None):
<ide> """
<ide> if normalization_type == 'no_norm':
<ide> layer = NoNorm(name=name)
<add> elif normalization_type == 'no_norm_clipped':
<add> layer = NoNormClipped(name=name)
<ide> elif normalization_type == 'layer_norm':
<ide> layer = tf.keras.layers.LayerNormalization(
<ide> name=name,
<ide><path>official/nlp/modeling/layers/mobile_bert_layers_test.py
<ide> def generate_fake_input(batch_size=1, seq_len=5, vocab_size=10000, seed=0):
<ide> return fake_input
<ide>
<ide>
<add>class EdgeTPUNoNormTest(tf.test.TestCase):
<add>
<add> def test_no_norm(self):
<add> layer = mobile_bert_layers.NoNormClipped()
<add> feature = tf.random.uniform(
<add> [2, 3, 4], minval=-8, maxval=8, dtype=tf.float32)
<add> output = layer(feature)
<add> output_shape = output.shape.as_list()
<add> expected_shape = [2, 3, 4]
<add> self.assertListEqual(output_shape, expected_shape, msg=None)
<add> output_min = tf.reduce_min(output)
<add> output_max = tf.reduce_max(output)
<add> self.assertGreaterEqual(6.0, output_max)
<add> self.assertLessEqual(-6.0, output_min)
<add>
<add>
<ide> class MobileBertEncoderTest(parameterized.TestCase, tf.test.TestCase):
<ide>
<ide> def test_embedding_layer_with_token_type(self): | 2 |
Python | Python | correct a bug with docker module and server mode | c51d4f57deb2a95800c535ec39fd366826d7e186 | <ide><path>glances/plugins/glances_docker.py
<ide> def update(self):
<ide> self.reset()
<ide>
<ide> # The Docker-py lib is mandatory
<del> if not docker_tag or self.args.disable_docker:
<add> if not docker_tag or (self.args is not None and self.args.disable_docker):
<ide> return self.stats
<ide>
<ide> if self.get_input() == 'local': | 1 |
Python | Python | fix causal padding dostrings | 330ffa41dd949fdf48cc11f76fb410bf3551657c | <ide><path>keras/layers/convolutional.py
<ide> class Conv1D(_Conv):
<ide> any `dilation_rate` value != 1.
<ide> padding: One of `"valid"`, `"causal"` or `"same"` (case-insensitive).
<ide> `"causal"` results in causal (dilated) convolutions, e.g. output[t]
<del> depends solely on input[:t-1]. Useful when modeling temporal data
<add> does not depend on input[t+1:]. Useful when modeling temporal data
<ide> where the model should not violate the temporal order.
<ide> See [WaveNet: A Generative Model for Raw Audio, section 2.1](https://arxiv.org/abs/1609.03499).
<ide> dilation_rate: an integer or tuple/list of a single integer, specifying | 1 |
Go | Go | remove unused field from engine.job | 92105ea0fa774607ea4c7f487aedfd22eb5598bc | <ide><path>engine/job.go
<ide> type Job struct {
<ide> handler Handler
<ide> status Status
<ide> end time.Time
<del> onExit []func()
<ide> }
<ide>
<ide> type Status int | 1 |
Go | Go | fail initialization if supported but got error | 4bdb8c03fc9ac4c7c49fd9838d7eccdfd66e1c5b | <ide><path>daemon/graphdriver/aufs/aufs.go
<ide> type Driver struct {
<ide> func Init(root string) (graphdriver.Driver, error) {
<ide> // Try to load the aufs kernel module
<ide> if err := supportsAufs(); err != nil {
<del> return nil, err
<add> return nil, graphdriver.ErrNotSupported
<ide> }
<ide> paths := []string{
<ide> "mnt",
<ide><path>daemon/graphdriver/aufs/aufs_test.go
<ide> var (
<ide> func testInit(dir string, t *testing.T) graphdriver.Driver {
<ide> d, err := Init(dir)
<ide> if err != nil {
<del> if err == ErrAufsNotSupported {
<add> if err == graphdriver.ErrNotSupported {
<ide> t.Skip(err)
<ide> } else {
<ide> t.Fatal(err)
<ide><path>daemon/graphdriver/btrfs/btrfs.go
<ide> func Init(home string) (graphdriver.Driver, error) {
<ide> }
<ide>
<ide> if buf.Type != 0x9123683E {
<del> return nil, fmt.Errorf("%s is not a btrfs filesystem", rootdir)
<add> return nil, graphdriver.ErrNotSupported
<ide> }
<ide>
<ide> return &Driver{
<ide><path>daemon/graphdriver/driver.go
<ide> package graphdriver
<ide>
<ide> import (
<add> "errors"
<ide> "fmt"
<ide> "github.com/dotcloud/docker/archive"
<del> "github.com/dotcloud/docker/utils"
<ide> "os"
<ide> "path"
<ide> )
<ide> var (
<ide> "devicemapper",
<ide> "vfs",
<ide> }
<add>
<add> ErrNotSupported = errors.New("driver not supported")
<ide> )
<ide>
<ide> func init() {
<ide> func GetDriver(name, home string) (Driver, error) {
<ide> if initFunc, exists := drivers[name]; exists {
<ide> return initFunc(path.Join(home, name))
<ide> }
<del> return nil, fmt.Errorf("No such driver: %s", name)
<add> return nil, ErrNotSupported
<ide> }
<ide>
<ide> func New(root string) (driver Driver, err error) {
<ide> func New(root string) (driver Driver, err error) {
<ide>
<ide> // Check for priority drivers first
<ide> for _, name := range priority {
<del> if driver, err = GetDriver(name, root); err != nil {
<del> utils.Debugf("Error loading driver %s: %s", name, err)
<del> continue
<add> driver, err = GetDriver(name, root)
<add> if err != nil {
<add> if err == ErrNotSupported {
<add> continue
<add> }
<add> return nil, err
<ide> }
<ide> return driver, nil
<ide> }
<ide>
<ide> // Check all registered drivers if no priority driver is found
<ide> for _, initFunc := range drivers {
<ide> if driver, err = initFunc(root); err != nil {
<del> continue
<add> if err == ErrNotSupported {
<add> continue
<add> }
<add> return nil, err
<ide> }
<ide> return driver, nil
<ide> }
<del> return nil, err
<add> return nil, fmt.Errorf("No supported storage backend found")
<ide> } | 4 |
PHP | PHP | allow dynamic arguments | 1dc956d1674f264f7c8f06f33d1f06b601a04e58 | <ide><path>src/Illuminate/Routing/Route.php
<ide> public function middleware($middleware = null)
<ide> }
<ide>
<ide> if (is_string($middleware)) {
<del> $middleware = [$middleware];
<add> $middleware = func_get_args();
<ide> }
<ide>
<ide> $this->action['middleware'] = array_merge( | 1 |
Python | Python | fix some typos in docs, comments, logging/errors | b24ead87e1be6bce17e4ec5c953b6d028e4b3af7 | <ide><path>src/transformers/commands/add_new_model.py
<ide> def run(self):
<ide> if not _has_cookiecutter:
<ide> raise ImportError(
<ide> "Model creation dependencies are required to use the `add_new_model` command. Install them by running "
<del> "the folowing at the root of your `transformers` clone:\n\n\t$ pip install -e .[modelcreation]\n"
<add> "the following at the root of your `transformers` clone:\n\n\t$ pip install -e .[modelcreation]\n"
<ide> )
<ide> # Ensure that there is no other `cookiecutter-template-xxx` directory in the current working directory
<ide> directories = [directory for directory in os.listdir() if "cookiecutter-template-" == directory[:22]]
<ide> if len(directories) > 0:
<ide> raise ValueError(
<ide> "Several directories starting with `cookiecutter-template-` in current working directory. "
<del> "Please clean your directory by removing all folders startign with `cookiecutter-template-` or "
<add> "Please clean your directory by removing all folders starting with `cookiecutter-template-` or "
<ide> "change your working directory."
<ide> )
<ide>
<ide><path>src/transformers/data/processors/squad.py
<ide> def squad_convert_example_to_features(
<ide> cls_index = span["input_ids"].index(tokenizer.cls_token_id)
<ide>
<ide> # p_mask: mask with 1 for token than cannot be in the answer (0 for token which can be in an answer)
<del> # Original TF implem also keep the classification token (set to 0)
<add> # Original TF implementation also keep the classification token (set to 0)
<ide> p_mask = np.ones_like(span["token_type_ids"])
<ide> if tokenizer.padding_side == "right":
<ide> p_mask[len(truncated_query) + sequence_added_tokens :] = 0
<ide><path>src/transformers/feature_extraction_sequence_utils.py
<ide> # See the License for the specific language governing permissions and
<ide> # limitations under the License.
<ide> """
<del> Sequence feature extraction class for common feature extrcactors to preprocess sequences.
<add> Sequence feature extraction class for common feature extractors to preprocess sequences.
<ide> """
<ide> from typing import Dict, List, Optional, Union
<ide>
<ide><path>src/transformers/file_utils.py
<ide> def wrapper(*args, **kwargs):
<ide> ("sklearn", (is_sklearn_available, SKLEARN_IMPORT_ERROR)),
<ide> ("speech", (is_speech_available, SPEECH_IMPORT_ERROR)),
<ide> ("tf", (is_tf_available, TENSORFLOW_IMPORT_ERROR)),
<del> ("tokenziers", (is_tokenizers_available, TOKENIZERS_IMPORT_ERROR)),
<add> ("tokenizers", (is_tokenizers_available, TOKENIZERS_IMPORT_ERROR)),
<ide> ("torch", (is_torch_available, PYTORCH_IMPORT_ERROR)),
<ide> ("vision", (is_vision_available, VISION_IMPORT_ERROR)),
<ide> ]
<ide><path>src/transformers/generation_logits_process.py
<ide> def _set_scores_to_inf_for_banned_tokens(self, scores: torch.Tensor, banned_toke
<ide>
<ide> class PrefixConstrainedLogitsProcessor(LogitsProcessor):
<ide> r"""
<del> :class:`transformers.LogitsProcessor` that enforces contrained generation and is useful for prefix-conditioned
<add> :class:`transformers.LogitsProcessor` that enforces constrained generation and is useful for prefix-conditioned
<ide> constrained generation. See `Autoregressive Entity Retrieval <https://arxiv.org/abs/2010.00904>`__ for more
<ide> information.
<ide>
<ide><path>src/transformers/generation_stopping_criteria.py
<ide> Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax
<ide> or scores for each vocabulary token after SoftMax.
<ide> kwargs:
<del> Additional stopping critera specific kwargs.
<add> Additional stopping criteria specific kwargs.
<ide>
<ide> Return:
<ide> :obj:`bool`. :obj:`False` indicates we should continue, :obj:`True` indicates we should stop.
<ide><path>src/transformers/generation_tf_utils.py
<ide> def _generate_no_beam_search(
<ide> **kwargs
<ide> ):
<ide> """
<del> Generate sequences for each example without beam search (num_beams == 1). All returned sequence are generated
<del> independantly.
<add> Generate sequences for each example without beam search (num_beams == 1). All returned sequences are generated
<add> independently.
<ide> """
<ide>
<ide> # length of generated sentences / unfinished sentences
<ide><path>src/transformers/generation_utils.py
<ide> def generate(
<ide> ... "at least two people were killed in a suspected bomb attack on a passenger bus "
<ide> ... "in the strife-torn southern philippines on monday , the military said."
<ide> ... )
<del> >>> # encode input contex
<add> >>> # encode input context
<ide> >>> input_ids = tokenizer(document, return_tensors="pt").input_ids
<ide> >>> # generate 3 independent sequences using beam search decoding (5 beams)
<ide> >>> # with T5 encoder-decoder model conditioned on short news article.
<ide><path>src/transformers/modeling_flax_utils.py
<ide> def __init__(
<ide> self.key = PRNGKey(seed)
<ide> self.dtype = dtype
<ide>
<del> # randomely initialized parameters
<add> # randomly initialized parameters
<ide> random_params = self.init_weights(self.key, input_shape)
<ide>
<ide> # save required_params as set
<ide><path>src/transformers/modeling_outputs.py
<ide> class CausalLMOutputWithPast(ModelOutput):
<ide> Language modeling loss (for next-token prediction).
<ide> logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, config.vocab_size)`):
<ide> Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
<del> past_key_values (:obj:`tuple(tupel(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``):
<add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``):
<ide> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 tensors
<ide> of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`)
<ide>
<ide> class SequenceClassifierOutputWithPast(ModelOutput):
<ide> Classification (or regression if config.num_labels==1) loss.
<ide> logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, config.num_labels)`):
<ide> Classification (or regression if config.num_labels==1) scores (before SoftMax).
<del> past_key_values (:obj:`tuple(tupel(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``):
<add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``):
<ide> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 tensors
<ide> of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`)
<ide>
<ide><path>src/transformers/modeling_tf_pytorch_utils.py
<ide> def convert_tf_weight_name_to_pt_weight_name(tf_name, start_prefix_to_remove="")
<ide> ) # '_._' is replaced by a level separation (can be used to convert TF2.0 lists in PyTorch nn.ModulesList)
<ide> tf_name = re.sub(r"//+", "/", tf_name) # Remove empty levels at the end
<ide> tf_name = tf_name.split("/") # Convert from TF2.0 '/' separators to PyTorch '.' separators
<del> # Some weights have a single name withtout "/" such as final_logits_bias in BART
<add> # Some weights have a single name without "/" such as final_logits_bias in BART
<ide> if len(tf_name) > 1:
<ide> tf_name = tf_name[1:] # Remove level zero
<ide>
<ide><path>src/transformers/modeling_tf_utils.py
<ide> def serving(self, inputs):
<ide>
<ide> Args:
<ide> inputs (:obj:`Dict[str, tf.Tensor]`):
<del> The input of the saved model as a dictionnary of tensors.
<add> The input of the saved model as a dictionary of tensors.
<ide> """
<ide> output = self.call(inputs)
<ide>
<ide> def _get_resized_lm_head_decoder(self, old_lm_head_decoder, new_num_tokens):
<ide> vectors from the end. If not provided or :obj:`None`, just returns None
<ide>
<ide> Return:
<del> :obj:`tf.Variable`: Pointer to the resized decoder or None if the output embeddings are differents of the
<add> :obj:`tf.Variable`: Pointer to the resized decoder or None if the output embeddings are different from the
<ide> input ones.
<ide> """
<ide> new_lm_head_decoder = old_lm_head_decoder
<ide><path>src/transformers/modeling_utils.py
<ide> def get_head_mask(
<ide> The mask indicating if we should keep the heads or not (1.0 for keep, 0.0 for discard).
<ide> num_hidden_layers (:obj:`int`):
<ide> The number of hidden layers in the model.
<del> is_attention_chunked: (:obj:`bool`, `optional, defaults to :obj:`False`):
<add> is_attention_chunked: (:obj:`bool`, `optional`, defaults to :obj:`False`):
<ide> Whether or not the attentions scores are computed by chunks or not.
<ide>
<ide> Returns:
<ide><path>src/transformers/models/auto/modeling_auto.py
<ide> "AutoModelForPreTraining", MODEL_FOR_PRETRAINING_MAPPING, head_doc="pretraining"
<ide> )
<ide>
<del># Private on puprose, the public class will add the deprecation warnings.
<add># Private on purpose, the public class will add the deprecation warnings.
<ide> _AutoModelWithLMHead = auto_class_factory(
<ide> "AutoModelWithLMHead", MODEL_WITH_LM_HEAD_MAPPING, head_doc="language modeling"
<ide> )
<ide><path>src/transformers/models/auto/modeling_flax_auto.py
<ide> )
<ide>
<ide> FlaxAutoModelForSequenceClassification = auto_class_factory(
<del> "AFlaxutoModelForSequenceClassification",
<add> "FlaxAutoModelForSequenceClassification",
<ide> FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
<ide> head_doc="sequence classification",
<ide> )
<ide><path>src/transformers/models/auto/modeling_tf_auto.py
<ide> "TFAutoModelForPreTraining", TF_MODEL_FOR_PRETRAINING_MAPPING, head_doc="pretraining"
<ide> )
<ide>
<del># Private on puprose, the public class will add the deprecation warnings.
<add># Private on purpose, the public class will add the deprecation warnings.
<ide> _TFAutoModelWithLMHead = auto_class_factory(
<ide> "TFAutoModelWithLMHead", TF_MODEL_WITH_LM_HEAD_MAPPING, head_doc="language modeling"
<ide> )
<ide><path>src/transformers/models/bart/configuration_bart.py
<ide> def __init__(
<ide> self.gradient_checkpointing = gradient_checkpointing
<ide> self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
<ide>
<del> # ensure backward compatibilty for BART CNN models
<add> # ensure backward compatibility for BART CNN models
<ide> if self.forced_bos_token_id is None and kwargs.get("force_bos_token_to_be_generated", False):
<ide> self.forced_bos_token_id = self.bos_token_id
<ide> warnings.warn(
<ide><path>src/transformers/models/bart/modeling_bart.py
<ide> class BartLearnedPositionalEmbedding(nn.Embedding):
<ide>
<ide> def __init__(self, num_embeddings: int, embedding_dim: int):
<ide> # Bart is set up so that if padding_idx is specified then offset the embedding ids by 2
<del> # and adjust num_embeddings appropriately. Other models dont have this hack
<add> # and adjust num_embeddings appropriately. Other models don't have this hack
<ide> self.offset = 2
<ide> super().__init__(num_embeddings + self.offset, embedding_dim)
<ide>
<ide> def forward(
<ide> attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
<ide>
<ide> if output_attentions:
<del> # this operation is a bit akward, but it's required to
<add> # this operation is a bit awkward, but it's required to
<ide> # make sure that attn_weights keeps its gradient.
<del> # In order to do so, attn_weights have to reshaped
<add> # In order to do so, attn_weights have to be reshaped
<ide> # twice and have to be reused in the following
<ide> attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
<ide> attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
<ide><path>src/transformers/models/bart/modeling_tf_bart.py
<ide> class TFBartLearnedPositionalEmbedding(TFSharedEmbeddings):
<ide>
<ide> def __init__(self, num_embeddings: int, embedding_dim: int, **kwargs):
<ide> # Bart is set up so that if padding_idx is specified then offset the embedding ids by 2
<del> # and adjust num_embeddings appropriately. Other models dont have this hack
<add> # and adjust num_embeddings appropriately. Other models don't have this hack
<ide> self.offset = 2
<ide> super().__init__(num_embeddings + self.offset, embedding_dim, **kwargs)
<ide>
<ide><path>src/transformers/models/bert_japanese/tokenization_bert_japanese.py
<ide> def tokenize(self, text, never_split=None, **kwargs):
<ide>
<ide>
<ide> class CharacterTokenizer:
<del> """Runs Character tokenziation."""
<add> """Runs Character tokenization."""
<ide>
<ide> def __init__(self, vocab, unk_token, normalize_text=True):
<ide> """
<ide><path>src/transformers/models/bertweet/tokenization_bertweet.py
<ide> def add_from_file(self, f):
<ide> the class Tokenizer.
<ide>
<ide> 4. When instantiating Tokenizer objects, there is a single option: preserve_case. By default, it is set to True. If it
<del> is set to False, then the tokenizer will downcase everything except for emoticons.
<add> is set to False, then the tokenizer will lowercase everything except for emoticons.
<ide>
<ide> """
<ide>
<ide><path>src/transformers/models/big_bird/modeling_big_bird.py
<ide> def bigbird_block_sparse_attention(
<ide> band_product, dim=-1
<ide> ) # [bsz, n_heads, from_seq_len//from_block_size-4, from_block_size, (5+n_rand_blocks)*to_block_size]
<ide>
<del> # contibution of sliding keys
<add> # contribution of sliding keys
<ide> # [bsz, n_heads, m//from_block_size-4, from_block_size, 3*to_block_size] x [bsz, n_heads, from_seq_len//from_block_size-4, 3*to_block_size, -1]
<ide> context_layer = self.torch_bmm_nd(
<ide> attn_weights[:, :, :, :, to_block_size : 4 * to_block_size], exp_blocked_value_matrix, ndim=5
<ide> def bigbird_block_sparse_attention(
<ide> attn_probs_view[:, :, q_idx, :, q_idx : q_idx + 3, :] = right_slice.view(
<ide> bsz, n_heads, from_block_size, 3, to_block_size
<ide> ) # inner_band_product
<del> # global keys (correspomding to 1st key block)
<add> # global keys (corresponding to 1st key block)
<ide> attention_probs[:, :, 2 * from_block_size : -2 * from_block_size, :to_block_size] = attn_weights[
<ide> :, :, :, :, :to_block_size
<ide> ].view(
<ide> def bigbird_block_sparse_attention(
<ide>
<ide> @staticmethod
<ide> def torch_gather_b2(params, indices):
<del> # this operation is equilvalent to tf.gather when batch_dims=2
<add> # this operation is equivalent to tf.gather when batch_dims=2
<ide>
<ide> if params.shape[:2] != indices.shape[:2]:
<ide> raise ValueError(
<ide> def _bigbird_block_rand_mask(
<ide> to_block_size: int. size of block in to sequence.
<ide> num_rand_blocks: int. Number of random chunks per row.
<ide> last_idx: if -1 then num_rand_blocks blocks chosen anywhere in to sequence,
<del> if positive then num_rand_blocks blocks choosen only upto last_idx.
<add> if positive then num_rand_blocks blocks chosen only up to last_idx.
<ide>
<ide> Returns:
<ide> adjacency list of size from_seq_length//from_block_size-2 by num_rand_blocks
<ide> def _bigbird_block_rand_mask_with_head(
<ide> plan_block_length = np.array(plan_from_length) // from_block_size
<ide> # till when to follow plan
<ide> max_plan_idx = plan_from_length.index(from_seq_length)
<del> # Random Attention adjajency list
<add> # Random Attention adjacency list
<ide> rand_attn = [
<ide> np.zeros((num_blocks, np.sum(plan_num_rand_blocks[: max_plan_idx + 1])), dtype=np.int32)
<ide> for i in range(num_heads)
<ide> def _get_single_block_row_attention(
<ide>
<ide> Args:
<ide> block_id: int. block id of row.
<del> to_start_block_id: int. random attention coloum start id.
<del> to_end_block_id: int. random attention coloum end id.
<add> to_start_block_id: int. random attention column start id.
<add> to_end_block_id: int. random attention column end id.
<ide> num_rand_blocks: int. number of random blocks to be selected.
<ide> window_block_left: int. number of blocks of window to left of a block.
<ide> window_block_right: int. number of blocks of window to right of a block.
<ide> def _init_weights(self, module):
<ide> @dataclass
<ide> class BigBirdForPreTrainingOutput(ModelOutput):
<ide> """
<del> Output type of :class:`~transformers.BigBirdtForPreTraining`.
<add> Output type of :class:`~transformers.BigBirdForPreTraining`.
<ide>
<ide> Args:
<ide> loss (`optional`, returned when ``labels`` is provided, ``torch.FloatTensor`` of shape :obj:`(1,)`):
<ide> def forward(
<ide>
<ide> logits_mask = None
<ide> if question_lengths is not None:
<del> # setting lengths logits to `-infi`
<add> # setting lengths logits to `-inf`
<ide> logits_mask = self.prepare_question_mask(question_lengths, seqlen)
<ide> if token_type_ids is None:
<ide> token_type_ids = (~logits_mask).long()
<ide><path>src/transformers/models/blenderbot/modeling_blenderbot.py
<ide> def forward(
<ide> attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
<ide>
<ide> if output_attentions:
<del> # this operation is a bit akward, but it's required to
<add> # this operation is a bit awkward, but it's required to
<ide> # make sure that attn_weights keeps its gradient.
<del> # In order to do so, attn_weights have to reshaped
<add> # In order to do so, attn_weights have to be reshaped
<ide> # twice and have to be reused in the following
<ide> attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
<ide> attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
<ide><path>src/transformers/models/blenderbot_small/modeling_blenderbot_small.py
<ide> def forward(
<ide> attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
<ide>
<ide> if output_attentions:
<del> # this operation is a bit akward, but it's required to
<add> # this operation is a bit awkward, but it's required to
<ide> # make sure that attn_weights keeps its gradient.
<del> # In order to do so, attn_weights have to reshaped
<add> # In order to do so, attn_weights have to be reshaped
<ide> # twice and have to be reused in the following
<ide> attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
<ide> attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
<ide><path>src/transformers/models/convbert/modeling_tf_convbert.py
<ide> class TFConvBertPreTrainedModel(TFPreTrainedModel):
<ide> Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (:obj:`Numpy array` or :obj:`tf.Tensor` of shape :obj:`({0})`, `optional`):
<ide> class TFConvBertPreTrainedModel(TFPreTrainedModel):
<ide>
<ide>
<ide> @add_start_docstrings(
<del> "The bare ConvBERT Model transformer outputing raw hidden-states without any specific head on top.",
<add> "The bare ConvBERT Model transformer outputting raw hidden-states without any specific head on top.",
<ide> CONVBERT_START_DOCSTRING,
<ide> )
<ide> class TFConvBertModel(TFConvBertPreTrainedModel):
<ide><path>src/transformers/models/ctrl/modeling_ctrl.py
<ide> def forward(
<ide> sequence_lengths = -1
<ide> logger.warning(
<ide> f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
<del> f"unexpected if using padding tokens in conjuction with `inputs_embeds.`"
<add> f"unexpected if using padding tokens in conjunction with `inputs_embeds.`"
<ide> )
<ide>
<ide> pooled_logits = logits[range(batch_size), sequence_lengths]
<ide><path>src/transformers/models/deberta_v2/modeling_deberta_v2.py
<ide> def build_relative_position(query_size, key_size, bucket_size=-1, max_position=-
<ide> query_size (int): the length of query
<ide> key_size (int): the length of key
<ide> bucket_size (int): the size of position bucket
<del> max_position (int): the maxium allowed absolute positoin
<add> max_position (int): the maximum allowed absolute position
<ide>
<ide> Return:
<ide> :obj:`torch.LongTensor`: A tensor with shape [1, query_size, key_size]
<ide> def disentangled_attention_bias(self, query_layer, key_layer, relative_pos, rel_
<ide> relative_pos = relative_pos.unsqueeze(1)
<ide> # bsz x height x query x key
<ide> elif relative_pos.dim() != 4:
<del> raise ValueError(f"Relative postion ids must be of dim 2 or 3 or 4. {relative_pos.dim()}")
<add> raise ValueError(f"Relative position ids must be of dim 2 or 3 or 4. {relative_pos.dim()}")
<ide>
<ide> att_span = self.pos_ebd_size
<ide> relative_pos = relative_pos.long().to(query_layer.device)
<ide><path>src/transformers/models/deberta_v2/tokenization_deberta_v2.py
<ide> def save_pretrained(self, path: str, filename_prefix: str = None):
<ide>
<ide> def _is_whitespace(char):
<ide> """Checks whether `chars` is a whitespace character."""
<del> # \t, \n, and \r are technically contorl characters but we treat them
<add> # \t, \n, and \r are technically control characters but we treat them
<ide> # as whitespace since they are generally considered as such.
<ide> if char == " " or char == "\t" or char == "\n" or char == "\r":
<ide> return True
<ide><path>src/transformers/models/fsmt/convert_fsmt_original_pytorch_checkpoint_to_pytorch.py
<ide> def convert_fsmt_checkpoint_to_pytorch(fsmt_checkpoint_path, pytorch_dump_folder
<ide> f.write(json.dumps(src_vocab, ensure_ascii=False, indent=json_indent))
<ide>
<ide> # detect whether this is a do_lower_case situation, which can be derived by checking whether we
<del> # have at least one upcase letter in the source vocab
<add> # have at least one uppercase letter in the source vocab
<ide> do_lower_case = True
<ide> for k in src_vocab.keys():
<ide> if not k.islower():
<ide><path>src/transformers/models/fsmt/modeling_fsmt.py
<ide> Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 indicates the head is **not masked**,
<del> - 0 indicates the heas is **masked**.
<add> - 0 indicates the head is **masked**.
<ide>
<ide> decoder_head_mask (:obj:`torch.Tensor` of shape :obj:`(decoder_layers, decoder_attention_heads)`, `optional`):
<ide> Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in ``[0, 1]``:
<ide> def forward(
<ide> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 indicates the head is **not masked**,
<del> - 0 indicates the heas is **masked**.
<add> - 0 indicates the head is **masked**.
<ide>
<ide> Returns:
<ide> BaseModelOutput or Tuple comprised of:
<ide> def forward(
<ide> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 indicates the head is **not masked**,
<del> - 0 indicates the heas is **masked**.
<add> - 0 indicates the head is **masked**.
<ide>
<ide> cross_attn_head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`):
<ide> Mask to nullify selected heads of the cross-attention modules. Mask values selected in ``[0, 1]``:
<ide><path>src/transformers/models/funnel/modeling_funnel.py
<ide> def __init__(self, config):
<ide> self.sin_dropout = nn.Dropout(config.hidden_dropout)
<ide> self.cos_dropout = nn.Dropout(config.hidden_dropout)
<ide> # Track where we are at in terms of pooling from the original input, e.g., by how much the sequence length was
<del> # dividide.
<add> # divided.
<ide> self.pooling_mult = None
<ide>
<ide> def init_attention_inputs(self, inputs_embeds, attention_mask=None, token_type_ids=None):
<ide> def get_position_embeds(self, seq_len, dtype, device):
<ide> For the factorized attention, it returns the matrices (phi, pi, psi, omega) used in the paper, appendix A.2.2,
<ide> final formula.
<ide>
<del> For the relative shif attention, it returns all possible vectors R used in the paper, appendix A.2.1, final
<add> For the relative shift attention, it returns all possible vectors R used in the paper, appendix A.2.1, final
<ide> formula.
<ide>
<ide> Paper link: https://arxiv.org/abs/2006.03236
<ide><path>src/transformers/models/funnel/modeling_tf_funnel.py
<ide> def get_position_embeds(self, seq_len, training=False):
<ide> For the factorized attention, it returns the matrices (phi, pi, psi, omega) used in the paper, appendix A.2.2,
<ide> final formula.
<ide>
<del> For the relative shif attention, it returns all possible vectors R used in the paper, appendix A.2.1, final
<add> For the relative shift attention, it returns all possible vectors R used in the paper, appendix A.2.1, final
<ide> formula.
<ide>
<ide> Paper link: https://arxiv.org/abs/2006.03236
<ide> class TFFunnelForPreTrainingOutput(ModelOutput):
<ide> Args:
<ide> logits (:obj:`tf.Tensor` of shape :obj:`(batch_size, sequence_length)`):
<ide> Prediction scores of the head (scores for each token before SoftMax).
<del> hidden_states (:obj:`tuple(tf.ensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
<add> hidden_states (:obj:`tuple(tf.Tensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
<ide> Tuple of :obj:`tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of
<ide> shape :obj:`(batch_size, sequence_length, hidden_size)`.
<ide>
<ide><path>src/transformers/models/gpt2/modeling_tf_gpt2.py
<ide> def __init__(self, nx, n_ctx, config, scale=False, **kwargs):
<ide> super().__init__(**kwargs)
<ide>
<ide> n_state = nx # in Attention: n_state=768 (nx=n_embd)
<del> # [switch nx => n_state from Block to Attention to keep identical to TF implem]
<add> # [switch nx => n_state from Block to Attention to keep identical to TF implementation]
<ide> assert n_state % config.n_head == 0
<ide> self.n_ctx = n_ctx
<ide> self.n_head = config.n_head
<ide><path>src/transformers/models/gpt2/tokenization_gpt2.py
<ide> def bytes_to_unicode():
<ide>
<ide> The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
<ide> if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
<del> decent coverage. This is a signficant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
<add> decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
<ide> tables between utf-8 bytes and unicode strings.
<ide> """
<ide> bs = (
<ide> def __init__(
<ide> self.cache = {}
<ide> self.add_prefix_space = add_prefix_space
<ide>
<del> # Should haved added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
<add> # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
<ide> self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
<ide>
<ide> @property
<ide> def _tokenize(self, text):
<ide> for token in re.findall(self.pat, text):
<ide> token = "".join(
<ide> self.byte_encoder[b] for b in token.encode("utf-8")
<del> ) # Maps all our bytes to unicode strings, avoiding controle tokens of the BPE (spaces in our case)
<add> ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
<ide> bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
<ide> return bpe_tokens
<ide>
<ide><path>src/transformers/models/gpt_neo/modeling_gpt_neo.py
<ide> def create_local_attention_mask(batch_size, seq_length, window_size, device, att
<ide> if attention_mask is None:
<ide> attention_mask = torch.ones(batch_size, seq_length, dtype=torch.long, device=device)
<ide>
<del> # A block can also be padded becuase of the _look_back operation
<add> # A block can also be padded because of the _look_back operation
<ide> # look back into the attention_block such that it will also get padded the same way
<ide> # and have 0s in the padded position
<ide> attention_mask = GPTNeoAttentionMixin._look_back(attention_mask, block_length, window_size, is_key_value=False)
<ide> def forward(
<ide>
<ide> # Prepare head mask if needed
<ide> # 1.0 in head_mask indicate we keep the head
<del> # attention_probs has shape bsz x num_headss x N x N
<del> # head_mask has shape n_layer x batch x num_headss x N x N
<add> # attention_probs has shape bsz x num_heads x N x N
<add> # head_mask has shape n_layer x batch x num_heads x N x N
<ide> head_mask = self.get_head_mask(head_mask, self.config.num_layers)
<ide>
<ide> if inputs_embeds is None:
<ide><path>src/transformers/models/ibert/quant_modules.py
<ide> class QuantEmbedding(nn.Module):
<ide> :obj:`torch.nn.Embedding`.
<ide>
<ide> Args:
<del> weight_bit (:obj:`int`, `optiona`l, defaults to :obj:`8`):
<add> weight_bit (:obj:`int`, `optional`, defaults to :obj:`8`):
<ide> Bitwidth for the quantized weight.
<del> momentum (:obj:`float`, `optional, defaults to :obj:`0.95`):
<add> momentum (:obj:`float`, `optional`, defaults to :obj:`0.95`):
<ide> Momentum for updating the activation quantization range.
<del> quant_mode (:obj:`bool`, `optional, defaults to :obj:`False`):
<add> quant_mode (:obj:`bool`, `optional`, defaults to :obj:`False`):
<ide> Whether or not the layer is quantized.
<ide> """
<ide>
<ide> def symmetric_linear_quantization_params(num_bits, saturation_min, saturation_ma
<ide> `saturation_max`.
<ide> """
<ide> # in this part, we do not need any gradient computation,
<del> # in order to enfore this, we put torch.no_grad()
<add> # in order to enforce this, we put torch.no_grad()
<ide> with torch.no_grad():
<ide> n = 2 ** (num_bits - 1) - 1
<ide>
<ide><path>src/transformers/models/led/modeling_led.py
<ide> def forward(
<ide> attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
<ide>
<ide> if output_attentions:
<del> # this operation is a bit akward, but it's required to
<add> # this operation is a bit awkward, but it's required to
<ide> # make sure that attn_weights keeps its gradient.
<del> # In order to do so, attn_weights have to reshaped
<add> # In order to do so, attn_weights have to be reshaped
<ide> # twice and have to be reused in the following
<ide> attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
<ide> attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
<ide> class LEDSeq2SeqQuestionAnsweringModelOutput(ModelOutput):
<ide> Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 indicates the head is **not masked**,
<del> - 0 indicates the heas is **masked**.
<add> - 0 indicates the head is **masked**.
<ide>
<ide> decoder_head_mask (:obj:`torch.Tensor` of shape :obj:`(decoder_layers, decoder_attention_heads)`, `optional`):
<ide> Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in ``[0, 1]``:
<ide> def forward(
<ide> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 indicates the head is **not masked**,
<del> - 0 indicates the heas is **masked**.
<add> - 0 indicates the head is **masked**.
<ide> inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
<ide> Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded
<ide> representation. This is useful if you want more control over how to convert :obj:`input_ids` indices
<ide> def forward(
<ide> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 indicates the head is **not masked**,
<del> - 0 indicates the heas is **masked**.
<add> - 0 indicates the head is **masked**.
<ide>
<ide> cross_attn_head_mask (:obj:`torch.Tensor` of shape :obj:`(decoder_layers, decoder_attention_heads)`, `optional`):
<ide> Mask to nullify selected heads of the cross-attention modules. Mask values selected in ``[0, 1]``:
<ide><path>src/transformers/models/led/modeling_tf_led.py
<ide> def _compute_global_attn_output_from_hidden(
<ide> # compute global attn probs
<ide> global_attn_probs_float = tf.nn.softmax(global_attn_scores, axis=-1)
<ide>
<del> # apply layer head maskin
<add> # apply layer head masking
<ide> if layer_head_mask is not None:
<ide> if tf.executing_eagerly():
<ide> tf.debugging.assert_equal(
<ide> class TFLEDSeq2SeqLMOutput(ModelOutput):
<ide> Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 indicates the head is **not masked**,
<del> - 0 indicates the heas is **masked**.
<add> - 0 indicates the head is **masked**.
<ide>
<ide> decoder_head_mask (:obj:`tf.Tensor` of shape :obj:`(decoder_layers, decoder_attention_heads)`, `optional`):
<ide> Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in ``[0, 1]``:
<ide> def call(
<ide> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 indicates the head is **not masked**,
<del> - 0 indicates the heas is **masked**.
<add> - 0 indicates the head is **masked**.
<ide>
<ide> inputs_embeds (:obj:`tf.Tensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
<ide> Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded
<ide> def call(
<ide> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 indicates the head is **not masked**,
<del> - 0 indicates the heas is **masked**.
<add> - 0 indicates the head is **masked**.
<ide>
<ide> encoder_head_mask (:obj:`tf.Tensor` of shape :obj:`(encoder_layers, encoder_attention_heads)`, `optional`):
<ide> Mask to nullify selected heads of the attention modules in encoder to avoid performing cross-attention
<ide> on hidden heads. Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 indicates the head is **not masked**,
<del> - 0 indicates the heas is **masked**.
<add> - 0 indicates the head is **masked**.
<ide>
<ide> past_key_values (:obj:`Tuple[Tuple[tf.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
<ide> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up
<ide><path>src/transformers/models/longformer/modeling_longformer.py
<ide> class LongformerTokenClassifierOutput(ModelOutput):
<ide>
<ide> def _get_question_end_index(input_ids, sep_token_id):
<ide> """
<del> Computes the index of the first occurance of `sep_token_id`.
<add> Computes the index of the first occurrence of `sep_token_id`.
<ide> """
<ide>
<ide> sep_token_indices = (input_ids == sep_token_id).nonzero()
<ide> def _init_weights(self, module):
<ide> Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 indicates the head is **not masked**,
<del> - 0 indicates the heas is **masked**.
<add> - 0 indicates the head is **masked**.
<ide>
<ide> decoder_head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`):
<ide> Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in ``[0, 1]``:
<ide><path>src/transformers/models/longformer/modeling_tf_longformer.py
<ide> def _compute_global_attn_output_from_hidden(
<ide> # compute global attn probs
<ide> global_attn_probs_float = tf.nn.softmax(global_attn_scores, axis=-1)
<ide>
<del> # apply layer head maskin
<add> # apply layer head masking
<ide> if layer_head_mask is not None:
<ide> if tf.executing_eagerly():
<ide> tf.debugging.assert_equal(
<ide> def call(
<ide> inputs["attention_mask"], (attention_mask_shape[0], attention_mask_shape[1], 1, 1)
<ide> )
<ide>
<del> # Since attention_mask is 1.0 for positions we want to locall attend locally and 0.0 for
<add> # Since attention_mask is 1.0 for positions we want to attend locally and 0.0 for
<ide> # masked and global attn positions, this operation will create a tensor which is 0.0 for
<ide> # positions we want to attend and -10000.0 for masked positions.
<ide> # Since we are adding it to the raw scores before the softmax, this is
<ide> def serving(self, inputs):
<ide> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 indicates the head is **not masked**,
<del> - 0 indicates the heas is **masked**.
<add> - 0 indicates the head is **masked**.
<ide>
<ide> global_attention_mask (:obj:`tf.Tensor` of shape :obj:`({0})`, `optional`):
<ide> Mask to decide the attention given on each token, local attention or global attention. Tokens with global
<ide><path>src/transformers/models/lxmert/configuration_lxmert.py
<ide> class LxmertConfig(PretrainedConfig):
<ide> Whether or not to add masked language modeling (as used in pretraining models such as BERT) to the loss
<ide> objective.
<ide> task_obj_predict (:obj:`bool`, `optional`, defaults to :obj:`True`):
<del> Whether or not to add object prediction, attribute ppredictionand feature regression to the loss objective.
<add> Whether or not to add object prediction, attribute prediction and feature regression to the loss objective.
<ide> task_qa (:obj:`bool`, `optional`, defaults to :obj:`True`):
<del> Whether or not to add the question-asansweringoss to the objective
<add> Whether or not to add the question-answering loss to the objective
<ide> visual_obj_loss (:obj:`bool`, `optional`, defaults to :obj:`True`):
<ide> Whether or not to calculate the object-prediction loss objective
<ide> visual_attr_loss (:obj:`bool`, `optional`, defaults to :obj:`True`):
<ide><path>src/transformers/models/m2m_100/modeling_m2m_100.py
<ide> def forward(
<ide> attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
<ide>
<ide> if output_attentions:
<del> # this operation is a bit akward, but it's required to
<add> # this operation is a bit awkward, but it's required to
<ide> # make sure that attn_weights keeps its gradient.
<del> # In order to do so, attn_weights have to reshaped
<add> # In order to do so, attn_weights have to be reshaped
<ide> # twice and have to be reused in the following
<ide> attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
<ide> attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
<ide><path>src/transformers/models/marian/modeling_marian.py
<ide> def forward(
<ide> attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
<ide>
<ide> if output_attentions:
<del> # this operation is a bit akward, but it's required to
<add> # this operation is a bit awkward, but it's required to
<ide> # make sure that attn_weights keeps its gradient.
<del> # In order to do so, attn_weights have to reshaped
<add> # In order to do so, attn_weights have to be reshaped
<ide> # twice and have to be reused in the following
<ide> attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
<ide> attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
<ide><path>src/transformers/models/mbart/modeling_mbart.py
<ide> class MBartLearnedPositionalEmbedding(nn.Embedding):
<ide>
<ide> def __init__(self, num_embeddings: int, embedding_dim: int):
<ide> # MBart is set up so that if padding_idx is specified then offset the embedding ids by 2
<del> # and adjust num_embeddings appropriately. Other models dont have this hack
<add> # and adjust num_embeddings appropriately. Other models don't have this hack
<ide> self.offset = 2
<ide> super().__init__(num_embeddings + self.offset, embedding_dim)
<ide>
<ide> def forward(
<ide> attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
<ide>
<ide> if output_attentions:
<del> # this operation is a bit akward, but it's required to
<add> # this operation is a bit awkward, but it's required to
<ide> # make sure that attn_weights keeps its gradient.
<del> # In order to do so, attn_weights have to reshaped
<add> # In order to do so, attn_weights have to be reshaped
<ide> # twice and have to be reused in the following
<ide> attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
<ide> attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
<ide><path>src/transformers/models/mbart/modeling_tf_mbart.py
<ide> class TFMBartLearnedPositionalEmbedding(TFSharedEmbeddings):
<ide>
<ide> def __init__(self, num_embeddings: int, embedding_dim: int, **kwargs):
<ide> # MBart is set up so that if padding_idx is specified then offset the embedding ids by 2
<del> # and adjust num_embeddings appropriately. Other models dont have this hack
<add> # and adjust num_embeddings appropriately. Other models don't have this hack
<ide> self.offset = 2
<ide> super().__init__(num_embeddings + self.offset, embedding_dim, **kwargs)
<ide>
<ide> def call(
<ide> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 indicates the head is **not masked**,
<del> - 0 indicates the heas is **masked**.
<add> - 0 indicates the head is **masked**.
<ide>
<ide> inputs_embeds (:obj:`tf.Tensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
<ide> Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded
<ide><path>src/transformers/models/mobilebert/modeling_mobilebert.py
<ide> def forward(
<ide>
<ide> @add_start_docstrings(
<ide> """
<del> MoibleBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
<add> MobileBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
<ide> for Named-Entity-Recognition (NER) tasks.
<ide> """,
<ide> MOBILEBERT_START_DOCSTRING,
<ide><path>src/transformers/models/mpnet/modeling_tf_mpnet.py
<ide> def call(
<ide>
<ide>
<ide> @add_start_docstrings(
<del> "The bare MPNet Model transformer outputing raw hidden-states without any specific head on top.",
<add> "The bare MPNet Model transformer outputting raw hidden-states without any specific head on top.",
<ide> MPNET_START_DOCSTRING,
<ide> )
<ide> class TFMPNetModel(TFMPNetPreTrainedModel):
<ide><path>src/transformers/models/mpnet/tokenization_mpnet_fast.py
<ide> def mask_token(self) -> str:
<ide> :obj:`str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while
<ide> not having been set.
<ide>
<del> MPNet tokenizer has a special mask token to be usble in the fill-mask pipeline. The mask token will greedily
<add> MPNet tokenizer has a special mask token to be usable in the fill-mask pipeline. The mask token will greedily
<ide> comprise the space before the `<mask>`.
<ide> """
<ide> if self._mask_token is None and self.verbose:
<ide><path>src/transformers/models/openai/modeling_openai.py
<ide> class Attention(nn.Module):
<ide> def __init__(self, nx, n_ctx, config, scale=False):
<ide> super().__init__()
<ide> n_state = nx # in Attention: n_state=768 (nx=n_embd)
<del> # [switch nx => n_state from Block to Attention to keep identical to TF implem]
<add> # [switch nx => n_state from Block to Attention to keep identical to TF implementation]
<ide> assert n_state % config.n_head == 0
<ide> self.register_buffer("bias", torch.tril(torch.ones(n_ctx, n_ctx)).view(1, 1, n_ctx, n_ctx))
<ide> self.n_head = config.n_head
<ide> def _attn(self, q, k, v, attention_mask=None, head_mask=None, output_attentions=
<ide> w = torch.matmul(q, k)
<ide> if self.scale:
<ide> w = w / math.sqrt(v.size(-1))
<del> # w = w * self.bias + -1e9 * (1 - self.bias) # TF implem method: mask_attn_weights
<add> # w = w * self.bias + -1e9 * (1 - self.bias) # TF implementation method: mask_attn_weights
<ide> # XD: self.b may be larger than w, so we need to crop it
<ide> b = self.bias[:, :, : w.size(-2), : w.size(-1)]
<ide> w = w * b + -1e4 * (1 - b)
<ide> def _attn(self, q, k, v, attention_mask=None, head_mask=None, output_attentions=
<ide> def merge_heads(self, x):
<ide> x = x.permute(0, 2, 1, 3).contiguous()
<ide> new_x_shape = x.size()[:-2] + (x.size(-2) * x.size(-1),)
<del> return x.view(*new_x_shape) # in Tensorflow implem: fct merge_states
<add> return x.view(*new_x_shape) # in Tensorflow implementation: fct merge_states
<ide>
<ide> def split_heads(self, x, k=False):
<ide> new_x_shape = x.size()[:-1] + (self.n_head, x.size(-1) // self.n_head)
<del> x = x.view(*new_x_shape) # in Tensorflow implem: fct split_states
<add> x = x.view(*new_x_shape) # in Tensorflow implementation: fct split_states
<ide> if k:
<ide> return x.permute(0, 2, 3, 1)
<ide> else:
<ide> def forward(
<ide> raise ValueError("You have to specify either input_ids or inputs_embeds")
<ide>
<ide> if position_ids is None:
<del> # Code is different from when we had a single embedding matrice from position and token embeddings
<add> # Code is different from when we had a single embedding matrix from position and token embeddings
<ide> position_ids = self.position_ids[None, : input_shape[-1]]
<ide>
<ide> # Attention mask.
<ide> def forward(
<ide> sequence_lengths = -1
<ide> logger.warning(
<ide> f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
<del> f"unexpected if using padding tokens in conjuction with `inputs_embeds.`"
<add> f"unexpected if using padding tokens in conjunction with `inputs_embeds.`"
<ide> )
<ide>
<ide> pooled_logits = logits[range(batch_size), sequence_lengths]
<ide><path>src/transformers/models/openai/modeling_tf_openai.py
<ide> def __init__(self, nx, n_ctx, config, scale=False, **kwargs):
<ide> super().__init__(**kwargs)
<ide>
<ide> n_state = nx # in Attention: n_state=768 (nx=n_embd)
<del> # [switch nx => n_state from Block to Attention to keep identical to TF implem]
<add> # [switch nx => n_state from Block to Attention to keep identical to TF implementation]
<ide> assert (
<ide> n_state % config.n_head == 0
<ide> ), f"Hidden dimension {n_state} not dividable by number of heads {config.n_head}"
<ide><path>src/transformers/models/pegasus/modeling_pegasus.py
<ide> def forward(
<ide> attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
<ide>
<ide> if output_attentions:
<del> # this operation is a bit akward, but it's required to
<add> # this operation is a bit awkward, but it's required to
<ide> # make sure that attn_weights keeps its gradient.
<del> # In order to do so, attn_weights have to reshaped
<add> # In order to do so, attn_weights have to be reshaped
<ide> # twice and have to be reused in the following
<ide> attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
<ide> attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
<ide><path>src/transformers/models/pegasus/modeling_tf_pegasus.py
<ide> def call(
<ide> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 indicates the head is **not masked**,
<del> - 0 indicates the heas is **masked**.
<add> - 0 indicates the head is **masked**.
<ide>
<ide> inputs_embeds (:obj:`tf.Tensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
<ide> Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded
<ide><path>src/transformers/models/prophetnet/modeling_prophetnet.py
<ide> def forward(
<ide> attn_weights = attn_weights + attention_mask
<ide>
<ide> if output_attentions:
<del> # this operation is a bit akward, but it's required to
<add> # this operation is a bit awkward, but it's required to
<ide> # make sure that attn_weights keeps its gradient.
<del> # In order to do so, attn_weights have to reshaped
<add> # In order to do so, attn_weights have to be reshaped
<ide> # twice and have to be reused in the following
<ide> attn_weights_reshaped = attn_weights.view(batch_size, self.num_attn_heads, tgt_len, src_len)
<ide> attn_weights = attn_weights_reshaped.view(batch_size * self.num_attn_heads, tgt_len, src_len)
<ide> class ProphetNetEncoder(ProphetNetPreTrainedModel):
<ide> r"""
<ide> word_embeddings (:obj:`torch.nn.Embeddings` of shape :obj:`(config.vocab_size, config.hidden_size)`, `optional`):
<ide> The word embedding parameters. This can be used to initialize :class:`~transformers.ProphetNetEncoder` with
<del> pre-defined word embeddings instead of randomely initialized word embeddings.
<add> pre-defined word embeddings instead of randomly initialized word embeddings.
<ide> """
<ide>
<ide> def __init__(self, config: ProphetNetConfig, word_embeddings: nn.Embedding = None):
<ide> class ProphetNetDecoder(ProphetNetPreTrainedModel):
<ide> r"""
<ide> word_embeddings (:obj:`torch.nn.Embeddings` of shape :obj:`(config.vocab_size, config.hidden_size)`, `optional`):
<ide> The word embedding parameters. This can be used to initialize :class:`~transformers.ProphetNetEncoder` with
<del> pre-defined word embeddings instead of randomely initialized word embeddings.
<add> pre-defined word embeddings instead of randomly initialized word embeddings.
<ide> """
<ide>
<ide> def __init__(self, config: ProphetNetConfig, word_embeddings: nn.Embedding = None):
<ide><path>src/transformers/models/rag/modeling_tf_rag.py
<ide> def from_pretrained_question_encoder_generator(
<ide>
<ide> >>> # load retriever
<ide> >>> retriever = RagRetriever.from_pretrained(PATH, index_name="exact", use_dummy_dataset=True)
<del> >>> # load fine-tuned model with retriver
<add> >>> # load fine-tuned model with retriever
<ide> >>> model = TFRagModel.from_pretrained("./rag", retriever=retriever)
<ide> """
<ide>
<ide><path>src/transformers/models/rag/retrieval_rag.py
<ide> class CanonicalHFIndex(HFIndexBase):
<ide> Args:
<ide> vector_size (:obj:`int`): the dimension of the passages embeddings used by the index
<ide> dataset_name (:obj:`str`, optional, defaults to ``wiki_dpr``):
<del> A datatset identifier of the indexed dataset on HuggingFace AWS bucket (list all available datasets and ids
<add> A dataset identifier of the indexed dataset on HuggingFace AWS bucket (list all available datasets and ids
<ide> with ``datasets.list_datasets()``).
<ide> dataset_split (:obj:`str`, optional, defaults to ``train``)
<ide> Which split of the ``dataset`` to load.
<ide> def save_pretrained(self, save_directory):
<ide>
<ide> def init_retrieval(self):
<ide> """
<del> Retriever initalization function. It loads the index into memory.
<add> Retriever initialization function. It loads the index into memory.
<ide> """
<ide>
<ide> logger.info("initializing retrieval")
<ide><path>src/transformers/models/reformer/modeling_reformer.py
<ide> def _hash_vectors(self, vectors, num_hashes, attention_mask, increase_num_bucket
<ide> if isinstance(self.num_buckets, int):
<ide> assert (
<ide> self.num_buckets % 2 == 0
<del> ), f"There should be an even number of bucktes, but `self.num_bucktes`: {self.num_buckets}"
<add> ), f"There should be an even number of buckets, but `self.num_buckets`: {self.num_buckets}"
<ide> rotation_size = self.num_buckets
<ide> num_buckets = self.num_buckets
<ide> else:
<ide><path>src/transformers/models/roberta/tokenization_roberta_fast.py
<ide> def mask_token(self) -> str:
<ide> :obj:`str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while
<ide> not having been set.
<ide>
<del> Roberta tokenizer has a special mask token to be usble in the fill-mask pipeline. The mask token will greedily
<add> Roberta tokenizer has a special mask token to be usable in the fill-mask pipeline. The mask token will greedily
<ide> comprise the space before the `<mask>`.
<ide> """
<ide> if self._mask_token is None and self.verbose:
<ide><path>src/transformers/models/speech_to_text/modeling_speech_to_text.py
<ide> def forward(
<ide> attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
<ide>
<ide> if output_attentions:
<del> # this operation is a bit akward, but it's required to
<add> # this operation is a bit awkward, but it's required to
<ide> # make sure that attn_weights keeps its gradient.
<del> # In order to do so, attn_weights have to reshaped
<add> # In order to do so, attn_weights have to be reshaped
<ide> # twice and have to be reused in the following
<ide> attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
<ide> attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
<ide> def _get_subsampled_output_lengths(self, input_lengths: torch.LongTensor):
<ide> return input_lengths
<ide>
<ide> def _get_subsampled_encoder_attn_mask(self, attention_mask):
<del> # generate creates 3D attention mask, becuase of the shape of input_features
<add> # generate creates 3D attention mask, because of the shape of input_features
<ide> # convert it to 2D if thats the case
<ide> if len(attention_mask.shape) > 2:
<ide> attention_mask = attention_mask[:, :, -1]
<ide><path>src/transformers/models/t5/modeling_t5.py
<ide> def forward(
<ide> Whether or not to return a :class:`~transformers.file_utils.ModelOutput` instead of a plain tuple.
<ide> """
<ide>
<del># Warning messafe for FutureWarning: head_mask was separated into two input args - head_mask, decoder_head_mask
<add># Warning message for FutureWarning: head_mask was separated into two input args - head_mask, decoder_head_mask
<ide> __HEAD_MASK_WARNING_MSG = """
<ide> The input argument `head_mask` was split into two arguments `head_mask` and `decoder_head_mask`. Currently,
<ide> `decoder_head_mask` is set to copy `head_mask`, but this feature is deprecated and will be removed in future versions.
<ide><path>src/transformers/models/t5/modeling_tf_t5.py
<ide> def call(
<ide> raise ValueError(f"You have to specify either {err_msg_prefix}inputs or {err_msg_prefix}inputs_embeds")
<ide>
<ide> if inputs["inputs_embeds"] is None:
<del> assert self.embed_tokens is not None, "You have to intialize the model with valid token embeddings"
<add> assert self.embed_tokens is not None, "You have to initialize the model with valid token embeddings"
<ide> inputs["inputs_embeds"] = self.embed_tokens(inputs["input_ids"])
<ide>
<ide> batch_size, seq_length = input_shape
<ide><path>src/transformers/models/tapas/modeling_tapas.py
<ide> def _calculate_aggregate_mask(answer, pooled_output, cell_selection_preference,
<ide> apply to numbers. If the answer is a number but does not appear in the table then we must use some aggregation
<ide> case. The ambiguous case is when the answer is a number that also appears in the table. In this case we use the
<ide> aggregation function probabilities predicted by the model to decide whether to select or aggregate. The threshold
<del> for this is a hyperparameter `cell_selection_preference
<add> for this is a hyperparameter `cell_selection_preference`
<ide>
<ide> Args:
<ide> answer (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, )`):
<ide> def _calculate_aggregate_mask(answer, pooled_output, cell_selection_preference,
<ide> aggregate_mask_init = torch.logical_not(torch.isnan(answer)).type(torch.FloatTensor).to(answer.device)
<ide> logits_aggregation = aggregation_classifier(pooled_output)
<ide> dist_aggregation = torch.distributions.categorical.Categorical(logits=logits_aggregation)
<del> # Index 0 correponds to "no aggregation".
<add> # Index 0 corresponds to "no aggregation".
<ide> aggregation_ops_total_mass = torch.sum(dist_aggregation.probs[:, 1:], dim=1)
<ide>
<ide> # Cell selection examples according to current model.
<ide> def _calculate_aggregation_loss_unknown(logits_aggregation, aggregate_mask):
<ide> answer supervision) per example.
<ide> """
<ide> dist_aggregation = torch.distributions.categorical.Categorical(logits=logits_aggregation)
<del> # Index 0 correponds to "no aggregation".
<add> # Index 0 corresponds to "no aggregation".
<ide> aggregation_ops_total_mass = torch.sum(dist_aggregation.probs[:, 1:], dim=1)
<ide> # Predict some aggregation in case of an answer that needs aggregation.
<ide> # This increases the probability of all aggregation functions, in a way
<ide><path>src/transformers/models/tapas/tokenization_tapas.py
<ide> def _get_numeric_value_from_date(date, mask):
<ide>
<ide>
<ide> def _get_span_length_key(span):
<del> """Sorts span by decreasing length first and incresing first index second."""
<add> """Sorts span by decreasing length first and increasing first index second."""
<ide> return span[1] - span[0], -span[0]
<ide>
<ide>
<ide><path>src/transformers/models/transfo_xl/tokenization_transfo_xl.py
<ide> def _build_from_file(self, vocab_file):
<ide> elif "<unk>" in self.sym2idx:
<ide> self.unk_idx = self.sym2idx["<unk>"]
<ide> else:
<del> raise ValueError("No <unkown> token in vocabulary")
<add> raise ValueError("No <unknown> token in vocabulary")
<ide>
<ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
<ide> if os.path.isdir(save_directory):
<ide><path>src/transformers/models/wav2vec2/modeling_wav2vec2.py
<ide> def forward(
<ide> attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
<ide>
<ide> if output_attentions:
<del> # this operation is a bit akward, but it's required to
<add> # this operation is a bit awkward, but it's required to
<ide> # make sure that attn_weights keeps its gradient.
<del> # In order to do so, attn_weights have to reshaped
<add> # In order to do so, attn_weights have to be reshaped
<ide> # twice and have to be reused in the following
<ide> attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
<ide> attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
<ide><path>src/transformers/models/wav2vec2/processing_wav2vec2.py
<ide> def __call__(self, *args, **kwargs):
<ide> When used in normal mode, this method forwards all its arguments to Wav2Vec2FeatureExtractor's
<ide> :meth:`~transformers.Wav2Vec2FeatureExtractor.__call__` and returns its output. If used in the context
<ide> :meth:`~transformers.Wav2Vec2Processor.as_target_processor` this method forwards all its arguments to
<del> Wav2Vec2CTCTokenizer's :meth:`~transformers.Wav2Vec2CTCTokenizer.__call__`. Please refer to the doctsring of
<add> Wav2Vec2CTCTokenizer's :meth:`~transformers.Wav2Vec2CTCTokenizer.__call__`. Please refer to the docstring of
<ide> the above two methods for more information.
<ide> """
<ide> return self.current_processor(*args, **kwargs)
<ide><path>src/transformers/models/xlm/modeling_xlm.py
<ide> class XLMForQuestionAnsweringOutput(ModelOutput):
<ide> A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
<ide> languages ids which can be obtained from the language names by using two conversion mappings provided in
<ide> the configuration of the model (only provided for multilingual models). More precisely, the `language name
<del> to language id` mapping is in :obj:`model.config.lang2id` (which is a dictionary strring to int) and the
<add> to language id` mapping is in :obj:`model.config.lang2id` (which is a dictionary string to int) and the
<ide> `language id to language name` mapping is in :obj:`model.config.id2lang` (dictionary int to string).
<ide>
<ide> See usage examples detailed in the :doc:`multilingual documentation <../multilingual>`.
<ide> def __init__(self, config, *inputs, **kwargs):
<ide>
<ide> self.init_weights()
<ide>
<del> @add_start_docstrings_to_model_forward(XLM_INPUTS_DOCSTRING.format("batch_size, num_choicec, sequence_length"))
<add> @add_start_docstrings_to_model_forward(XLM_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
<ide> @add_code_sample_docstrings(
<ide> tokenizer_class=_TOKENIZER_FOR_DOC,
<ide> checkpoint=_CHECKPOINT_FOR_DOC,
<ide><path>src/transformers/models/xlm/tokenization_xlm.py
<ide> def bpe(self, token):
<ide>
<ide> def _tokenize(self, text, lang="en", bypass_tokenizer=False):
<ide> """
<del> Tokenize a string given language code. For Chinese, Japanese and Thai, we use a language specific
<del> tokenizerself. Otherwise, we use Moses.
<add> Tokenize a string given language code. For Chinese, Japanese and Thai, we use a language specific tokenizer.
<add> Otherwise, we use Moses.
<ide>
<ide> Details of tokenization:
<ide>
<ide><path>src/transformers/models/xlnet/modeling_tf_xlnet.py
<ide> class TFXLNetForQuestionAnsweringSimpleOutput(ModelOutput):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **masked**,
<del> - 0 for tokens that are **not maked**.
<add> - 0 for tokens that are **not masked**.
<ide>
<ide> You can only uses one of :obj:`input_mask` and :obj:`attention_mask`.
<ide> head_mask (:obj:`Numpy array` or :obj:`tf.Tensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`):
<ide><path>src/transformers/optimization_tf.py
<ide> class AdamWeightDecay(tf.keras.optimizers.Adam):
<ide> name (:obj:`str`, `optional`, defaults to 'AdamWeightDecay'):
<ide> Optional name for the operations created when applying gradients.
<ide> kwargs:
<del> Keyward arguments. Allowed to be {``clipnorm``, ``clipvalue``, ``lr``, ``decay``}. ``clipnorm`` is clip
<add> Keyword arguments. Allowed to be {``clipnorm``, ``clipvalue``, ``lr``, ``decay``}. ``clipnorm`` is clip
<ide> gradients by norm; ``clipvalue`` is clip gradients by value, ``decay`` is included for backward
<ide> compatibility to allow time inverse decay of learning rate. ``lr`` is included for backward compatibility,
<ide> recommended to use ``learning_rate`` instead.
<ide><path>src/transformers/pipelines/conversational.py
<ide> def iter_texts(self):
<ide> """
<ide> Iterates over all blobs of the conversation.
<ide>
<del> Retuns: Iterator of (is_user, text_chunk) in chronological order of the conversation. ``is_user`` is a
<add> Returns: Iterator of (is_user, text_chunk) in chronological order of the conversation. ``is_user`` is a
<ide> :obj:`bool`, ``text_chunks`` is a :obj:`str`.
<ide> """
<ide> for user_input, generated_response in zip(self.past_user_inputs, self.generated_responses):
<ide><path>src/transformers/pipelines/text2text_generation.py
<ide> def __init__(self, *args, **kwargs):
<ide>
<ide> def check_inputs(self, input_length: int, min_length: int, max_length: int):
<ide> """
<del> Checks wether there might be something wrong with given input with regard to the model.
<add> Checks whether there might be something wrong with given input with regard to the model.
<ide> """
<ide> return True
<ide>
<ide> def __call__(self, *args, **kwargs):
<ide>
<ide> def check_inputs(self, input_length: int, min_length: int, max_length: int) -> bool:
<ide> """
<del> Checks wether there might be something wrong with given input with regard to the model.
<add> Checks whether there might be something wrong with given input with regard to the model.
<ide> """
<ide> if input_length < min_length // 2:
<ide> logger.warning(
<ide><path>src/transformers/tokenization_utils_fast.py
<ide> def _save_pretrained(
<ide> filename_prefix: Optional[str] = None,
<ide> ) -> Tuple[str]:
<ide> """
<del> Save a tokenizer using the slow-tokenizer/legacy format: vocabulary + added tokens as well asin a unique JSON
<add> Save a tokenizer using the slow-tokenizer/legacy format: vocabulary + added tokens as well as in a unique JSON
<ide> file containing {config + vocab + added-tokens}.
<ide> """
<ide> save_directory = str(save_directory)
<ide><path>src/transformers/trainer.py
<ide> class Trainer:
<ide>
<ide> Note that if it's a :obj:`torch.utils.data.dataset.IterableDataset` with some randomization and you are
<ide> training in a distributed fashion, your iterable dataset should either use a internal attribute
<del> :obj:`generator` that is a :obj:`torch.Generator` for the randomization that must be identic on all
<add> :obj:`generator` that is a :obj:`torch.Generator` for the randomization that must be identical on all
<ide> processes (and the Trainer will manually set the seed of this :obj:`generator` at each epoch) or have a
<ide> :obj:`set_epoch()` method that internally sets the seed of the RNGs used.
<ide> eval_dataset (:obj:`torch.utils.data.dataset.Dataset`, `optional`):
<ide><path>src/transformers/trainer_callback.py
<ide> class TrainerState:
<ide>
<ide> In all this class, one step is to be understood as one update step. When using gradient accumulation, one
<ide> update step may require several forward and backward passes: if you use :obj:`gradient_accumulation_steps=n`,
<del> then one update step requires going throuch `n` batches.
<add> then one update step requires going through `n` batches.
<ide>
<ide> Args:
<ide> epoch (:obj:`float`, `optional`):
<ide><path>src/transformers/trainer_pt_utils.py
<ide> class SequentialDistributedSampler(Sampler):
<ide>
<ide> def __init__(self, dataset, num_replicas=None, rank=None, batch_size=None):
<ide> warnings.warn(
<del> "SequentialDistributedSampler is deprecated and will be removed in v5 of Tranformers.",
<add> "SequentialDistributedSampler is deprecated and will be removed in v5 of Transformers.",
<ide> FutureWarning,
<ide> )
<ide> if num_replicas is None:
<ide> class DistributedTensorGatherer:
<ide>
<ide> def __init__(self, world_size, num_samples, make_multiple_of=None, padding_index=-100):
<ide> warnings.warn(
<del> "DistributedTensorGatherer is deprecated and will be removed in v5 of Tranformers.",
<add> "DistributedTensorGatherer is deprecated and will be removed in v5 of Transformers.",
<ide> FutureWarning,
<ide> )
<ide> self.world_size = world_size
<ide><path>src/transformers/trainer_seq2seq.py
<ide> def prediction_step(
<ide> def _pad_tensors_to_max_len(self, tensor, max_length):
<ide> if self.tokenizer is None:
<ide> raise ValueError(
<del> f"Tensor need to be padded to `max_length={max_length}` but no tokenzier was passed when creating "
<add> f"Tensor need to be padded to `max_length={max_length}` but no tokenizer was passed when creating "
<ide> "this `Trainer`. Make sure to create your `Trainer` with the appropriate tokenizer."
<ide> )
<ide> # If PAD token is not defined at least EOS token has to be defined
<ide><path>src/transformers/utils/logging.py
<ide> def get_verbosity() -> int:
<ide>
<ide> def set_verbosity(verbosity: int) -> None:
<ide> """
<del> Set the vebosity level for the 🤗 Transformers's root logger.
<add> Set the verbosity level for the 🤗 Transformers's root logger.
<ide>
<ide> Args:
<ide> verbosity (:obj:`int`): | 77 |
PHP | PHP | remove unneeded test | f6106c4095f2b26833db6b600ff7ead88c2edb43 | <ide><path>tests/Database/DatabaseQueryBuilderTest.php
<ide> public function testGetPaginationCountGetsResultCount()
<ide> }
<ide>
<ide>
<del> public function testGetPaginationCountGetsResultCountWithSelectDistinct()
<del> {
<del> unset($_SERVER['orders']);
<del> $builder = $this->getBuilder();
<del> $builder->getConnection()->shouldReceive('select')->once()->with('select count(distinct "foo", "bar") as aggregate from "users"', array())->andReturn(array(array('aggregate' => 1)));
<del> $builder->getProcessor()->shouldReceive('processSelect')->once()->andReturnUsing(function($query, $results)
<del> {
<del> $_SERVER['orders'] = $query->orders;
<del> return $results;
<del> });
<del> $results = $builder->distinct()->select('foo', 'bar')->from('users')->orderBy('foo', 'desc')->getPaginationCount();
<del>
<del> $this->assertNull($_SERVER['orders']);
<del> unset($_SERVER['orders']);
<del>
<del> $this->assertEquals(array('foo', 'bar'), $builder->columns);
<del> $this->assertEquals(array(0 => array('column' => 'foo', 'direction' => 'desc')), $builder->orders);
<del> $this->assertEquals(1, $results);
<del> }
<del>
<del>
<ide> public function testPluckMethodReturnsSingleColumn()
<ide> {
<ide> $builder = $this->getBuilder(); | 1 |
Ruby | Ruby | support openssl style | 2f757ee5aae8fb480118196c0e62e43b165715ca | <ide><path>Library/Homebrew/bottle_version.rb
<ide> def self._parse spec
<ide> m = /[a-z]{3}\d-(\d{1}-\d{8})/.match(stem)
<ide> return m.captures.first unless m.nil?
<ide>
<add> # e.g. 1.0.2a-1 from openssl-1.0.2a-1.yosemite.bottle.1.tar.gz
<add> m = /-(\d+\.\d+(\.\d+)+[a-z]-\d+)/.match(stem)
<add> return m.captures.first unless m.nil?
<add>
<ide> # e.g. perforce-2013.1.610569-x86_64.mountain_lion.bottle.tar.gz
<ide> m = /-([\d\.]+-x86(_64)?)/.match(stem)
<ide> return m.captures.first unless m.nil?
<ide><path>Library/Homebrew/test/test_bottle_versions.rb
<ide> def test_gcc_versions_style
<ide> assert_version_detected '5-20150215',
<ide> 'gcc5-5-20150215.yosemite.bottle.tar.gz'
<ide> end
<add>
<add> def test_openssl_style
<add> assert_version_detected '1.0.2a-1',
<add> 'openssl-1.0.2a-1.yosemite.bottle.1.tar.gz'
<add> end
<ide> end | 2 |
Javascript | Javascript | remove openssl -no_rand_screen opts | 425c5ca27d25b35091783262ea21baef1f742579 | <ide><path>test/parallel/test-https-foafssl.js
<ide> server.listen(0, function() {
<ide> '-cert', fixtures.path('foafssl.crt'),
<ide> '-key', fixtures.path('foafssl.key')];
<ide>
<del> // for the performance and stability issue in s_client on Windows
<del> if (common.isWindows)
<del> args.push('-no_rand_screen');
<del>
<ide> const client = spawn(common.opensslCli, args);
<ide>
<ide> client.stdout.on('data', function(data) {
<ide><path>test/parallel/test-tls-alert.js
<ide> const server = tls.Server({
<ide> const args = ['s_client', '-quiet', '-tls1_1',
<ide> '-connect', `127.0.0.1:${this.address().port}`];
<ide>
<del> // for the performance and stability issue in s_client on Windows
<del> if (common.isWindows)
<del> args.push('-no_rand_screen');
<del>
<ide> const client = spawn(common.opensslCli, args);
<ide> let out = '';
<ide> client.stderr.setEncoding('utf8');
<ide><path>test/parallel/test-tls-dhe.js
<ide> function test(keylen, expectedCipher, cb) {
<ide> const args = ['s_client', '-connect', `127.0.0.1:${this.address().port}`,
<ide> '-cipher', ciphers];
<ide>
<del> // for the performance and stability issue in s_client on Windows
<del> if (common.isWindows)
<del> args.push('-no_rand_screen');
<del>
<ide> const client = spawn(common.opensslCli, args);
<ide> let out = '';
<ide> client.stdout.setEncoding('utf8');
<ide><path>test/parallel/test-tls-ecdh-auto.js
<ide> server.listen(0, function() {
<ide> '-cipher', `${options.ciphers}`,
<ide> '-connect', `127.0.0.1:${this.address().port}`];
<ide>
<del> // for the performance and stability issue in s_client on Windows
<del> if (common.isWindows)
<del> args.push('-no_rand_screen');
<del>
<ide> const client = spawn(common.opensslCli, args);
<ide>
<ide> client.stdout.on('data', function(data) {
<ide><path>test/parallel/test-tls-ecdh-disable.js
<ide> common.expectWarning('DeprecationWarning',
<ide> const server = tls.createServer(options, common.mustNotCall());
<ide>
<ide> server.listen(0, '127.0.0.1', common.mustCall(function() {
<del> let cmd = `"${common.opensslCli}" s_client -cipher ${
<add> const cmd = `"${common.opensslCli}" s_client -cipher ${
<ide> options.ciphers} -connect 127.0.0.1:${this.address().port}`;
<ide>
<del> // for the performance and stability issue in s_client on Windows
<del> if (common.isWindows)
<del> cmd += ' -no_rand_screen';
<del>
<ide> exec(cmd, common.mustCall(function(err, stdout, stderr) {
<ide> // Old versions of openssl will still exit with 0 so we
<ide> // can't just check if err is not null.
<ide><path>test/parallel/test-tls-ecdh-multiple.js
<ide> server.listen(0, function() {
<ide> '-cipher', `${options.ciphers}`,
<ide> '-connect', `127.0.0.1:${this.address().port}`];
<ide>
<del> // for the performance and stability issue in s_client on Windows
<del> if (common.isWindows)
<del> args.push('-no_rand_screen');
<del>
<ide> const client = spawn(common.opensslCli, args);
<ide>
<ide> client.stdout.on('data', function(data) {
<ide><path>test/parallel/test-tls-ecdh.js
<ide> const server = tls.createServer(options, common.mustCall(function(conn) {
<ide> }));
<ide>
<ide> server.listen(0, '127.0.0.1', common.mustCall(function() {
<del> let cmd = `"${common.opensslCli}" s_client -cipher ${
<add> const cmd = `"${common.opensslCli}" s_client -cipher ${
<ide> options.ciphers} -connect 127.0.0.1:${this.address().port}`;
<ide>
<del> // for the performance and stability issue in s_client on Windows
<del> if (common.isWindows)
<del> cmd += ' -no_rand_screen';
<del>
<ide> exec(cmd, common.mustCall(function(err, stdout, stderr) {
<ide> assert.ifError(err);
<ide> assert(stdout.includes(reply));
<ide><path>test/parallel/test-tls-no-sslv3.js
<ide> server.listen(0, '127.0.0.1', function() {
<ide> '-ssl3',
<ide> '-connect', address];
<ide>
<del> // for the performance and stability issue in s_client on Windows
<del> if (common.isWindows)
<del> args.push('-no_rand_screen');
<del>
<ide> const client = spawn(common.opensslCli, args, { stdio: 'pipe' });
<ide> client.stdout.pipe(process.stdout);
<ide> client.stderr.pipe(process.stderr);
<ide><path>test/parallel/test-tls-securepair-server.js
<ide> server.listen(0, common.mustCall(function() {
<ide>
<ide> const args = ['s_client', '-connect', `127.0.0.1:${this.address().port}`];
<ide>
<del> // for the performance and stability issue in s_client on Windows
<del> if (common.isWindows)
<del> args.push('-no_rand_screen');
<del>
<ide> const client = spawn(common.opensslCli, args);
<ide>
<ide>
<ide><path>test/parallel/test-tls-server-verify.js
<ide> function runClient(prefix, port, options, cb) {
<ide>
<ide> const args = ['s_client', '-connect', `127.0.0.1:${port}`];
<ide>
<del> // for the performance issue in s_client on Windows
<del> if (common.isWindows)
<del> args.push('-no_rand_screen');
<del>
<ide> console.log(`${prefix} connecting with`, options.name);
<ide>
<ide> switch (options.name) {
<ide><path>test/parallel/test-tls-session-cache.js
<ide> function doTest(testOptions, callback) {
<ide> '-reconnect'
<ide> ].concat(testOptions.tickets ? [] : '-no_ticket');
<ide>
<del> // for the performance and stability issue in s_client on Windows
<del> if (common.isWindows)
<del> args.push('-no_rand_screen');
<del>
<ide> function spawnClient() {
<ide> const client = spawn(common.opensslCli, args, {
<ide> stdio: [ 0, 1, 'pipe' ]
<ide><path>test/parallel/test-tls-set-ciphers.js
<ide> const server = tls.createServer(options, common.mustCall(function(conn) {
<ide> }));
<ide>
<ide> server.listen(0, '127.0.0.1', function() {
<del> let cmd = `"${common.opensslCli}" s_client -cipher ${
<add> const cmd = `"${common.opensslCli}" s_client -cipher ${
<ide> options.ciphers} -connect 127.0.0.1:${this.address().port}`;
<ide>
<del> // for the performance and stability issue in s_client on Windows
<del> if (common.isWindows)
<del> cmd += ' -no_rand_screen';
<del>
<ide> exec(cmd, function(err, stdout, stderr) {
<ide> assert.ifError(err);
<ide> response = stdout; | 12 |
Ruby | Ruby | fix actionpack typos [ci skip] | 6cb854f70717071529b293e4a3f4dc577fe89006 | <ide><path>actionpack/lib/action_controller/base.rb
<ide> def self.without_modules(*modules)
<ide> HttpAuthentication::Digest::ControllerMethods,
<ide> HttpAuthentication::Token::ControllerMethods,
<ide>
<del> # Before callbacks should also be executed the earliest as possible, so
<add> # Before callbacks should also be executed as early as possible, so
<ide> # also include them at the bottom.
<ide> AbstractController::Callbacks,
<ide>
<ide><path>actionpack/lib/action_controller/renderer.rb
<ide> module ActionController
<ide> #
<ide> # ApplicationController.renderer.render template: '...'
<ide> #
<del> # You can use a shortcut on controller to replace previous example with:
<add> # You can use this shortcut in a controller, instead of the previous example:
<ide> #
<ide> # ApplicationController.render template: '...'
<ide> #
<del> # #render method allows you to use any options as when rendering in controller.
<add> # #render allows you to use the same options that you can use when rendering in a controller.
<ide> # For example,
<ide> #
<ide> # FooController.render :action, locals: { ... }, assigns: { ... } | 2 |
Ruby | Ruby | convert `associationqueryvalue` to poro queries | baf6072e4550cf2cf5e52240d0192a56dbe8e949 | <ide><path>activerecord/lib/active_record/relation/predicate_builder.rb
<ide> def initialize(table)
<ide> register_handler(RangeHandler::RangeWithBinds, RangeHandler.new)
<ide> register_handler(Relation, RelationHandler.new)
<ide> register_handler(Array, ArrayHandler.new(self))
<del> register_handler(AssociationQueryValue, AssociationQueryHandler.new(self))
<ide> register_handler(PolymorphicArrayValue, PolymorphicArrayHandler.new(self))
<ide> end
<ide>
<ide> def expand_from_hash(attributes)
<ide> end
<ide>
<ide> def create_binds_for_hash(attributes)
<del> result = attributes.dup
<add> result = {}
<ide> binds = []
<ide>
<ide> attributes.each do |column_name, value|
<del> binds.concat(value.bound_attributes) if value.is_a?(Relation)
<ide> case
<ide> when value.is_a?(Hash) && !table.has_column?(column_name)
<ide> attrs, bvs = associated_predicate_builder(column_name).create_binds_for_hash(value)
<ide> def create_binds_for_hash(attributes)
<ide> #
<ide> # For polymorphic relationships, find the foreign key and type:
<ide> # PriceEstimate.where(estimate_of: treasure)
<del> result[column_name] = AssociationQueryHandler.value_for(table, column_name, value)
<add> associated_table = table.associated_table(column_name)
<add> if associated_table.polymorphic_association?
<add> case value.is_a?(Array) ? value.first : value
<add> when Base, Relation
<add> binds.concat(value.bound_attributes) if value.is_a?(Relation)
<add> value = [value] unless value.is_a?(Array)
<add> klass = PolymorphicArrayValue
<add> end
<add> end
<add>
<add> if klass
<add> result[column_name] = klass.new(associated_table, value)
<add> else
<add> queries = AssociationQueryValue.new(associated_table, value).queries
<add> attrs, bvs = create_binds_for_hash(queries)
<add> result.merge!(attrs)
<add> binds.concat(bvs)
<add> end
<ide> when value.is_a?(Range) && !table.type(column_name).respond_to?(:subtype)
<ide> first = value.begin
<ide> last = value.end
<ide> def create_binds_for_hash(attributes)
<ide> result[column_name] = RangeHandler::RangeWithBinds.new(first, last, value.exclude_end?)
<ide> else
<ide> if can_be_bound?(column_name, value)
<del> result[column_name] = Arel::Nodes::BindParam.new
<ide> binds << build_bind_param(column_name, value)
<add> value = Arel::Nodes::BindParam.new
<add> elsif value.is_a?(Relation)
<add> binds.concat(value.bound_attributes)
<ide> end
<add> result[column_name] = value
<ide> end
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/relation/predicate_builder/association_query_handler.rb
<ide> module ActiveRecord
<ide> class PredicateBuilder
<del> class AssociationQueryHandler # :nodoc:
<del> def self.value_for(table, column, value)
<del> associated_table = table.associated_table(column)
<del> if associated_table.polymorphic_association?
<del> case value.is_a?(Array) ? value.first : value
<del> when Base, Relation
<del> value = [value] unless value.is_a?(Array)
<del> klass = PolymorphicArrayValue
<del> end
<del> end
<del>
<del> klass ||= AssociationQueryValue
<del> klass.new(associated_table, value)
<del> end
<del>
<del> def initialize(predicate_builder)
<del> @predicate_builder = predicate_builder
<del> end
<del>
<del> def call(attribute, value)
<del> predicate_builder.build_from_hash(value.queries)
<del> end
<del>
<del> # TODO Change this to private once we've dropped Ruby 2.2 support.
<del> # Workaround for Ruby 2.2 "private attribute?" warning.
<del> protected
<del>
<del> attr_reader :predicate_builder
<del> end
<del>
<ide> class AssociationQueryValue # :nodoc:
<ide> attr_reader :associated_table, :value
<ide> | 2 |
Text | Text | add an example with additional arguments | 1160e4e9bfbdc452a9bf1742e4980480ce3de3c3 | <ide><path>client/src/pages/guide/english/python/range-function/index.md
<ide> for i in range(5):
<ide> 4
<ide> ```
<ide>
<add>#### Example with optional additional arguments
<add>The first argument, *start* includes the number at which to start the progression.
<add>The second argument, *stop* is the same as in the example above, and the progression stops before this number.
<add>The third argument, *step* is for when you want to generate numbers, but at a step greater than one.
<add> ```py
<add>for i in range(3,12,2):
<add> print(i)
<add> ```
<add>
<add> #### Output
<add> ```
<add>3
<add>5
<add>7
<add>9
<add>11
<add> ``` | 1 |
Ruby | Ruby | use freeze instead of close! | 29592a7f09dda2e7e1e0a915d9230fe6a9b5c0af | <ide><path>actionpack/lib/action_dispatch/middleware/cookies.rb
<ide> def initialize(secret = nil, host = nil, secure = false)
<ide> @delete_cookies = {}
<ide> @host = host
<ide> @secure = secure
<del> @closed = false
<ide> @cookies = {}
<ide> end
<ide>
<del> attr_reader :closed
<del> alias :closed? :closed
<del> def close!; @closed = true end
<add> alias :closed? :frozen?
<ide>
<ide> # Returns the value of the cookie by +name+, or +nil+ if no such cookie exists.
<ide> def [](name)
<ide> def call(env)
<ide> [status, headers, body]
<ide> ensure
<ide> cookie_jar = ActionDispatch::Request.new(env).cookie_jar unless cookie_jar
<del> cookie_jar.close!
<add> cookie_jar.freeze
<ide> end
<ide> end
<ide> end
<ide><path>actionpack/lib/action_dispatch/middleware/flash.rb
<ide> class Flash
<ide> class FlashNow #:nodoc:
<ide> def initialize(flash)
<ide> @flash = flash
<del> @closed = false
<ide> end
<ide>
<del> attr_reader :closed
<del> alias :closed? :closed
<del> def close!; @closed = true end
<add> alias :closed? :frozen?
<ide>
<ide> def []=(k, v)
<ide> raise ClosedError, :flash if closed?
<ide> class FlashHash < Hash
<ide> def initialize #:nodoc:
<ide> super
<ide> @used = Set.new
<del> @closed = false
<ide> end
<ide>
<del> attr_reader :closed
<del> alias :closed? :closed
<del> def close!; @closed = true end
<add> alias :closed? :frozen?
<ide>
<ide> def []=(k, v) #:nodoc:
<ide> raise ClosedError, :flash if closed?
<ide> def call(env)
<ide> if !flash_hash.empty? || session.key?('flash')
<ide> session["flash"] = flash_hash
<ide> end
<del> flash_hash.close!
<add> flash_hash.freeze
<ide> end
<ide>
<ide> if session.key?('flash') && session['flash'].empty?
<ide><path>actionpack/test/dispatch/cookies_test.rb
<ide> class CookiesIntegrationTest < ActionDispatch::IntegrationTest
<ide>
<ide> class TestController < ActionController::Base
<ide> def dont_set_cookies
<add> # initialize lazy loaded objects
<add> cookies.permanent
<add> cookies.signed
<ide> head :ok
<ide> end
<ide>
<ide> def set_cookies
<add> # initialize lazy loaded objects
<add> cookies.permanent
<add> cookies.signed
<ide> cookies["that"] = "hello"
<ide> head :ok
<ide> end | 3 |
Go | Go | use describable interfaces | 2c60430a3d1431e0879aa1c66ca23143de987b35 | <ide><path>distribution/pull_v2.go
<ide> type v2LayerDescriptor struct {
<ide> V2MetadataService *metadata.V2MetadataService
<ide> tmpFile *os.File
<ide> verifier digest.Verifier
<del> foreignSrc *distribution.Descriptor
<add> src distribution.Descriptor
<ide> }
<ide>
<ide> func (ld *v2LayerDescriptor) Key() string {
<ide> func (p *v2Puller) pullSchema2(ctx context.Context, ref reference.Named, mfst *s
<ide> repo: p.repo,
<ide> repoInfo: p.repoInfo,
<ide> V2MetadataService: p.V2MetadataService,
<del> }
<del>
<del> if d.MediaType == schema2.MediaTypeForeignLayer && len(d.URLs) > 0 {
<del> if !layer.ForeignSourceSupported() {
<del> return "", "", errors.New("foreign layers are not supported on this OS")
<del> }
<del>
<del> layerDescriptor.foreignSrc = &d
<add> src: d,
<ide> }
<ide>
<ide> descriptors = append(descriptors, layerDescriptor)
<ide><path>distribution/pull_v2_windows.go
<ide> import (
<ide> "github.com/docker/distribution"
<ide> "github.com/docker/distribution/context"
<ide> "github.com/docker/distribution/manifest/schema1"
<add> "github.com/docker/distribution/manifest/schema2"
<ide> "github.com/docker/distribution/registry/client/transport"
<ide> "github.com/docker/docker/image"
<del> "github.com/docker/docker/layer"
<ide> )
<ide>
<ide> func detectBaseLayer(is image.Store, m *schema1.Manifest, rootFS *image.RootFS) error {
<ide> func detectBaseLayer(is image.Store, m *schema1.Manifest, rootFS *image.RootFS)
<ide> return fmt.Errorf("Invalid base layer %q", v1img.Parent)
<ide> }
<ide>
<del>var _ layer.ForeignSourcer = &v2LayerDescriptor{}
<add>var _ distribution.Describable = &v2LayerDescriptor{}
<ide>
<del>func (ld *v2LayerDescriptor) ForeignSource() *distribution.Descriptor {
<del> return ld.foreignSrc
<add>func (ld *v2LayerDescriptor) Descriptor() distribution.Descriptor {
<add> if ld.src.MediaType == schema2.MediaTypeForeignLayer && len(ld.src.URLs) > 0 {
<add> return ld.src
<add> }
<add> return distribution.Descriptor{}
<ide> }
<ide>
<ide> func (ld *v2LayerDescriptor) open(ctx context.Context) (distribution.ReadSeekCloser, error) {
<del> if ld.foreignSrc == nil {
<add> if len(ld.src.URLs) == 0 {
<ide> blobs := ld.repo.Blobs(ctx)
<ide> return blobs.Open(ctx, ld.digest)
<ide> }
<ide> func (ld *v2LayerDescriptor) open(ctx context.Context) (distribution.ReadSeekClo
<ide> )
<ide>
<ide> // Find the first URL that results in a 200 result code.
<del> for _, url := range ld.foreignSrc.URLs {
<add> for _, url := range ld.src.URLs {
<ide> rsc = transport.NewHTTPReadSeeker(http.DefaultClient, url, nil)
<ide> _, err = rsc.Seek(0, os.SEEK_SET)
<ide> if err == nil {
<ide><path>distribution/push_v2.go
<ide> func (pd *v2PushDescriptor) DiffID() layer.DiffID {
<ide> }
<ide>
<ide> func (pd *v2PushDescriptor) Upload(ctx context.Context, progressOutput progress.Output) (distribution.Descriptor, error) {
<del> if fs, ok := pd.layer.(layer.ForeignSourcer); ok {
<del> if d := fs.ForeignSource(); d != nil {
<add> if fs, ok := pd.layer.(distribution.Describable); ok {
<add> if d := fs.Descriptor(); len(d.URLs) > 0 {
<ide> progress.Update(progressOutput, pd.ID(), "Skipped foreign layer")
<del> return *d, nil
<add> return d, nil
<ide> }
<ide> }
<ide>
<ide><path>distribution/xfer/download.go
<ide> func (ldm *LayerDownloadManager) makeDownloadFunc(descriptor DownloadDescriptor,
<ide> return
<ide> }
<ide>
<del> var src *distribution.Descriptor
<del> if fs, ok := descriptor.(layer.ForeignSourcer); ok {
<del> src = fs.ForeignSource()
<add> var src distribution.Descriptor
<add> if fs, ok := descriptor.(distribution.Describable); ok {
<add> src = fs.Descriptor()
<add> }
<add> if ds, ok := d.layerStore.(layer.DescribableStore); ok {
<add> d.layer, err = ds.RegisterWithDescriptor(inflatedLayerData, parentLayer, src)
<add> } else {
<add> d.layer, err = d.layerStore.Register(inflatedLayerData, parentLayer)
<ide> }
<del> d.layer, err = d.layerStore.RegisterForeign(inflatedLayerData, parentLayer, src)
<ide> if err != nil {
<ide> select {
<ide> case <-d.Transfer.Context().Done():
<ide> func (ldm *LayerDownloadManager) makeDownloadFuncFromDownload(descriptor Downloa
<ide> }
<ide> defer layerReader.Close()
<ide>
<del> var src *distribution.Descriptor
<del> if fs, ok := l.(layer.ForeignSourcer); ok {
<del> src = fs.ForeignSource()
<add> var src distribution.Descriptor
<add> if fs, ok := l.(distribution.Describable); ok {
<add> src = fs.Descriptor()
<add> }
<add> if ds, ok := d.layerStore.(layer.DescribableStore); ok {
<add> d.layer, err = ds.RegisterWithDescriptor(layerReader, parentLayer, src)
<add> } else {
<add> d.layer, err = d.layerStore.Register(layerReader, parentLayer)
<ide> }
<del> d.layer, err = d.layerStore.RegisterForeign(layerReader, parentLayer, src)
<ide> if err != nil {
<ide> d.err = fmt.Errorf("failed to register layer: %v", err)
<ide> return
<ide><path>distribution/xfer/download_test.go
<ide> func createChainIDFromParent(parent layer.ChainID, dgsts ...layer.DiffID) layer.
<ide> }
<ide>
<ide> func (ls *mockLayerStore) Register(reader io.Reader, parentID layer.ChainID) (layer.Layer, error) {
<del> return ls.RegisterForeign(reader, parentID, nil)
<add> return ls.RegisterWithDescriptor(reader, parentID, distribution.Descriptor{})
<ide> }
<ide>
<del>func (ls *mockLayerStore) RegisterForeign(reader io.Reader, parentID layer.ChainID, _ *distribution.Descriptor) (layer.Layer, error) {
<add>func (ls *mockLayerStore) RegisterWithDescriptor(reader io.Reader, parentID layer.ChainID, _ distribution.Descriptor) (layer.Layer, error) {
<ide> var (
<ide> parent layer.Layer
<ide> err error
<ide><path>image/tarexport/load.go
<ide> func (l *tarexporter) Load(inTar io.ReadCloser, outStream io.Writer, quiet bool)
<ide> var parentLinks []parentLink
<ide>
<ide> for _, m := range manifest {
<del> if m.LayerSources != nil && !layer.ForeignSourceSupported() {
<del> return fmt.Errorf("invalid manifest, foreign layers not supported on this operating system")
<del> }
<del>
<ide> configPath, err := safePath(tmpDir, m.Config)
<ide> if err != nil {
<ide> return err
<ide> func (l *tarexporter) setParentID(id, parentID image.ID) error {
<ide> return l.is.SetParent(id, parentID)
<ide> }
<ide>
<del>func (l *tarexporter) loadLayer(filename string, rootFS image.RootFS, id string, foreignSrc *distribution.Descriptor, progressOutput progress.Output) (layer.Layer, error) {
<add>func (l *tarexporter) loadLayer(filename string, rootFS image.RootFS, id string, foreignSrc distribution.Descriptor, progressOutput progress.Output) (layer.Layer, error) {
<ide> rawTar, err := os.Open(filename)
<ide> if err != nil {
<ide> logrus.Debugf("Error reading embedded tar: %v", err)
<ide> func (l *tarexporter) loadLayer(filename string, rootFS image.RootFS, id string,
<ide>
<ide> progressReader := progress.NewProgressReader(inflatedLayerData, progressOutput, fileInfo.Size(), stringid.TruncateID(id), "Loading layer")
<ide>
<del> return l.ls.RegisterForeign(progressReader, rootFS.ChainID(), foreignSrc)
<add> if ds, ok := l.ls.(layer.DescribableStore); ok {
<add> return ds.RegisterWithDescriptor(progressReader, rootFS.ChainID(), foreignSrc)
<add> }
<add> return l.ls.Register(progressReader, rootFS.ChainID())
<add>
<add> }
<add>
<add> if ds, ok := l.ls.(layer.DescribableStore); ok {
<add> return ds.RegisterWithDescriptor(inflatedLayerData, rootFS.ChainID(), foreignSrc)
<ide> }
<del> return l.ls.RegisterForeign(inflatedLayerData, rootFS.ChainID(), foreignSrc)
<add> return l.ls.Register(inflatedLayerData, rootFS.ChainID())
<ide> }
<ide>
<ide> func (l *tarexporter) setLoadedTag(ref reference.NamedTagged, imgID image.ID, outStream io.Writer) error {
<ide> func (l *tarexporter) legacyLoadImage(oldID, sourceDir string, loadedMap map[str
<ide> if err != nil {
<ide> return err
<ide> }
<del> newLayer, err := l.loadLayer(layerPath, *rootFS, oldID, nil, progressOutput)
<add> newLayer, err := l.loadLayer(layerPath, *rootFS, oldID, distribution.Descriptor{}, progressOutput)
<ide> if err != nil {
<ide> return err
<ide> }
<ide><path>image/tarexport/save.go
<ide> func (s *saveSession) save(outStream io.Writer) error {
<ide> return nil
<ide> }
<ide>
<del>func (s *saveSession) saveImage(id image.ID) (map[layer.DiffID]*distribution.Descriptor, error) {
<add>func (s *saveSession) saveImage(id image.ID) (map[layer.DiffID]distribution.Descriptor, error) {
<ide> img, err := s.is.Get(id)
<ide> if err != nil {
<ide> return nil, err
<ide> func (s *saveSession) saveImage(id image.ID) (map[layer.DiffID]*distribution.Des
<ide>
<ide> var parent digest.Digest
<ide> var layers []string
<del> var foreignSrcs map[layer.DiffID]*distribution.Descriptor
<add> var foreignSrcs map[layer.DiffID]distribution.Descriptor
<ide> for i := range img.RootFS.DiffIDs {
<ide> v1Img := image.V1Image{}
<ide> if i == len(img.RootFS.DiffIDs)-1 {
<ide> func (s *saveSession) saveImage(id image.ID) (map[layer.DiffID]*distribution.Des
<ide> }
<ide> layers = append(layers, v1Img.ID)
<ide> parent = v1ID
<del> if src != nil {
<add> if src.Digest != "" {
<ide> if foreignSrcs == nil {
<del> foreignSrcs = make(map[layer.DiffID]*distribution.Descriptor)
<add> foreignSrcs = make(map[layer.DiffID]distribution.Descriptor)
<ide> }
<ide> foreignSrcs[img.RootFS.DiffIDs[i]] = src
<ide> }
<ide> func (s *saveSession) saveImage(id image.ID) (map[layer.DiffID]*distribution.Des
<ide> return foreignSrcs, nil
<ide> }
<ide>
<del>func (s *saveSession) saveLayer(id layer.ChainID, legacyImg image.V1Image, createdTime time.Time) (*distribution.Descriptor, error) {
<add>func (s *saveSession) saveLayer(id layer.ChainID, legacyImg image.V1Image, createdTime time.Time) (distribution.Descriptor, error) {
<ide> if _, exists := s.savedLayers[legacyImg.ID]; exists {
<del> return nil, nil
<add> return distribution.Descriptor{}, nil
<ide> }
<ide>
<ide> outDir := filepath.Join(s.outDir, legacyImg.ID)
<ide> if err := os.Mkdir(outDir, 0755); err != nil {
<del> return nil, err
<add> return distribution.Descriptor{}, err
<ide> }
<ide>
<ide> // todo: why is this version file here?
<ide> if err := ioutil.WriteFile(filepath.Join(outDir, legacyVersionFileName), []byte("1.0"), 0644); err != nil {
<del> return nil, err
<add> return distribution.Descriptor{}, err
<ide> }
<ide>
<ide> imageConfig, err := json.Marshal(legacyImg)
<ide> if err != nil {
<del> return nil, err
<add> return distribution.Descriptor{}, err
<ide> }
<ide>
<ide> if err := ioutil.WriteFile(filepath.Join(outDir, legacyConfigFileName), imageConfig, 0644); err != nil {
<del> return nil, err
<add> return distribution.Descriptor{}, err
<ide> }
<ide>
<ide> // serialize filesystem
<ide> tarFile, err := os.Create(filepath.Join(outDir, legacyLayerFileName))
<ide> if err != nil {
<del> return nil, err
<add> return distribution.Descriptor{}, err
<ide> }
<ide> defer tarFile.Close()
<ide>
<ide> l, err := s.ls.Get(id)
<ide> if err != nil {
<del> return nil, err
<add> return distribution.Descriptor{}, err
<ide> }
<ide> defer layer.ReleaseAndLog(s.ls, l)
<ide>
<ide> arch, err := l.TarStream()
<ide> if err != nil {
<del> return nil, err
<add> return distribution.Descriptor{}, err
<ide> }
<ide> defer arch.Close()
<ide>
<ide> if _, err := io.Copy(tarFile, arch); err != nil {
<del> return nil, err
<add> return distribution.Descriptor{}, err
<ide> }
<ide>
<ide> for _, fname := range []string{"", legacyVersionFileName, legacyConfigFileName, legacyLayerFileName} {
<ide> // todo: maybe save layer created timestamp?
<ide> if err := system.Chtimes(filepath.Join(outDir, fname), createdTime, createdTime); err != nil {
<del> return nil, err
<add> return distribution.Descriptor{}, err
<ide> }
<ide> }
<ide>
<ide> s.savedLayers[legacyImg.ID] = struct{}{}
<ide>
<del> var src *distribution.Descriptor
<del> if fs, ok := l.(layer.ForeignSourcer); ok {
<del> src = fs.ForeignSource()
<add> var src distribution.Descriptor
<add> if fs, ok := l.(distribution.Describable); ok {
<add> src = fs.Descriptor()
<ide> }
<ide> return src, nil
<ide> }
<ide><path>image/tarexport/tarexport.go
<ide> type manifestItem struct {
<ide> Config string
<ide> RepoTags []string
<ide> Layers []string
<del> Parent image.ID `json:",omitempty"`
<del> LayerSources map[layer.DiffID]*distribution.Descriptor `json:",omitempty"`
<add> Parent image.ID `json:",omitempty"`
<add> LayerSources map[layer.DiffID]distribution.Descriptor `json:",omitempty"`
<ide> }
<ide>
<ide> type tarexporter struct {
<ide><path>layer/filestore.go
<ide> var (
<ide> // digest.SHA384, // Currently not used
<ide> // digest.SHA512, // Currently not used
<ide> }
<del>
<del> // ErrNoForeignSource is returned when no foreign source is set for a layer.
<del> ErrNoForeignSource = errors.New("layer does not have a foreign source")
<ide> )
<ide>
<ide> type fileMetadataStore struct {
<ide> func (fm *fileMetadataTransaction) SetCacheID(cacheID string) error {
<ide> return ioutil.WriteFile(filepath.Join(fm.root, "cache-id"), []byte(cacheID), 0644)
<ide> }
<ide>
<del>func (fm *fileMetadataTransaction) SetForeignSource(ref distribution.Descriptor) error {
<add>func (fm *fileMetadataTransaction) SetDescriptor(ref distribution.Descriptor) error {
<ide> jsonRef, err := json.Marshal(ref)
<ide> if err != nil {
<ide> return err
<ide> func (fms *fileMetadataStore) GetCacheID(layer ChainID) (string, error) {
<ide> return content, nil
<ide> }
<ide>
<del>func (fms *fileMetadataStore) GetForeignSource(layer ChainID) (distribution.Descriptor, error) {
<add>func (fms *fileMetadataStore) GetDescriptor(layer ChainID) (distribution.Descriptor, error) {
<ide> content, err := ioutil.ReadFile(fms.getLayerFilename(layer, "descriptor.json"))
<ide> if err != nil {
<ide> if os.IsNotExist(err) {
<del> return distribution.Descriptor{}, ErrNoForeignSource
<add> // only return empty descriptor to represent what is stored
<add> return distribution.Descriptor{}, nil
<ide> }
<ide> return distribution.Descriptor{}, err
<ide> }
<ide><path>layer/layer.go
<ide> type Layer interface {
<ide> Metadata() (map[string]string, error)
<ide> }
<ide>
<del>// ForeignSourcer is an interface used to describe the source of layers
<del>// and objects representing layers, when the source is a foreign URL.
<del>type ForeignSourcer interface {
<del> // ForeignSource returns the descriptor for this layer if it is
<del> // a foreign layer, or nil for ordinary layers.
<del> ForeignSource() *distribution.Descriptor
<del>}
<del>
<ide> // RWLayer represents a layer which is
<ide> // read and writable
<ide> type RWLayer interface {
<ide> type MountInit func(root string) error
<ide> // read-only and read-write layers.
<ide> type Store interface {
<ide> Register(io.Reader, ChainID) (Layer, error)
<del> RegisterForeign(io.Reader, ChainID, *distribution.Descriptor) (Layer, error)
<ide> Get(ChainID) (Layer, error)
<ide> Release(Layer) ([]Metadata, error)
<ide>
<ide> type Store interface {
<ide> DriverName() string
<ide> }
<ide>
<add>// DescribableStore represents a layer store capable of storing
<add>// descriptors for layers.
<add>type DescribableStore interface {
<add> RegisterWithDescriptor(io.Reader, ChainID, distribution.Descriptor) (Layer, error)
<add>}
<add>
<ide> // MetadataTransaction represents functions for setting layer metadata
<ide> // with a single transaction.
<ide> type MetadataTransaction interface {
<ide> SetSize(int64) error
<ide> SetParent(parent ChainID) error
<ide> SetDiffID(DiffID) error
<ide> SetCacheID(string) error
<del> SetForeignSource(distribution.Descriptor) error
<add> SetDescriptor(distribution.Descriptor) error
<ide> TarSplitWriter(compressInput bool) (io.WriteCloser, error)
<ide>
<ide> Commit(ChainID) error
<ide> type MetadataStore interface {
<ide> GetParent(ChainID) (ChainID, error)
<ide> GetDiffID(ChainID) (DiffID, error)
<ide> GetCacheID(ChainID) (string, error)
<del> GetForeignSource(ChainID) (distribution.Descriptor, error)
<add> GetDescriptor(ChainID) (distribution.Descriptor, error)
<ide> TarSplitReader(ChainID) (io.ReadCloser, error)
<ide>
<ide> SetMountID(string, string) error
<ide><path>layer/layer_store.go
<ide> func (ls *layerStore) loadLayer(layer ChainID) (*roLayer, error) {
<ide> return nil, fmt.Errorf("failed to get parent for %s: %s", layer, err)
<ide> }
<ide>
<add> descriptor, err := ls.store.GetDescriptor(layer)
<add> if err != nil {
<add> return nil, fmt.Errorf("failed to get descriptor for %s: %s", layer, err)
<add> }
<add>
<ide> cl = &roLayer{
<ide> chainID: layer,
<ide> diffID: diff,
<ide> size: size,
<ide> cacheID: cacheID,
<ide> layerStore: ls,
<ide> references: map[Layer]struct{}{},
<del> }
<del>
<del> foreignSrc, err := ls.store.GetForeignSource(layer)
<del> if err == nil {
<del> cl.foreignSrc = &foreignSrc
<del> } else if err != ErrNoForeignSource {
<del> return nil, fmt.Errorf("failed to get foreign reference for %s: %s", layer, err)
<add> descriptor: descriptor,
<ide> }
<ide>
<ide> if parent != "" {
<ide> func (ls *layerStore) applyTar(tx MetadataTransaction, ts io.Reader, parent stri
<ide> }
<ide>
<ide> func (ls *layerStore) Register(ts io.Reader, parent ChainID) (Layer, error) {
<del> return ls.RegisterForeign(ts, parent, nil)
<add> return ls.registerWithDescriptor(ts, parent, distribution.Descriptor{})
<ide> }
<ide>
<del>func (ls *layerStore) RegisterForeign(ts io.Reader, parent ChainID, foreignSrc *distribution.Descriptor) (Layer, error) {
<add>func (ls *layerStore) registerWithDescriptor(ts io.Reader, parent ChainID, descriptor distribution.Descriptor) (Layer, error) {
<ide> // err is used to hold the error which will always trigger
<ide> // cleanup of creates sources but may not be an error returned
<ide> // to the caller (already exists).
<ide> func (ls *layerStore) RegisterForeign(ts io.Reader, parent ChainID, foreignSrc *
<ide> layer := &roLayer{
<ide> parent: p,
<ide> cacheID: stringid.GenerateRandomID(),
<del> foreignSrc: foreignSrc,
<ide> referenceCount: 1,
<ide> layerStore: ls,
<ide> references: map[Layer]struct{}{},
<add> descriptor: descriptor,
<ide> }
<ide>
<ide> if err = ls.driver.Create(layer.cacheID, pid, "", nil); err != nil {
<ide><path>layer/layer_store_windows.go
<add>package layer
<add>
<add>import (
<add> "io"
<add>
<add> "github.com/docker/distribution"
<add>)
<add>
<add>func (ls *layerStore) RegisterWithDescriptor(ts io.Reader, parent ChainID, descriptor distribution.Descriptor) (Layer, error) {
<add> return ls.registerWithDescriptor(ts, parent, descriptor)
<add>}
<ide><path>layer/layer_unix.go
<ide> import "github.com/docker/docker/pkg/stringid"
<ide> func (ls *layerStore) mountID(name string) string {
<ide> return stringid.GenerateRandomID()
<ide> }
<del>
<del>// ForeignSourceSupported returns whether layers downloaded from foreign sources are
<del>// supported in this daemon.
<del>func ForeignSourceSupported() bool {
<del> return false
<del>}
<ide><path>layer/layer_windows.go
<ide> func (ls *layerStore) mountID(name string) string {
<ide> func (ls *layerStore) GraphDriver() graphdriver.Driver {
<ide> return ls.driver
<ide> }
<del>
<del>// ForeignSourceSupported returns whether layers downloaded from foreign sources are
<del>// supported in this daemon.
<del>func ForeignSourceSupported() bool {
<del> return true
<del>}
<ide><path>layer/ro_layer.go
<ide> type roLayer struct {
<ide> cacheID string
<ide> size int64
<ide> layerStore *layerStore
<del> foreignSrc *distribution.Descriptor
<add> descriptor distribution.Descriptor
<ide>
<ide> referenceCount int
<ide> references map[Layer]struct{}
<ide> func storeLayer(tx MetadataTransaction, layer *roLayer) error {
<ide> if err := tx.SetCacheID(layer.cacheID); err != nil {
<ide> return err
<ide> }
<del> if layer.parent != nil {
<del> if err := tx.SetParent(layer.parent.chainID); err != nil {
<add> // Do not store empty descriptors
<add> if layer.descriptor.Digest != "" {
<add> if err := tx.SetDescriptor(layer.descriptor); err != nil {
<ide> return err
<ide> }
<ide> }
<del> if layer.foreignSrc != nil {
<del> if err := tx.SetForeignSource(*layer.foreignSrc); err != nil {
<add> if layer.parent != nil {
<add> if err := tx.SetParent(layer.parent.chainID); err != nil {
<ide> return err
<ide> }
<ide> }
<ide><path>layer/ro_layer_windows.go
<ide> package layer
<ide>
<ide> import "github.com/docker/distribution"
<ide>
<del>var _ ForeignSourcer = &roLayer{}
<add>var _ distribution.Describable = &roLayer{}
<ide>
<del>func (rl *roLayer) ForeignSource() *distribution.Descriptor {
<del> return rl.foreignSrc
<add>func (rl *roLayer) Descriptor() distribution.Descriptor {
<add> return rl.descriptor
<ide> } | 16 |
Javascript | Javascript | create crlfchecker module and use it in make.js | 2ffd3ae1c73c17cd4513c28d03933b0d27d4a29f | <ide><path>external/crlfchecker/crlfchecker.js
<add>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
<add>/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
<add>
<add>function checkIfCrlfIsPresent(files) {
<add> var failed = [];
<add>
<add> (ls(files)).forEach(function checkCrlf(file) {
<add> if ((cat(file)).match(/.*\r.*/)) {
<add> failed.push(file);
<add> }
<add> });
<add>
<add> if (failed.length) {
<add> var errorMessage =
<add> 'Please remove carriage return\'s from\n' + failed.join('\n') + '\n' +
<add> 'Also check your setting for: git config core.autocrlf.';
<add>
<add> echo();
<add> echo(errorMessage);
<add> exit(1);
<add> }
<add>}
<add>
<add>exports.checkIfCrlfIsPresent = checkIfCrlfIsPresent;
<add>
<ide><path>make.js
<ide> #!/usr/bin/env node
<ide> require('./external/shelljs/make');
<ide> var builder = require('./external/builder/builder.js');
<add>var crlfchecker = require('./external/crlfchecker/crlfchecker.js');
<ide>
<ide> var ROOT_DIR = __dirname + '/', // absolute path to project's root
<ide> BUILD_DIR = 'build/',
<ide> var DEFINES = {
<ide> CHROME: false
<ide> };
<ide>
<del>//
<del>// Helper functions
<del>//
<del>function checkIfCarriageReturnsArePresent(string, throwOnError) {
<del> if (string.match(/.*\r.*/)) {
<del> var errorMessage =
<del> 'Carriage Return\'s should not be present. Please remove them.\n' +
<del> 'Also check your setting for: git config core.autocrlf.';
<del>
<del> if (throwOnError) {
<del> throw(errorMessage);
<del> } else {
<del> echo();
<del> echo(errorMessage);
<del> }
<del> }
<del>}
<del>
<del>function throwIfCarriageReturnsArePresent(string) {
<del> checkIfCarriageReturnsArePresent(string, true);
<del>}
<del>
<del>function warnIfCarriageReturnsArePresent(string) {
<del> checkIfCarriageReturnsArePresent(string, false);
<del>}
<del>
<ide> //
<ide> // make all
<ide> //
<ide> target.bundle = function() {
<ide> {silent: true}).output.replace('\n', '');
<ide>
<ide> // Handle only src/*.js for now.
<del> throwIfCarriageReturnsArePresent(cat('*.js'));
<add> crlfchecker.checkIfCrlfIsPresent(['*.js']);
<ide>
<ide> // This just preprocesses the empty pdf.js file, we don't actually want to
<ide> // preprocess everything yet since other build targets use this file.
<ide> target.lint = function() {
<ide> exec('gjslint --nojsdoc ' + LINT_FILES.join(' '));
<ide>
<ide> // Handle only src/*.js for now.
<del> warnIfCarriageReturnsArePresent(cat('src/*.js'));
<add> crlfchecker.checkIfCrlfIsPresent(['src/*.js']);
<ide> };
<ide>
<ide> // | 2 |
Ruby | Ruby | add mandoc to allowed list | e7f723e5435b434f015a0f8d55f6769c63e02f5d | <ide><path>Library/Homebrew/rubocops/uses_from_macos.rb
<ide> class UsesFromMacos < FormulaCop
<ide> groff
<ide> gzip
<ide> less
<add> mandoc
<ide> openssl
<ide> perl
<ide> php | 1 |
Javascript | Javascript | increase pbkdf2 test coverage | d50e1a291694ee96890c1734e7ed9b0295d5262c | <ide><path>test/parallel/test-crypto-pbkdf2.js
<ide> common.expectsError(
<ide> }
<ide> );
<ide>
<add>common.expectsError(
<add> () => crypto.pbkdf2Sync('password', 'salt', -1, 20, null),
<add> {
<add> code: 'ERR_OUT_OF_RANGE',
<add> type: RangeError,
<add> message: 'The "iterations" argument is out of range'
<add> }
<add>);
<add>
<add>['str', null, undefined, [], {}].forEach((notNumber) => {
<add> common.expectsError(
<add> () => {
<add> crypto.pbkdf2Sync('password', 'salt', 1, notNumber, 'sha256');
<add> }, {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> type: TypeError,
<add> message: 'The "keylen" argument must be of type number'
<add> });
<add>});
<add>
<ide> [Infinity, -Infinity, NaN, -1, 4073741824, INT_MAX + 1].forEach((i) => {
<ide> common.expectsError(
<ide> () => { | 1 |
Ruby | Ruby | detect more 'pkgshare' candidates (#328) | af42deca4ab70816216ffc060f3aa8f55e469cac | <ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit_line(line, lineno)
<ide> problem "Use \#{pkgshare} instead of \#{share}/#{formula.name}"
<ide> end
<ide>
<del> if line =~ %r{share/"#{Regexp.escape(formula.name)}[/'"]}
<del> problem "Use pkgshare instead of (share/\"#{formula.name}\")"
<add> if line =~ %r{share(\s*[/+]\s*)(['"])#{Regexp.escape(formula.name)}(?:\2|/)}
<add> problem "Use pkgshare instead of (share#{$1}\"#{formula.name}\")"
<ide> end
<ide> end
<ide> end | 1 |
Ruby | Ruby | change the method visibility | 44e1cda314cc562f6432f30d0064759c2fdc39b5 | <ide><path>actionview/lib/action_view/helpers/tags/translator.rb
<ide> module ActionView
<ide> module Helpers
<ide> module Tags # :nodoc:
<ide> class Translator # :nodoc:
<del> attr_reader :object_name, :method_and_value, :i18n_scope, :model
<del>
<ide> def initialize(object, object_name, method_and_value, i18n_scope)
<ide> @object_name = object_name.gsub(/\[(.*)_attributes\]\[\d+\]/, '.\1')
<ide> @method_and_value = method_and_value
<ide> def call
<ide> translated_attribute || human_attribute_name
<ide> end
<ide>
<add> private
<add>
<add> attr_reader :object_name, :method_and_value, :i18n_scope, :model
<add>
<ide> def i18n_default
<ide> if model
<ide> key = model.model_name.i18n_key | 1 |
Java | Java | add reactfragment for android | d0792d4b8ac42711dfd9fccb782f16e72ce3e335 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactActivityDelegate.java
<ide>
<ide> import com.facebook.infer.annotation.Assertions;
<ide> import com.facebook.react.bridge.Callback;
<del>import com.facebook.react.devsupport.DoubleTapReloadRecognizer;
<del>import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
<add>import com.facebook.react.uimanager.RootView;
<ide> import com.facebook.react.modules.core.PermissionListener;
<ide>
<ide> import javax.annotation.Nullable;
<ide> public class ReactActivityDelegate {
<ide> private final @Nullable Activity mActivity;
<ide> private final @Nullable String mMainComponentName;
<ide>
<del> private @Nullable ReactRootView mReactRootView;
<del> private @Nullable DoubleTapReloadRecognizer mDoubleTapReloadRecognizer;
<ide> private @Nullable PermissionListener mPermissionListener;
<ide> private @Nullable Callback mPermissionsCallback;
<add> private ReactDelegate mReactDelegate;
<ide>
<ide> @Deprecated
<ide> public ReactActivityDelegate(Activity activity, @Nullable String mainComponentName) {
<ide> public ReactActivityDelegate(ReactActivity activity, @Nullable String mainCompon
<ide> }
<ide>
<ide> protected ReactRootView createRootView() {
<del> return new ReactRootView(getContext());
<add> return mReactDelegate.createRootView();
<ide> }
<ide>
<ide> /**
<ide> protected ReactNativeHost getReactNativeHost() {
<ide> }
<ide>
<ide> public ReactInstanceManager getReactInstanceManager() {
<del> return getReactNativeHost().getReactInstanceManager();
<add> return mReactDelegate.getReactInstanceManager();
<ide> }
<ide>
<ide> public String getMainComponentName() {
<ide> public String getMainComponentName() {
<ide>
<ide> protected void onCreate(Bundle savedInstanceState) {
<ide> String mainComponentName = getMainComponentName();
<del> if (mainComponentName != null) {
<add> mReactDelegate = new ReactDelegate(getPlainActivity(), getReactNativeHost(), mainComponentName, getLaunchOptions());
<add> if (mMainComponentName != null) {
<ide> loadApp(mainComponentName);
<ide> }
<del> mDoubleTapReloadRecognizer = new DoubleTapReloadRecognizer();
<ide> }
<ide>
<ide> protected void loadApp(String appKey) {
<del> if (mReactRootView != null) {
<del> throw new IllegalStateException("Cannot loadApp while app is already running.");
<del> }
<del> mReactRootView = createRootView();
<del> mReactRootView.startReactApplication(
<del> getReactNativeHost().getReactInstanceManager(),
<del> appKey,
<del> getLaunchOptions());
<del> getPlainActivity().setContentView(mReactRootView);
<add> mReactDelegate.loadApp(appKey);
<add> getPlainActivity().setContentView(mReactDelegate.getReactRootView());
<ide> }
<ide>
<ide> protected void onPause() {
<del> if (getReactNativeHost().hasInstance()) {
<del> getReactNativeHost().getReactInstanceManager().onHostPause(getPlainActivity());
<del> }
<add> mReactDelegate.onHostPause();
<ide> }
<ide>
<ide> protected void onResume() {
<del> if (getReactNativeHost().hasInstance()) {
<del> getReactNativeHost().getReactInstanceManager().onHostResume(
<del> getPlainActivity(),
<del> (DefaultHardwareBackBtnHandler) getPlainActivity());
<del> }
<add> mReactDelegate.onHostResume();
<ide>
<ide> if (mPermissionsCallback != null) {
<ide> mPermissionsCallback.invoke();
<ide> protected void onResume() {
<ide> }
<ide>
<ide> protected void onDestroy() {
<del> if (mReactRootView != null) {
<del> mReactRootView.unmountReactApplication();
<del> mReactRootView = null;
<del> }
<del> if (getReactNativeHost().hasInstance()) {
<del> getReactNativeHost().getReactInstanceManager().onHostDestroy(getPlainActivity());
<del> }
<add> mReactDelegate.onHostDestroy();
<ide> }
<ide>
<ide> public void onActivityResult(int requestCode, int resultCode, Intent data) {
<del> if (getReactNativeHost().hasInstance()) {
<del> getReactNativeHost().getReactInstanceManager()
<del> .onActivityResult(getPlainActivity(), requestCode, resultCode, data);
<del> }
<add> mReactDelegate.onActivityResult(requestCode, resultCode, data, true);
<ide> }
<ide>
<ide> public boolean onKeyDown(int keyCode, KeyEvent event) {
<ide> && getReactNativeHost().getUseDeveloperSupport()
<ide> }
<ide>
<ide> public boolean onKeyUp(int keyCode, KeyEvent event) {
<del> if (getReactNativeHost().hasInstance() && getReactNativeHost().getUseDeveloperSupport()) {
<del> if (keyCode == KeyEvent.KEYCODE_MENU) {
<del> getReactNativeHost().getReactInstanceManager().showDevOptionsDialog();
<del> return true;
<del> }
<del> boolean didDoubleTapR = Assertions.assertNotNull(mDoubleTapReloadRecognizer)
<del> .didDoubleTapR(keyCode, getPlainActivity().getCurrentFocus());
<del> if (didDoubleTapR) {
<del> getReactNativeHost().getReactInstanceManager().getDevSupportManager().handleReloadJS();
<del> return true;
<del> }
<del> }
<del> return false;
<add> return mReactDelegate.shouldShowDevMenuOrReload(keyCode, event);
<ide> }
<ide>
<ide> public boolean onKeyLongPress(int keyCode, KeyEvent event) {
<ide> && getReactNativeHost().getUseDeveloperSupport()
<ide> }
<ide>
<ide> public boolean onBackPressed() {
<del> if (getReactNativeHost().hasInstance()) {
<del> getReactNativeHost().getReactInstanceManager().onBackPressed();
<del> return true;
<del> }
<del> return false;
<add> return mReactDelegate.onBackPressed();
<ide> }
<ide>
<ide> public boolean onNewIntent(Intent intent) {
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactDelegate.java
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> */
<add>
<add>package com.facebook.react;
<add>
<add>import android.app.Activity;
<add>import android.content.Intent;
<add>import android.os.Bundle;
<add>import android.view.KeyEvent;
<add>
<add>import com.facebook.infer.annotation.Assertions;
<add>import com.facebook.react.devsupport.DoubleTapReloadRecognizer;
<add>import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
<add>
<add>import javax.annotation.Nullable;
<add>
<add>/**
<add> * A delegate for handling React Application support. This delegate is unaware whether it is used in
<add> * an {@link Activity} or a {@link android.app.Fragment}.
<add> */
<add>public class ReactDelegate {
<add>
<add> private final Activity mActivity;
<add> private ReactRootView mReactRootView;
<add>
<add> @Nullable
<add> private final String mMainComponentName;
<add>
<add> @Nullable
<add> private Bundle mLaunchOptions;
<add>
<add> @Nullable
<add> private DoubleTapReloadRecognizer mDoubleTapReloadRecognizer;
<add>
<add> private ReactNativeHost mReactNativeHost;
<add>
<add>
<add> public ReactDelegate(Activity activity, ReactNativeHost reactNativeHost, @Nullable String appKey, @Nullable Bundle launchOptions) {
<add> mActivity = activity;
<add> mMainComponentName = appKey;
<add> mLaunchOptions = launchOptions;
<add> mDoubleTapReloadRecognizer = new DoubleTapReloadRecognizer();
<add> mReactNativeHost = reactNativeHost;
<add> }
<add>
<add> public void onHostResume() {
<add> if (getReactNativeHost().hasInstance()) {
<add> if (mActivity instanceof DefaultHardwareBackBtnHandler) {
<add> getReactNativeHost().getReactInstanceManager().onHostResume(mActivity, (DefaultHardwareBackBtnHandler) mActivity);
<add> } else {
<add> throw new ClassCastException("Host Activity does not implement DefaultHardwareBackBtnHandler");
<add> }
<add> }
<add> }
<add>
<add> public void onHostPause() {
<add> if (getReactNativeHost().hasInstance()) {
<add> getReactNativeHost().getReactInstanceManager().onHostPause(mActivity);
<add> }
<add> }
<add>
<add> public void onHostDestroy() {
<add> if (mReactRootView != null) {
<add> mReactRootView.unmountReactApplication();
<add> mReactRootView = null;
<add> }
<add> if (getReactNativeHost().hasInstance()) {
<add> getReactNativeHost().getReactInstanceManager().onHostDestroy(mActivity);
<add> }
<add> }
<add>
<add> public boolean onBackPressed() {
<add> if (getReactNativeHost().hasInstance()) {
<add> getReactNativeHost().getReactInstanceManager().onBackPressed();
<add> return true;
<add> }
<add> return false;
<add> }
<add>
<add> public void onActivityResult(int requestCode, int resultCode, Intent data, boolean shouldForwardToReactInstance) {
<add> if (getReactNativeHost().hasInstance() && shouldForwardToReactInstance) {
<add> getReactNativeHost().getReactInstanceManager().onActivityResult(mActivity, requestCode, resultCode, data);
<add> }
<add> }
<add>
<add> public void loadApp() {
<add> loadApp(mMainComponentName);
<add> }
<add>
<add> public void loadApp(String appKey) {
<add> if (mReactRootView != null) {
<add> throw new IllegalStateException("Cannot loadApp while app is already running.");
<add> }
<add> mReactRootView = createRootView();
<add> mReactRootView.startReactApplication(
<add> getReactNativeHost().getReactInstanceManager(),
<add> appKey,
<add> mLaunchOptions);
<add>
<add> }
<add>
<add> public ReactRootView getReactRootView() {
<add> return mReactRootView;
<add> }
<add>
<add>
<add> protected ReactRootView createRootView() {
<add> return new ReactRootView(mActivity);
<add> }
<add>
<add> /**
<add> * Handles delegating the {@link Activity#onKeyUp(int, KeyEvent)} method to determine whether
<add> * the application should show the developer menu or should reload the React Application.
<add> *
<add> * @return true if we consume the event and either shoed the develop menu or reloaded the application.
<add> */
<add> public boolean shouldShowDevMenuOrReload(int keyCode, KeyEvent event) {
<add> if (getReactNativeHost().hasInstance() && getReactNativeHost().getUseDeveloperSupport()) {
<add> if (keyCode == KeyEvent.KEYCODE_MENU) {
<add> getReactNativeHost().getReactInstanceManager().showDevOptionsDialog();
<add> return true;
<add> }
<add> boolean didDoubleTapR = Assertions.assertNotNull(mDoubleTapReloadRecognizer).didDoubleTapR(keyCode, mActivity.getCurrentFocus());
<add> if (didDoubleTapR) {
<add> getReactNativeHost().getReactInstanceManager().getDevSupportManager().handleReloadJS();
<add> return true;
<add> }
<add> }
<add> return false;
<add> }
<add>
<add> /**
<add> * Get the {@link ReactNativeHost} used by this app.
<add> */
<add> private ReactNativeHost getReactNativeHost() {
<add> return mReactNativeHost;
<add> }
<add>
<add> public ReactInstanceManager getReactInstanceManager() {
<add> return getReactNativeHost().getReactInstanceManager();
<add> }
<add>
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactFragment.java
<add>
<add>/**
<add>* Copyright (c) Facebook, Inc. and its affiliates.
<add>*
<add>* This source code is licensed under the MIT license found in the
<add>* LICENSE file in the root directory of this source tree.
<add>*/
<add>
<add>package com.facebook.react;
<add>
<add>import android.annotation.TargetApi;
<add>import android.app.Activity;
<add>import android.content.Intent;
<add>import android.os.Build;
<add>import android.os.Bundle;
<add>import android.view.KeyEvent;
<add>import android.view.LayoutInflater;
<add>import android.view.View;
<add>import android.view.ViewGroup;
<add>
<add>import com.facebook.react.modules.core.PermissionAwareActivity;
<add>import com.facebook.react.modules.core.PermissionListener;
<add>
<add>import javax.annotation.Nullable;
<add>
<add>import androidx.fragment.app.Fragment;
<add>
<add>/**
<add>* Fragment for creating a React View. This allows the developer to "embed" a React Application
<add>* inside native components such as a Drawer, ViewPager, etc.
<add>*/
<add>public class ReactFragment extends Fragment implements PermissionAwareActivity {
<add>
<add>private static final String ARG_COMPONENT_NAME = "arg_component_name";
<add>private static final String ARG_LAUNCH_OPTIONS = "arg_launch_options";
<add>
<add>private ReactDelegate mReactDelegate;
<add>
<add>@Nullable
<add>private PermissionListener mPermissionListener;
<add>
<add>
<add>public ReactFragment() {
<add> // Required empty public constructor
<add>}
<add>
<add>/**
<add> * @param componentName The name of the react native component
<add> * @return A new instance of fragment ReactFragment.
<add> */
<add>private static ReactFragment newInstance(String componentName, Bundle launchOptions) {
<add> ReactFragment fragment = new ReactFragment();
<add> Bundle args = new Bundle();
<add> args.putString(ARG_COMPONENT_NAME, componentName);
<add> args.putBundle(ARG_LAUNCH_OPTIONS, launchOptions);
<add> fragment.setArguments(args);
<add> return fragment;
<add>}
<add>
<add>// region Lifecycle
<add>@Override
<add>public void onCreate(Bundle savedInstanceState) {
<add> super.onCreate(savedInstanceState);
<add> String mainComponentName = null;
<add> Bundle launchOptions = null;
<add> if (getArguments() != null) {
<add> mainComponentName = getArguments().getString(ARG_COMPONENT_NAME);
<add> launchOptions = getArguments().getBundle(ARG_LAUNCH_OPTIONS);
<add> }
<add> if (mainComponentName == null) {
<add> throw new IllegalStateException("Cannot loadApp if component name is null");
<add> }
<add> mReactDelegate = new ReactDelegate(getActivity(), getReactNativeHost(), mainComponentName, launchOptions);
<add>}
<add>
<add>/**
<add> * Get the {@link ReactNativeHost} used by this app. By default, assumes
<add> * {@link Activity#getApplication()} is an instance of {@link ReactApplication} and calls
<add> * {@link ReactApplication#getReactNativeHost()}. Override this method if your application class
<add> * does not implement {@code ReactApplication} or you simply have a different mechanism for
<add> * storing a {@code ReactNativeHost}, e.g. as a static field somewhere.
<add> */
<add>protected ReactNativeHost getReactNativeHost() {
<add> return ((ReactApplication) getActivity().getApplication()).getReactNativeHost();
<add>}
<add>
<add>@Override
<add>public View onCreateView(LayoutInflater inflater, ViewGroup container,
<add> Bundle savedInstanceState) {
<add> mReactDelegate.loadApp();
<add> return mReactDelegate.getReactRootView();
<add>}
<add>
<add>@Override
<add>public void onResume() {
<add> super.onResume();
<add> mReactDelegate.onHostResume();
<add>}
<add>
<add>@Override
<add>public void onPause() {
<add> super.onPause();
<add> mReactDelegate.onHostPause();
<add>}
<add>
<add>@Override
<add>public void onDestroy() {
<add> super.onDestroy();
<add> mReactDelegate.onHostDestroy();
<add>}
<add>// endregion
<add>
<add>@Override
<add>public void onActivityResult(int requestCode, int resultCode, Intent data) {
<add> super.onActivityResult(requestCode, resultCode, data);
<add> mReactDelegate.onActivityResult(requestCode, resultCode, data, false);
<add>}
<add>
<add>/**
<add> * Helper to forward hardware back presses to our React Native Host
<add> *
<add> * This must be called via a forward from your host Activity
<add> *
<add> */
<add>public boolean onBackPressed() {
<add> return mReactDelegate.onBackPressed();
<add>}
<add>
<add>/**
<add> * Helper to forward onKeyUp commands from our host Activity.
<add> * This allows ReactFragment to handle double tap reloads and dev menus
<add> *
<add> * This must be called via a forward from your host Activity
<add> *
<add> * @param keyCode keyCode
<add> * @param event event
<add> * @return true if we handled onKeyUp
<add> */
<add>public boolean onKeyUp(int keyCode, KeyEvent event) {
<add> return mReactDelegate.shouldShowDevMenuOrReload(keyCode, event);
<add>}
<add>
<add>@Override
<add>public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
<add> super.onRequestPermissionsResult(requestCode, permissions, grantResults);
<add> if (mPermissionListener != null &&
<add> mPermissionListener.onRequestPermissionsResult(requestCode, permissions, grantResults)) {
<add> mPermissionListener = null;
<add> }
<add>}
<add>
<add>@Override
<add>public int checkPermission(String permission, int pid, int uid) {
<add> return getActivity().checkPermission(permission, pid, uid);
<add>}
<add>
<add>@TargetApi(Build.VERSION_CODES.M)
<add>@Override
<add>public int checkSelfPermission(String permission) {
<add> return getActivity().checkSelfPermission(permission);
<add>}
<add>
<add>@TargetApi(Build.VERSION_CODES.M)
<add>@Override
<add>public void requestPermissions(String[] permissions, int requestCode, PermissionListener listener) {
<add> mPermissionListener = listener;
<add> requestPermissions(permissions, requestCode);
<add>}
<add>
<add>/**
<add> * Builder class to help instantiate a ReactFragment
<add> */
<add>public static class Builder {
<add>
<add> String mComponentName;
<add> Bundle mLaunchOptions;
<add>
<add> public Builder() {
<add> mComponentName = null;
<add> mLaunchOptions = null;
<add> }
<add>
<add> /**
<add> * Set the Component name for our React Native instance.
<add> *
<add> * @param componentName The name of the component
<add> * @return Builder
<add> */
<add> public Builder setComponentName(String componentName) {
<add> mComponentName = componentName;
<add> return this;
<add> }
<add>
<add> /**
<add> * Set the Launch Options for our React Native instance.
<add> *
<add> * @param launchOptions launchOptions
<add> * @return Builder
<add> */
<add> public Builder setLaunchOptions(Bundle launchOptions) {
<add> mLaunchOptions = launchOptions;
<add> return this;
<add> }
<add>
<add> public ReactFragment build() {
<add> return ReactFragment.newInstance(mComponentName, mLaunchOptions);
<add> }
<add>
<add>}
<add>} | 3 |
Text | Text | use consistent typography for node-addon-api | b01d314167c472237036798783eed7de96cfdfc5 | <ide><path>doc/api/n-api.md
<ide> properties:
<ide> The N-API is a C API that ensures ABI stability across Node.js versions
<ide> and different compiler levels. A C++ API can be easier to use.
<ide> To support using C++, the project maintains a
<del>C++ wrapper module called [node-addon-api][].
<add>C++ wrapper module called [`node-addon-api`][].
<ide> This wrapper provides an inlineable C++ API. Binaries built
<ide> with `node-addon-api` will depend on the symbols for the N-API C-based
<ide> functions exported by Node.js. `node-addon-api` is a more
<ide> for `node-addon-api`.
<ide>
<ide> The [N-API Resource](https://nodejs.github.io/node-addon-examples/) offers an
<ide> excellent orientation and tips for developers just getting started with N-API
<del>and node-addon-api.
<add>and `node-addon-api`.
<ide>
<ide> ## Implications of ABI stability
<ide>
<ide> This API may only be called from the main thread.
<ide> [`napi_throw`]: #n_api_napi_throw
<ide> [`napi_unwrap`]: #n_api_napi_unwrap
<ide> [`napi_wrap`]: #n_api_napi_wrap
<add>[`node-addon-api`]: https://github.com/nodejs/node-addon-api
<ide> [`node_api.h`]: https://github.com/nodejs/node/blob/master/src/node_api.h
<ide> [`process.release`]: process.html#process_process_release
<ide> [`uv_ref`]: https://docs.libuv.org/en/v1.x/handle.html#c.uv_ref
<ide> This API may only be called from the main thread.
<ide> [docs]: https://github.com/nodejs/node-addon-api#api-documentation
<ide> [global scope]: globals.html
<ide> [module scope]: modules.html#modules_the_module_scope
<del>[node-addon-api]: https://github.com/nodejs/node-addon-api
<ide> [node-gyp]: https://github.com/nodejs/node-gyp
<ide> [node-pre-gyp]: https://github.com/mapbox/node-pre-gyp
<ide> [prebuild]: https://github.com/prebuild/prebuild | 1 |
Javascript | Javascript | pass arguments to _super | e929b74d2c0768c8d1842bd0d31cf21ebad604b1 | <ide><path>packages/ember-application/lib/system/application-instance.js
<ide> export default EmberObject.extend({
<ide> rootElement: null,
<ide>
<ide> init: function() {
<del> this._super();
<add> this._super.apply(this, arguments);
<ide> this.container = this.registry.container();
<ide> },
<ide> | 1 |
PHP | PHP | expand test coverage for controller task | 2a85ffe4954f48d97f962adf8776638c5ea138cb | <ide><path>src/Console/Command/Task/ControllerTask.php
<ide> public function execute() {
<ide> }
<ide>
<ide> if (empty($this->args)) {
<del> $this->out(__d('cake_console', 'Possible Controllers based on your current database:'));
<add> $this->out(__d('cake_console', 'Possible controllers based on your current database:'));
<ide> foreach ($this->listAll() as $table) {
<ide> $this->out('- ' . $this->_controllerName($table));
<ide> }
<ide><path>tests/TestCase/Console/Command/Task/ControllerTaskTest.php
<ide> public function testBakeTestDisabled() {
<ide> $this->Task->bakeTest('BakeArticles');
<ide> }
<ide>
<add>/**
<add> * Test execute no args.
<add> *
<add> * @return void
<add> */
<add> public function testExecuteNoArgs() {
<add> $this->Task->expects($this->never())
<add> ->method('createFile');
<add>
<add> $this->Task->expects($this->at(0))
<add> ->method('out')
<add> ->with($this->stringContains('Possible controllers based on your current database'));
<add>
<add> $this->Task->execute();
<add> }
<add>
<ide> /**
<ide> * test that execute runs all when the first arg == all
<ide> * | 2 |
PHP | PHP | remove duplicate code | 046ed726b9da0b191699980bfad115353af8bd94 | <ide><path>Cake/Test/TestCase/View/Helper/PaginatorHelperTest.php
<ide> public function testFirstFullBaseUrl() {
<ide> $this->Paginator->request->params['paging']['Article']['page'] = 3;
<ide> $this->Paginator->request->params['paging']['Article']['direction'] = 'DESC';
<ide> $this->Paginator->request->params['paging']['Article']['sort'] = 'Article.title';
<del> $this->Paginator->request->params['paging']['Article']['direction'] = 'DESC';
<ide>
<ide> $this->Paginator->options(array('url' => array('_full' => true)));
<ide> | 1 |
Python | Python | increase max hr@10 to cover the rare >.640 | 725f65b68a20ad742378f58b07e9623c10bfdbe5 | <ide><path>official/recommendation/ncf_keras_benchmark.py
<ide> def _run_and_report_benchmark_mlperf_like(self):
<ide> """
<ide> self._run_and_report_benchmark(hr_at_10_min=0.61)
<ide>
<del> def _run_and_report_benchmark(self, hr_at_10_min=0.630, hr_at_10_max=0.640):
<add> def _run_and_report_benchmark(self, hr_at_10_min=0.630, hr_at_10_max=0.645):
<ide> """Run test and report results.
<ide>
<ide> Note: Target is 0.635, but some runs are below that level. Until we have | 1 |
Ruby | Ruby | prevent state leak | f81bd7c67daca8e9970fb23d7c78224e1f5fa937 | <ide><path>actionpack/lib/action_controller/test_case.rb
<ide> def process(action, http_method = 'GET', *args)
<ide>
<ide> unless @controller.respond_to?(:recycle!)
<ide> @controller.extend(Testing::Functional)
<del> @controller.class.class_eval { include Testing }
<ide> end
<ide>
<ide> @request.recycle!
<ide><path>actionpack/test/controller/new_base/bare_metal_test.rb
<ide>
<ide> module BareMetalTest
<ide> class BareController < ActionController::Metal
<add> include ActionController::RackDelegation
<add>
<ide> def index
<ide> self.response_body = "Hello world"
<ide> end
<ide><path>actionpack/test/controller/render_test.rb
<ide> class MetalTestController < ActionController::Metal
<ide> include AbstractController::Rendering
<ide> include ActionView::Rendering
<ide> include ActionController::Rendering
<add> include ActionController::RackDelegation
<add>
<ide>
<ide> def accessing_logger_in_template
<ide> render :inline => "<%= logger.class %>"
<ide><path>actionpack/test/controller/send_file_test.rb
<ide> def file_data() @data ||= File.open(file_path, 'rb') { |f| f.read } end
<ide>
<ide> class SendFileController < ActionController::Base
<ide> include TestFileUtils
<add> include ActionController::Testing
<ide> layout "layouts/standard" # to make sure layouts don't interfere
<ide>
<ide> attr_writer :options | 4 |
Mixed | Java | fix text input spans | de586bfa186289114974674bc2aece462f40393e | <ide><path>Examples/UIExplorer/TextInputExample.android.js
<ide> class RewriteExample extends React.Component {
<ide> }
<ide> }
<ide>
<add>class TokenizedTextExample extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {text: 'Hello #World'};
<add> }
<add> render() {
<add>
<add> //define delimiter
<add> let delimiter = /\s+/;
<add>
<add> //split string
<add> let _text = this.state.text;
<add> let token, index, parts = [];
<add> while (_text) {
<add> delimiter.lastIndex = 0;
<add> token = delimiter.exec(_text);
<add> if (token === null) {
<add> break;
<add> }
<add> index = token.index;
<add> if (token[0].length === 0) {
<add> index = 1;
<add> }
<add> parts.push(_text.substr(0, index));
<add> parts.push(token[0]);
<add> index = index + token[0].length;
<add> _text = _text.slice(index);
<add> }
<add> parts.push(_text);
<add>
<add> //highlight hashtags
<add> parts = parts.map((text) => {
<add> if (/^#/.test(text)) {
<add> return <Text key={text} style={styles.hashtag}>{text}</Text>;
<add> } else {
<add> return text;
<add> }
<add> });
<add>
<add> return (
<add> <View>
<add> <TextInput
<add> multiline={true}
<add> style={styles.multiline}
<add> onChangeText={(text) => {
<add> this.setState({text});
<add> }}>
<add> <Text>{parts}</Text>
<add> </TextInput>
<add> </View>
<add> );
<add> }
<add>}
<add>
<ide> var styles = StyleSheet.create({
<ide> multiline: {
<ide> height: 60,
<ide> var styles = StyleSheet.create({
<ide> singleLineWithHeightTextInput: {
<ide> height: 30,
<ide> },
<add> hashtag: {
<add> color: 'blue',
<add> fontWeight: 'bold',
<add> },
<ide> });
<ide>
<ide> exports.title = '<TextInput>';
<ide> exports.examples = [
<ide> );
<ide> }
<ide> },
<add> {
<add> title: 'Attributed text',
<add> render: function() {
<add> return <TokenizedTextExample />;
<add> }
<add> },
<ide> ];
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditText.java
<ide> import android.text.SpannableStringBuilder;
<ide> import android.text.Spanned;
<ide> import android.text.TextWatcher;
<add>import android.text.style.AbsoluteSizeSpan;
<add>import android.text.style.BackgroundColorSpan;
<add>import android.text.style.ForegroundColorSpan;
<ide> import android.view.Gravity;
<ide> import android.view.KeyEvent;
<ide> import android.view.inputmethod.InputMethodManager;
<ide> import android.widget.EditText;
<ide>
<ide> import com.facebook.infer.annotation.Assertions;
<add>import com.facebook.react.views.text.CustomStyleSpan;
<add>import com.facebook.react.views.text.ReactTagSpan;
<ide>
<ide> /**
<ide> * A wrapper around the EditText that lets us better control what happens when an EditText gets
<ide> public void maybeSetText(ReactTextUpdate reactTextUpdate) {
<ide> private void manageSpans(SpannableStringBuilder spannableStringBuilder) {
<ide> Object[] spans = getText().getSpans(0, length(), Object.class);
<ide> for (int spanIdx = 0; spanIdx < spans.length; spanIdx++) {
<add> // Remove all styling spans we might have previously set
<add> if (ForegroundColorSpan.class.isInstance(spans[spanIdx]) ||
<add> BackgroundColorSpan.class.isInstance(spans[spanIdx]) ||
<add> AbsoluteSizeSpan.class.isInstance(spans[spanIdx]) ||
<add> CustomStyleSpan.class.isInstance(spans[spanIdx]) ||
<add> ReactTagSpan.class.isInstance(spans[spanIdx])) {
<add> getText().removeSpan(spans[spanIdx]);
<add> }
<add>
<ide> if ((getText().getSpanFlags(spans[spanIdx]) & Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) !=
<ide> Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) {
<ide> continue;
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextChangedEvent.java
<ide>
<ide> /**
<ide> * Event emitted by EditText native view when text changes.
<add> * VisibleForTesting from {@link TextInputEventsTestCase}.
<ide> */
<del>/* package */ class ReactTextChangedEvent extends Event<ReactTextChangedEvent> {
<add>public class ReactTextChangedEvent extends Event<ReactTextChangedEvent> {
<ide>
<ide> public static final String EVENT_NAME = "topChange";
<ide>
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputEvent.java
<ide>
<ide> /**
<ide> * Event emitted by EditText native view when text changes.
<add> * VisibleForTesting from {@link TextInputEventsTestCase}.
<ide> */
<del>/* package */ class ReactTextInputEvent extends Event<ReactTextInputEvent> {
<add>public class ReactTextInputEvent extends Event<ReactTextInputEvent> {
<ide>
<ide> public static final String EVENT_NAME = "topTextInput";
<ide> | 4 |
Javascript | Javascript | fix usedexports issue | 407cdd5eb40aacbc3111cd10eaee1cdc37fc56cb | <ide><path>lib/dependencies/HarmonyExportImportedSpecifierDependency.js
<ide> class ExportMode {
<ide> this.name = null;
<ide> /** @type {Map<string, string[]>} */
<ide> this.map = EMPTY_MAP;
<del> /** @type {ExportInfo} */
<add> /** @type {Map<string, ExportInfo>|undefined|ExportInfo} */
<ide> this.partialNamespaceExportInfo = undefined;
<ide> /** @type {Set<string>|null} */
<ide> this.ignored = null;
<ide> class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
<ide> default:
<ide> mode = new ExportMode("normal-reexport");
<ide> mode.map = new Map([[name, ids]]);
<add> mode.partialNamespaceExportInfo = new Map();
<add> mode.partialNamespaceExportInfo.set(name, exportInfo);
<ide> mode.checked = EMPTY_SET;
<ide> break;
<ide> }
<ide> class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
<ide>
<ide> /** @type {Map<string, string[]>} */
<ide> const map = new Map();
<add> /** @type {Map<string, ExportInfo>} */
<add> const exportsInfoMap = new Map();
<ide> for (const exportName of exports) {
<ide> map.set(exportName, [exportName]);
<add> exportsInfoMap.set(
<add> exportName,
<add> exportsInfo.getReadOnlyExportInfo(exportName)
<add> );
<ide> }
<ide>
<ide> const mode = new ExportMode("normal-reexport");
<ide>
<ide> mode.map = map;
<add> mode.partialNamespaceExportInfo = exportsInfoMap;
<ide> mode.checked = checked;
<ide>
<ide> return mode;
<ide> class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
<ide> processExportInfo(
<ide> referencedExports,
<ide> [],
<del> mode.partialNamespaceExportInfo
<add> /** @type {ExportInfo} */ (mode.partialNamespaceExportInfo)
<ide> );
<ide> return referencedExports;
<ide> }
<ide> class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
<ide> processExportInfo(
<ide> referencedExports,
<ide> [],
<del> mode.partialNamespaceExportInfo,
<add> /** @type {ExportInfo} */ (mode.partialNamespaceExportInfo),
<ide> mode.type === "reexport-fake-namespace-object"
<ide> );
<ide> return referencedExports;
<ide> class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
<ide> case "dynamic-reexport":
<ide> return Dependency.EXPORTS_OBJECT_REFERENCED;
<ide>
<del> case "normal-reexport":
<del> return Array.from(mode.map.values());
<add> case "normal-reexport": {
<add> if (!mode.partialNamespaceExportInfo)
<add> return Array.from(mode.map.values());
<add>
<add> const referencedExports = [];
<add> for (const [key, value] of mode.map) {
<add> const exportInfo = /** @type {Map<string, ExportInfo>} */ (mode.partialNamespaceExportInfo).get(
<add> key
<add> );
<add> processExportInfo(referencedExports, value, exportInfo, false);
<add> }
<add>
<add> return referencedExports;
<add> }
<ide>
<ide> default:
<ide> throw new Error(`Unknown mode ${mode.type}`);
<ide><path>test/cases/parsing/harmony-export-import-specifier/index.js
<ide> it("namespace export as from commonjs should override named export", function()
<ide>
<ide> it("named namespace export should work correctly", function () {
<ide> expect(d2).toBe(2);
<del> expect(usedD1).toBe(true); // TODO
<add> expect(usedD1).toBe(false);
<ide> expect(usedD2).toBe(true);
<ide>
<ide> expect(b1.d2).toBe(2); | 2 |
Python | Python | add type hints to binary_tree_traversals.py | 4fea48072ae88c19f5133a2303e6707eddf96700 | <ide><path>traversals/binary_tree_traversals.py
<ide> """
<ide> This is pure python implementation of tree traversal algorithms
<ide> """
<del>from __future__ import print_function
<del>
<ide> import queue
<del>
<del>try:
<del> raw_input # Python 2
<del>except NameError:
<del> raw_input = input # Python 3
<add>from typing import List
<ide>
<ide>
<ide> class TreeNode:
<ide> def __init__(self, data):
<ide>
<ide> def build_tree():
<ide> print("\n********Press N to stop entering at any point of time********\n")
<del> print("Enter the value of the root node: ", end="")
<del> check = raw_input().strip().lower()
<del> if check == 'n':
<add> check = input("Enter the value of the root node: ").strip().lower() or "n"
<add> if check == "n":
<ide> return None
<del> data = int(check)
<del> q = queue.Queue()
<del> tree_node = TreeNode(data)
<add> q: queue.Queue = queue.Queue()
<add> tree_node = TreeNode(int(check))
<ide> q.put(tree_node)
<ide> while not q.empty():
<ide> node_found = q.get()
<del> print("Enter the left node of %s: " % node_found.data, end="")
<del> check = raw_input().strip().lower()
<del> if check == 'n':
<add> msg = "Enter the left node of %s: " % node_found.data
<add> check = input(msg).strip().lower() or "n"
<add> if check == "n":
<ide> return tree_node
<del> left_data = int(check)
<del> left_node = TreeNode(left_data)
<add> left_node = TreeNode(int(check))
<ide> node_found.left = left_node
<ide> q.put(left_node)
<del> print("Enter the right node of %s: " % node_found.data, end="")
<del> check = raw_input().strip().lower()
<del> if check == 'n':
<add> msg = "Enter the right node of %s: " % node_found.data
<add> check = input(msg).strip().lower() or "n"
<add> if check == "n":
<ide> return tree_node
<del> right_data = int(check)
<del> right_node = TreeNode(right_data)
<add> right_node = TreeNode(int(check))
<ide> node_found.right = right_node
<ide> q.put(right_node)
<ide>
<ide>
<del>def pre_order(node):
<add>def pre_order(node: TreeNode) -> None:
<ide> if not isinstance(node, TreeNode) or not node:
<ide> return
<ide> print(node.data, end=" ")
<ide> pre_order(node.left)
<ide> pre_order(node.right)
<ide>
<ide>
<del>def in_order(node):
<add>def in_order(node: TreeNode) -> None:
<ide> if not isinstance(node, TreeNode) or not node:
<ide> return
<ide> in_order(node.left)
<ide> print(node.data, end=" ")
<ide> in_order(node.right)
<ide>
<ide>
<del>def post_order(node):
<add>def post_order(node: TreeNode) -> None:
<ide> if not isinstance(node, TreeNode) or not node:
<ide> return
<ide> post_order(node.left)
<ide> post_order(node.right)
<ide> print(node.data, end=" ")
<ide>
<ide>
<del>def level_order(node):
<add>def level_order(node: TreeNode) -> None:
<ide> if not isinstance(node, TreeNode) or not node:
<ide> return
<del> q = queue.Queue()
<add> q: queue.Queue = queue.Queue()
<ide> q.put(node)
<ide> while not q.empty():
<ide> node_dequeued = q.get()
<ide> def level_order(node):
<ide> q.put(node_dequeued.right)
<ide>
<ide>
<del>def level_order_actual(node):
<add>def level_order_actual(node: TreeNode) -> None:
<ide> if not isinstance(node, TreeNode) or not node:
<ide> return
<del> q = queue.Queue()
<add> q: queue.Queue = queue.Queue()
<ide> q.put(node)
<ide> while not q.empty():
<ide> list = []
<ide> def level_order_actual(node):
<ide>
<ide>
<ide> # iteration version
<del>def pre_order_iter(node):
<add>def pre_order_iter(node: TreeNode) -> None:
<ide> if not isinstance(node, TreeNode) or not node:
<ide> return
<del> stack = []
<add> stack: List[TreeNode] = []
<ide> n = node
<ide> while n or stack:
<ide> while n: # start from root node, find its left child
<ide> def pre_order_iter(node):
<ide> n = n.right
<ide>
<ide>
<del>def in_order_iter(node):
<add>def in_order_iter(node: TreeNode) -> None:
<ide> if not isinstance(node, TreeNode) or not node:
<ide> return
<del> stack = []
<add> stack: List[TreeNode] = []
<ide> n = node
<ide> while n or stack:
<ide> while n:
<ide> def in_order_iter(node):
<ide> n = n.right
<ide>
<ide>
<del>def post_order_iter(node):
<add>def post_order_iter(node: TreeNode) -> None:
<ide> if not isinstance(node, TreeNode) or not node:
<ide> return
<ide> stack1, stack2 = [], []
<ide> def post_order_iter(node):
<ide> print(stack2.pop().data, end=" ")
<ide>
<ide>
<del>if __name__ == '__main__':
<del> print("\n********* Binary Tree Traversals ************\n")
<add>def prompt(s: str = "", width=50, char="*") -> str:
<add> if not s:
<add> return "\n" + width * char
<add> left, extra = divmod(width - len(s) - 2, 2)
<add> return f"{left * char} {s} {(left + extra) * char}"
<add>
<add>
<add>if __name__ == "__main__":
<add> print(prompt("Binary Tree Traversals"))
<ide>
<ide> node = build_tree()
<del> print("\n********* Pre Order Traversal ************")
<add> print(prompt("Pre Order Traversal"))
<ide> pre_order(node)
<del> print("\n******************************************\n")
<add> print(prompt() + "\n")
<ide>
<del> print("\n********* In Order Traversal ************")
<add> print(prompt("In Order Traversal"))
<ide> in_order(node)
<del> print("\n******************************************\n")
<add> print(prompt() + "\n")
<ide>
<del> print("\n********* Post Order Traversal ************")
<add> print(prompt("Post Order Traversal"))
<ide> post_order(node)
<del> print("\n******************************************\n")
<add> print(prompt() + "\n")
<ide>
<del> print("\n********* Level Order Traversal ************")
<add> print(prompt("Level Order Traversal"))
<ide> level_order(node)
<del> print("\n******************************************\n")
<add> print(prompt() + "\n")
<ide>
<del> print("\n********* Actual Level Order Traversal ************")
<add> print(prompt("Actual Level Order Traversal"))
<ide> level_order_actual(node)
<del> print("\n******************************************\n")
<add> print("*" * 50 + "\n")
<ide>
<del> print("\n********* Pre Order Traversal - Iteration Version ************")
<add> print(prompt("Pre Order Traversal - Iteration Version"))
<ide> pre_order_iter(node)
<del> print("\n******************************************\n")
<add> print(prompt() + "\n")
<ide>
<del> print("\n********* In Order Traversal - Iteration Version ************")
<add> print(prompt("In Order Traversal - Iteration Version"))
<ide> in_order_iter(node)
<del> print("\n******************************************\n")
<add> print(prompt() + "\n")
<ide>
<del> print("\n********* Post Order Traversal - Iteration Version ************")
<add> print(prompt("Post Order Traversal - Iteration Version"))
<ide> post_order_iter(node)
<del> print("\n******************************************\n")
<add> print(prompt()) | 1 |
Javascript | Javascript | use fastbuffer when fill is set to 0 | b07852d1f7a6bd29f32d0bb9b442f18d4ca6528d | <ide><path>lib/buffer.js
<ide> function assertSize(size) {
<ide> */
<ide> Buffer.alloc = function alloc(size, fill, encoding) {
<ide> assertSize(size);
<del> if (fill !== undefined && size > 0) {
<add> if (fill !== undefined && fill !== 0 && size > 0) {
<ide> return _fill(createUnsafeBuffer(size), fill, encoding);
<ide> }
<ide> return new FastBuffer(size); | 1 |
Python | Python | improve collatz_sequence algorithm | 1608d75351be2b11b0e1ce891e2f71296f0be24b | <ide><path>maths/collatz_sequence.py
<del>def collatz_sequence(n):
<add>from typing import List
<add>
<add>
<add>def collatz_sequence(n: int) -> List[int]:
<ide> """
<del> Collatz conjecture: start with any positive integer n.Next term is obtained from the previous term as follows:
<del> if the previous term is even, the next term is one half of the previous term.
<del> If the previous term is odd, the next term is 3 times the previous term plus 1.
<del> The conjecture states the sequence will always reach 1 regaardless of starting value n.
<add> Collatz conjecture: start with any positive integer n. The next term is
<add> obtained as follows:
<add> If n term is even, the next term is: n / 2 .
<add> If n is odd, the next term is: 3 * n + 1.
<add>
<add> The conjecture states the sequence will always reach 1 for any starting value n.
<ide> Example:
<add> >>> collatz_sequence(2.1)
<add> Traceback (most recent call last):
<add> ...
<add> Exception: Sequence only defined for natural numbers
<add> >>> collatz_sequence(0)
<add> Traceback (most recent call last):
<add> ...
<add> Exception: Sequence only defined for natural numbers
<ide> >>> collatz_sequence(43)
<ide> [43, 130, 65, 196, 98, 49, 148, 74, 37, 112, 56, 28, 14, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
<ide> """
<add>
<add> if not isinstance(n, int) or n < 1:
<add> raise Exception("Sequence only defined for natural numbers")
<add>
<ide> sequence = [n]
<ide> while n != 1:
<del> if n % 2 == 0: # even number condition
<del> n //= 2
<del> else:
<del> n = 3 * n + 1
<add> n = 3 * n + 1 if n & 1 else n // 2
<ide> sequence.append(n)
<ide> return sequence
<ide>
<ide> def main():
<ide> n = 43
<ide> sequence = collatz_sequence(n)
<ide> print(sequence)
<del> print("collatz sequence from %d took %d steps." % (n, len(sequence)))
<add> print(f"collatz sequence from {n} took {len(sequence)} steps.")
<ide>
<ide>
<ide> if __name__ == "__main__": | 1 |
Text | Text | remove require logging | 1c893bc2f94fd2e9e2c0d253eac0faedcd0046b8 | <ide><path>actioncable/README.md
<ide> application. The recommended basic setup is as follows:
<ide> require ::File.expand_path('../../config/environment', __FILE__)
<ide> Rails.application.eager_load!
<ide>
<del>require 'action_cable/process/logging'
<del>
<ide> run ActionCable.server
<ide> ```
<ide> | 1 |
PHP | PHP | fix code styling | 55f39ada11eb30d7e628a5e07f3fb2b8a302bf27 | <ide><path>src/Illuminate/Container/BoundMethod.php
<ide> protected static function addDependencyForCallParameter($container, $parameter,
<ide> $dependencies[] = $container->make($parameter->getClass()->name);
<ide> } elseif ($parameter->isDefaultValueAvailable()) {
<ide> $dependencies[] = $parameter->getDefaultValue();
<del> } elseif(!$parameter->isOptional() && !array_key_exists($parameter->name, $parameters)) {
<add> } elseif(! $parameter->isOptional() && ! array_key_exists($parameter->name, $parameters)) {
<ide> $message = "Unresolvable dependency resolving [$parameter] in class {$parameter->getDeclaringClass()->getName()}";
<ide>
<ide> throw new BindingResolutionException($message);
<ide><path>tests/Container/ContainerCallTest.php
<ide> public function testCallWithoutRequiredParamsThrowsException()
<ide> $this->expectExceptionMessage('Unresolvable dependency resolving [Parameter #0 [ <required> $foo ]] in class Illuminate\Tests\Container\ContainerTestCallStub');
<ide>
<ide> $container = new Container;
<del> $container->call(ContainerTestCallStub::class . '@unresolvable');
<add> $container->call(ContainerTestCallStub::class.'@unresolvable');
<ide> }
<ide> }
<ide> | 2 |
Javascript | Javascript | watch sample folder | 8db79ae365cd212045c3f11701dd9665eb4b4db1 | <ide><path>gulpfile.js
<ide> gulp.task('watch', function(){
<ide> livereload.changed(evt.path);
<ide> };
<ide>
<del> gulp.watch('Chart.js', reloadPage);
<add> gulp.watch(['Chart.js', 'samples/*'], reloadPage);
<ide>
<ide> });
<ide> | 1 |
Ruby | Ruby | show previous verison in cask upgrade | 28061369dc4f11b3fcbbf790c95858f53e1c3e21 | <ide><path>Library/Homebrew/cask/cmd/upgrade.rb
<ide> def run
<ide>
<ide> ohai "Casks with `auto_updates` or `version :latest` will not be upgraded" if args.empty? && !greedy?
<ide> oh1 "Upgrading #{Formatter.pluralize(outdated_casks.length, "outdated package")}, with result:"
<del> puts outdated_casks.map { |f| "#{f.full_name} #{f.version}" } * ", "
<add> cask_upgrades = outdated_casks.map do |f|
<add> if f.installed_caskfile.nil?
<add> "#{f.full_name} #{f.version}"
<add> else
<add> "#{f.full_name} #{CaskLoader.load(f.installed_caskfile).version} -> #{f.version}"
<add> end
<add> end
<add> puts cask_upgrades.join(", ")
<ide>
<ide> outdated_casks.each do |old_cask|
<ide> odebug "Started upgrade process for Cask #{old_cask}" | 1 |
Javascript | Javascript | add test case to test for brakets | 0b7775eecd450a862b6b5295f12ead3c8f8fdc78 | <ide><path>test/configCases/plugins/define-plugin/index.js
<ide> it("should assign to process.env", function() {
<ide> process.env.TEST = "test";
<ide> process.env.TEST.should.be.eql("test");
<ide> });
<add>it("should not have brakets on start", function() {
<add> function f() {
<add> throw new Error("should not be called");
<add> }
<add> f // <- no semicolon here
<add> OBJECT;
<add>}); | 1 |
Mixed | Ruby | keep track of dirty attrs after after rollback | 37c238927fbed059de3f26a90d8923fb377568a5 | <ide><path>activerecord/CHANGELOG.md
<add>* Keep track of dirty attributes after transaction is rollback.
<add>
<add> Related #13166.
<add>
<add> *Bogdan Gusiev* *arthurnn*
<add>
<ide> * Add support for module-level `table_name_suffix` in models.
<ide>
<ide> This makes `table_name_suffix` work the same way as `table_name_prefix` when
<ide><path>activerecord/lib/active_record/core.rb
<ide> def init_internals
<ide> @destroyed_by_association = nil
<ide> @new_record = true
<ide> @txn = nil
<add> @_start_transaction_state = {}
<ide> @transaction_state = nil
<ide> @reflects_state = [false]
<ide> end
<ide><path>activerecord/lib/active_record/transactions.rb
<ide> def with_transaction_returning_status
<ide>
<ide> # Save the new record state and id of a record so it can be restored later if a transaction fails.
<ide> def remember_transaction_record_state #:nodoc:
<del> @_start_transaction_state ||= {}
<ide> @_start_transaction_state[:id] = id if has_attribute?(self.class.primary_key)
<ide> unless @_start_transaction_state.include?(:new_record)
<ide> @_start_transaction_state[:new_record] = @new_record
<ide> def remember_transaction_record_state #:nodoc:
<ide> @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) + 1
<ide> @_start_transaction_state[:frozen?] = @attributes.frozen?
<ide> @_start_transaction_state[:changed_attributes] ||= changed_attributes
<del> @_start_transaction_state
<ide> end
<ide>
<ide> # Clear the new record state and id of a record.
<ide><path>activerecord/test/cases/transactions_test.rb
<ide> def test_invalid_keys_for_transaction
<ide> end
<ide> end
<ide>
<del> def test_dirty_state_rollback
<add> def test_rollback_when_changing_inside_transaction
<ide> assert !@first.approved?
<ide> Topic.transaction do
<ide> @first.approved = true
<ide> def test_dirty_state_rollback
<ide> assert @first.reload.approved
<ide> end
<ide>
<del> def test_dirty_state_rollback2
<add> def test_rollback_when_changing_outside_transaction
<ide> assert !@first.approved?
<ide> @first.approved = true
<ide> Topic.transaction do
<ide> def test_dirty_state_rollback2
<ide> assert @first.reload.approved
<ide> end
<ide>
<del> def test_dirty_state_rollback3
<del> assert !@first.approved?
<del> @first.approved = true
<del> @first.save!
<del> Topic.transaction do
<del> @first.approved = false
<del> @first.save!
<del> raise ActiveRecord::Rollback
<del> end
<del> assert !@first.approved
<del> assert @first.changes["approved"]
<del> @first.save!
<del> assert !@first.reload.approved
<del> end
<del>
<del> def test_dirty_state_rollback4
<add> def test_rollback_when_changing_back_to_prev_stage
<ide> assert !@first.approved?
<ide> Topic.transaction do
<ide> @first.approved = true
<ide> def test_dirty_state_rollback4
<ide> assert !@first.reload.approved
<ide> end
<ide>
<add>
<ide> def test_force_savepoint_in_nested_transaction
<ide> Topic.transaction do
<ide> @first.approved = true | 4 |
Javascript | Javascript | fix effectcomposer memory problem | cd5e9888d54e82aea98752601879ba931b77290b | <ide><path>examples/js/postprocessing/EffectComposer.js
<ide> THREE.EffectComposer.prototype = {
<ide>
<ide> }
<ide>
<add> this.renderTarget1.dispose();
<ide> this.renderTarget1 = renderTarget;
<add> this.renderTarget2.dispose();
<ide> this.renderTarget2 = renderTarget.clone();
<ide>
<ide> this.writeBuffer = this.renderTarget1;
<ide> THREE.EffectComposer.prototype = {
<ide>
<ide> setSize: function ( width, height ) {
<ide>
<del> var renderTarget = this.renderTarget1.clone();
<del>
<del> renderTarget.width = width;
<del> renderTarget.height = height;
<del>
<del> this.reset( renderTarget );
<add> this.renderTarget1.setSize( width, height );
<add> this.renderTarget2.setSize( width, height );
<ide>
<ide> }
<ide>
<ide><path>src/renderers/WebGLRenderer.js
<ide> THREE.WebGLRenderer = function ( parameters ) {
<ide>
<ide> }
<ide>
<del> properties.delete( renderTargetProperties );
<add> properties.delete( renderTarget );
<ide>
<ide> }
<ide> | 2 |
Python | Python | add test for rare reduce dtype mismatch error path | 1f27ae7779cfb93cf88052775c422f1b1ea7cc34 | <ide><path>numpy/core/tests/test_custom_dtypes.py
<ide> def test_basic_multiply(self):
<ide> expected_view = a.view(np.float64) * b.view(np.float64)
<ide> assert_array_equal(res.view(np.float64), expected_view)
<ide>
<add> def test_possible_and_impossible_reduce(self):
<add> # For reductions to work, the first and last operand must have the
<add> # same dtype. For this parametric DType that is not necessarily true.
<add> a = self._get_array(2.)
<add> # Addition reductin works (as of writing requires to pass initial
<add> # because setting a scaled-float from the default `0` fails).
<add> res = np.add.reduce(a, initial=0.)
<add> assert res == a.astype(np.float64).sum()
<add>
<add> # But each multiplication changes the factor, so a reduction is not
<add> # possible (the relaxed version of the old refusal to handle any
<add> # flexible dtype).
<add> with pytest.raises(TypeError,
<add> match="The resolved dtypes are not compatible"):
<add> np.multiply.reduce(a)
<add>
<ide> def test_basic_multiply_promotion(self):
<ide> float_a = np.array([1., 2., 3.])
<ide> b = self._get_array(2.) | 1 |
Python | Python | shorten length line | cf5644dcb6cc5cd16ca2e7e467b830143992c709 | <ide><path>libcloud/compute/providers.py
<ide> Provider.RUNABOVE:
<ide> ('libcloud.compute.drivers.runabove', 'RunAboveNodeDriver'),
<ide> Provider.INTERNETSOLUTIONS:
<del> ('libcloud.compute.drivers.internetsolutions', 'InternetSolutionsNodeDriver'),
<add> ('libcloud.compute.drivers.internetsolutions',
<add> 'InternetSolutionsNodeDriver'),
<ide> Provider.INDOSAT:
<ide> ('libcloud.compute.drivers.indosat', 'IndosatNodeDriver'),
<ide> Provider.MEDONE: | 1 |
Go | Go | remove job from logs | 91bfed604959c591a076c2e330cb3ded7443f504 | <ide><path>api/server/server.go
<ide> func getContainersLogs(eng *engine.Engine, version version.Version, w http.Respo
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<ide>
<del> var (
<del> inspectJob = eng.Job("container_inspect", vars["name"])
<del> logsJob = eng.Job("logs", vars["name"])
<del> c, err = inspectJob.Stdout.AddEnv()
<del> )
<del> if err != nil {
<del> return err
<del> }
<del> logsJob.Setenv("follow", r.Form.Get("follow"))
<del> logsJob.Setenv("tail", r.Form.Get("tail"))
<del> logsJob.Setenv("stdout", r.Form.Get("stdout"))
<del> logsJob.Setenv("stderr", r.Form.Get("stderr"))
<del> logsJob.Setenv("timestamps", r.Form.Get("timestamps"))
<ide> // Validate args here, because we can't return not StatusOK after job.Run() call
<del> stdout, stderr := logsJob.GetenvBool("stdout"), logsJob.GetenvBool("stderr")
<add> stdout, stderr := toBool(r.Form.Get("stdout")), toBool(r.Form.Get("stderr"))
<ide> if !(stdout || stderr) {
<ide> return fmt.Errorf("Bad parameters: you must choose at least one stream")
<ide> }
<del> if err = inspectJob.Run(); err != nil {
<del> return err
<del> }
<ide>
<del> var outStream, errStream io.Writer
<del> outStream = utils.NewWriteFlusher(w)
<del>
<del> if c.GetSubEnv("Config") != nil && !c.GetSubEnv("Config").GetBool("Tty") && version.GreaterThanOrEqualTo("1.6") {
<del> errStream = stdcopy.NewStdWriter(outStream, stdcopy.Stderr)
<del> outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout)
<del> } else {
<del> errStream = outStream
<add> logsConfig := &daemon.ContainerLogsConfig{
<add> Follow: toBool(r.Form.Get("follow")),
<add> Timestamps: toBool(r.Form.Get("timestamps")),
<add> Tail: r.Form.Get("tail"),
<add> UseStdout: stdout,
<add> UseStderr: stderr,
<add> OutStream: utils.NewWriteFlusher(w),
<ide> }
<ide>
<del> logsJob.Stdout.Add(outStream)
<del> logsJob.Stderr.Set(errStream)
<del> if err := logsJob.Run(); err != nil {
<del> fmt.Fprintf(outStream, "Error running logs job: %s\n", err)
<add> d := getDaemon(eng)
<add> if err := d.ContainerLogs(vars["name"], logsConfig); err != nil {
<add> fmt.Fprintf(w, "Error running logs job: %s\n", err)
<ide> }
<add>
<ide> return nil
<ide> }
<ide>
<ide><path>api/server/server_unit_test.go
<ide> import (
<ide> "io"
<ide> "net/http"
<ide> "net/http/httptest"
<del> "strings"
<ide> "testing"
<ide>
<ide> "github.com/docker/docker/api"
<ide> func TestGetContainersByName(t *testing.T) {
<ide> }
<ide> }
<ide>
<del>func TestLogs(t *testing.T) {
<del> eng := engine.New()
<del> var inspect bool
<del> var logs bool
<del> eng.Register("container_inspect", func(job *engine.Job) error {
<del> inspect = true
<del> if len(job.Args) == 0 {
<del> t.Fatal("Job arguments is empty")
<del> }
<del> if job.Args[0] != "test" {
<del> t.Fatalf("Container name %s, must be test", job.Args[0])
<del> }
<del> return nil
<del> })
<del> expected := "logs"
<del> eng.Register("logs", func(job *engine.Job) error {
<del> logs = true
<del> if len(job.Args) == 0 {
<del> t.Fatal("Job arguments is empty")
<del> }
<del> if job.Args[0] != "test" {
<del> t.Fatalf("Container name %s, must be test", job.Args[0])
<del> }
<del> follow := job.Getenv("follow")
<del> if follow != "1" {
<del> t.Fatalf("follow: %s, must be 1", follow)
<del> }
<del> stdout := job.Getenv("stdout")
<del> if stdout != "1" {
<del> t.Fatalf("stdout %s, must be 1", stdout)
<del> }
<del> stderr := job.Getenv("stderr")
<del> if stderr != "" {
<del> t.Fatalf("stderr %s, must be empty", stderr)
<del> }
<del> timestamps := job.Getenv("timestamps")
<del> if timestamps != "1" {
<del> t.Fatalf("timestamps %s, must be 1", timestamps)
<del> }
<del> job.Stdout.Write([]byte(expected))
<del> return nil
<del> })
<del> r := serveRequest("GET", "/containers/test/logs?follow=1&stdout=1×tamps=1", nil, eng, t)
<del> if r.Code != http.StatusOK {
<del> t.Fatalf("Got status %d, expected %d", r.Code, http.StatusOK)
<del> }
<del> if !inspect {
<del> t.Fatal("container_inspect job was not called")
<del> }
<del> if !logs {
<del> t.Fatal("logs job was not called")
<del> }
<del> res := r.Body.String()
<del> if res != expected {
<del> t.Fatalf("Output %s, expected %s", res, expected)
<del> }
<del>}
<del>
<del>func TestLogsNoStreams(t *testing.T) {
<del> eng := engine.New()
<del> var inspect bool
<del> var logs bool
<del> eng.Register("container_inspect", func(job *engine.Job) error {
<del> inspect = true
<del> if len(job.Args) == 0 {
<del> t.Fatal("Job arguments is empty")
<del> }
<del> if job.Args[0] != "test" {
<del> t.Fatalf("Container name %s, must be test", job.Args[0])
<del> }
<del> return nil
<del> })
<del> eng.Register("logs", func(job *engine.Job) error {
<del> logs = true
<del> return nil
<del> })
<del> r := serveRequest("GET", "/containers/test/logs", nil, eng, t)
<del> if r.Code != http.StatusBadRequest {
<del> t.Fatalf("Got status %d, expected %d", r.Code, http.StatusBadRequest)
<del> }
<del> if inspect {
<del> t.Fatal("container_inspect job was called, but it shouldn't")
<del> }
<del> if logs {
<del> t.Fatal("logs job was called, but it shouldn't")
<del> }
<del> res := strings.TrimSpace(r.Body.String())
<del> expected := "Bad parameters: you must choose at least one stream"
<del> if !strings.Contains(res, expected) {
<del> t.Fatalf("Output %s, expected %s in it", res, expected)
<del> }
<del>}
<del>
<ide> func TestGetImagesByName(t *testing.T) {
<ide> eng := engine.New()
<ide> name := "image_name"
<ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) Install(eng *engine.Engine) error {
<ide> "create": daemon.ContainerCreate,
<ide> "export": daemon.ContainerExport,
<ide> "info": daemon.CmdInfo,
<del> "logs": daemon.ContainerLogs,
<ide> "restart": daemon.ContainerRestart,
<ide> "start": daemon.ContainerStart,
<ide> "stop": daemon.ContainerStop,
<ide><path>daemon/logs.go
<ide> import (
<ide> "sync"
<ide>
<ide> "github.com/Sirupsen/logrus"
<del> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/pkg/jsonlog"
<add> "github.com/docker/docker/pkg/stdcopy"
<ide> "github.com/docker/docker/pkg/tailfile"
<ide> "github.com/docker/docker/pkg/timeutils"
<ide> )
<ide>
<del>func (daemon *Daemon) ContainerLogs(job *engine.Job) error {
<del> if len(job.Args) != 1 {
<del> return fmt.Errorf("Usage: %s CONTAINER\n", job.Name)
<del> }
<add>type ContainerLogsConfig struct {
<add> Follow, Timestamps bool
<add> Tail string
<add> UseStdout, UseStderr bool
<add> OutStream io.Writer
<add>}
<ide>
<add>func (daemon *Daemon) ContainerLogs(name string, config *ContainerLogsConfig) error {
<ide> var (
<del> name = job.Args[0]
<del> stdout = job.GetenvBool("stdout")
<del> stderr = job.GetenvBool("stderr")
<del> tail = job.Getenv("tail")
<del> follow = job.GetenvBool("follow")
<del> times = job.GetenvBool("timestamps")
<ide> lines = -1
<ide> format string
<ide> )
<del> if !(stdout || stderr) {
<add> if !(config.UseStdout || config.UseStderr) {
<ide> return fmt.Errorf("You must choose at least one stream")
<ide> }
<del> if times {
<add> if config.Timestamps {
<ide> format = timeutils.RFC3339NanoFixed
<ide> }
<del> if tail == "" {
<del> tail = "all"
<add> if config.Tail == "" {
<add> config.Tail = "all"
<ide> }
<add>
<ide> container, err := daemon.Get(name)
<ide> if err != nil {
<ide> return err
<ide> }
<add>
<add> var (
<add> outStream = config.OutStream
<add> errStream io.Writer
<add> )
<add> if !container.Config.Tty {
<add> errStream = stdcopy.NewStdWriter(outStream, stdcopy.Stderr)
<add> outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout)
<add> } else {
<add> errStream = outStream
<add> }
<add>
<ide> if container.LogDriverType() != "json-file" {
<ide> return fmt.Errorf("\"logs\" endpoint is supported only for \"json-file\" logging driver")
<ide> }
<ide> cLog, err := container.ReadLog("json")
<ide> if err != nil && os.IsNotExist(err) {
<ide> // Legacy logs
<ide> logrus.Debugf("Old logs format")
<del> if stdout {
<add> if config.UseStdout {
<ide> cLog, err := container.ReadLog("stdout")
<ide> if err != nil {
<ide> logrus.Errorf("Error reading logs (stdout): %s", err)
<del> } else if _, err := io.Copy(job.Stdout, cLog); err != nil {
<add> } else if _, err := io.Copy(outStream, cLog); err != nil {
<ide> logrus.Errorf("Error streaming logs (stdout): %s", err)
<ide> }
<ide> }
<del> if stderr {
<add> if config.UseStderr {
<ide> cLog, err := container.ReadLog("stderr")
<ide> if err != nil {
<ide> logrus.Errorf("Error reading logs (stderr): %s", err)
<del> } else if _, err := io.Copy(job.Stderr, cLog); err != nil {
<add> } else if _, err := io.Copy(errStream, cLog); err != nil {
<ide> logrus.Errorf("Error streaming logs (stderr): %s", err)
<ide> }
<ide> }
<ide> } else if err != nil {
<ide> logrus.Errorf("Error reading logs (json): %s", err)
<ide> } else {
<del> if tail != "all" {
<add> if config.Tail != "all" {
<ide> var err error
<del> lines, err = strconv.Atoi(tail)
<add> lines, err = strconv.Atoi(config.Tail)
<ide> if err != nil {
<del> logrus.Errorf("Failed to parse tail %s, error: %v, show all logs", tail, err)
<add> logrus.Errorf("Failed to parse tail %s, error: %v, show all logs", config.Tail, err)
<ide> lines = -1
<ide> }
<ide> }
<ide> func (daemon *Daemon) ContainerLogs(job *engine.Job) error {
<ide> break
<ide> }
<ide> logLine := l.Log
<del> if times {
<add> if config.Timestamps {
<ide> // format can be "" or time format, so here can't be error
<ide> logLine, _ = l.Format(format)
<ide> }
<del> if l.Stream == "stdout" && stdout {
<del> io.WriteString(job.Stdout, logLine)
<add> if l.Stream == "stdout" && config.UseStdout {
<add> io.WriteString(outStream, logLine)
<ide> }
<del> if l.Stream == "stderr" && stderr {
<del> io.WriteString(job.Stderr, logLine)
<add> if l.Stream == "stderr" && config.UseStderr {
<add> io.WriteString(errStream, logLine)
<ide> }
<ide> l.Reset()
<ide> }
<ide> }
<ide> }
<del> if follow && container.IsRunning() {
<add> if config.Follow && container.IsRunning() {
<ide> errors := make(chan error, 2)
<ide> wg := sync.WaitGroup{}
<ide>
<del> if stdout {
<add> if config.UseStdout {
<ide> wg.Add(1)
<ide> stdoutPipe := container.StdoutLogPipe()
<ide> defer stdoutPipe.Close()
<ide> go func() {
<del> errors <- jsonlog.WriteLog(stdoutPipe, job.Stdout, format)
<add> errors <- jsonlog.WriteLog(stdoutPipe, outStream, format)
<ide> wg.Done()
<ide> }()
<ide> }
<del> if stderr {
<add> if config.UseStderr {
<ide> wg.Add(1)
<ide> stderrPipe := container.StderrLogPipe()
<ide> defer stderrPipe.Close()
<ide> go func() {
<del> errors <- jsonlog.WriteLog(stderrPipe, job.Stderr, format)
<add> errors <- jsonlog.WriteLog(stderrPipe, errStream, format)
<ide> wg.Done()
<ide> }()
<ide> }
<ide><path>integration-cli/docker_api_containers_test.go
<ide> package main
<ide> import (
<ide> "bytes"
<ide> "encoding/json"
<del> "github.com/docker/docker/api/types"
<del> "github.com/docker/docker/pkg/stringid"
<del> "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
<ide> "io"
<ide> "os/exec"
<ide> "strings"
<ide> "testing"
<ide> "time"
<add>
<add> "github.com/docker/docker/api/types"
<add> "github.com/docker/docker/pkg/stringid"
<add> "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
<ide> )
<ide>
<ide> func TestContainerApiGetAll(t *testing.T) {
<ide> func TestContainerApiGetAll(t *testing.T) {
<ide> t.Fatalf("Error on container creation: %v, output: %q", err, out)
<ide> }
<ide>
<del> body, err := sockRequest("GET", "/containers/json?all=1", nil)
<add> _, body, err := sockRequest("GET", "/containers/json?all=1", nil)
<ide> if err != nil {
<ide> t.Fatalf("GET all containers sockRequest failed: %v", err)
<ide> }
<ide> func TestContainerApiGetExport(t *testing.T) {
<ide> t.Fatalf("Error on container creation: %v, output: %q", err, out)
<ide> }
<ide>
<del> body, err := sockRequest("GET", "/containers/"+name+"/export", nil)
<add> _, body, err := sockRequest("GET", "/containers/"+name+"/export", nil)
<ide> if err != nil {
<ide> t.Fatalf("GET containers/export sockRequest failed: %v", err)
<ide> }
<ide> func TestContainerApiGetChanges(t *testing.T) {
<ide> t.Fatalf("Error on container creation: %v, output: %q", err, out)
<ide> }
<ide>
<del> body, err := sockRequest("GET", "/containers/"+name+"/changes", nil)
<add> _, body, err := sockRequest("GET", "/containers/"+name+"/changes", nil)
<ide> if err != nil {
<ide> t.Fatalf("GET containers/changes sockRequest failed: %v", err)
<ide> }
<ide> func TestContainerApiStartVolumeBinds(t *testing.T) {
<ide> "Volumes": map[string]struct{}{"/tmp": {}},
<ide> }
<ide>
<del> if _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && !strings.Contains(err.Error(), "201 Created") {
<add> if _, _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && !strings.Contains(err.Error(), "201 Created") {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide> bindPath := randomUnixTmpDirPath("test")
<ide> config = map[string]interface{}{
<ide> "Binds": []string{bindPath + ":/tmp"},
<ide> }
<del> if _, err := sockRequest("POST", "/containers/"+name+"/start", config); err != nil && !strings.Contains(err.Error(), "204 No Content") {
<add> if _, _, err := sockRequest("POST", "/containers/"+name+"/start", config); err != nil && !strings.Contains(err.Error(), "204 No Content") {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide> func TestContainerApiStartDupVolumeBinds(t *testing.T) {
<ide> "Volumes": map[string]struct{}{"/tmp": {}},
<ide> }
<ide>
<del> if _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && !strings.Contains(err.Error(), "201 Created") {
<add> if _, _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && !strings.Contains(err.Error(), "201 Created") {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide> func TestContainerApiStartDupVolumeBinds(t *testing.T) {
<ide> config = map[string]interface{}{
<ide> "Binds": []string{bindPath1 + ":/tmp", bindPath2 + ":/tmp"},
<ide> }
<del> if body, err := sockRequest("POST", "/containers/"+name+"/start", config); err == nil {
<add> if _, body, err := sockRequest("POST", "/containers/"+name+"/start", config); err == nil {
<ide> t.Fatal("expected container start to fail when duplicate volume binds to same container path")
<ide> } else {
<ide> if !strings.Contains(string(body), "Duplicate volume") {
<ide> func TestContainerApiStartVolumesFrom(t *testing.T) {
<ide> "Volumes": map[string]struct{}{volPath: {}},
<ide> }
<ide>
<del> if _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && !strings.Contains(err.Error(), "201 Created") {
<add> if _, _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && !strings.Contains(err.Error(), "201 Created") {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide> config = map[string]interface{}{
<ide> "VolumesFrom": []string{volName},
<ide> }
<del> if _, err := sockRequest("POST", "/containers/"+name+"/start", config); err != nil && !strings.Contains(err.Error(), "204 No Content") {
<add> if _, _, err := sockRequest("POST", "/containers/"+name+"/start", config); err != nil && !strings.Contains(err.Error(), "204 No Content") {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide> func TestVolumesFromHasPriority(t *testing.T) {
<ide> "Volumes": map[string]struct{}{volPath: {}},
<ide> }
<ide>
<del> if _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && !strings.Contains(err.Error(), "201 Created") {
<add> if _, _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && !strings.Contains(err.Error(), "201 Created") {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide> func TestVolumesFromHasPriority(t *testing.T) {
<ide> "VolumesFrom": []string{volName},
<ide> "Binds": []string{bindPath + ":/tmp"},
<ide> }
<del> if _, err := sockRequest("POST", "/containers/"+name+"/start", config); err != nil && !strings.Contains(err.Error(), "204 No Content") {
<add> if _, _, err := sockRequest("POST", "/containers/"+name+"/start", config); err != nil && !strings.Contains(err.Error(), "204 No Content") {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide> func TestGetContainerStats(t *testing.T) {
<ide> }
<ide> bc := make(chan b, 1)
<ide> go func() {
<del> body, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
<add> _, body, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
<ide> bc <- b{body, err}
<ide> }()
<ide>
<ide> func TestGetStoppedContainerStats(t *testing.T) {
<ide> go func() {
<ide> // We'll never get return for GET stats from sockRequest as of now,
<ide> // just send request and see if panic or error would happen on daemon side.
<del> _, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
<add> _, _, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestBuildApiDockerfilePath(t *testing.T) {
<ide> t.Fatalf("failed to close tar archive: %v", err)
<ide> }
<ide>
<del> out, err := sockRequestRaw("POST", "/build?dockerfile=../Dockerfile", buffer, "application/x-tar")
<add> _, out, err := sockRequestRaw("POST", "/build?dockerfile=../Dockerfile", buffer, "application/x-tar")
<ide> if err == nil {
<ide> t.Fatalf("Build was supposed to fail: %s", out)
<ide> }
<ide> RUN find /tmp/`,
<ide> }
<ide> defer server.Close()
<ide>
<del> buf, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+server.URL()+"/testD", nil, "application/json")
<add> _, buf, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+server.URL()+"/testD", nil, "application/json")
<ide> if err != nil {
<ide> t.Fatalf("Build failed: %s", err)
<ide> }
<ide> RUN echo from dockerfile`,
<ide> }
<ide> defer git.Close()
<ide>
<del> buf, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json")
<add> _, buf, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json")
<ide> if err != nil {
<ide> t.Fatalf("Build failed: %s\n%q", err, buf)
<ide> }
<ide> RUN echo from Dockerfile`,
<ide> defer git.Close()
<ide>
<ide> // Make sure it tries to 'dockerfile' query param value
<del> buf, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+git.RepoURL, nil, "application/json")
<add> _, buf, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+git.RepoURL, nil, "application/json")
<ide> if err != nil {
<ide> t.Fatalf("Build failed: %s\n%q", err, buf)
<ide> }
<ide> RUN echo from dockerfile`,
<ide> defer git.Close()
<ide>
<ide> // Make sure it tries to 'dockerfile' query param value
<del> buf, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json")
<add> _, buf, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json")
<ide> if err != nil {
<ide> t.Fatalf("Build failed: %s", err)
<ide> }
<ide> func TestBuildApiDockerfileSymlink(t *testing.T) {
<ide> t.Fatalf("failed to close tar archive: %v", err)
<ide> }
<ide>
<del> out, err := sockRequestRaw("POST", "/build", buffer, "application/x-tar")
<add> _, out, err := sockRequestRaw("POST", "/build", buffer, "application/x-tar")
<ide> if err == nil {
<ide> t.Fatalf("Build was supposed to fail: %s", out)
<ide> }
<ide> func TestPostContainerBindNormalVolume(t *testing.T) {
<ide> }
<ide>
<ide> bindSpec := map[string][]string{"Binds": {fooDir + ":/foo"}}
<del> _, err = sockRequest("POST", "/containers/two/start", bindSpec)
<add> _, _, err = sockRequest("POST", "/containers/two/start", bindSpec)
<ide> if err != nil && !strings.Contains(err.Error(), "204 No Content") {
<ide> t.Fatal(err)
<ide> }
<ide> func TestContainerApiPause(t *testing.T) {
<ide> }
<ide> ContainerID := strings.TrimSpace(out)
<ide>
<del> if _, err = sockRequest("POST", "/containers/"+ContainerID+"/pause", nil); err != nil && !strings.Contains(err.Error(), "204 No Content") {
<add> if _, _, err = sockRequest("POST", "/containers/"+ContainerID+"/pause", nil); err != nil && !strings.Contains(err.Error(), "204 No Content") {
<ide> t.Fatalf("POST a container pause: sockRequest failed: %v", err)
<ide> }
<ide>
<ide> func TestContainerApiPause(t *testing.T) {
<ide> t.Fatalf("there should be one paused container and not %d", len(pausedContainers))
<ide> }
<ide>
<del> if _, err = sockRequest("POST", "/containers/"+ContainerID+"/unpause", nil); err != nil && !strings.Contains(err.Error(), "204 No Content") {
<add> if _, _, err = sockRequest("POST", "/containers/"+ContainerID+"/unpause", nil); err != nil && !strings.Contains(err.Error(), "204 No Content") {
<ide> t.Fatalf("POST a container pause: sockRequest failed: %v", err)
<ide> }
<ide>
<ide><path>integration-cli/docker_api_exec_test.go
<ide> func TestExecApiCreateNoCmd(t *testing.T) {
<ide> t.Fatal(out, err)
<ide> }
<ide>
<del> body, err := sockRequest("POST", fmt.Sprintf("/containers/%s/exec", name), map[string]interface{}{"Cmd": nil})
<add> _, body, err := sockRequest("POST", fmt.Sprintf("/containers/%s/exec", name), map[string]interface{}{"Cmd": nil})
<ide> if err == nil || !bytes.Contains(body, []byte("No exec command specified")) {
<ide> t.Fatalf("Expected error when creating exec command with no Cmd specified: %q", err)
<ide> }
<ide><path>integration-cli/docker_api_images_test.go
<ide> import (
<ide> )
<ide>
<ide> func TestLegacyImages(t *testing.T) {
<del> body, err := sockRequest("GET", "/v1.6/images/json", nil)
<add> _, body, err := sockRequest("GET", "/v1.6/images/json", nil)
<ide> if err != nil {
<ide> t.Fatalf("Error on GET: %s", err)
<ide> }
<ide><path>integration-cli/docker_api_inspect_test.go
<ide> func TestInspectApiContainerResponse(t *testing.T) {
<ide> if testVersion != "latest" {
<ide> endpoint = "/" + testVersion + endpoint
<ide> }
<del> body, err := sockRequest("GET", endpoint, nil)
<add> _, body, err := sockRequest("GET", endpoint, nil)
<ide> if err != nil {
<ide> t.Fatalf("sockRequest failed for %s version: %v", testVersion, err)
<ide> }
<ide><path>integration-cli/docker_api_logs_test.go
<add>package main
<add>
<add>import (
<add> "bytes"
<add> "fmt"
<add> "net/http"
<add> "os/exec"
<add> "testing"
<add>)
<add>
<add>func TestLogsApiWithStdout(t *testing.T) {
<add> defer deleteAllContainers()
<add> name := "logs_test"
<add>
<add> runCmd := exec.Command(dockerBinary, "run", "-d", "-t", "--name", name, "busybox", "bin/sh", "-c", "sleep 10 && echo "+name)
<add> if out, _, err := runCommandWithOutput(runCmd); err != nil {
<add> t.Fatal(out, err)
<add> }
<add>
<add> statusCode, body, err := sockRequest("GET", fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1×tamps=1", name), nil)
<add>
<add> if err != nil || statusCode != http.StatusOK {
<add> t.Fatalf("Expected %d from logs request, got %d", http.StatusOK, statusCode)
<add> }
<add>
<add> if !bytes.Contains(body, []byte(name)) {
<add> t.Fatalf("Expected %s, got %s", name, string(body[:]))
<add> }
<add>
<add> logDone("logs API - with stdout ok")
<add>}
<add>
<add>func TestLogsApiNoStdoutNorStderr(t *testing.T) {
<add> defer deleteAllContainers()
<add> name := "logs_test"
<add> runCmd := exec.Command(dockerBinary, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh")
<add> if out, _, err := runCommandWithOutput(runCmd); err != nil {
<add> t.Fatal(out, err)
<add> }
<add>
<add> statusCode, body, err := sockRequest("GET", fmt.Sprintf("/containers/%s/logs", name), nil)
<add>
<add> if err == nil || statusCode != http.StatusBadRequest {
<add> t.Fatalf("Expected %d from logs request, got %d", http.StatusBadRequest, statusCode)
<add> }
<add>
<add> expected := "Bad parameters: you must choose at least one stream"
<add> if !bytes.Contains(body, []byte(expected)) {
<add> t.Fatalf("Expected %s, got %s", expected, string(body[:]))
<add> }
<add>
<add> logDone("logs API - returns error when no stdout nor stderr specified")
<add>}
<ide><path>integration-cli/docker_api_resize_test.go
<ide> func TestResizeApiResponse(t *testing.T) {
<ide> cleanedContainerID := strings.TrimSpace(out)
<ide>
<ide> endpoint := "/containers/" + cleanedContainerID + "/resize?h=40&w=40"
<del> _, err = sockRequest("POST", endpoint, nil)
<add> _, _, err = sockRequest("POST", endpoint, nil)
<ide> if err != nil {
<ide> t.Fatalf("resize Request failed %v", err)
<ide> }
<ide> func TestResizeApiResponseWhenContainerNotStarted(t *testing.T) {
<ide> }
<ide>
<ide> endpoint := "/containers/" + cleanedContainerID + "/resize?h=40&w=40"
<del> body, err := sockRequest("POST", endpoint, nil)
<add> _, body, err := sockRequest("POST", endpoint, nil)
<ide> if err == nil {
<ide> t.Fatalf("resize should fail when container is not started")
<ide> }
<ide><path>integration-cli/docker_cli_rm_test.go
<ide> func TestRmRunningContainerCheckError409(t *testing.T) {
<ide> createRunningContainer(t, "foo")
<ide>
<ide> endpoint := "/containers/foo"
<del> _, err := sockRequest("DELETE", endpoint, nil)
<add> _, _, err := sockRequest("DELETE", endpoint, nil)
<ide>
<ide> if err == nil {
<ide> t.Fatalf("Expected error, can't rm a running container")
<ide><path>integration-cli/docker_utils.go
<ide> func sockConn(timeout time.Duration) (net.Conn, error) {
<ide> }
<ide> }
<ide>
<del>func sockRequest(method, endpoint string, data interface{}) ([]byte, error) {
<add>func sockRequest(method, endpoint string, data interface{}) (int, []byte, error) {
<ide> jsonData := bytes.NewBuffer(nil)
<ide> if err := json.NewEncoder(jsonData).Encode(data); err != nil {
<del> return nil, err
<add> return -1, nil, err
<ide> }
<ide>
<ide> return sockRequestRaw(method, endpoint, jsonData, "application/json")
<ide> }
<ide>
<del>func sockRequestRaw(method, endpoint string, data io.Reader, ct string) ([]byte, error) {
<add>func sockRequestRaw(method, endpoint string, data io.Reader, ct string) (int, []byte, error) {
<ide> c, err := sockConn(time.Duration(10 * time.Second))
<ide> if err != nil {
<del> return nil, fmt.Errorf("could not dial docker daemon: %v", err)
<add> return -1, nil, fmt.Errorf("could not dial docker daemon: %v", err)
<ide> }
<ide>
<ide> client := httputil.NewClientConn(c, nil)
<ide> defer client.Close()
<ide>
<ide> req, err := http.NewRequest(method, endpoint, data)
<ide> if err != nil {
<del> return nil, fmt.Errorf("could not create new request: %v", err)
<add> return -1, nil, fmt.Errorf("could not create new request: %v", err)
<ide> }
<ide>
<ide> if ct == "" {
<ide> func sockRequestRaw(method, endpoint string, data io.Reader, ct string) ([]byte,
<ide>
<ide> resp, err := client.Do(req)
<ide> if err != nil {
<del> return nil, fmt.Errorf("could not perform request: %v", err)
<add> return -1, nil, fmt.Errorf("could not perform request: %v", err)
<ide> }
<ide> defer resp.Body.Close()
<ide> if resp.StatusCode != http.StatusOK {
<ide> body, _ := ioutil.ReadAll(resp.Body)
<del> return body, fmt.Errorf("received status != 200 OK: %s", resp.Status)
<add> return resp.StatusCode, body, fmt.Errorf("received status != 200 OK: %s", resp.Status)
<ide> }
<ide>
<del> return ioutil.ReadAll(resp.Body)
<add> b, err := ioutil.ReadAll(resp.Body)
<add>
<add> return resp.StatusCode, b, err
<ide> }
<ide>
<ide> func deleteContainer(container string) error {
<ide> func daemonTime(t *testing.T) time.Time {
<ide> return time.Now()
<ide> }
<ide>
<del> body, err := sockRequest("GET", "/info", nil)
<add> _, body, err := sockRequest("GET", "/info", nil)
<ide> if err != nil {
<ide> t.Fatalf("daemonTime: failed to get /info: %v", err)
<ide> }
<ide><path>integration-cli/requirements.go
<ide> var (
<ide> func() bool {
<ide> if daemonExecDriver == "" {
<ide> // get daemon info
<del> body, err := sockRequest("GET", "/info", nil)
<add> _, body, err := sockRequest("GET", "/info", nil)
<ide> if err != nil {
<ide> log.Fatalf("sockRequest failed for /info: %v", err)
<ide> } | 13 |
PHP | PHP | guess database factory model by default | 9915831d22c150d68e562f443aca303151d70a4d | <ide><path>database/factories/UserFactory.php
<ide>
<ide> namespace Database\Factories;
<ide>
<del>use App\Models\User;
<ide> use Illuminate\Database\Eloquent\Factories\Factory;
<ide> use Illuminate\Support\Str;
<ide>
<ide> class UserFactory extends Factory
<ide> {
<del> /**
<del> * The name of the factory's corresponding model.
<del> *
<del> * @var string
<del> */
<del> protected $model = User::class;
<del>
<ide> /**
<ide> * Define the model's default state.
<ide> * | 1 |
Mixed | Text | remove some references to "register" through login | 971c080b67836b5dd62bc9270dfb348abb8536a7 | <ide><path>cli/common.go
<ide> var dockerCommands = []Command{
<ide> {"inspect", "Return low-level information on a container or image"},
<ide> {"kill", "Kill a running container"},
<ide> {"load", "Load an image from a tar archive or STDIN"},
<del> {"login", "Register or log in to a Docker registry"},
<add> {"login", "Log in to a Docker registry"},
<ide> {"logout", "Log out from a Docker registry"},
<ide> {"logs", "Fetch the logs of a container"},
<ide> {"network", "Manage Docker networks"},
<ide><path>man/docker-logout.1.md
<ide> There are no available options.
<ide> # docker logout localhost:8080
<ide>
<ide> # See also
<del>**docker-login(1)** to register or log in to a Docker registry server.
<add>**docker-login(1)** to log in to a Docker registry server.
<ide>
<ide> # HISTORY
<ide> June 2014, Originally compiled by Daniel, Dao Quang Minh (daniel at nitrous dot io)
<ide><path>man/docker.1.md
<ide> inside it)
<ide> See **docker-load(1)** for full documentation on the **load** command.
<ide>
<ide> **login**
<del> Register or login to a Docker Registry
<add> Log in to a Docker Registry
<ide> See **docker-login(1)** for full documentation on the **login** command.
<ide>
<ide> **logout** | 3 |
Javascript | Javascript | attach origin of a 3rd party command | ab8c00e896de8ac9083870709d6b19a59c5ced16 | <ide><path>local-cli/cliEntry.js
<ide> function printHelpInformation() {
<ide> cmdName = cmdName + '|' + this._alias;
<ide> }
<ide>
<add> const sourceInformation = this.pkg
<add> ? [
<add> ` ${chalk.bold('Source:')} ${this.pkg.name}@${this.pkg.version}`,
<add> '',
<add> ]
<add> : [];
<add>
<ide> let output = [
<ide> '',
<ide> chalk.bold(chalk.cyan((` react-native ${cmdName} ${this.usage()}`))),
<ide> ` ${this._description}`,
<ide> '',
<add> ...sourceInformation,
<ide> ` ${chalk.bold('Options:')}`,
<ide> '',
<ide> this.optionHelp().replace(/^/gm, ' '),
<ide> const addCommand = (command: Command, config: Config) => {
<ide>
<ide> cmd.helpInformation = printHelpInformation.bind(cmd);
<ide> cmd.examples = command.examples;
<add> cmd.pkg = command.pkg;
<ide>
<ide> options
<ide> .forEach(opt => cmd.option(
<ide><path>local-cli/commands.js
<ide> export type Command = {
<ide> desc: string,
<ide> cmd: string,
<ide> }>,
<add> pkg?: {
<add> version: string,
<add> name: string,
<add> },
<ide> };
<ide>
<ide> const documentedCommands = [
<ide><path>local-cli/core/getCommands.js
<ide> const path = require('path');
<ide> const findPlugins = require('./findPlugins');
<ide> const flatten = require('lodash').flatten;
<ide>
<add>const attachPackage = (command, pkg) => Array.isArray(command)
<add> ? command.map(cmd => attachPackage(cmd, pkg))
<add> : { ...command, pkg };
<add>
<ide> /**
<ide> * @return {Array} Array of commands
<ide> */
<ide> module.exports = function getCommands() {
<ide> const appRoot = process.cwd();
<del> const plugins = findPlugins([appRoot]).map(name => require(path.join(appRoot, 'node_modules', name)));
<add> const plugins = findPlugins([appRoot])
<add> .map(pathToCommands => {
<add> const name = pathToCommands.split('/')[0];
<add>
<add> return attachPackage(
<add> require(path.join(appRoot, 'node_modules', pathToCommands)),
<add> require(path.join(appRoot, 'node_modules', name, 'package.json'))
<add> );
<add> });
<add>
<ide> return flatten(plugins);
<ide> }; | 3 |
Python | Python | fix command substitution | 6da3500728af537df22f7b147a624956b74c4397 | <ide><path>spacy/cli/project.py
<ide> from .. import about
<ide> from ..schemas import ProjectConfigSchema, validate
<ide> from ..util import ensure_path, run_command, make_tempdir, working_dir
<del>from ..util import get_hash, get_checksum
<add>from ..util import get_hash, get_checksum, split_command
<ide>
<ide>
<ide> CONFIG_FILE = "project.yml"
<ide> def run_commands(
<ide> ) -> None:
<ide> """Run a sequence of commands in a subprocess, in order.
<ide>
<del> commands (List[str]): The split commands.
<add> commands (List[str]): The string commands.
<ide> variables (Dict[str, str]): Dictionary of variable names, mapped to their
<ide> values. Will be used to substitute format string variables in the
<ide> commands.
<ide> def run_commands(
<ide> for command in commands:
<ide> # Substitute variables, e.g. "./{NAME}.json"
<ide> command = command.format(**variables)
<add> command = split_command(command)
<ide> # Not sure if this is needed or a good idea. Motivation: users may often
<ide> # use commands in their config that reference "python" and we want to
<ide> # make sure that it's always executing the same Python that spaCy is | 1 |
Text | Text | add myself to list of tsc members | 61e287953964367202a5293cfaea05de412362d4 | <ide><path>README.md
<ide> For more information about the governance of the Node.js project, see
<ide> **Michaël Zasso** <targos@protonmail.com> (he/him)
<ide> * [thefourtheye](https://github.com/thefourtheye) -
<ide> **Sakthipriyan Vairamani** <thechargingvolcano@gmail.com> (he/him)
<add>* [TimothyGu](https://github.com/TimothyGu) -
<add>**Tiancheng "Timothy" Gu** <timothygu99@gmail.com> (he/him)
<ide> * [Trott](https://github.com/Trott) -
<ide> **Rich Trott** <rtrott@gmail.com> (he/him)
<ide> | 1 |
Java | Java | add option to encode with an object value | 181482fa15b02a1ae27f54aea39ea0a8acdc35ec | <ide><path>spring-core/src/main/java/org/springframework/core/codec/ByteArrayEncoder.java
<ide> public Flux<DataBuffer> encode(Publisher<? extends byte[]> inputStream,
<ide> DataBufferFactory bufferFactory, ResolvableType elementType, @Nullable MimeType mimeType,
<ide> @Nullable Map<String, Object> hints) {
<ide>
<del> // The following (byte[] bytes) lambda signature declaration is necessary for Eclipse.
<del> return Flux.from(inputStream).map((byte[] bytes) -> {
<del> DataBuffer dataBuffer = bufferFactory.wrap(bytes);
<del> if (logger.isDebugEnabled() && !Hints.isLoggingSuppressed(hints)) {
<del> String logPrefix = Hints.getLogPrefix(hints);
<del> logger.debug(logPrefix + "Writing " + dataBuffer.readableByteCount() + " bytes");
<del> }
<del> return dataBuffer;
<del> });
<add> // Use (byte[] bytes) for Eclipse
<add> return Flux.from(inputStream).map((byte[] bytes) ->
<add> encodeValue(bytes, bufferFactory, elementType, mimeType, hints));
<add> }
<add>
<add> @Override
<add> public DataBuffer encodeValue(byte[] bytes, DataBufferFactory bufferFactory,
<add> ResolvableType valueType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<add>
<add> DataBuffer dataBuffer = bufferFactory.wrap(bytes);
<add> if (logger.isDebugEnabled() && !Hints.isLoggingSuppressed(hints)) {
<add> String logPrefix = Hints.getLogPrefix(hints);
<add> logger.debug(logPrefix + "Writing " + dataBuffer.readableByteCount() + " bytes");
<add> }
<add> return dataBuffer;
<ide> }
<ide>
<ide> }
<ide><path>spring-core/src/main/java/org/springframework/core/codec/ByteBufferEncoder.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public Flux<DataBuffer> encode(Publisher<? extends ByteBuffer> inputStream,
<ide> DataBufferFactory bufferFactory, ResolvableType elementType, @Nullable MimeType mimeType,
<ide> @Nullable Map<String, Object> hints) {
<ide>
<del> return Flux.from(inputStream).map(byteBuffer -> {
<del> DataBuffer dataBuffer = bufferFactory.wrap(byteBuffer);
<del> if (logger.isDebugEnabled() && !Hints.isLoggingSuppressed(hints)) {
<del> String logPrefix = Hints.getLogPrefix(hints);
<del> logger.debug(logPrefix + "Writing " + dataBuffer.readableByteCount() + " bytes");
<del> }
<del> return dataBuffer;
<del> });
<add> return Flux.from(inputStream).map(byteBuffer ->
<add> encodeValue(byteBuffer, bufferFactory, elementType, mimeType, hints));
<add> }
<add>
<add> @Override
<add> public DataBuffer encodeValue(ByteBuffer byteBuffer, DataBufferFactory bufferFactory,
<add> ResolvableType valueType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<add>
<add> DataBuffer dataBuffer = bufferFactory.wrap(byteBuffer);
<add> if (logger.isDebugEnabled() && !Hints.isLoggingSuppressed(hints)) {
<add> String logPrefix = Hints.getLogPrefix(hints);
<add> logger.debug(logPrefix + "Writing " + dataBuffer.readableByteCount() + " bytes");
<add> }
<add> return dataBuffer;
<ide> }
<ide>
<ide> }
<ide><path>spring-core/src/main/java/org/springframework/core/codec/CharSequenceEncoder.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public Flux<DataBuffer> encode(Publisher<? extends CharSequence> inputStream,
<ide> DataBufferFactory bufferFactory, ResolvableType elementType,
<ide> @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<ide>
<del> Charset charset = getCharset(mimeType);
<add> return Flux.from(inputStream).map(charSequence ->
<add> encodeValue(charSequence, bufferFactory, elementType, mimeType, hints));
<add> }
<ide>
<del> return Flux.from(inputStream).map(charSequence -> {
<del> if (!Hints.isLoggingSuppressed(hints)) {
<del> LogFormatUtils.traceDebug(logger, traceOn -> {
<del> String formatted = LogFormatUtils.formatValue(charSequence, !traceOn);
<del> return Hints.getLogPrefix(hints) + "Writing " + formatted;
<del> });
<del> }
<del> boolean release = true;
<del> int capacity = calculateCapacity(charSequence, charset);
<del> DataBuffer dataBuffer = bufferFactory.allocateBuffer(capacity);
<del> try {
<del> dataBuffer.write(charSequence, charset);
<del> release = false;
<del> }
<del> catch (CoderMalfunctionError ex) {
<del> throw new EncodingException("String encoding error: " + ex.getMessage(), ex);
<del> }
<del> finally {
<del> if (release) {
<del> DataBufferUtils.release(dataBuffer);
<del> }
<add> @Override
<add> public DataBuffer encodeValue(CharSequence charSequence, DataBufferFactory bufferFactory,
<add> ResolvableType valueType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<add>
<add> if (!Hints.isLoggingSuppressed(hints)) {
<add> LogFormatUtils.traceDebug(logger, traceOn -> {
<add> String formatted = LogFormatUtils.formatValue(charSequence, !traceOn);
<add> return Hints.getLogPrefix(hints) + "Writing " + formatted;
<add> });
<add> }
<add> boolean release = true;
<add> Charset charset = getCharset(mimeType);
<add> int capacity = calculateCapacity(charSequence, charset);
<add> DataBuffer dataBuffer = bufferFactory.allocateBuffer(capacity);
<add> try {
<add> dataBuffer.write(charSequence, charset);
<add> release = false;
<add> }
<add> catch (CoderMalfunctionError ex) {
<add> throw new EncodingException("String encoding error: " + ex.getMessage(), ex);
<add> }
<add> finally {
<add> if (release) {
<add> DataBufferUtils.release(dataBuffer);
<ide> }
<del> return dataBuffer;
<del> });
<add> }
<add> return dataBuffer;
<ide> }
<ide>
<ide> int calculateCapacity(CharSequence sequence, Charset charset) {
<ide><path>spring-core/src/main/java/org/springframework/core/codec/DataBufferEncoder.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public Flux<DataBuffer> encode(Publisher<? extends DataBuffer> inputStream,
<ide> @Nullable Map<String, Object> hints) {
<ide>
<ide> Flux<DataBuffer> flux = Flux.from(inputStream);
<add> if (logger.isDebugEnabled() && !Hints.isLoggingSuppressed(hints)) {
<add> flux = flux.doOnNext(buffer -> logValue(buffer, hints));
<add> }
<add> return flux;
<add> }
<add>
<add> @Override
<add> public DataBuffer encodeValue(DataBuffer buffer, DataBufferFactory bufferFactory,
<add> ResolvableType valueType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<ide>
<ide> if (logger.isDebugEnabled() && !Hints.isLoggingSuppressed(hints)) {
<del> flux = flux.doOnNext(buffer -> {
<del> String logPrefix = Hints.getLogPrefix(hints);
<del> logger.debug(logPrefix + "Writing " + buffer.readableByteCount() + " bytes");
<del> });
<add> logValue(buffer, hints);
<ide> }
<add> return buffer;
<add> }
<ide>
<del> return flux;
<add> private void logValue(DataBuffer buffer, @Nullable Map<String, Object> hints) {
<add> String logPrefix = Hints.getLogPrefix(hints);
<add> logger.debug(logPrefix + "Writing " + buffer.readableByteCount() + " bytes");
<ide> }
<ide>
<ide> }
<ide><path>spring-core/src/main/java/org/springframework/core/codec/Encoder.java
<ide> * @param elementType the expected type of elements in the input stream;
<ide> * this type must have been previously passed to the {@link #canEncode}
<ide> * method and it must have returned {@code true}.
<del> * @param mimeType the MIME type for the output stream (optional)
<del> * @param hints additional information about how to do encode
<add> * @param mimeType the MIME type for the output content (optional)
<add> * @param hints additional information about how to encode
<ide> * @return the output stream
<ide> */
<ide> Flux<DataBuffer> encode(Publisher<? extends T> inputStream, DataBufferFactory bufferFactory,
<ide> ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints);
<ide>
<add> /**
<add> * Encode an Object of type T to a data buffer. This is useful for scenarios
<add> * that produce a stream of discrete messages (or events) and the
<add> * content for each is encoded individually.
<add> * <p>By default this method raises {@link UnsupportedOperationException}
<add> * and it is expected that some encoders cannot produce a single buffer or
<add> * cannot do so synchronously (e.g. encoding a {@code Resource}).
<add> * @param value the value to be encoded
<add> * @param bufferFactory for creating the output {@code DataBuffer}
<add> * @param valueType the type for the value being encoded
<add> * @param mimeType the MIME type for the output content (optional)
<add> * @param hints additional information about how to encode
<add> * @return the encoded content
<add> * @since 5.2
<add> */
<add> default DataBuffer encodeValue(T value, DataBufferFactory bufferFactory,
<add> ResolvableType valueType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<add>
<add> // It may not be possible to produce a single DataBuffer synchronously
<add> throw new UnsupportedOperationException();
<add> }
<add>
<ide> /**
<ide> * Return the list of mime types this encoder supports.
<ide> */
<ide><path>spring-core/src/main/java/org/springframework/core/io/buffer/DataBufferUtils.java
<ide> public static Consumer<DataBuffer> releaseConsumer() {
<ide> public static Mono<DataBuffer> join(Publisher<DataBuffer> dataBuffers) {
<ide> Assert.notNull(dataBuffers, "'dataBuffers' must not be null");
<ide>
<add> if (dataBuffers instanceof Mono) {
<add> return (Mono<DataBuffer>) dataBuffers;
<add> }
<add>
<ide> return Flux.from(dataBuffers)
<ide> .collectList()
<ide> .filter(list -> !list.isEmpty())
<ide><path>spring-web/src/main/java/org/springframework/http/codec/json/AbstractJackson2Encoder.java
<ide> public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory buffe
<ide>
<ide> if (inputStream instanceof Mono) {
<ide> return Mono.from(inputStream).map(value ->
<del> encodeValue(value, mimeType, bufferFactory, elementType, hints, encoding)).flux();
<add> encodeValue(value, bufferFactory, elementType, mimeType, hints, encoding)).flux();
<ide> }
<ide> else {
<ide> return this.streamingMediaTypes.stream()
<ide> public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory buffe
<ide> byte[] separator = STREAM_SEPARATORS.getOrDefault(mediaType, NEWLINE_SEPARATOR);
<ide> return Flux.from(inputStream).map(value -> {
<ide> DataBuffer buffer = encodeValue(
<del> value, mimeType, bufferFactory, elementType, hints, encoding);
<add> value, bufferFactory, elementType, mimeType, hints, encoding);
<ide> if (separator != null) {
<ide> buffer.write(separator);
<ide> }
<ide> public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory buffe
<ide> .orElseGet(() -> {
<ide> ResolvableType listType = ResolvableType.forClassWithGenerics(List.class, elementType);
<ide> return Flux.from(inputStream).collectList().map(list ->
<del> encodeValue(list, mimeType, bufferFactory, listType, hints, encoding)).flux();
<add> encodeValue(list, bufferFactory, listType, mimeType, hints, encoding)).flux();
<ide> });
<ide> }
<ide> }
<ide>
<del> private DataBuffer encodeValue(Object value, @Nullable MimeType mimeType, DataBufferFactory bufferFactory,
<del> ResolvableType elementType, @Nullable Map<String, Object> hints, JsonEncoding encoding) {
<add> @Override
<add> public DataBuffer encodeValue(Object value, DataBufferFactory bufferFactory,
<add> ResolvableType valueType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<add>
<add> return encodeValue(value, bufferFactory, valueType, mimeType, hints, getJsonEncoding(mimeType));
<add> }
<add>
<add> private DataBuffer encodeValue(Object value, DataBufferFactory bufferFactory, ResolvableType valueType,
<add> @Nullable MimeType mimeType, @Nullable Map<String, Object> hints, JsonEncoding encoding) {
<ide>
<ide> if (!Hints.isLoggingSuppressed(hints)) {
<ide> LogFormatUtils.traceDebug(logger, traceOn -> {
<ide> private DataBuffer encodeValue(Object value, @Nullable MimeType mimeType, DataBu
<ide> });
<ide> }
<ide>
<del> JavaType javaType = getJavaType(elementType.getType(), null);
<add> JavaType javaType = getJavaType(valueType.getType(), null);
<ide> Class<?> jsonView = (hints != null ? (Class<?>) hints.get(Jackson2CodecSupport.JSON_VIEW_HINT) : null);
<ide> ObjectWriter writer = (jsonView != null ?
<ide> getObjectMapper().writerWithView(jsonView) : getObjectMapper().writer());
<ide> private DataBuffer encodeValue(Object value, @Nullable MimeType mimeType, DataBu
<ide> writer = writer.forType(javaType);
<ide> }
<ide>
<del> writer = customizeWriter(writer, mimeType, elementType, hints);
<add> writer = customizeWriter(writer, mimeType, valueType, hints);
<ide>
<ide> DataBuffer buffer = bufferFactory.allocateBuffer();
<ide> boolean release = true;
<ide><path>spring-web/src/main/java/org/springframework/http/codec/protobuf/ProtobufEncoder.java
<ide> public boolean canEncode(ResolvableType elementType, @Nullable MimeType mimeType
<ide> public Flux<DataBuffer> encode(Publisher<? extends Message> inputStream, DataBufferFactory bufferFactory,
<ide> ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<ide>
<del> return Flux.from(inputStream)
<del> .map(message -> {
<del> DataBuffer buffer = bufferFactory.allocateBuffer();
<del> boolean release = true;
<del> try {
<del> if (!(inputStream instanceof Mono)) {
<del> message.writeDelimitedTo(buffer.asOutputStream());
<del> }
<del> else {
<del> message.writeTo(buffer.asOutputStream());
<del> }
<del> release = false;
<del> return buffer;
<del> }
<del> catch (IOException ex) {
<del> throw new IllegalStateException("Unexpected I/O error while writing to data buffer", ex);
<del> }
<del> finally {
<del> if (release) {
<del> DataBufferUtils.release(buffer);
<del> }
<del> }
<del> });
<add> return Flux.from(inputStream).map(message ->
<add> encodeValue(message, bufferFactory, !(inputStream instanceof Mono)));
<add> }
<add>
<add> @Override
<add> public DataBuffer encodeValue(Message message, DataBufferFactory bufferFactory,
<add> ResolvableType valueType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<add>
<add> return encodeValue(message, bufferFactory, false);
<add> }
<add>
<add> private DataBuffer encodeValue(Message message, DataBufferFactory bufferFactory, boolean delimited) {
<add>
<add> DataBuffer buffer = bufferFactory.allocateBuffer();
<add> boolean release = true;
<add> try {
<add> if (delimited) {
<add> message.writeDelimitedTo(buffer.asOutputStream());
<add> }
<add> else {
<add> message.writeTo(buffer.asOutputStream());
<add> }
<add> release = false;
<add> return buffer;
<add> }
<add> catch (IOException ex) {
<add> throw new IllegalStateException("Unexpected I/O error while writing to data buffer", ex);
<add> }
<add> finally {
<add> if (release) {
<add> DataBufferUtils.release(buffer);
<add> }
<add> }
<ide> }
<ide>
<ide> @Override
<ide><path>spring-web/src/main/java/org/springframework/http/codec/xml/Jaxb2XmlEncoder.java
<ide> public boolean canEncode(ResolvableType elementType, @Nullable MimeType mimeType
<ide>
<ide> @Override
<ide> protected Flux<DataBuffer> encode(Object value, DataBufferFactory bufferFactory,
<del> ResolvableType type, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<add> ResolvableType valueType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<add>
<add> // we're relying on doOnDiscard in base class
<add> return Mono.fromCallable(() -> encodeValue(value, bufferFactory, valueType, mimeType, hints)).flux();
<add> }
<add>
<add> @Override
<add> public DataBuffer encodeValue(Object value, DataBufferFactory bufferFactory,
<add> ResolvableType valueType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<ide>
<ide> if (!Hints.isLoggingSuppressed(hints)) {
<ide> LogFormatUtils.traceDebug(logger, traceOn -> {
<ide> protected Flux<DataBuffer> encode(Object value, DataBufferFactory bufferFactory,
<ide> });
<ide> }
<ide>
<del> return Flux.defer(() -> {
<del> boolean release = true;
<del> DataBuffer buffer = bufferFactory.allocateBuffer(1024);
<del> try {
<del> OutputStream outputStream = buffer.asOutputStream();
<del> Class<?> clazz = ClassUtils.getUserClass(value);
<del> Marshaller marshaller = initMarshaller(clazz);
<del> marshaller.marshal(value, outputStream);
<del> release = false;
<del> return Mono.fromCallable(() -> buffer); // relying on doOnDiscard in base class
<del> }
<del> catch (MarshalException ex) {
<del> return Flux.error(new EncodingException(
<del> "Could not marshal " + value.getClass() + " to XML", ex));
<del> }
<del> catch (JAXBException ex) {
<del> return Flux.error(new CodecException("Invalid JAXB configuration", ex));
<del> }
<del> finally {
<del> if (release) {
<del> DataBufferUtils.release(buffer);
<del> }
<add> boolean release = true;
<add> DataBuffer buffer = bufferFactory.allocateBuffer(1024);
<add> try {
<add> OutputStream outputStream = buffer.asOutputStream();
<add> Class<?> clazz = ClassUtils.getUserClass(value);
<add> Marshaller marshaller = initMarshaller(clazz);
<add> marshaller.marshal(value, outputStream);
<add> release = false;
<add> return buffer;
<add> }
<add> catch (MarshalException ex) {
<add> throw new EncodingException("Could not marshal " + value.getClass() + " to XML", ex);
<add> }
<add> catch (JAXBException ex) {
<add> throw new CodecException("Invalid JAXB configuration", ex);
<add> }
<add> finally {
<add> if (release) {
<add> DataBufferUtils.release(buffer);
<ide> }
<del> });
<add> }
<ide> }
<ide>
<ide> private Marshaller initMarshaller(Class<?> clazz) throws JAXBException { | 9 |
Javascript | Javascript | add e2e test for a modal component | 23ae702d97103105a24d85fc7d26f9fb9f15bb3e | <ide><path>packages/rn-tester/js/examples/Modal/ModalCustomizable.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow strict-local
<add> * @format
<add> */
<add>
<add>import * as React from 'react';
<add>import {
<add> Modal,
<add> Picker,
<add> Platform,
<add> StyleSheet,
<add> Switch,
<add> Text,
<add> TouchableHighlight,
<add> View,
<add> ScrollView,
<add>} from 'react-native';
<add>import type {RNTesterExampleModuleItem} from '../../types/RNTesterTypes';
<add>
<add>const Item = Picker.Item;
<add>
<add>class Button extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
<add> state = {
<add> active: false,
<add> };
<add>
<add> _onHighlight = () => {
<add> this.setState({active: true});
<add> };
<add>
<add> _onUnhighlight = () => {
<add> this.setState({active: false});
<add> };
<add>
<add> render() {
<add> const colorStyle = {
<add> color: this.state.active ? '#fff' : '#000',
<add> };
<add> return (
<add> <TouchableHighlight
<add> onHideUnderlay={this._onUnhighlight}
<add> onPress={this.props.onPress}
<add> onShowUnderlay={this._onHighlight}
<add> style={[styles.button, this.props.style]}
<add> underlayColor="#a9d9d4">
<add> <Text style={[styles.buttonText, colorStyle]}>
<add> {this.props.children}
<add> </Text>
<add> </TouchableHighlight>
<add> );
<add> }
<add>}
<add>
<add>const supportedOrientationsPickerValues = [
<add> ['portrait'],
<add> ['landscape'],
<add> ['landscape-left'],
<add> ['portrait', 'landscape-right'],
<add> ['portrait', 'landscape'],
<add> [],
<add>];
<add>
<add>class ModalExample extends React.Component<{...}, $FlowFixMe> {
<add> state: $FlowFixMe = {
<add> animationType: 'none',
<add> modalVisible: false,
<add> transparent: false,
<add> hardwareAccelerated: false,
<add> statusBarTranslucent: false,
<add> presentationStyle: 'fullScreen',
<add> selectedSupportedOrientation: '0',
<add> currentOrientation: 'unknown',
<add> action: '',
<add> };
<add>
<add> _setModalVisible = visible => {
<add> this.setState({modalVisible: visible});
<add> };
<add>
<add> _setAnimationType = type => {
<add> this.setState({animationType: type});
<add> };
<add>
<add> _toggleTransparent = () => {
<add> this.setState({transparent: !this.state.transparent});
<add> };
<add>
<add> _toggleHardwareAccelerated = () => {
<add> this.setState({hardwareAccelerated: !this.state.hardwareAccelerated});
<add> };
<add>
<add> _toggleStatusBarTranslucent = () => {
<add> this.setState({statusBarTranslucent: !this.state.statusBarTranslucent});
<add> };
<add>
<add> renderSwitch(): React.Node {
<add> if (Platform.isTV) {
<add> return null;
<add> }
<add> if (Platform.OS === 'android') {
<add> return (
<add> <>
<add> <Text style={styles.rowTitle}>Hardware Accelerated</Text>
<add> <Switch
<add> value={this.state.hardwareAccelerated}
<add> onValueChange={this._toggleHardwareAccelerated}
<add> />
<add> <Text style={styles.rowTitle}>Status Bar Translucent</Text>
<add> <Switch
<add> value={this.state.statusBarTranslucent}
<add> onValueChange={this._toggleStatusBarTranslucent}
<add> />
<add> <Text style={styles.rowTitle}>Transparent</Text>
<add> <Switch
<add> value={this.state.transparent}
<add> onValueChange={this._toggleTransparent}
<add> />
<add> </>
<add> );
<add> }
<add> return (
<add> <Switch
<add> value={this.state.transparent}
<add> onValueChange={this._toggleTransparent}
<add> />
<add> );
<add> }
<add>
<add> render(): React.Node {
<add> const modalBackgroundStyle = {
<add> backgroundColor: this.state.transparent
<add> ? 'rgba(0, 0, 0, 0.5)'
<add> : '#f5fcff',
<add> };
<add> const innerContainerTransparentStyle = this.state.transparent
<add> ? {backgroundColor: '#fff', padding: 20}
<add> : null;
<add> const activeButtonStyle = {
<add> backgroundColor: '#ddd',
<add> };
<add>
<add> return (
<add> <ScrollView contentContainerStyle={styles.ScrollView}>
<add> <Modal
<add> animationType={this.state.animationType}
<add> presentationStyle={this.state.presentationStyle}
<add> transparent={this.state.transparent}
<add> hardwareAccelerated={this.state.hardwareAccelerated}
<add> statusBarTranslucent={this.state.statusBarTranslucent}
<add> visible={this.state.modalVisible}
<add> onRequestClose={() => this._setModalVisible(false)}
<add> supportedOrientations={
<add> supportedOrientationsPickerValues[
<add> Number(this.state.selectedSupportedOrientation)
<add> ]
<add> }
<add> onOrientationChange={evt =>
<add> this.setState({currentOrientation: evt.nativeEvent.orientation})
<add> }
<add> onDismiss={() => {
<add> if (this.state.action === 'onDismiss') {
<add> alert(this.state.action);
<add> }
<add> }}
<add> onShow={() => {
<add> if (this.state.action === 'onShow') {
<add> alert(this.state.action);
<add> }
<add> }}>
<add> <View style={[styles.container, modalBackgroundStyle]}>
<add> <View
<add> style={[styles.innerContainer, innerContainerTransparentStyle]}>
<add> <Text>
<add> This modal was presented{' '}
<add> {this.state.animationType === 'none' ? 'without' : 'with'}{' '}
<add> animation.
<add> </Text>
<add> <Text>
<add> It is currently displayed in {this.state.currentOrientation}{' '}
<add> mode.
<add> </Text>
<add> <Button
<add> onPress={this._setModalVisible.bind(this, false)}
<add> style={styles.modalButton}>
<add> Close
<add> </Button>
<add> </View>
<add> </View>
<add> </Modal>
<add> <View style={styles.row}>
<add> <Text style={styles.rowTitle}>Animation Type</Text>
<add> <Button
<add> onPress={this._setAnimationType.bind(this, 'none')}
<add> style={
<add> this.state.animationType === 'none' ? activeButtonStyle : {}
<add> }>
<add> none
<add> </Button>
<add> <Button
<add> onPress={this._setAnimationType.bind(this, 'slide')}
<add> style={
<add> this.state.animationType === 'slide' ? activeButtonStyle : {}
<add> }>
<add> slide
<add> </Button>
<add> <Button
<add> onPress={this._setAnimationType.bind(this, 'fade')}
<add> style={
<add> this.state.animationType === 'fade' ? activeButtonStyle : {}
<add> }>
<add> fade
<add> </Button>
<add> </View>
<add>
<add> <View style={styles.row}>{this.renderSwitch()}</View>
<add> {this.renderPickers()}
<add> <Button onPress={this._setModalVisible.bind(this, true)}>
<add> Present
<add> </Button>
<add> </ScrollView>
<add> );
<add> }
<add> renderPickers(): React.Node {
<add> if (Platform.isTV) {
<add> return null;
<add> }
<add> return (
<add> <View>
<add> <View>
<add> <Text style={styles.rowTitle}>Presentation style</Text>
<add> <Picker
<add> selectedValue={this.state.presentationStyle}
<add> onValueChange={presentationStyle =>
<add> this.setState({presentationStyle})
<add> }
<add> itemStyle={styles.pickerItem}>
<add> <Item label="Full Screen" value="fullScreen" />
<add> <Item label="Page Sheet" value="pageSheet" />
<add> <Item label="Form Sheet" value="formSheet" />
<add> <Item label="Over Full Screen" value="overFullScreen" />
<add> <Item label="Default presentationStyle" value={null} />
<add> </Picker>
<add> </View>
<add>
<add> <View>
<add> <Text style={styles.rowTitle}>Supported orientations</Text>
<add> <Picker
<add> selectedValue={this.state.selectedSupportedOrientation}
<add> onValueChange={(_, i) =>
<add> this.setState({selectedSupportedOrientation: i.toString()})
<add> }
<add> itemStyle={styles.pickerItem}>
<add> <Item label="Portrait" value={'0'} />
<add> <Item label="Landscape" value={'1'} />
<add> <Item label="Landscape left" value={'2'} />
<add> <Item label="Portrait and landscape right" value={'3'} />
<add> <Item label="Portrait and landscape" value={'4'} />
<add> <Item label="Default supportedOrientations" value={'5'} />
<add> </Picker>
<add> </View>
<add>
<add> <View>
<add> <Text style={styles.rowTitle}>Actions</Text>
<add> {Platform.OS === 'ios' ? (
<add> <Picker
<add> selectedValue={this.state.action}
<add> onValueChange={action => this.setState({action})}
<add> itemStyle={styles.pickerItem}>
<add> <Item label="None" value="" />
<add> <Item label="On Dismiss" value="onDismiss" />
<add> <Item label="On Show" value="onShow" />
<add> </Picker>
<add> ) : (
<add> <Picker
<add> selectedValue={this.state.action}
<add> onValueChange={action => this.setState({action})}
<add> itemStyle={styles.pickerItem}>
<add> <Item label="None" value="" />
<add> <Item label="On Show" value="onShow" />
<add> </Picker>
<add> )}
<add> </View>
<add> </View>
<add> );
<add> }
<add>}
<add>
<add>const styles = StyleSheet.create({
<add> container: {
<add> flex: 1,
<add> justifyContent: 'center',
<add> padding: 20,
<add> },
<add> innerContainer: {
<add> borderRadius: 10,
<add> alignItems: 'center',
<add> },
<add> row: {
<add> alignItems: 'center',
<add> flex: 1,
<add> flexDirection: 'row',
<add> marginBottom: 20,
<add> },
<add> rowTitle: {
<add> flex: 1,
<add> fontWeight: 'bold',
<add> },
<add> button: {
<add> borderRadius: 5,
<add> flexGrow: 1,
<add> height: 44,
<add> alignSelf: 'stretch',
<add> justifyContent: 'center',
<add> overflow: 'hidden',
<add> },
<add> buttonText: {
<add> fontSize: 18,
<add> margin: 5,
<add> textAlign: 'center',
<add> },
<add> modalButton: {
<add> marginTop: 10,
<add> },
<add> pickerItem: {
<add> fontSize: 16,
<add> },
<add> ScrollView: {
<add> paddingTop: 10,
<add> paddingBottom: 100,
<add> },
<add>});
<add>
<add>export default ({
<add> title: 'Modal Presentation',
<add> name: 'basic',
<add> description: 'Modals can be presented with or without animation',
<add> render: (): React.Node => <ModalExample />,
<add>}: RNTesterExampleModuleItem);
<ide><path>packages/rn-tester/js/examples/Modal/ModalExample.js
<ide> * This source code is licensed under the MIT license found in the
<ide> * LICENSE file in the root directory of this source tree.
<ide> *
<del> * @format
<ide> * @flow strict-local
<add> * @format
<ide> */
<ide>
<del>'use strict';
<del>
<del>const React = require('react');
<del>
<del>const {
<del> Modal,
<del> Picker,
<del> Platform,
<del> StyleSheet,
<del> Switch,
<del> Text,
<del> TouchableHighlight,
<del> View,
<del> ScrollView,
<del>} = require('react-native');
<del>
<del>const Item = Picker.Item;
<del>
<del>exports.displayName = (undefined: ?string);
<del>exports.framework = 'React';
<del>exports.title = 'Modal';
<del>exports.category = 'UI';
<del>exports.documentationURL = 'https://reactnative.dev/docs/modal';
<del>exports.description = 'Component for presenting modal views.';
<del>
<del>class Button extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
<del> state = {
<del> active: false,
<del> };
<del>
<del> _onHighlight = () => {
<del> this.setState({active: true});
<del> };
<del>
<del> _onUnhighlight = () => {
<del> this.setState({active: false});
<del> };
<del>
<del> render() {
<del> const colorStyle = {
<del> color: this.state.active ? '#fff' : '#000',
<del> };
<del> return (
<del> <TouchableHighlight
<del> onHideUnderlay={this._onUnhighlight}
<del> onPress={this.props.onPress}
<del> onShowUnderlay={this._onHighlight}
<del> style={[styles.button, this.props.style]}
<del> underlayColor="#a9d9d4">
<del> <Text style={[styles.buttonText, colorStyle]}>
<del> {this.props.children}
<del> </Text>
<del> </TouchableHighlight>
<del> );
<del> }
<del>}
<del>
<del>const supportedOrientationsPickerValues = [
<del> ['portrait'],
<del> ['landscape'],
<del> ['landscape-left'],
<del> ['portrait', 'landscape-right'],
<del> ['portrait', 'landscape'],
<del> [],
<del>];
<del>
<del>class ModalExample extends React.Component<{...}, $FlowFixMeState> {
<del> state = {
<del> animationType: 'none',
<del> modalVisible: false,
<del> transparent: false,
<del> hardwareAccelerated: false,
<del> statusBarTranslucent: false,
<del> presentationStyle: 'fullScreen',
<del> selectedSupportedOrientation: '0',
<del> currentOrientation: 'unknown',
<del> action: '',
<del> };
<del>
<del> _setModalVisible = visible => {
<del> this.setState({modalVisible: visible});
<del> };
<del>
<del> _setAnimationType = type => {
<del> this.setState({animationType: type});
<del> };
<del>
<del> _toggleTransparent = () => {
<del> this.setState({transparent: !this.state.transparent});
<del> };
<del>
<del> _toggleHardwareAccelerated = () => {
<del> this.setState({hardwareAccelerated: !this.state.hardwareAccelerated});
<del> };
<del>
<del> _toggleStatusBarTranslucent = () => {
<del> this.setState({statusBarTranslucent: !this.state.statusBarTranslucent});
<del> };
<del>
<del> renderSwitch() {
<del> if (Platform.isTV) {
<del> return null;
<del> }
<del> if (Platform.OS === 'android') {
<del> return (
<del> <>
<del> <Text style={styles.rowTitle}>Hardware Accelerated</Text>
<del> <Switch
<del> value={this.state.hardwareAccelerated}
<del> onValueChange={this._toggleHardwareAccelerated}
<del> />
<del> <Text style={styles.rowTitle}>Status Bar Translucent</Text>
<del> <Switch
<del> value={this.state.statusBarTranslucent}
<del> onValueChange={this._toggleStatusBarTranslucent}
<del> />
<del> <Text style={styles.rowTitle}>Transparent</Text>
<del> <Switch
<del> value={this.state.transparent}
<del> onValueChange={this._toggleTransparent}
<del> />
<del> </>
<del> );
<del> }
<del> return (
<del> <Switch
<del> value={this.state.transparent}
<del> onValueChange={this._toggleTransparent}
<del> />
<del> );
<del> }
<del>
<del> render() {
<del> const modalBackgroundStyle = {
<del> backgroundColor: this.state.transparent
<del> ? 'rgba(0, 0, 0, 0.5)'
<del> : '#f5fcff',
<del> };
<del> const innerContainerTransparentStyle = this.state.transparent
<del> ? {backgroundColor: '#fff', padding: 20}
<del> : null;
<del> const activeButtonStyle = {
<del> backgroundColor: '#ddd',
<del> };
<del>
<del> return (
<del> <ScrollView contentContainerStyle={styles.ScrollView}>
<del> <Modal
<del> animationType={this.state.animationType}
<del> presentationStyle={this.state.presentationStyle}
<del> transparent={this.state.transparent}
<del> hardwareAccelerated={this.state.hardwareAccelerated}
<del> statusBarTranslucent={this.state.statusBarTranslucent}
<del> visible={this.state.modalVisible}
<del> onRequestClose={() => this._setModalVisible(false)}
<del> supportedOrientations={
<del> supportedOrientationsPickerValues[
<del> Number(this.state.selectedSupportedOrientation)
<del> ]
<del> }
<del> onOrientationChange={evt =>
<del> this.setState({currentOrientation: evt.nativeEvent.orientation})
<del> }
<del> onDismiss={() => {
<del> if (this.state.action === 'onDismiss') alert(this.state.action);
<del> }}
<del> onShow={() => {
<del> if (this.state.action === 'onShow') alert(this.state.action);
<del> }}>
<del> <View style={[styles.container, modalBackgroundStyle]}>
<del> <View
<del> style={[styles.innerContainer, innerContainerTransparentStyle]}>
<del> <Text>
<del> This modal was presented{' '}
<del> {this.state.animationType === 'none' ? 'without' : 'with'}{' '}
<del> animation.
<del> </Text>
<del> <Text>
<del> It is currently displayed in {this.state.currentOrientation}{' '}
<del> mode.
<del> </Text>
<del> <Button
<del> onPress={this._setModalVisible.bind(this, false)}
<del> style={styles.modalButton}>
<del> Close
<del> </Button>
<del> </View>
<del> </View>
<del> </Modal>
<del> <View style={styles.row}>
<del> <Text style={styles.rowTitle}>Animation Type</Text>
<del> <Button
<del> onPress={this._setAnimationType.bind(this, 'none')}
<del> style={
<del> this.state.animationType === 'none' ? activeButtonStyle : {}
<del> }>
<del> none
<del> </Button>
<del> <Button
<del> onPress={this._setAnimationType.bind(this, 'slide')}
<del> style={
<del> this.state.animationType === 'slide' ? activeButtonStyle : {}
<del> }>
<del> slide
<del> </Button>
<del> <Button
<del> onPress={this._setAnimationType.bind(this, 'fade')}
<del> style={
<del> this.state.animationType === 'fade' ? activeButtonStyle : {}
<del> }>
<del> fade
<del> </Button>
<del> </View>
<del>
<del> <View style={styles.row}>{this.renderSwitch()}</View>
<del> {this.renderPickers()}
<del> <Button onPress={this._setModalVisible.bind(this, true)}>
<del> Present
<del> </Button>
<del> </ScrollView>
<del> );
<del> }
<del> renderPickers() {
<del> if (Platform.isTV) {
<del> return null;
<del> }
<del> return (
<del> <View>
<del> <View>
<del> <Text style={styles.rowTitle}>Presentation style</Text>
<del> <Picker
<del> selectedValue={this.state.presentationStyle}
<del> onValueChange={presentationStyle =>
<del> this.setState({presentationStyle})
<del> }
<del> itemStyle={styles.pickerItem}>
<del> <Item label="Full Screen" value="fullScreen" />
<del> <Item label="Page Sheet" value="pageSheet" />
<del> <Item label="Form Sheet" value="formSheet" />
<del> <Item label="Over Full Screen" value="overFullScreen" />
<del> <Item label="Default presentationStyle" value={null} />
<del> </Picker>
<del> </View>
<del>
<del> <View>
<del> <Text style={styles.rowTitle}>Supported orientations</Text>
<del> <Picker
<del> selectedValue={this.state.selectedSupportedOrientation}
<del> onValueChange={(_, i) =>
<del> this.setState({selectedSupportedOrientation: i.toString()})
<del> }
<del> itemStyle={styles.pickerItem}>
<del> <Item label="Portrait" value={'0'} />
<del> <Item label="Landscape" value={'1'} />
<del> <Item label="Landscape left" value={'2'} />
<del> <Item label="Portrait and landscape right" value={'3'} />
<del> <Item label="Portrait and landscape" value={'4'} />
<del> <Item label="Default supportedOrientations" value={'5'} />
<del> </Picker>
<del> </View>
<del>
<del> <View>
<del> <Text style={styles.rowTitle}>Actions</Text>
<del> {Platform.OS === 'ios' ? (
<del> <Picker
<del> selectedValue={this.state.action}
<del> onValueChange={action => this.setState({action})}
<del> itemStyle={styles.pickerItem}>
<del> <Item label="None" value="" />
<del> <Item label="On Dismiss" value="onDismiss" />
<del> <Item label="On Show" value="onShow" />
<del> </Picker>
<del> ) : (
<del> <Picker
<del> selectedValue={this.state.action}
<del> onValueChange={action => this.setState({action})}
<del> itemStyle={styles.pickerItem}>
<del> <Item label="None" value="" />
<del> <Item label="On Show" value="onShow" />
<del> </Picker>
<del> )}
<del> </View>
<del> </View>
<del> );
<del> }
<del>}
<del>
<del>exports.examples = [
<del> {
<del> title: 'Modal Presentation',
<del> name: 'basic',
<del> description: 'Modals can be presented with or without animation',
<del> render: (): React.Node => <ModalExample />,
<del> },
<del>];
<del>
<del>const styles = StyleSheet.create({
<del> container: {
<del> flex: 1,
<del> justifyContent: 'center',
<del> padding: 20,
<del> },
<del> innerContainer: {
<del> borderRadius: 10,
<del> alignItems: 'center',
<del> },
<del> row: {
<del> alignItems: 'center',
<del> flex: 1,
<del> flexDirection: 'row',
<del> marginBottom: 20,
<del> },
<del> rowTitle: {
<del> flex: 1,
<del> fontWeight: 'bold',
<del> },
<del> button: {
<del> borderRadius: 5,
<del> flexGrow: 1,
<del> height: 44,
<del> alignSelf: 'stretch',
<del> justifyContent: 'center',
<del> overflow: 'hidden',
<del> },
<del> buttonText: {
<del> fontSize: 18,
<del> margin: 5,
<del> textAlign: 'center',
<del> },
<del> modalButton: {
<del> marginTop: 10,
<del> },
<del> pickerItem: {
<del> fontSize: 16,
<del> },
<del> ScrollView: {
<del> paddingTop: 10,
<del> paddingBottom: 100,
<del> },
<del>});
<add>import ModalCustomizable from './ModalCustomizable';
<add>import ModalOnShow from './ModalOnShow';
<add>import type {RNTesterExampleModuleItem} from '../../types/RNTesterTypes';
<add>
<add>export const displayName = (undefined: ?string);
<add>export const framework = 'React';
<add>export const title = 'Modal';
<add>export const category = 'UI';
<add>export const documentationURL = 'https://reactnative.dev/docs/modal';
<add>export const description = 'Component for presenting modal views.';
<add>export const examples = ([
<add> ModalCustomizable,
<add> ModalOnShow,
<add>]: Array<RNTesterExampleModuleItem>);
<ide><path>packages/rn-tester/js/examples/Modal/ModalOnShow.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow strict-local
<add> * @format
<add> */
<add>
<add>import * as React from 'react';
<add>import {Modal, Pressable, StyleSheet, Text, View} from 'react-native';
<add>import type {RNTesterExampleModuleItem} from '../../types/RNTesterTypes';
<add>
<add>function ModalOnShowOnDismiss(): React.Node {
<add> const [modalVisible, setModalVisible] = React.useState(false);
<add> const [onShowCount, setOnShowCount] = React.useState(0);
<add> const [onDismissCount, setOnDismissCount] = React.useState(0);
<add>
<add> return (
<add> <View style={styles.container}>
<add> <Modal
<add> animationType="slide"
<add> transparent={true}
<add> visible={modalVisible}
<add> onShow={() => {
<add> setOnShowCount(onShowCount + 1);
<add> }}
<add> onDismiss={() => {
<add> setOnDismissCount(onDismissCount + 1);
<add> }}
<add> onRequestClose={() => {
<add> setModalVisible(false);
<add> }}>
<add> <View style={[styles.centeredView, styles.modalBackdrop]}>
<add> <View style={styles.modalView}>
<add> <Text testID="modal-on-show-count">
<add> onShow is called {onShowCount} times
<add> </Text>
<add> <Text testID="modal-on-dismiss-count">
<add> onDismiss is called {onDismissCount} times
<add> </Text>
<add> <Pressable
<add> style={[styles.button, styles.buttonClose]}
<add> onPress={() => setModalVisible(false)}>
<add> <Text testID="dismiss-modal" style={styles.textStyle}>
<add> Hide Modal
<add> </Text>
<add> </Pressable>
<add> </View>
<add> </View>
<add> </Modal>
<add> <Text testID="on-show-count">onShow is called {onShowCount} times</Text>
<add> <Text testID="on-dismiss-count">
<add> onDismiss is called {onDismissCount} times
<add> </Text>
<add> <Pressable
<add> style={[styles.button, styles.buttonOpen]}
<add> onPress={() => setModalVisible(true)}>
<add> <Text testID="open-modal" style={styles.textStyle}>
<add> Show Modal
<add> </Text>
<add> </Pressable>
<add> </View>
<add> );
<add>}
<add>
<add>const styles = StyleSheet.create({
<add> container: {
<add> display: 'flex',
<add> alignItems: 'center',
<add> paddingVertical: 30,
<add> },
<add> centeredView: {
<add> flex: 1,
<add> justifyContent: 'center',
<add> alignItems: 'center',
<add> },
<add> modalBackdrop: {
<add> backgroundColor: 'rgba(0, 0, 0, 0.5)',
<add> },
<add> modalView: {
<add> margin: 20,
<add> backgroundColor: 'white',
<add> borderRadius: 20,
<add> padding: 35,
<add> alignItems: 'center',
<add> shadowColor: '#000',
<add> shadowOffset: {
<add> width: 0,
<add> height: 2,
<add> },
<add> shadowOpacity: 0.25,
<add> shadowRadius: 4,
<add> elevation: 5,
<add> },
<add> button: {
<add> borderRadius: 20,
<add> padding: 10,
<add> marginVertical: 20,
<add> elevation: 2,
<add> },
<add> buttonOpen: {
<add> backgroundColor: '#F194FF',
<add> },
<add> buttonClose: {
<add> backgroundColor: '#2196F3',
<add> },
<add> textStyle: {
<add> color: 'white',
<add> fontWeight: 'bold',
<add> textAlign: 'center',
<add> },
<add>});
<add>
<add>export default ({
<add> title: "Modal's onShow/onDismiss",
<add> name: 'onShow',
<add> description:
<add> 'onShow and onDismiss (iOS only) callbacks are called when modals is shown/dissmissed',
<add> render: (): React.Node => <ModalOnShowOnDismiss />,
<add>}: RNTesterExampleModuleItem); | 3 |
Text | Text | fix typo in security rails guide. [ci-skip] | d6d861659af3b6135402fadd04366b49c95b92ee | <ide><path>guides/source/security.md
<ide> After reading this guide, you will know:
<ide> Introduction
<ide> ------------
<ide>
<del>Web application frameworks are made to help developers build web applications. Some of them also help you with securing the web application. In fact one framework is not more secure than another: If you use it correctly, you will be able to build secure apps with many frameworks. Ruby on Rails has some clever helper methods, for example against SQL injection, so that this is hardly a problem.
<add>Web application frameworks are made to help developers build web applications. Some of them also help you with securing the web application. In fact one framework is not more secure than another: If you use it correctly, you will be able to build secure apps with many frameworks. Ruby on Rails has some clever helper methods, for example against SQL injection, so this is hardly a problem.
<ide>
<ide> In general there is no such thing as plug-n-play security. Security depends on the people using the framework, and sometimes on the development method. And it depends on all layers of a web application environment: The back-end storage, the web server, and the web application itself (and possibly other layers or applications).
<ide> | 1 |
Java | Java | use keyvalue.none_value where possible | 5dca43ebd6411e902b8f89f9dc55816df620844a | <ide><path>spring-web/src/main/java/org/springframework/http/client/observation/ClientHttpObservationDocumentation.java
<ide>
<ide> package org.springframework.http.client.observation;
<ide>
<add>import io.micrometer.common.KeyValue;
<ide> import io.micrometer.common.docs.KeyName;
<ide> import io.micrometer.observation.Observation;
<ide> import io.micrometer.observation.ObservationConvention;
<ide> public KeyName[] getHighCardinalityKeyNames() {
<ide> public enum LowCardinalityKeyNames implements KeyName {
<ide>
<ide> /**
<del> * Name of HTTP request method or {@code "none"} if the request could not be created.
<add> * Name of HTTP request method or {@value KeyValue#NONE_VALUE} if the request could not be created.
<ide> */
<ide> METHOD {
<ide> @Override
<ide> public String asString() {
<ide> },
<ide>
<ide> /**
<del> * URI template used for HTTP request, or {@code "none"} if none was provided.
<add> * URI template used for HTTP request, or {@value KeyValue#NONE_VALUE} if none was provided.
<ide> */
<ide> URI {
<ide> @Override
<ide> public String asString() {
<ide> },
<ide>
<ide> /**
<del> * Name of the exception thrown during the exchange, or {@code "none"} if no exception happened.
<add> * Name of the exception thrown during the exchange, or {@value KeyValue#NONE_VALUE} if no exception happened.
<ide> */
<ide> EXCEPTION {
<ide> @Override
<ide><path>spring-web/src/main/java/org/springframework/http/client/observation/DefaultClientRequestObservationConvention.java
<ide> public class DefaultClientRequestObservationConvention implements ClientRequestO
<ide>
<ide> private static final String DEFAULT_NAME = "http.client.requests";
<ide>
<del> private static final KeyValue URI_NONE = KeyValue.of(ClientHttpObservationDocumentation.LowCardinalityKeyNames.URI, "none");
<add> private static final KeyValue URI_NONE = KeyValue.of(ClientHttpObservationDocumentation.LowCardinalityKeyNames.URI, KeyValue.NONE_VALUE);
<ide>
<del> private static final KeyValue METHOD_NONE = KeyValue.of(ClientHttpObservationDocumentation.LowCardinalityKeyNames.METHOD, "none");
<add> private static final KeyValue METHOD_NONE = KeyValue.of(ClientHttpObservationDocumentation.LowCardinalityKeyNames.METHOD, KeyValue.NONE_VALUE);
<ide>
<ide> private static final KeyValue STATUS_IO_ERROR = KeyValue.of(ClientHttpObservationDocumentation.LowCardinalityKeyNames.STATUS, "IO_ERROR");
<ide>
<ide> public class DefaultClientRequestObservationConvention implements ClientRequestO
<ide>
<ide> private static final KeyValue HTTP_OUTCOME_UNKNOWN = KeyValue.of(ClientHttpObservationDocumentation.LowCardinalityKeyNames.OUTCOME, "UNKNOWN");
<ide>
<del> private static final KeyValue EXCEPTION_NONE = KeyValue.of(ClientHttpObservationDocumentation.LowCardinalityKeyNames.EXCEPTION, "none");
<add> private static final KeyValue EXCEPTION_NONE = KeyValue.of(ClientHttpObservationDocumentation.LowCardinalityKeyNames.EXCEPTION, KeyValue.NONE_VALUE);
<ide>
<del> private static final KeyValue HTTP_URL_NONE = KeyValue.of(ClientHttpObservationDocumentation.HighCardinalityKeyNames.HTTP_URL, "none");
<add> private static final KeyValue HTTP_URL_NONE = KeyValue.of(ClientHttpObservationDocumentation.HighCardinalityKeyNames.HTTP_URL, KeyValue.NONE_VALUE);
<ide>
<del> private static final KeyValue CLIENT_NAME_NONE = KeyValue.of(ClientHttpObservationDocumentation.HighCardinalityKeyNames.CLIENT_NAME, "none");
<add> private static final KeyValue CLIENT_NAME_NONE = KeyValue.of(ClientHttpObservationDocumentation.HighCardinalityKeyNames.CLIENT_NAME, KeyValue.NONE_VALUE);
<ide>
<ide>
<ide> private final String name;
<ide><path>spring-web/src/main/java/org/springframework/http/observation/DefaultServerRequestObservationConvention.java
<ide> public class DefaultServerRequestObservationConvention implements ServerRequestO
<ide>
<ide> private static final KeyValue URI_REDIRECTION = KeyValue.of(ServerHttpObservationDocumentation.LowCardinalityKeyNames.URI, "REDIRECTION");
<ide>
<del> private static final KeyValue EXCEPTION_NONE = KeyValue.of(ServerHttpObservationDocumentation.LowCardinalityKeyNames.EXCEPTION, "none");
<add> private static final KeyValue EXCEPTION_NONE = KeyValue.of(ServerHttpObservationDocumentation.LowCardinalityKeyNames.EXCEPTION, KeyValue.NONE_VALUE);
<ide>
<ide> private static final KeyValue HTTP_URL_UNKNOWN = KeyValue.of(ServerHttpObservationDocumentation.HighCardinalityKeyNames.HTTP_URL, "UNKNOWN");
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/observation/ServerHttpObservationDocumentation.java
<ide>
<ide> package org.springframework.http.observation;
<ide>
<add>import io.micrometer.common.KeyValue;
<ide> import io.micrometer.common.docs.KeyName;
<ide> import io.micrometer.observation.Observation;
<ide> import io.micrometer.observation.ObservationConvention;
<ide> public KeyName[] getHighCardinalityKeyNames() {
<ide> public enum LowCardinalityKeyNames implements KeyName {
<ide>
<ide> /**
<del> * Name of HTTP request method or {@code "none"} if the request was not received properly.
<add> * Name of HTTP request method or {@value KeyValue#NONE_VALUE} if the request was not received properly.
<ide> */
<ide> METHOD {
<ide> @Override
<ide> public String asString() {
<ide> },
<ide>
<ide> /**
<del> * Name of the exception thrown during the exchange, or {@code "none"} if no exception happened.
<add> * Name of the exception thrown during the exchange, or {@value KeyValue#NONE_VALUE}} if no exception happened.
<ide> */
<ide> EXCEPTION {
<ide> @Override
<ide><path>spring-web/src/main/java/org/springframework/http/observation/reactive/DefaultServerRequestObservationConvention.java
<ide> public class DefaultServerRequestObservationConvention implements ServerRequestO
<ide>
<ide> private static final KeyValue URI_REDIRECTION = KeyValue.of(ServerHttpObservationDocumentation.LowCardinalityKeyNames.URI, "REDIRECTION");
<ide>
<del> private static final KeyValue EXCEPTION_NONE = KeyValue.of(ServerHttpObservationDocumentation.LowCardinalityKeyNames.EXCEPTION, "none");
<add> private static final KeyValue EXCEPTION_NONE = KeyValue.of(ServerHttpObservationDocumentation.LowCardinalityKeyNames.EXCEPTION, KeyValue.NONE_VALUE);
<ide>
<ide> private static final KeyValue HTTP_URL_UNKNOWN = KeyValue.of(ServerHttpObservationDocumentation.HighCardinalityKeyNames.HTTP_URL, "UNKNOWN");
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/observation/reactive/ServerHttpObservationDocumentation.java
<ide>
<ide> package org.springframework.http.observation.reactive;
<ide>
<add>import io.micrometer.common.KeyValue;
<ide> import io.micrometer.common.docs.KeyName;
<ide> import io.micrometer.observation.Observation;
<ide> import io.micrometer.observation.ObservationConvention;
<ide> public KeyName[] getHighCardinalityKeyNames() {
<ide> public enum LowCardinalityKeyNames implements KeyName {
<ide>
<ide> /**
<del> * Name of HTTP request method or {@code "none"} if the request was not received properly.
<add> * Name of HTTP request method or {@value KeyValue#NONE_VALUE} if the request was not received properly.
<ide> */
<ide> METHOD {
<ide> @Override
<ide> public String asString() {
<ide> },
<ide>
<ide> /**
<del> * Name of the exception thrown during the exchange, or {@code "none"} if no exception happened.
<add> * Name of the exception thrown during the exchange, or {@value KeyValue#NONE_VALUE} if no exception happened.
<ide> */
<ide> EXCEPTION {
<ide> @Override
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/ClientHttpObservationDocumentation.java
<ide>
<ide> package org.springframework.web.reactive.function.client;
<ide>
<add>import io.micrometer.common.KeyValue;
<ide> import io.micrometer.common.docs.KeyName;
<ide> import io.micrometer.observation.Observation;
<ide> import io.micrometer.observation.ObservationConvention;
<ide> public KeyName[] getHighCardinalityKeyNames() {
<ide> public enum LowCardinalityKeyNames implements KeyName {
<ide>
<ide> /**
<del> * Name of HTTP request method or {@code "none"} if the request could not be created.
<add> * Name of HTTP request method or {@value KeyValue#NONE_VALUE} if the request could not be created.
<ide> */
<ide> METHOD {
<ide> @Override
<ide> public String asString() {
<ide> },
<ide>
<ide> /**
<del> * URI template used for HTTP request, or {@code "none"} if none was provided.
<add> * URI template used for HTTP request, or {@value KeyValue#NONE_VALUE} if none was provided.
<ide> */
<ide> URI {
<ide> @Override
<ide> public String asString() {
<ide> },
<ide>
<ide> /**
<del> * Name of the exception thrown during the exchange, or {@code "none"} if no exception happened.
<add> * Name of the exception thrown during the exchange, or {@value KeyValue#NONE_VALUE} if no exception happened.
<ide> */
<ide> EXCEPTION {
<ide> @Override
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultClientRequestObservationConvention.java
<ide> public class DefaultClientRequestObservationConvention implements ClientRequestO
<ide>
<ide> private static final String DEFAULT_NAME = "http.client.requests";
<ide>
<del> private static final KeyValue URI_NONE = KeyValue.of(ClientHttpObservationDocumentation.LowCardinalityKeyNames.URI, "none");
<add> private static final KeyValue URI_NONE = KeyValue.of(ClientHttpObservationDocumentation.LowCardinalityKeyNames.URI, KeyValue.NONE_VALUE);
<ide>
<del> private static final KeyValue METHOD_NONE = KeyValue.of(ClientHttpObservationDocumentation.LowCardinalityKeyNames.METHOD, "none");
<add> private static final KeyValue METHOD_NONE = KeyValue.of(ClientHttpObservationDocumentation.LowCardinalityKeyNames.METHOD, KeyValue.NONE_VALUE);
<ide>
<ide> private static final KeyValue STATUS_IO_ERROR = KeyValue.of(ClientHttpObservationDocumentation.LowCardinalityKeyNames.STATUS, "IO_ERROR");
<ide>
<ide> public class DefaultClientRequestObservationConvention implements ClientRequestO
<ide>
<ide> private static final KeyValue HTTP_OUTCOME_UNKNOWN = KeyValue.of(ClientHttpObservationDocumentation.LowCardinalityKeyNames.OUTCOME, "UNKNOWN");
<ide>
<del> private static final KeyValue EXCEPTION_NONE = KeyValue.of(ClientHttpObservationDocumentation.LowCardinalityKeyNames.EXCEPTION, "none");
<add> private static final KeyValue EXCEPTION_NONE = KeyValue.of(ClientHttpObservationDocumentation.LowCardinalityKeyNames.EXCEPTION, KeyValue.NONE_VALUE);
<ide>
<del> private static final KeyValue HTTP_URL_NONE = KeyValue.of(ClientHttpObservationDocumentation.HighCardinalityKeyNames.HTTP_URL, "none");
<add> private static final KeyValue HTTP_URL_NONE = KeyValue.of(ClientHttpObservationDocumentation.HighCardinalityKeyNames.HTTP_URL, KeyValue.NONE_VALUE);
<ide>
<del> private static final KeyValue CLIENT_NAME_NONE = KeyValue.of(ClientHttpObservationDocumentation.HighCardinalityKeyNames.CLIENT_NAME, "none");
<add> private static final KeyValue CLIENT_NAME_NONE = KeyValue.of(ClientHttpObservationDocumentation.HighCardinalityKeyNames.CLIENT_NAME, KeyValue.NONE_VALUE);
<ide>
<ide> private final String name;
<ide> | 8 |
PHP | PHP | fix scaffold delete messages with uuids | ef1da3146eb5947d0fd25a28b5094b86b251693b | <ide><path>lib/Cake/Controller/Scaffold.php
<ide> protected function _scaffoldDelete(CakeRequest $request) {
<ide> throw new NotFoundException(__d('cake', 'Invalid %s', Inflector::humanize($this->modelClass)));
<ide> }
<ide> if ($this->ScaffoldModel->delete()) {
<del> $message = __d('cake', 'The %1$s with id: %2$d has been deleted.', Inflector::humanize($this->modelClass), $id);
<add> $message = __d('cake', 'The %1$s with id: %2$s has been deleted.', Inflector::humanize($this->modelClass), $id);
<ide> return $this->_sendMessage($message);
<ide> } else {
<ide> $message = __d('cake',
<del> 'There was an error deleting the %1$s with id: %2$d',
<add> 'There was an error deleting the %1$s with id: %2$s',
<ide> Inflector::humanize($this->modelClass),
<ide> $id
<ide> ); | 1 |
PHP | PHP | offer an "attribute casting" of encrypt | fcf3b659197413766665be728537cebf0f70af0a | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> protected function isJsonCastable($key)
<ide> return $this->hasCast($key, ['array', 'json', 'object', 'collection']);
<ide> }
<ide>
<add> /**
<add> * Determine whether a value should be encrypted.
<add> *
<add> * @param string $key
<add> * @return bool
<add> */
<add> protected function isEncryptCastable($key) {
<add> return $this->hasCast($key, ['encrypt']);
<add> }
<add>
<ide> /**
<ide> * Get the type of cast for a model attribute.
<ide> *
<ide> protected function castAttribute($key, $value)
<ide> return $this->asDateTime($value);
<ide> case 'timestamp':
<ide> return $this->asTimeStamp($value);
<add> case 'encrypt':
<add> return decrypt($value);
<ide> default:
<ide> return $value;
<ide> }
<ide> public function setAttribute($key, $value)
<ide> $value = $this->fromDateTime($value);
<ide> }
<ide>
<add> if($this->isEncryptCastable($key) && ! is_null($value)) {
<add> $value = $this->asEncrypted($value);
<add> }
<add>
<ide> if ($this->isJsonCastable($key) && ! is_null($value)) {
<ide> $value = $this->asJson($value);
<ide> }
<ide> protected function asJson($value)
<ide> {
<ide> return json_encode($value);
<ide> }
<del>
<add>
<ide> /**
<ide> * Decode the given JSON back into an array or object.
<ide> *
<ide> public function fromJson($value, $asObject = false)
<ide> return json_decode($value, ! $asObject);
<ide> }
<ide>
<add> /**
<add> * Encrypt to given value
<add> *
<add> * @param mixed $value
<add> * @return string
<add> */
<add> protected function asEncrypted($value)
<add> {
<add> return encrypt($value);
<add> }
<add>
<ide> /**
<ide> * Clone the model into a new, non-existing instance.
<ide> * | 1 |
Go | Go | update testhttpsinforoguecert for go 1.7 | 496adadcec4ba00d230e546239ddc10e4ea41dcf | <ide><path>integration-cli/docker_cli_daemon_test.go
<ide> func (s *DockerDaemonSuite) TestTlsVerify(c *check.C) {
<ide> // by using a rogue client certificate and checks that it fails with the expected error.
<ide> func (s *DockerDaemonSuite) TestHttpsInfoRogueCert(c *check.C) {
<ide> const (
<del> errBadCertificate = "remote error: bad certificate"
<add> errBadCertificate = "bad certificate"
<ide> testDaemonHTTPSAddr = "tcp://localhost:4271"
<ide> )
<ide> | 1 |
Text | Text | add react remote conf 2016. | 346dcaacfa38f62593a47f10d1b9de100ffb2f1b | <ide><path>docs/community/conferences.md
<ide> April 16 in Amsterdam, The Netherlands
<ide> ### ReactEurope 2016
<ide> June 2 & 3 in Paris, France
<ide>
<del>[Website](http://www.react-europe.org/) - [Schedule](http://www.react-europe.org/#schedule)
<add>[Website](http://www.react-europe.org/) - [Schedule](http://www.react-europe.org/#schedule) - [Videos](https://www.youtube.com/channel/UCorlLn2oZfgOJ-FUcF2eZ1A/playlists)
<ide>
<ide> ### ReactRally 2016
<ide> August 25-26 in Salt Lake City, UT
<ide> August 25-26 in Salt Lake City, UT
<ide> ### ReactNext 2016
<ide> September 15 in Tel Aviv, Israel
<ide>
<del>[Website](http://react-next.com/) - [Schedule](http://react-next.com/#schedule)
<add>[Website](http://react-next.com/) - [Schedule](http://react-next.com/#schedule) - [Videos](https://www.youtube.com/channel/UC3BT8hh3yTTYxbLQy_wbk2w)
<ide>
<ide> ### ReactNL 2016
<del>October 13 in Amsterdam, The Netherlands
<add>October 13 in Amsterdam, The Netherlands - [Schedule](http://reactnl.org/#program)
<ide>
<ide> [Website](http://reactnl.org/)
<ide>
<ide> ### Reactive 2016
<ide> October 26-28 in Bratislava, Slovakia
<ide>
<ide> [Website](https://reactiveconf.com/)
<add>
<add>### React Remote Conf 2016
<add>October 26-28 online
<add>
<add>[Website](https://allremoteconfs.com/react-2016) - [Schedule](https://allremoteconfs.com/react-2016#schedule)
<ide>\ No newline at end of file | 1 |
Text | Text | rewrite contributing guidelines | 8c41c5c1b7a6421824c3eb071ea944004403c15f | <ide><path>CONTRIBUTING.md
<del>Contributing
<del>============
<add>Contributing to Chart.js
<add>========================
<ide>
<del>New contributions to the library are welcome, just a couple of guidelines:
<add>Contributions to Chart.js are welcome and encouraged, but please have a look through the guidelines in this document before raising an issue, or writing code for the project.
<ide>
<del> * Tabs for indentation, not spaces please.
<del> * Please ensure you're changing the individual files in /src, not the concatenated output in the Chart.js file in the root of the repo.
<del> * Please check that your code will pass jshint code standards, `gulp jshint` will run this for you.
<del> * Please keep pull requests concise, and document new functionality in the relevant .md file.
<del> * Consider whether your changes are useful for all users, or if creating a Chart.js extension would be more appropriate.
<del> * Please avoid committing in the build Chart.js & Chart.min.js file, as it causes conflicts when merging.
<del>
<del>New Chart Types
<del>===============
<ide>
<del>Chart.js is designed to be modular. See http://www.chartjs.org/docs/#advanced-usage-writing-new-chart-types
<add>Using issues
<add>------------
<ide>
<del>All discussion of new chart types (horizontal bar charts, X-Y scatter plot, etc.) should be done in the Chart.js Google Group at https://groups.google.com/forum/#!forum/chartjs-user-discussion This will get the most exposure for getting people to help define requirements, complete programming and documentation of your vision.
<add>The [issue tracker](https://github.com/nnnick/Chart.js/issues) is the preferred channel for reporting bugs, requesting new features and submitting pull requests.
<ide>
<del>Please do not request new chart types in the project issues. Fully implemented, documented, and useful new charts may be maintained in a new repository. Later, we may add a link to selected external repositories from this project.
<add>If you're suggesting a new chart type, please take a look at [writing new chart types](https://github.com/nnnick/Chart.js/blob/master/docs/06-Advanced.md#writing-new-chart-types) in the documentation, and some of the [community extensions](https://github.com/nnnick/Chart.js/blob/master/docs/06-Advanced.md#community-extensions) that have been created already.
<add>
<add>To keep the library lightweight for everyone, it's unlikely we'll add many more chart types to the core of Chart.js, but issues are a good medium to design and spec out how new chart types could work and look.
<add>
<add>Please do not use issues for support requests. For help using Chart.js, please take a look at the [`chartjs`](http://stackoverflow.com/questions/tagged/chartjs) tag on Stack Overflow.
<add>
<add>
<add>Reporting bugs
<add>--------------
<add>
<add>Well structured, detailed bug reports are hugely valuable for the project.
<add>
<add>Guidlines for reporting bugs:
<add>
<add> - Check the issue search to see if it has already been reported
<add> - Isolate the problem to a simple test case
<add> - Provide a demonstration of the problem on [jsbin](http://jsbin.com) or similar
<add>
<add>Please provide any additional details associated with the bug, if it's browser of screen density specific, or only happens with a certain configuration or data.
<add>
<add>
<add>Pull requests
<add>-------------
<add>
<add>Clear, concise pull requests are excellent at continuing the projects community driven growth. But please review the guidelines below before starting work on the project.
<add>
<add>Guidlines:
<add>
<add> - Please ask before starting significant work on a pull request to check it's a change within the project scope, and isn't a duplicate effort
<add> - Please make changes to the files in [`/src`](https://github.com/nnnick/Chart.js/tree/master/src), not `Chart.js` or `Chart.min.js` in the repo root directory
<add> - Tabs for indentation, not spaces please.
<add> - If adding new functionality, please also update the relevant `.md` file in [`/docs`](https://github.com/nnnick/Chart.js/tree/master/docs)
<add> - Please make your commits in logical sections with clear commit messages
<add> - Please avoid committing in the build Chart.js & Chart.min.js file, as it may cause conflicts when merging back
<add>
<add>
<add>License
<add>-------
<add>
<add>By contributing your code, you agree to license your contribution under the [MIT license](https://github.com/nnnick/Chart.js/blob/master/LICENSE.md). | 1 |
Python | Python | test more types of behavior in test_iter_options | 33d6d4a420ed9d94f9eeef12c9da31278a39b866 | <ide><path>tests/test_fields.py
<ide> def test_iter_options(self):
<ide> field = serializers.ChoiceField(
<ide> choices=[
<ide> ('Numbers', ['integer', 'float']),
<del> ('Strings', ['text', 'email', 'url'])
<add> ('Strings', ['text', 'email', 'url']),
<add> 'boolean'
<ide> ]
<ide> )
<ide> items = list(field.iter_options())
<ide> def test_iter_options(self):
<ide> assert items[7].value == 'url'
<ide> assert items[8].end_option_group
<ide>
<add> assert items[9].value == 'boolean'
<add>
<ide>
<ide> class TestChoiceFieldWithType(FieldValues):
<ide> """ | 1 |
Javascript | Javascript | fix lint errors | a4a208f5d1903fa898571da631fcc5f2b50836aa | <ide><path>src/renderers/WebGLRenderer.js
<ide> function WebGLRenderer( parameters ) {
<ide>
<ide> utils = new WebGLUtils( _gl, extensions, capabilities );
<ide>
<del> state = new WebGLState( _gl, extensions, capabilities, utils );
<add> state = new WebGLState( _gl, extensions, capabilities );
<ide> state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
<ide> state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
<ide>
<ide><path>src/renderers/webgl/WebGLBindingStates.js
<ide> function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
<ide> enableAttributeAndDivisor( programAttribute + 2, 1 );
<ide> enableAttributeAndDivisor( programAttribute + 3, 1 );
<ide>
<del> gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
<add> gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
<ide>
<ide> gl.vertexAttribPointer( programAttribute + 0, 4, type, false, 64, 0 );
<ide> gl.vertexAttribPointer( programAttribute + 1, 4, type, false, 64, 16 );
<ide><path>src/renderers/webgl/WebGLState.js
<ide> import { NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, CullFaceFront, CullFaceBack, CullFaceNone, DoubleSide, BackSide, CustomBlending, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NoBlending, NormalBlending, AddEquation, SubtractEquation, ReverseSubtractEquation, MinEquation, MaxEquation, ZeroFactor, OneFactor, SrcColorFactor, SrcAlphaFactor, SrcAlphaSaturateFactor, DstColorFactor, DstAlphaFactor, OneMinusSrcColorFactor, OneMinusSrcAlphaFactor, OneMinusDstColorFactor, OneMinusDstAlphaFactor } from '../../constants.js';
<ide> import { Vector4 } from '../../math/Vector4.js';
<ide>
<del>function WebGLState( gl, extensions, capabilities, utils ) {
<add>function WebGLState( gl, extensions, capabilities ) {
<ide>
<ide> var isWebGL2 = capabilities.isWebGL2;
<ide> | 3 |
Java | Java | add completable.takeuntil(completable) operator | 7e301d44d6dee9dce12f5417b41134f3a9eda12f | <ide><path>src/main/java/io/reactivex/Completable.java
<ide> public final Completable subscribeOn(final Scheduler scheduler) {
<ide> return RxJavaPlugins.onAssembly(new CompletableSubscribeOn(this, scheduler));
<ide> }
<ide>
<add> /**
<add> * Terminates the downstream if this or the other {@code Completable}
<add> * terminates (wins the termination race) while disposing the connection to the losing source.
<add> * <p>
<add> * <img width="640" height="468" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.takeuntil.c.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code takeUntil} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * <dt><b>Error handling:</b></dt>
<add> * <dd>If both this and the other sources signal an error, only one of the errors
<add> * is signaled to the downstream and the other error is signaled to the global
<add> * error handler via {@link RxJavaPlugins#onError(Throwable)}.</dd>
<add> * </dl>
<add> * @param other the other completable source to observe for the terminal signals
<add> * @return the new Completable instance
<add> * @since 2.1.17 - experimental
<add> */
<add> @CheckReturnValue
<add> @Experimental
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> public final Completable takeUntil(CompletableSource other) {
<add> ObjectHelper.requireNonNull(other, "other is null");
<add>
<add> return RxJavaPlugins.onAssembly(new CompletableTakeUntilCompletable(this, other));
<add> }
<add>
<ide> /**
<ide> * Returns a Completable that runs this Completable and emits a TimeoutException in case
<ide> * this Completable doesn't complete within the given time.
<ide><path>src/main/java/io/reactivex/internal/operators/completable/CompletableTakeUntilCompletable.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.completable;
<add>
<add>import java.util.concurrent.atomic.*;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.annotations.Experimental;
<add>import io.reactivex.disposables.Disposable;
<add>import io.reactivex.internal.disposables.DisposableHelper;
<add>import io.reactivex.plugins.RxJavaPlugins;
<add>
<add>/**
<add> * Terminates the sequence if either the main or the other Completable terminate.
<add> * @since 2.1.17 - experimental
<add> */
<add>@Experimental
<add>public final class CompletableTakeUntilCompletable extends Completable {
<add>
<add> final Completable source;
<add>
<add> final CompletableSource other;
<add>
<add> public CompletableTakeUntilCompletable(Completable source,
<add> CompletableSource other) {
<add> this.source = source;
<add> this.other = other;
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(CompletableObserver s) {
<add> TakeUntilMainObserver parent = new TakeUntilMainObserver(s);
<add> s.onSubscribe(parent);
<add>
<add> other.subscribe(parent.other);
<add> source.subscribe(parent);
<add> }
<add>
<add> static final class TakeUntilMainObserver extends AtomicReference<Disposable>
<add> implements CompletableObserver, Disposable {
<add>
<add> private static final long serialVersionUID = 3533011714830024923L;
<add>
<add> final CompletableObserver downstream;
<add>
<add> final OtherObserver other;
<add>
<add> final AtomicBoolean once;
<add>
<add> TakeUntilMainObserver(CompletableObserver downstream) {
<add> this.downstream = downstream;
<add> this.other = new OtherObserver(this);
<add> this.once = new AtomicBoolean();
<add> }
<add>
<add> @Override
<add> public void dispose() {
<add> if (once.compareAndSet(false, true)) {
<add> DisposableHelper.dispose(this);
<add> DisposableHelper.dispose(other);
<add> }
<add> }
<add>
<add> @Override
<add> public boolean isDisposed() {
<add> return once.get();
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> DisposableHelper.setOnce(this, d);
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> if (once.compareAndSet(false, true)) {
<add> DisposableHelper.dispose(other);
<add> downstream.onComplete();
<add> }
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> if (once.compareAndSet(false, true)) {
<add> DisposableHelper.dispose(other);
<add> downstream.onError(e);
<add> } else {
<add> RxJavaPlugins.onError(e);
<add> }
<add> }
<add>
<add> void innerComplete() {
<add> if (once.compareAndSet(false, true)) {
<add> DisposableHelper.dispose(this);
<add> downstream.onComplete();
<add> }
<add> }
<add>
<add> void innerError(Throwable e) {
<add> if (once.compareAndSet(false, true)) {
<add> DisposableHelper.dispose(this);
<add> downstream.onError(e);
<add> } else {
<add> RxJavaPlugins.onError(e);
<add> }
<add> }
<add>
<add> static final class OtherObserver extends AtomicReference<Disposable>
<add> implements CompletableObserver {
<add>
<add> private static final long serialVersionUID = 5176264485428790318L;
<add> final TakeUntilMainObserver parent;
<add>
<add> OtherObserver(TakeUntilMainObserver parent) {
<add> this.parent = parent;
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> DisposableHelper.setOnce(this, d);
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> parent.innerComplete();
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> parent.innerError(e);
<add> }
<add> }
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/internal/operators/completable/CompletableTakeUntilTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.completable;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>import java.util.List;
<add>import java.util.concurrent.atomic.AtomicReference;
<add>
<add>import org.junit.Test;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.disposables.Disposables;
<add>import io.reactivex.exceptions.TestException;
<add>import io.reactivex.observers.TestObserver;
<add>import io.reactivex.plugins.RxJavaPlugins;
<add>import io.reactivex.subjects.CompletableSubject;
<add>
<add>public class CompletableTakeUntilTest {
<add>
<add> @Test
<add> public void consumerDisposes() {
<add> CompletableSubject cs1 = CompletableSubject.create();
<add> CompletableSubject cs2 = CompletableSubject.create();
<add>
<add> TestObserver<Void> to = cs1.takeUntil(cs2).test();
<add>
<add> to.assertEmpty();
<add>
<add> assertTrue(cs1.hasObservers());
<add> assertTrue(cs2.hasObservers());
<add>
<add> to.dispose();
<add>
<add> assertFalse(cs1.hasObservers());
<add> assertFalse(cs2.hasObservers());
<add> }
<add>
<add> @Test
<add> public void mainCompletes() {
<add> CompletableSubject cs1 = CompletableSubject.create();
<add> CompletableSubject cs2 = CompletableSubject.create();
<add>
<add> TestObserver<Void> to = cs1.takeUntil(cs2).test();
<add>
<add> to.assertEmpty();
<add>
<add> assertTrue(cs1.hasObservers());
<add> assertTrue(cs2.hasObservers());
<add>
<add> cs1.onComplete();
<add>
<add> assertFalse(cs1.hasObservers());
<add> assertFalse(cs2.hasObservers());
<add>
<add> to.assertResult();
<add> }
<add>
<add> @Test
<add> public void otherCompletes() {
<add> CompletableSubject cs1 = CompletableSubject.create();
<add> CompletableSubject cs2 = CompletableSubject.create();
<add>
<add> TestObserver<Void> to = cs1.takeUntil(cs2).test();
<add>
<add> to.assertEmpty();
<add>
<add> assertTrue(cs1.hasObservers());
<add> assertTrue(cs2.hasObservers());
<add>
<add> cs2.onComplete();
<add>
<add> assertFalse(cs1.hasObservers());
<add> assertFalse(cs2.hasObservers());
<add>
<add> to.assertResult();
<add> }
<add>
<add> @Test
<add> public void mainErrors() {
<add> CompletableSubject cs1 = CompletableSubject.create();
<add> CompletableSubject cs2 = CompletableSubject.create();
<add>
<add> TestObserver<Void> to = cs1.takeUntil(cs2).test();
<add>
<add> to.assertEmpty();
<add>
<add> assertTrue(cs1.hasObservers());
<add> assertTrue(cs2.hasObservers());
<add>
<add> cs1.onError(new TestException());
<add>
<add> assertFalse(cs1.hasObservers());
<add> assertFalse(cs2.hasObservers());
<add>
<add> to.assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void otherErrors() {
<add> CompletableSubject cs1 = CompletableSubject.create();
<add> CompletableSubject cs2 = CompletableSubject.create();
<add>
<add> TestObserver<Void> to = cs1.takeUntil(cs2).test();
<add>
<add> to.assertEmpty();
<add>
<add> assertTrue(cs1.hasObservers());
<add> assertTrue(cs2.hasObservers());
<add>
<add> cs2.onError(new TestException());
<add>
<add> assertFalse(cs1.hasObservers());
<add> assertFalse(cs2.hasObservers());
<add>
<add> to.assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void isDisposed() {
<add> CompletableSubject cs1 = CompletableSubject.create();
<add> CompletableSubject cs2 = CompletableSubject.create();
<add>
<add> TestHelper.checkDisposed(cs1.takeUntil(cs2));
<add> }
<add>
<add> @Test
<add> public void mainErrorLate() {
<add>
<add> List<Throwable> errors = TestHelper.trackPluginErrors();
<add> try {
<add>
<add> new Completable() {
<add> @Override
<add> protected void subscribeActual(CompletableObserver s) {
<add> s.onSubscribe(Disposables.empty());
<add> s.onError(new TestException());
<add> }
<add> }.takeUntil(Completable.complete())
<add> .test()
<add> .assertResult();
<add>
<add> TestHelper.assertUndeliverable(errors, 0, TestException.class);
<add> } finally {
<add> RxJavaPlugins.reset();
<add> }
<add> }
<add>
<add> @Test
<add> public void mainCompleteLate() {
<add>
<add> List<Throwable> errors = TestHelper.trackPluginErrors();
<add> try {
<add>
<add> new Completable() {
<add> @Override
<add> protected void subscribeActual(CompletableObserver s) {
<add> s.onSubscribe(Disposables.empty());
<add> s.onComplete();
<add> }
<add> }.takeUntil(Completable.complete())
<add> .test()
<add> .assertResult();
<add>
<add> assertTrue(errors.isEmpty());
<add> } finally {
<add> RxJavaPlugins.reset();
<add> }
<add> }
<add>
<add> @Test
<add> public void otherErrorLate() {
<add>
<add> List<Throwable> errors = TestHelper.trackPluginErrors();
<add> try {
<add>
<add> final AtomicReference<CompletableObserver> ref = new AtomicReference<CompletableObserver>();
<add>
<add> Completable.complete()
<add> .takeUntil(new Completable() {
<add> @Override
<add> protected void subscribeActual(CompletableObserver s) {
<add> s.onSubscribe(Disposables.empty());
<add> ref.set(s);
<add> }
<add> })
<add> .test()
<add> .assertResult();
<add>
<add> ref.get().onError(new TestException());
<add>
<add> TestHelper.assertUndeliverable(errors, 0, TestException.class);
<add> } finally {
<add> RxJavaPlugins.reset();
<add> }
<add> }
<add>
<add> @Test
<add> public void otherCompleteLate() {
<add>
<add> List<Throwable> errors = TestHelper.trackPluginErrors();
<add> try {
<add>
<add> final AtomicReference<CompletableObserver> ref = new AtomicReference<CompletableObserver>();
<add>
<add> Completable.complete()
<add> .takeUntil(new Completable() {
<add> @Override
<add> protected void subscribeActual(CompletableObserver s) {
<add> s.onSubscribe(Disposables.empty());
<add> ref.set(s);
<add> }
<add> })
<add> .test()
<add> .assertResult();
<add>
<add> ref.get().onComplete();
<add>
<add> assertTrue(errors.isEmpty());
<add> } finally {
<add> RxJavaPlugins.reset();
<add> }
<add> }
<add>} | 3 |
Text | Text | fix broken link to api routes doc | 4f5975ffc49967f49acb7ea595b75723aa1356df | <ide><path>examples/api-routes-graphql/README.md
<ide> # API routes with GraphQL server
<ide>
<del>Next.js ships with [API routes](https://github.com/vercel/next.js#api-routes), which provide an easy solution to build your own `API`. This example shows their usage alongside [apollo-server-micro](https://github.com/apollographql/apollo-server/tree/main/packages/apollo-server-micro) to provide simple GraphQL server consumed by Next.js app.
<add>Next.js ships with [API routes](https://nextjs.org/docs/api-routes/introduction), which provide an easy solution to build your own `API`. This example shows their usage alongside [apollo-server-micro](https://github.com/apollographql/apollo-server/tree/main/packages/apollo-server-micro) to provide simple GraphQL server consumed by Next.js app.
<ide>
<ide> ## Preview
<ide> | 1 |
Javascript | Javascript | limit persistent history correctly on load | 73b7e052c04c25887b1aba4542d30a37e39fa60a | <ide><path>lib/internal/repl.js
<ide> function setupHistory(repl, historyPath, oldHistoryPath, ready) {
<ide> }
<ide>
<ide> if (data) {
<del> repl.history = data.split(/[\n\r]+/).slice(-repl.historySize);
<add> repl.history = data.split(/[\n\r]+/, repl.historySize);
<ide> } else if (oldHistoryPath) {
<ide> // Grab data from the older pre-v3.0 JSON NODE_REPL_HISTORY_FILE format.
<ide> repl._writeToOutput(
<ide> function setupHistory(repl, historyPath, oldHistoryPath, ready) {
<ide> if (!Array.isArray(repl.history)) {
<ide> throw new Error('Expected array, got ' + typeof repl.history);
<ide> }
<del> repl.history = repl.history.slice(-repl.historySize);
<add> repl.history = repl.history.slice(0, repl.historySize);
<ide> } catch (err) {
<ide> if (err.code !== 'ENOENT') {
<ide> return ready(
<ide><path>test/sequential/test-repl-persistent-history.js
<ide> const tests = [{
<ide> expected: [prompt, prompt + '\'42\'', prompt + '\'=^.^=\'', '\'=^.^=\'\n',
<ide> prompt]
<ide> },
<add>{
<add> env: { NODE_REPL_HISTORY: historyPath,
<add> NODE_REPL_HISTORY_SIZE: 1 },
<add> test: [UP, UP, CLEAR],
<add> expected: [prompt, prompt + '\'you look fabulous today\'', prompt]
<add>},
<add>{
<add> env: { NODE_REPL_HISTORY_FILE: oldHistoryPath,
<add> NODE_REPL_HISTORY_SIZE: 1 },
<add> test: [UP, UP, UP, CLEAR],
<add> expected: [prompt, convertMsg, prompt, prompt + '\'=^.^=\'', prompt]
<add>},
<ide> { // Make sure this is always the last test, since we change os.homedir()
<ide> before: function mockHomedirFailure() {
<ide> // Mock os.homedir() failure | 2 |
Text | Text | add the content for how services work | 2b0892c02eb50c20e8752643faf558dd150dbc77 | <ide><path>docs/swarm/how-swarm-mode-works/menu.md
<ide> weight=11
<ide> ## TOC
<ide>
<ide> * [How nodes work](nodes.md)
<add>* [How services work](services.md) | 1 |
Ruby | Ruby | remove private api test | 679902b916098667dec04e3a47011d244af3056a | <ide><path>activerecord/test/cases/base_test.rb
<ide> def setup
<ide> class BasicsTest < ActiveRecord::TestCase
<ide> fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, 'warehouse-things', :authors, :categorizations, :categories, :posts
<ide>
<del> def test_generated_methods_modules
<del> modules = Computer.ancestors
<del> assert modules.include?(Computer::GeneratedFeatureMethods)
<del> assert_equal(Computer::GeneratedFeatureMethods, Computer.generated_feature_methods)
<del> assert(modules.index(Computer.generated_attribute_methods) > modules.index(Computer.generated_feature_methods),
<del> "generated_attribute_methods must be higher in inheritance hierarchy than generated_feature_methods")
<del> assert_not_equal Computer.generated_feature_methods, Post.generated_feature_methods
<del> assert(modules.index(Computer.generated_attribute_methods) < modules.index(ActiveRecord::Base.ancestors[1]))
<del> end
<del>
<ide> def test_column_names_are_escaped
<ide> conn = ActiveRecord::Base.connection
<ide> classname = conn.class.name[/[^:]*$/] | 1 |
Mixed | Ruby | add validity for postgresql indexes | d152a11a4c75ed21816e97191a1fce2110a4a2ce | <ide><path>activerecord/CHANGELOG.md
<add>* Add validity for PostgreSQL indexes.
<add>
<add> ```ruby
<add> connection.index_exists?(:users, :email, valid: true)
<add> connection.indexes(:users).select(&:valid?)
<add> ```
<add>
<add> *fatkodima*
<add>
<ide> * Fix eager loading for models without primary keys.
<ide>
<ide> *Anmol Chopra*, *Matt Lawrence*, and *Jonathan Hefner*
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
<ide> module ConnectionAdapters # :nodoc:
<ide> # this type are typically created and returned by methods in database
<ide> # adapters. e.g. ActiveRecord::ConnectionAdapters::MySQL::SchemaStatements#indexes
<ide> class IndexDefinition # :nodoc:
<del> attr_reader :table, :name, :unique, :columns, :lengths, :orders, :opclasses, :where, :type, :using, :comment
<add> attr_reader :table, :name, :unique, :columns, :lengths, :orders, :opclasses, :where, :type, :using, :comment, :valid
<ide>
<ide> def initialize(
<ide> table, name,
<ide> def initialize(
<ide> where: nil,
<ide> type: nil,
<ide> using: nil,
<del> comment: nil
<add> comment: nil,
<add> valid: true
<ide> )
<ide> @table = table
<ide> @name = name
<ide> def initialize(
<ide> @type = type
<ide> @using = using
<ide> @comment = comment
<add> @valid = valid
<add> end
<add>
<add> def valid?
<add> @valid
<ide> end
<ide>
<ide> def column_options
<ide> def column_options
<ide> }
<ide> end
<ide>
<add> def defined_for?(columns = nil, name: nil, unique: nil, valid: nil, **options)
<add> (columns.nil? || Array(self.columns) == Array(columns).map(&:to_s)) &&
<add> (name.nil? || self.name == name.to_s) &&
<add> (unique.nil? || self.unique == unique) &&
<add> (valid.nil? || self.valid == valid)
<add> end
<add>
<ide> private
<ide> def concise_options(options)
<ide> if columns.size == options.size && options.values.uniq.size == 1
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
<ide> def indexes(table_name)
<ide> # # Check an index with a custom name exists
<ide> # index_exists?(:suppliers, :company_id, name: "idx_company_id")
<ide> #
<add> # # Check a valid index exists (PostgreSQL only)
<add> # index_exists?(:suppliers, :company_id, valid: true)
<add> #
<ide> def index_exists?(table_name, column_name, **options)
<del> checks = []
<del>
<del> if column_name.present?
<del> column_names = Array(column_name).map(&:to_s)
<del> checks << lambda { |i| Array(i.columns) == column_names }
<del> end
<del>
<del> checks << lambda { |i| i.unique } if options[:unique]
<del> checks << lambda { |i| i.name == options[:name].to_s } if options[:name]
<del>
<del> indexes(table_name).any? { |i| checks.all? { |check| check[i] } }
<add> indexes(table_name).any? { |i| i.defined_for?(column_name, **options) }
<ide> end
<ide>
<ide> # Returns an array of +Column+ objects for the table specified by +table_name+.
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
<ide> def indexes(table_name) # :nodoc:
<ide>
<ide> result = query(<<~SQL, "SCHEMA")
<ide> SELECT distinct i.relname, d.indisunique, d.indkey, pg_get_indexdef(d.indexrelid), t.oid,
<del> pg_catalog.obj_description(i.oid, 'pg_class') AS comment
<add> pg_catalog.obj_description(i.oid, 'pg_class') AS comment, d.indisvalid
<ide> FROM pg_class t
<ide> INNER JOIN pg_index d ON t.oid = d.indrelid
<ide> INNER JOIN pg_class i ON d.indexrelid = i.oid
<ide> def indexes(table_name) # :nodoc:
<ide> inddef = row[3]
<ide> oid = row[4]
<ide> comment = row[5]
<add> valid = row[6]
<ide>
<ide> using, expressions, where = inddef.scan(/ USING (\w+?) \((.+?)\)(?: WHERE (.+))?\z/m).flatten
<ide>
<ide> def indexes(table_name) # :nodoc:
<ide> opclasses: opclasses,
<ide> where: where,
<ide> using: using.to_sym,
<del> comment: comment.presence
<add> comment: comment.presence,
<add> valid: valid
<ide> )
<ide> end
<ide> end
<ide><path>activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb
<ide> def test_index_with_opclass
<ide> end
<ide> end
<ide>
<add> def test_invalid_index
<add> with_example_table do
<add> @connection.exec_query("INSERT INTO ex (number) VALUES (1), (1)")
<add> error = assert_raises(ActiveRecord::RecordNotUnique) do
<add> @connection.add_index(:ex, :number, unique: true, algorithm: :concurrently, name: :invalid_index)
<add> end
<add> assert_match(/could not create unique index/, error.message)
<add>
<add> assert @connection.index_exists?(:ex, :number, name: :invalid_index)
<add> assert_not @connection.index_exists?(:ex, :number, name: :invalid_index, valid: true)
<add> assert @connection.index_exists?(:ex, :number, name: :invalid_index, valid: false)
<add> end
<add> end
<add>
<ide> def test_columns_for_distinct_zero_orders
<ide> assert_equal "posts.id",
<ide> @connection.columns_for_distinct("posts.id", []) | 5 |
Python | Python | adjust message [ci skip] | 2d0c0134bcaa2527a40d13e62be594bf05ac389b | <ide><path>spacy/lang/zh/__init__.py
<ide> def deserialize_pkuseg_processors(b):
<ide> import spacy_pkuseg
<ide> except ImportError:
<ide> raise ImportError(
<del> "spacy_pkuseg not installed. To use this model, "
<add> "spacy-pkuseg not installed. To use this model, "
<ide> + _PKUSEG_INSTALL_MSG
<ide> ) from None
<ide> self.pkuseg_seg = spacy_pkuseg.pkuseg(str(tempdir))
<ide> def load_pkuseg_model(path):
<ide> except ImportError:
<ide> if self.segmenter == Segmenter.pkuseg:
<ide> raise ImportError(
<del> "spacy_pkuseg not installed. To use this model, "
<add> "spacy-pkuseg not installed. To use this model, "
<ide> + _PKUSEG_INSTALL_MSG
<ide> ) from None
<ide> if path.exists():
<ide> def try_pkuseg_import(pkuseg_model: str, pkuseg_user_dict: str) -> None:
<ide> import spacy_pkuseg
<ide>
<ide> except ImportError:
<del> msg = "spacy_pkuseg not installed. To use pkuseg, " + _PKUSEG_INSTALL_MSG
<add> msg = "spacy-pkuseg not installed. To use pkuseg, " + _PKUSEG_INSTALL_MSG
<ide> raise ImportError(msg) from None
<ide> try:
<ide> return spacy_pkuseg.pkuseg(pkuseg_model, pkuseg_user_dict) | 1 |
Java | Java | improve getmultipartcontenttype in mock request | a15a726fef4be798a24250003f57b9e88f869058 | <ide><path>spring-test/src/main/java/org/springframework/mock/web/MockMultipartHttpServletRequest.java
<ide>
<ide> package org.springframework.mock.web;
<ide>
<add>import java.io.IOException;
<ide> import java.util.Collections;
<ide> import java.util.Enumeration;
<ide> import java.util.Iterator;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<ide> import javax.servlet.ServletContext;
<add>import javax.servlet.ServletException;
<add>import javax.servlet.http.Part;
<ide>
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<ide> public String getMultipartContentType(String paramOrFileName) {
<ide> if (file != null) {
<ide> return file.getContentType();
<ide> }
<del> else {
<del> return null;
<add>
<add> try {
<add> Part part = getPart(paramOrFileName);
<add> if (part != null) {
<add> return part.getContentType();
<add> }
<add> } catch (ServletException | IOException e) {
<add> throw new IllegalStateException("Cannot extract content type from multipart request.", e);
<ide> }
<add>
<add> return null;
<ide> }
<ide>
<ide> @Override
<ide><path>spring-test/src/test/java/org/springframework/mock/web/MockMultipartHttpServletRequestTests.java
<ide>
<ide> import org.junit.jupiter.api.Test;
<ide>
<add>import org.springframework.http.HttpHeaders;
<add>import org.springframework.http.MediaType;
<ide> import org.springframework.util.FileCopyUtils;
<ide> import org.springframework.util.ObjectUtils;
<ide> import org.springframework.web.multipart.MultipartFile;
<ide> void mockMultipartHttpServletRequestWithInputStream() throws IOException {
<ide> doTestMultipartHttpServletRequest(request);
<ide> }
<ide>
<add> @Test
<add> void mockMultiPartHttpServletRequestWithMixedData() {
<add> MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();
<add> request.addFile(new MockMultipartFile("file", "myOrigFilename", MediaType.TEXT_PLAIN_VALUE, "myContent2".getBytes()));
<add>
<add> MockPart metadataPart = new MockPart("metadata", "{\"foo\": \"bar\"}".getBytes());
<add> metadataPart.getHeaders().setContentType(MediaType.APPLICATION_JSON);
<add> request.addPart(metadataPart);
<add>
<add> HttpHeaders fileHttpHeaders = request.getMultipartHeaders("file");
<add> assertThat(fileHttpHeaders).isNotNull();
<add> assertThat(fileHttpHeaders.getContentType()).isEqualTo(MediaType.TEXT_PLAIN);
<add>
<add> HttpHeaders dataHttpHeaders = request.getMultipartHeaders("metadata");
<add> assertThat(dataHttpHeaders).isNotNull();
<add> assertThat(dataHttpHeaders.getContentType()).isEqualTo(MediaType.APPLICATION_JSON);
<add> }
<add>
<ide> private void doTestMultipartHttpServletRequest(MultipartHttpServletRequest request) throws IOException {
<ide> Set<String> fileNames = new HashSet<>();
<ide> Iterator<String> fileIter = request.getFileNames(); | 2 |
Python | Python | add thai norm_exceptions | 189c90743ca69013f2fdaaafd67756dc49076ed4 | <ide><path>spacy/lang/th/__init__.py
<ide> from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
<ide> from .tag_map import TAG_MAP
<ide> from .stop_words import STOP_WORDS
<add>from .norm_exceptions import NORM_EXCEPTIONS
<ide>
<del>from ...attrs import LANG
<add>from ..norm_exceptions import BASE_NORMS
<add>from ...attrs import LANG, NORM
<ide> from ...language import Language
<ide> from ...tokens import Doc
<del>from ...util import DummyTokenizer
<add>from ...util import DummyTokenizer, add_lookups
<ide>
<ide>
<ide> class ThaiTokenizer(DummyTokenizer):
<ide> def __call__(self, text):
<ide> class ThaiDefaults(Language.Defaults):
<ide> lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
<ide> lex_attr_getters[LANG] = lambda _text: "th"
<del>
<add> lex_attr_getters[NORM] = add_lookups(
<add> Language.Defaults.lex_attr_getters[NORM], BASE_NORMS, NORM_EXCEPTIONS
<add> )
<ide> tokenizer_exceptions = dict(TOKENIZER_EXCEPTIONS)
<ide> tag_map = TAG_MAP
<ide> stop_words = STOP_WORDS
<ide><path>spacy/lang/th/norm_exceptions.py
<add># coding: utf8
<add>from __future__ import unicode_literals
<add>
<add>
<add>_exc = {
<add> # Conjugation and Diversion invalid to Tonal form (ผันอักษรและเสียงไม่ตรงกับรูปวรรณยุกต์)
<add> "สนุ๊กเกอร์": "สนุกเกอร์",
<add> "โน้ต": "โน้ต",
<add> # Misspelled because of being lazy or hustle (สะกดผิดเพราะขี้เกียจพิมพ์ หรือเร่งรีบ)
<add> "โทสับ": "โทรศัพท์",
<add> "พุ่งนี้": "พรุ่งนี้",
<add> # Strange (ให้ดูแปลกตา)
<add> "ชะมะ": "ใช่ไหม",
<add> "ชิมิ": "ใช่ไหม",
<add> "ชะ": "ใช่ไหม",
<add> "ช่ายมะ": "ใช่ไหม",
<add> "ป่าว": "เปล่า",
<add> "ป่ะ": "เปล่า",
<add> "ปล่าว": "เปล่า",
<add> "คัย": "ใคร",
<add> "ไค": "ใคร",
<add> "คราย": "ใคร",
<add> "เตง": "ตัวเอง",
<add> "ตะเอง": "ตัวเอง",
<add> "รึ": "หรือ",
<add> "เหรอ": "หรือ",
<add> "หรา": "หรือ",
<add> "หรอ": "หรือ",
<add> "ชั้น": "ฉัน",
<add> "ชั้ล": "ฉัน",
<add> "ช้าน": "ฉัน",
<add> "เทอ": "เธอ",
<add> "เทอร์": "เธอ",
<add> "เทอว์": "เธอ",
<add> "แกร": "แก",
<add> "ป๋ม": "ผม",
<add> "บ่องตง": "บอกตรงๆ",
<add> "ถ่ามตง": "ถามตรงๆ",
<add> "ต่อมตง": "ตอบตรงๆ",
<add> # Misspelled to express emotions (คำที่สะกดผิดเพื่อแสดงอารมณ์)
<add> "เปงราย": "เป็นอะไร",
<add> "เปนรัย": "เป็นอะไร",
<add> "เปงรัย": "เป็นอะไร",
<add> "เป็นอัลไล": "เป็นอะไร",
<add> "ทามมาย": "ทำไม",
<add> "ทามมัย": "ทำไม",
<add> "จังรุย": "จังเลย",
<add> "จังเยย": "จังเลย",
<add> "จุงเบย": "จังเลย",
<add> "ไม่รู้": "มะรุ",
<add> "เฮ่ย": "เฮ้ย",
<add> "เห้ย": "เฮ้ย",
<add> "น่าร็อคอ่ะ": "น่ารักอ่ะ",
<add> "น่าร๊ากอ้ะ": "น่ารักอ่ะ",
<add> "ตั้ลล๊ากอ่ะ": "น่ารักอ่ะ",
<add> # Reduce rough words or Avoid to software filter (คำที่สะกดผิดเพื่อลดความหยาบของคำ หรืออาจใช้หลีกเลี่ยงการกรองคำหยาบของซอฟต์แวร์)
<add> "กรู": "กู",
<add> "กุ": "กู",
<add> "กรุ": "กู",
<add> "ตู": "กู",
<add> "ตรู": "กู",
<add> "มรึง": "มึง",
<add> "เมิง": "มึง",
<add> "มืง": "มึง",
<add> "มุง": "มึง",
<add> "สาด": "สัตว์",
<add> "สัส": "สัตว์",
<add> "สัก": "สัตว์",
<add> "แสรด": "สัตว์",
<add> "โคโตะ": "โคตร",
<add> "โคด": "โคตร",
<add> "โครต": "โคตร",
<add> "โคตะระ": "โคตร",
<add> # Imitate words (คำเลียนเสียง โดยส่วนใหญ่จะเพิ่มทัณฑฆาต หรือซ้ำตัวอักษร)
<add> "แอร๊ยย": "อ๊าย",
<add> "อร๊ายยย": "อ๊าย",
<add> "มันส์": "มัน",
<add> "วู๊วววววววว์": "วู้",
<add>}
<add>
<add>
<add>NORM_EXCEPTIONS = {}
<add>
<add>for string, norm in _exc.items():
<add> NORM_EXCEPTIONS[string] = norm
<add> NORM_EXCEPTIONS[string.title()] = norm | 2 |
Text | Text | remove duplicate words in api docs | d74a1ed7d9e6eccd5d511ccb7becb17f3c03b88f | <ide><path>doc/api/child_process.md
<ide> pipes between the parent and child. The value is one of the following:
<ide> have an underlying descriptor (file streams do not until the `'open'`
<ide> event has occurred).
<ide> 5. Positive integer - The integer value is interpreted as a file descriptor
<del> that is is currently open in the parent process. It is shared with the child
<add> that is currently open in the parent process. It is shared with the child
<ide> process, similar to how {Stream} objects can be shared.
<ide> 6. `null`, `undefined` - Use default value. For stdio fds 0, 1, and 2 (in other
<ide> words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the
<ide><path>doc/api/perf_hooks.md
<ide> Creates a new `PerformanceMeasure` entry in the Performance Timeline. A
<ide> `startMark` and `endMark`.
<ide>
<ide> The `startMark` argument may identify any *existing* `PerformanceMark` in the
<del>the Performance Timeline, or *may* identify any of the timestamp properties
<add>Performance Timeline, or *may* identify any of the timestamp properties
<ide> provided by the `PerformanceNodeTiming` class. If the named `startMark` does
<ide> not exist, then `startMark` is set to [`timeOrigin`][] by default.
<ide>
<ide> The `endMark` argument must identify any *existing* `PerformanceMark` in the
<del>the Performance Timeline or any of the timestamp properties provided by the
<add>Performance Timeline or any of the timestamp properties provided by the
<ide> `PerformanceNodeTiming` class. If the named `endMark` does not exist, an
<ide> error will be thrown.
<ide> | 2 |
PHP | PHP | use constant for csrf token | 8e5852b7ebb28016cfeebe3b8fe50c1b32b152f9 | <ide><path>laravel/form.php
<ide> <?php namespace Laravel;
<ide>
<add>use Laravel\Session\Payload as Session;
<add>
<ide> class Form {
<ide>
<ide> /**
<ide> public static function token()
<ide> {
<ide> $token = IoC::core('session')->token();
<ide>
<del> return static::input('hidden', 'csrf_token', $token);
<add> return static::input('hidden', Session::token, $token);
<ide> }
<ide>
<ide> /** | 1 |
Ruby | Ruby | eliminate warning with layout is unset | 90be80361f26d717f9842170315dd8659f35429d | <ide><path>actionpack/lib/abstract_controller/layouts.rb
<ide> def _implied_layout_name
<ide> # name, return that string. Otherwise, use the superclass'
<ide> # layout (which might also be implied)
<ide> def _write_layout_method
<del> case @_layout
<add> case @_layout ||= nil
<ide> when String
<ide> self.class_eval %{def _layout(details) #{@_layout.inspect} end}
<ide> when Symbol | 1 |
Python | Python | fix typo in a docstring | 7bf69edca0d0622deb171f5a16af754dbcd04ce2 | <ide><path>airflow/providers/google/cloud/operators/gcs.py
<ide> def execute(self, context) -> None:
<ide>
<ide> class GCSListObjectsOperator(BaseOperator):
<ide> """
<del> List all objects from the bucket with the give string prefix and delimiter in name.
<add> List all objects from the bucket with the given string prefix and delimiter in name.
<ide>
<ide> This operator returns a python list with the name of objects which can be used by
<ide> `xcom` in the downstream task. | 1 |
Javascript | Javascript | add isnumeric constraint on venmo phone validation | f0b5ad7bf0ea59141ce9152a5187bd791d11f980 | <ide><path>controllers/api.js
<ide> exports.postVenmo = function(req, res, next) {
<ide> }
<ide>
<ide> var token = _.findWhere(req.user.tokens, { kind: 'venmo' });
<add>
<ide> var formData = {
<ide> access_token: token.accessToken,
<ide> note: req.body.note,
<ide> exports.postVenmo = function(req, res, next) {
<ide>
<ide> if (validator.isEmail(req.body.user)) {
<ide> formData.email = req.body.user;
<del> } else if (validator.isLength(req.body.user, 10, 11)) {
<add> } else if (validator.isNumberic(req.body.user) &&
<add> validator.isLength(req.body.user, 10, 11)) {
<ide> formData.phone = req.body.user;
<ide> } else {
<ide> formData.user_id = req.body.user;
<ide> }
<ide>
<del>
<ide> // Send money
<del> request.post('https://api.venmo.com/v1/payments', { form: formData }, function(err, request, body) {
<add> request.post('https://sandbox-api.venmo.com/v1/payments', { form: formData }, function(err, request, body) {
<ide> if (err) return next(err);
<ide> if (request.statusCode !== 200) {
<ide> req.flash('errors', { msg: JSON.parse(body).error.message });
<ide> return res.redirect('/api/venmo');
<ide> }
<del> req.flash('success', 'Venmo money transfer complete');
<add> req.flash('success', { msg: 'Venmo money transfer complete' });
<ide> res.redirect('/api/venmo');
<ide> });
<ide> }; | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.