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
|
|---|---|---|---|---|---|
Text
|
Text
|
add cola119 to collaborators
|
611e7711f4c711e7525853884e32b509d89474bb
|
<ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> **Colin Ihrig** <<cjihrig@gmail.com>> (he/him)
<ide> * [codebytere](https://github.com/codebytere) -
<ide> **Shelley Vohr** <<shelley.vohr@gmail.com>> (she/her)
<add>* [cola119](https://github.com/cola119) -
<add> **Kohei Ueno** <<kohei.ueno119@gmail.com>> (he/him)
<ide> * [danbev](https://github.com/danbev) -
<ide> **Daniel Bevenius** <<daniel.bevenius@gmail.com>> (he/him)
<ide> * [danielleadams](https://github.com/danielleadams) -
| 1
|
Java
|
Java
|
ignore failing map test case
|
a417aa2ea3f0e1bd9abd91bbc06c0fc750906259
|
<ide><path>org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/Spr7839Tests.java
<ide> import java.util.Map;
<ide>
<ide> import org.junit.Before;
<add>import org.junit.Ignore;
<ide> import org.junit.Test;
<ide> import org.springframework.core.convert.converter.Converter;
<ide> import org.springframework.core.convert.support.ConversionServiceFactory;
<ide> public void listElement() throws Exception {
<ide> }
<ide>
<ide> @Test
<add> public void listElementAutogrowObject() throws Exception {
<add> request.setRequestURI("/nested/listElement");
<add> request.addParameter("nested.list[0].foo", "Nested");
<add> adapter.handle(request, response, controller);
<add> }
<add>
<add> @Test
<add> public void listOfListsElement() throws Exception {
<add> request.setRequestURI("/nested/listOfLists");
<add> request.addParameter("nested.listOfLists[0][0]", "Nested");
<add> adapter.handle(request, response, controller);
<add> }
<add>
<add> @Test
<add> public void listOfListsElementAutogrowObject() throws Exception {
<add> request.setRequestURI("/nested/listOfLists");
<add> request.addParameter("nested.listOfLists[0][0].foo", "Nested");
<add> adapter.handle(request, response, controller);
<add> }
<add>
<add> @Test
<add> @Ignore
<ide> public void map() throws Exception {
<ide> request.setRequestURI("/nested/map");
<ide> request.addParameter("nested.map['apple'].foo", "bar");
<ide> public void handlerMap(JavaBean bean) {
<ide> public void handlerListElement(JavaBean bean) {
<ide> assertEquals("Nested", bean.nested.list.get(0).foo);
<ide> }
<add>
<add> @RequestMapping("/nested/listOfLists")
<add> public void handlerListOfLists(JavaBean bean) {
<add> assertEquals("Nested", bean.nested.listOfLists.get(0).get(0).foo);
<add> }
<ide>
<ide> }
<ide>
<ide> public static class NestedBean {
<ide> private String foo;
<ide>
<ide> private List<NestedBean> list;
<del>
<add>
<add> private List<List<NestedBean>> listOfLists;
<add>
<ide> private Map<String, NestedBean> map = new HashMap<String, NestedBean>();
<ide>
<ide> public NestedBean() {
<ide> public void setMap(Map<String, NestedBean> map) {
<ide> this.map = map;
<ide> }
<ide>
<del>
<add> public List<List<NestedBean>> getListOfLists() {
<add> return listOfLists;
<add> }
<add>
<add> public void setListOfLists(List<List<NestedBean>> listOfLists) {
<add> this.listOfLists = listOfLists;
<add> }
<ide>
<ide> }
<ide>
| 1
|
Javascript
|
Javascript
|
fix empty name problem in gltfloader
|
65089d82e7e5e5ac78d53efc5dbb206dbf590fcf
|
<ide><path>examples/js/loaders/GLTFLoader.js
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> texture.flipY = false;
<ide>
<del> if ( textureDef.name !== undefined ) texture.name = textureDef.name;
<add> if ( textureDef.name ) texture.name = textureDef.name;
<ide>
<ide> // Ignore unknown mime types, like DDS files.
<ide> if ( source.mimeType in MIME_TYPE_FORMATS ) {
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> }
<ide>
<del> if ( materialDef.name !== undefined ) material.name = materialDef.name;
<add> if ( materialDef.name ) material.name = materialDef.name;
<ide>
<ide> // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
<ide> if ( material.map ) material.map.encoding = THREE.sRGBEncoding;
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> }
<ide>
<del> if ( cameraDef.name !== undefined ) camera.name = cameraDef.name;
<add> if ( cameraDef.name ) camera.name = cameraDef.name;
<ide>
<ide> assignExtrasToUserData( camera, cameraDef );
<ide>
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> }
<ide>
<del> var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex;
<add> var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
<ide>
<ide> return new THREE.AnimationClip( name, undefined, tracks );
<ide>
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> }
<ide>
<del> if ( nodeDef.name !== undefined ) {
<add> if ( nodeDef.name ) {
<ide>
<ide> node.userData.name = nodeDef.name;
<ide> node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name );
<ide> THREE.GLTFLoader = ( function () {
<ide> var parser = this;
<ide>
<ide> var scene = new THREE.Scene();
<del> if ( sceneDef.name !== undefined ) scene.name = sceneDef.name;
<add> if ( sceneDef.name ) scene.name = sceneDef.name;
<ide>
<ide> assignExtrasToUserData( scene, sceneDef );
<ide>
<ide><path>examples/jsm/loaders/GLTFLoader.js
<ide> var GLTFLoader = ( function () {
<ide>
<ide> texture.flipY = false;
<ide>
<del> if ( textureDef.name !== undefined ) texture.name = textureDef.name;
<add> if ( textureDef.name ) texture.name = textureDef.name;
<ide>
<ide> // Ignore unknown mime types, like DDS files.
<ide> if ( source.mimeType in MIME_TYPE_FORMATS ) {
<ide> var GLTFLoader = ( function () {
<ide>
<ide> }
<ide>
<del> if ( materialDef.name !== undefined ) material.name = materialDef.name;
<add> if ( materialDef.name ) material.name = materialDef.name;
<ide>
<ide> // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
<ide> if ( material.map ) material.map.encoding = sRGBEncoding;
<ide> var GLTFLoader = ( function () {
<ide>
<ide> }
<ide>
<del> if ( cameraDef.name !== undefined ) camera.name = cameraDef.name;
<add> if ( cameraDef.name ) camera.name = cameraDef.name;
<ide>
<ide> assignExtrasToUserData( camera, cameraDef );
<ide>
<ide> var GLTFLoader = ( function () {
<ide>
<ide> }
<ide>
<del> var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex;
<add> var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
<ide>
<ide> return new AnimationClip( name, undefined, tracks );
<ide>
<ide> var GLTFLoader = ( function () {
<ide>
<ide> }
<ide>
<del> if ( nodeDef.name !== undefined ) {
<add> if ( nodeDef.name ) {
<ide>
<ide> node.userData.name = nodeDef.name;
<ide> node.name = PropertyBinding.sanitizeNodeName( nodeDef.name );
<ide> var GLTFLoader = ( function () {
<ide> var parser = this;
<ide>
<ide> var scene = new Scene();
<del> if ( sceneDef.name !== undefined ) scene.name = sceneDef.name;
<add> if ( sceneDef.name ) scene.name = sceneDef.name;
<ide>
<ide> assignExtrasToUserData( scene, sceneDef );
<ide>
| 2
|
Python
|
Python
|
add xfailing test for
|
aadf586789bba5df81540b6e1d6ab46bec087493
|
<ide><path>spacy/tests/regression/test_issue3331.py
<add># coding: utf-8
<add>from __future__ import unicode_literals
<add>
<add>import pytest
<add>from spacy.matcher import PhraseMatcher
<add>from spacy.tokens import Doc
<add>
<add>
<add>@pytest.mark.xfail
<add>def test_issue3331(en_vocab):
<add> """Test that duplicate patterns for different rules result in multiple
<add> matches, one per rule.
<add> """
<add> matcher = PhraseMatcher(en_vocab)
<add> matcher.add("A", None, Doc(en_vocab, words=["Barack", "Obama"]))
<add> matcher.add("B", None, Doc(en_vocab, words=["Barack", "Obama"]))
<add> doc = Doc(en_vocab, words=["Barack", "Obama", "lifts", "America"])
<add> matches = matcher(doc)
<add> assert len(matches) == 2
<add> match_ids = [en_vocab.strings[matches[0][0]], en_vocab.strings[matches[1][0]]]
<add> assert sorted(match_ids) == ["A", "B"]
| 1
|
Go
|
Go
|
remove redundant init() stub for windows
|
0e4f473a9f7f82a62c9e66023909243b2d08a601
|
<ide><path>pkg/chrootarchive/init_windows.go
<del>package chrootarchive // import "github.com/docker/docker/pkg/chrootarchive"
<del>
<del>func init() {
<del>}
| 1
|
Javascript
|
Javascript
|
expose isolatescope() getter similar to scope()
|
27e9340b3c25b512e45213b39811098d07e12e3b
|
<ide><path>src/Angular.js
<ide> function bindJQuery() {
<ide> jqLite = jQuery;
<ide> extend(jQuery.fn, {
<ide> scope: JQLitePrototype.scope,
<add> isolateScope: JQLitePrototype.isolateScope,
<ide> controller: JQLitePrototype.controller,
<ide> injector: JQLitePrototype.injector,
<ide> inheritedData: JQLitePrototype.inheritedData
<ide><path>src/jqLite.js
<ide> * - `injector()` - retrieves the injector of the current element or its parent.
<ide> * - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the current
<ide> * element or its parent.
<add> * - `isolateScope()` - retrieves an isolate {@link api/ng.$rootScope.Scope scope} if one is attached directly to the
<add> * current element. This getter should be used only on elements that contain a directive which starts a new isolate
<add> * scope. Calling `scope()` on this element always returns the original non-isolate scope.
<ide> * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
<ide> * parent element is reached.
<ide> *
<ide> function jqLiteInheritedData(element, name, value) {
<ide> if(element[0].nodeType == 9) {
<ide> element = element.find('html');
<ide> }
<add> var names = isArray(name) ? name : [name];
<ide>
<ide> while (element.length) {
<del> if ((value = element.data(name)) !== undefined) return value;
<add>
<add> for (var i = 0, ii = names.length; i < ii; i++) {
<add> if ((value = element.data(names[i])) !== undefined) return value;
<add> }
<ide> element = element.parent();
<ide> }
<ide> }
<ide> forEach({
<ide> inheritedData: jqLiteInheritedData,
<ide>
<ide> scope: function(element) {
<del> return jqLiteInheritedData(element, '$scope');
<add> // Can't use jqLiteData here directly so we stay compatible with jQuery!
<add> return jqLite(element).data('$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
<add> },
<add>
<add> isolateScope: function(element) {
<add> // Can't use jqLiteData here directly so we stay compatible with jQuery!
<add> return jqLite(element).data('$isolateScope') || jqLite(element).data('$isolateScopeNoTemplate');
<ide> },
<ide>
<ide> controller: jqLiteController ,
<ide><path>src/ng/compile.js
<ide> function $CompileProvider($provide) {
<ide> var $linkNode = jqLite(linkNode);
<ide>
<ide> isolateScope = scope.$new(true);
<del> $linkNode.data('$isolateScope', isolateScope);
<add>
<add> if (templateDirective && (templateDirective === newIsolateScopeDirective.$$originalDirective)) {
<add> $linkNode.data('$isolateScope', isolateScope) ;
<add> } else {
<add> $linkNode.data('$isolateScopeNoTemplate', isolateScope);
<add> }
<add>
<add>
<add>
<ide> safeAddClass($linkNode, 'ng-isolate-scope');
<ide>
<ide> forEach(newIsolateScopeDirective.scope, function(definition, scopeName) {
<ide> function $CompileProvider($provide) {
<ide> origAsyncDirective = directives.shift(),
<ide> // The fact that we have to copy and patch the directive seems wrong!
<ide> derivedSyncDirective = extend({}, origAsyncDirective, {
<del> templateUrl: null, transclude: null, replace: null
<add> templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
<ide> }),
<ide> templateUrl = (isFunction(origAsyncDirective.templateUrl))
<ide> ? origAsyncDirective.templateUrl($compileNode, tAttrs)
<ide><path>test/jqLiteSpec.js
<ide> describe('jqLite', function() {
<ide> dealoc(element);
<ide> });
<ide>
<add> it('should retrieve isolate scope attached to the current element', function() {
<add> var element = jqLite('<i>foo</i>');
<add> element.data('$isolateScope', scope);
<add> expect(element.isolateScope()).toBe(scope);
<add> dealoc(element);
<add> });
<add>
<ide> it('should retrieve scope attached to the html element if its requested on the document',
<ide> function() {
<ide> var doc = jqLite(document),
<ide> describe('jqLite', function() {
<ide> });
<ide>
<ide>
<add> describe('isolateScope', function() {
<add>
<add> it('should retrieve isolate scope attached to the current element', function() {
<add> var element = jqLite('<i>foo</i>');
<add> element.data('$isolateScope', scope);
<add> expect(element.isolateScope()).toBe(scope);
<add> dealoc(element);
<add> });
<add>
<add>
<add> it('should not walk up the dom to find scope', function() {
<add> var element = jqLite('<ul><li><p><b>deep deep</b><p></li></ul>');
<add> var deepChild = jqLite(element[0].getElementsByTagName('b')[0]);
<add> element.data('$isolateScope', scope);
<add> expect(deepChild.isolateScope()).toBeUndefined();
<add> dealoc(element);
<add> });
<add>
<add>
<add> it('should return undefined when no scope was found', function() {
<add> var element = jqLite('<div></div>');
<add> expect(element.isolateScope()).toBeFalsy();
<add> dealoc(element);
<add> });
<add> });
<add>
<add>
<ide> describe('injector', function() {
<ide> it('should retrieve injector attached to the current element or its parent', function() {
<ide> var template = jqLite('<div><span></span></div>'),
<ide><path>test/ng/compileSpec.js
<ide> describe('$compile', function() {
<ide> return function (scope, element) {
<ide> iscope = scope;
<ide> log(scope.$id);
<del> expect(element.data('$isolateScope')).toBe(scope);
<add> expect(element.data('$isolateScopeNoTemplate')).toBe(scope);
<ide> };
<ide> }
<ide> };
<ide> describe('$compile', function() {
<ide> );
<ide>
<ide>
<del> it('should allow more one new scope directives per element, but directives should share' +
<add> it('should allow more than one new scope directives per element, but directives should share' +
<ide> 'the scope', inject(
<ide> function($rootScope, $compile, log) {
<ide> element = $compile('<div class="scope-a; scope-b"></div>')($rootScope);
<ide> describe('$compile', function() {
<ide> expect(log).toEqual('002');
<ide> })
<ide> );
<add>
<add>
<add> describe('scope()/isolate() scope getters', function() {
<add>
<add> describe('with no directives', function() {
<add>
<add> it('should return the scope of the parent node', inject(
<add> function($rootScope, $compile) {
<add> element = $compile('<div></div>')($rootScope);
<add> expect(element.scope()).toBe($rootScope);
<add> })
<add> );
<add> });
<add>
<add>
<add> describe('with new scope directives', function() {
<add>
<add> it('should return the new scope at the directive element', inject(
<add> function($rootScope, $compile) {
<add> element = $compile('<div scope></div>')($rootScope);
<add> expect(element.scope().$parent).toBe($rootScope);
<add> })
<add> );
<add>
<add>
<add> it('should return the new scope for children in the original template', inject(
<add> function($rootScope, $compile) {
<add> element = $compile('<div scope><a></a></div>')($rootScope);
<add> expect(element.find('a').scope().$parent).toBe($rootScope);
<add> })
<add> );
<add>
<add>
<add> it('should return the new scope for children in the directive template', inject(
<add> function($rootScope, $compile, $httpBackend) {
<add> $httpBackend.expect('GET', 'tscope.html').respond('<a></a>');
<add> element = $compile('<div tscope></div>')($rootScope);
<add> $httpBackend.flush();
<add> expect(element.find('a').scope().$parent).toBe($rootScope);
<add> })
<add> );
<add> });
<add>
<add>
<add> describe('with isolate scope directives', function() {
<add>
<add> it('should return the root scope for directives at the root element', inject(
<add> function($rootScope, $compile) {
<add> element = $compile('<div iscope></div>')($rootScope);
<add> expect(element.scope()).toBe($rootScope);
<add> })
<add> );
<add>
<add>
<add> it('should return the non-isolate scope at the directive element', inject(
<add> function($rootScope, $compile) {
<add> var directiveElement;
<add> element = $compile('<div><div iscope></div></div>')($rootScope);
<add> directiveElement = element.children();
<add> expect(directiveElement.scope()).toBe($rootScope);
<add> expect(directiveElement.isolateScope().$parent).toBe($rootScope);
<add> })
<add> );
<add>
<add>
<add> it('should return the isolate scope for children in the original template', inject(
<add> function($rootScope, $compile) {
<add> element = $compile('<div iscope><a></a></div>')($rootScope);
<add> expect(element.find('a').scope()).toBe($rootScope); //xx
<add> })
<add> );
<add>
<add>
<add> it('should return the isolate scope for children in directive template', inject(
<add> function($rootScope, $compile, $httpBackend) {
<add> $httpBackend.expect('GET', 'tiscope.html').respond('<a></a>');
<add> element = $compile('<div tiscope></div>')($rootScope);
<add> expect(element.isolateScope()).toBeUndefined(); // this is the current behavior, not desired feature
<add> $httpBackend.flush();
<add> expect(element.find('a').scope()).toBe(element.isolateScope());
<add> expect(element.isolateScope()).not.toBe($rootScope);
<add> })
<add> );
<add> });
<add>
<add>
<add> describe('with isolate scope directives and directives that manually create a new scope', function() {
<add>
<add> it('should return the new scope at the directive element', inject(
<add> function($rootScope, $compile) {
<add> var directiveElement;
<add> element = $compile('<div><a ng-if="true" iscope></a></div>')($rootScope);
<add> $rootScope.$apply();
<add> directiveElement = element.find('a');
<add> expect(directiveElement.scope().$parent).toBe($rootScope);
<add> expect(directiveElement.scope()).not.toBe(directiveElement.isolateScope());
<add> })
<add> );
<add>
<add>
<add> it('should return the isolate scope for child elements', inject(
<add> function($rootScope, $compile, $httpBackend) {
<add> var directiveElement, child;
<add> $httpBackend.expect('GET', 'tiscope.html').respond('<span></span>');
<add> element = $compile('<div><a ng-if="true" tiscope></a></div>')($rootScope);
<add> $rootScope.$apply();
<add> $httpBackend.flush();
<add> directiveElement = element.find('a');
<add> child = directiveElement.find('span');
<add> expect(child.scope()).toBe(directiveElement.isolateScope());
<add> })
<add> );
<add> });
<add> });
<ide> });
<ide> });
<ide> });
<ide> describe('$compile', function() {
<ide> });
<ide> }));
<ide>
<add>
<ide> it('should give other directives the parent scope', inject(function($rootScope) {
<ide> compile('<div><input type="text" my-component store-scope ng-model="value"></div>');
<ide> $rootScope.$apply(function() {
<ide> describe('$compile', function() {
<ide> expect(componentScope.$parent).toBe(regularScope)
<ide> }));
<ide>
<add>
<ide> it('should not give the isolate scope to other directive template', function() {
<ide> module(function() {
<ide> directive('otherTplDir', function() {
| 5
|
Javascript
|
Javascript
|
add object#fromentries polyfill
|
4199da09b8211a6687ca1ea4acbde6a1d597c576
|
<ide><path>packages/next-polyfill-module/src/index.js
<ide> if (!Promise.prototype.finally) {
<ide> )
<ide> }
<ide> }
<add>
<add>/**
<add> * Available in:
<add> * Edge: never
<add> * Firefox: 63
<add> * Chrome: 73
<add> * Safari: 12.1
<add> *
<add> * https://caniuse.com/mdn-javascript_builtins_object_fromentries
<add> */
<add>// Modified from https://github.com/tc39/proposal-object-from-entries/blob/main/polyfill.js
<add>// Modified from https://github.com/feross/fromentries/blob/29b52a850bb3a47c390937631c2638edf3443942/index.js
<add>// License MIT
<add>if (!Object.fromEntries) {
<add> Object.fromEntries = function (iterable) {
<add> // Assume the input is either an iterable object or an array-like object
<add> return Array.from(iterable).reduce(function (obj, entry) {
<add> // https://github.com/tc39/proposal-object-from-entries/blob/e4837799c1586a07c101570b27997497e5290c22/polyfill.js#L9-L10
<add> // contract is that entry has "0" and "1" keys, not that it is an array or iterable.
<add> obj[entry[0]] = entry[1]
<add> return obj
<add> }, {})
<add> }
<add>}
| 1
|
Python
|
Python
|
fix the method defaults for _construct_volume
|
791a175988c78c920df733fc79c40c1b0579b688
|
<ide><path>airflow/kubernetes/worker_configuration.py
<ide> def _get_volume_mounts(self) -> List[k8s.V1VolumeMount]:
<ide> return list(volume_mounts.values())
<ide>
<ide> def _get_volumes(self) -> List[k8s.V1Volume]:
<del> def _construct_volume(name, claim, host) -> k8s.V1Volume:
<add> def _construct_volume(name: str, claim: str = '', host: str = '') -> k8s.V1Volume:
<ide> volume = k8s.V1Volume(name=name)
<ide>
<ide> if claim:
| 1
|
Javascript
|
Javascript
|
add pending deprecation warning
|
d2d32ea5a22a30f428a6e08bcb707c3538558933
|
<ide><path>lib/buffer.js
<ide> 'use strict';
<ide>
<ide> const binding = process.binding('buffer');
<add>const config = process.binding('config');
<ide> const { compare: compare_, compareOffset } = binding;
<ide> const { isAnyArrayBuffer, isUint8Array } = process.binding('util');
<ide> const bindingObj = {};
<ide> const internalUtil = require('internal/util');
<add>const pendingDeprecation = !!config.pendingDeprecation;
<ide>
<ide> class FastBuffer extends Uint8Array {
<ide> constructor(arg1, arg2, arg3) {
<ide> super(arg1, arg2, arg3);
<ide> }
<ide> }
<del>
<ide> FastBuffer.prototype.constructor = Buffer;
<add>
<ide> Buffer.prototype = FastBuffer.prototype;
<ide>
<ide> exports.Buffer = Buffer;
<ide> function alignPool() {
<ide> }
<ide> }
<ide>
<add>var bufferWarn = true;
<add>const bufferWarning = 'The Buffer() and new Buffer() constructors are not ' +
<add> 'recommended for use due to security and usability ' +
<add> 'concerns. Please use the new Buffer.alloc(), ' +
<add> 'Buffer.allocUnsafe(), or Buffer.from() construction ' +
<add> 'methods instead.';
<add>
<add>function showFlaggedDeprecation() {
<add> if (bufferWarn) {
<add> // This is a *pending* deprecation warning. It is not emitted by
<add> // default unless the --pending-deprecation command-line flag is
<add> // used or the NODE_PENDING_DEPRECATION=1 envvar is set.
<add> process.emitWarning(bufferWarning, 'DeprecationWarning', 'DEP0005');
<add> bufferWarn = false;
<add> }
<add>}
<add>
<add>const doFlaggedDeprecation =
<add> pendingDeprecation ?
<add> showFlaggedDeprecation :
<add> function() {};
<add>
<ide> /**
<ide> * The Buffer() construtor is deprecated in documentation and should not be
<ide> * used moving forward. Rather, developers should use one of the three new
<ide> function alignPool() {
<ide> * Deprecation Code: DEP0005
<ide> **/
<ide> function Buffer(arg, encodingOrOffset, length) {
<add> doFlaggedDeprecation();
<ide> // Common case.
<ide> if (typeof arg === 'number') {
<ide> if (typeof encodingOrOffset === 'string') {
<ide> function Buffer(arg, encodingOrOffset, length) {
<ide> return Buffer.from(arg, encodingOrOffset, length);
<ide> }
<ide>
<add>Object.defineProperty(Buffer, Symbol.species, {
<add> enumerable: false,
<add> configurable: true,
<add> get() { return FastBuffer; }
<add>});
<add>
<ide> /**
<ide> * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
<ide> * if value is a number.
<ide><path>test/parallel/test-buffer-nopendingdep-map.js
<add>// Flags: --no-warnings --pending-deprecation
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const Buffer = require('buffer').Buffer;
<add>
<add>process.on('warning', common.mustNotCall('A warning should not be emitted'));
<add>
<add>// With the --pending-deprecation flag, the deprecation warning for
<add>// new Buffer() should not be emitted when Uint8Array methods are called.
<add>
<add>Buffer.from('abc').map((i) => i);
<add>Buffer.from('abc').filter((i) => i);
<add>Buffer.from('abc').slice(1, 2);
<ide><path>test/parallel/test-buffer-pending-deprecation.js
<add>// Flags: --pending-deprecation --no-warnings
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const Buffer = require('buffer').Buffer;
<add>
<add>const bufferWarning = 'The Buffer() and new Buffer() constructors are not ' +
<add> 'recommended for use due to security and usability ' +
<add> 'concerns. Please use the new Buffer.alloc(), ' +
<add> 'Buffer.allocUnsafe(), or Buffer.from() construction ' +
<add> 'methods instead.';
<add>
<add>common.expectWarning('DeprecationWarning', bufferWarning);
<add>
<add>new Buffer(10);
| 3
|
Text
|
Text
|
remove personal pronoun usage in addons.md
|
36ce039347e94a9a0f8239c7bc639868e496258d
|
<ide><path>doc/api/addons.md
<ide> Addons are dynamically-linked shared objects written in C++. The
<ide> Addons provide an interface between JavaScript and C/C++ libraries.
<ide>
<ide> There are three options for implementing Addons: N-API, nan, or direct
<del>use of internal V8, libuv and Node.js libraries. Unless you need direct
<del>access to functionality which is not exposed by N-API, use N-API.
<add>use of internal V8, libuv and Node.js libraries. Unless there is a need for
<add>direct access to functionality which is not exposed by N-API, use N-API.
<ide> Refer to [C/C++ Addons with N-API](n-api.html) for more information on N-API.
<ide>
<ide> When not using N-API, implementing Addons is complicated,
| 1
|
Javascript
|
Javascript
|
pass unsupported messages to original console
|
bccc4548e4d22b275f28a9beaf573f74d8b69213
|
<ide><path>Libraries/polyfills/console.js
<ide> if (global.nativeLoggingHook) {
<ide> };
<ide> }
<ide> });
<add>
<add> // The following methods are not supported by this polyfill but
<add> // we still should pass them to original console if they are
<add> // supported by it.
<add> [
<add> 'assert',
<add> 'clear',
<add> 'dir',
<add> 'dirxml',
<add> 'groupCollapsed',
<add> 'profile',
<add> 'profileEnd',
<add> ].forEach(methodName => {
<add> if (typeof originalConsole[methodName] === 'function') {
<add> console[methodName] = function() {
<add> originalConsole[methodName](...arguments);
<add> };
<add> }
<add> });
<ide> }
<ide> } else if (!global.console) {
<ide> const log = global.print || function consoleLoggingStub() {};
| 1
|
Text
|
Text
|
add a . to increase readability
|
906d5297c2ec22d6410e0b0f65d4eca47fecf098
|
<ide><path>README.md
<ide> See [CONTRIBUTING.md](https://github.com/emberjs/ember.js/blob/master/CONTRIBUTI
<ide>
<ide> 3. Then visit <http://localhost:4200/>. This will run all tests.
<ide>
<del>4. To test a specific package visit `http://localhost:4200/tests/index.html?package=PACKAGE_NAME` Replace
<add>4. To test a specific package visit `http://localhost:4200/tests/index.html?package=PACKAGE_NAME`. Replace
<ide> `PACKAGE_NAME` with the name of the package you want to test. For
<ide> example:
<ide>
| 1
|
Ruby
|
Ruby
|
construct formula object correctly
|
579f288bd2507d781d315e9fcc56ea6d52eaefee
|
<ide><path>Library/Homebrew/cmd/test-bot.rb
<ide> def test_bot
<ide> Dir.glob("*.bottle*.tar.gz") do |filename|
<ide> # Skip taps for now until we're using Bintray for Homebrew/homebrew
<ide> next if tap
<del> formula = bottle_filename_formula_name filename
<del> existing_bottles[formula.name] = !!formula.bottle
<add> formula_name = bottle_filename_formula_name filename
<add> formula = Formulary.factory formula_name
<add> existing_bottles[formula_name] = !!formula.bottle
<ide> end
<ide>
<ide> ENV["GIT_AUTHOR_NAME"] = ENV["GIT_COMMITTER_NAME"]
<ide> def test_bot
<ide> next if tap
<ide> version = BottleVersion.parse(filename).to_s
<ide> formula = bottle_filename_formula_name filename
<del> existing_bottle = existing_bottles[formula.name]
<add> existing_bottle = existing_bottles[formula]
<ide>
<ide> repo_url = "https://api.bintray.com/packages/homebrew/#{repo}"
<ide> package_url = "#{repo_url}/#{formula}"
| 1
|
Mixed
|
Python
|
add fp16 training
|
66b0090877db3f9b65f24b21400f1e29a23f72d6
|
<ide><path>README.md
<ide> python -m pytest -sv tests/
<ide>
<ide> BERT-base and BERT-large are respectively 110M and 340M parameters models and it can be difficult to fine-tune them on a single GPU with the recommended batch size for good performance (in most case a batch size of 32).
<ide>
<del>To help with fine-tuning these models, we have included four techniques that you can activate in the fine-tuning scripts `run_classifier.py` and `run_squad.py`: optimize on CPU, gradient-accumulation, multi-gpu and distributed training. For more details on how to use these techniques you can read [the tips on training large batches in PyTorch](https://medium.com/huggingface/training-larger-batches-practical-tips-on-1-gpu-multi-gpu-distributed-setups-ec88c3e51255) that I published earlier this month.
<add>To help with fine-tuning these models, we have included five techniques that you can activate in the fine-tuning scripts `run_classifier.py` and `run_squad.py`: gradient-accumulation, multi-gpu training, distributed training, optimize on CPU and 16-bits training . For more details on how to use these techniques you can read [the tips on training large batches in PyTorch](https://medium.com/huggingface/training-larger-batches-practical-tips-on-1-gpu-multi-gpu-distributed-setups-ec88c3e51255) that I published earlier this month.
<ide>
<ide> Here is how to use these techniques in our scripts:
<ide>
<del>- **Optimize on CPU**: The Adam optimizer comprise 2 moving average of all the weights of the model which means that if you keep them on GPU 1 (typical behavior), your first GPU will have to store 3-times the size of the model. This is not optimal when using a large model like `BERT-large` and means your batch size is a lot lower than it could be. This option will perform the optimization and store the averages on the CPU to free more room on the GPU(s). As the most computational intensive operation is the backward pass, this usually doesn't increase the computation time by a lot. This is the only way to fine-tune `BERT-large` in a reasonable time on GPU(s) (see below). Activate this option with `--optimize_on_cpu` on the `run_squad.py` script.
<ide> - **Gradient Accumulation**: Gradient accumulation can be used by supplying a integer greater than 1 to the `--gradient_accumulation_steps` argument. The batch at each step will be divided by this integer and gradient will be accumulated over `gradient_accumulation_steps` steps.
<ide> - **Multi-GPU**: Multi-GPU is automatically activated when several GPUs are detected and the batches are splitted over the GPUs.
<del>- **Distributed training**: Distributed training can be activated by supplying an integer greater or equal to 0 to the `--local_rank` argument. To use Distributed training, you will need to run one training script on each of your machines. This can be done for example by running the following command on each server (see the above blog post for more details):
<add>- **Distributed training**: Distributed training can be activated by supplying an integer greater or equal to 0 to the `--local_rank` argument.
<add>- **Optimize on CPU**: The Adam optimizer comprise 2 moving average of all the weights of the model which means that if you keep them on GPU 1 (typical behavior), your first GPU will have to store 3-times the size of the model. This is not optimal when using a large model like `BERT-large` and means your batch size is a lot lower than it could be. This option will perform the optimization and store the averages on the CPU to free more room on the GPU(s). As the most computational intensive operation is the backward pass, this usually doesn't increase the computation time by a lot. This is the only way to fine-tune `BERT-large` in a reasonable time on GPU(s) (see below). Activate this option with `--optimize_on_cpu` on the `run_squad.py` script.
<add>- **16-bits training**: 16-bits training, also called mixed-precision training, can reduce the memory requirement of your model on the GPU by a factor of 2, basically allowing to double the batch size. If you have a recent GPU (starting from NVIDIA Volta architecture) you should see no decrease in speed. 16bits training natively incoporate the behavior of `--optimize_on_gpu` so it's not needed to have the two flags at the same time. A good introduction to Mixed precision training can be found [here](https://devblogs.nvidia.com/mixed-precision-training-deep-neural-networks/) and a full documentation is [here](https://docs.nvidia.com/deeplearning/sdk/mixed-precision-training/index.html). In our scripts, this option can be activated by setting the `--fp16` flag and you can play with loss scaling using the `--loss_scaling` flag (see the previously linked documentation for details on loss scaling). If the loss scaling is too high (`Nan` in the gradients) it will be automatically scaled down until the value is acceptable. The default loss scaling is 128 which behaved nicely in our tests.
<ide>
<add>Note: To use *Distributed Training*, you will need to run one training script on each of your machines. This can be done for example by running the following command on each server (see [the above mentioned blog post]((https://medium.com/huggingface/training-larger-batches-practical-tips-on-1-gpu-multi-gpu-distributed-setups-ec88c3e51255)) for more details):
<ide> ```bash
<ide> python -m torch.distributed.launch --nproc_per_node=4 --nnodes=2 --node_rank=$THIS_MACHINE_INDEX --master_addr="192.168.1.1" --master_port=1234 run_classifier.py (--arg1 --arg2 --arg3 and all other arguments of the run_classifier script)
<ide> ```
<del>
<ide> Where `$THIS_MACHINE_INDEX` is an sequential index assigned to each of your machine (0, 1, 2...) and the machine with rank 0 has an IP address `192.168.1.1` and an open port `1234`.
<ide>
<ide> ## TPU support and pretraining scripts
<ide> To get these results we used a combination of:
<ide> - 2 steps of gradient accumulation and
<ide> - perform the optimization step on CPU to store Adam's averages in RAM.
<ide>
<del>Here are the full list of hyper-parameters for this run:
<add>Here is the full list of hyper-parameters for this run:
<ide> ```bash
<ide> python ./run_squad.py \
<ide> --vocab_file $BERT_LARGE_DIR/vocab.txt \
<ide><path>modeling.py
<ide> def forward(self, input_ids, token_type_ids=None, attention_mask=None):
<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> # effectively the same as removing these entirely.
<del> extended_attention_mask = extended_attention_mask.float()
<add> extended_attention_mask = extended_attention_mask.to(dtype=next(self.parameters()).dtype) # fp16 compatibility
<ide> extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
<ide>
<ide> embedding_output = self.embeddings(input_ids, token_type_ids)
<ide><path>run_classifier.py
<ide> def accuracy(out, labels):
<ide> outputs = np.argmax(out, axis=1)
<ide> return np.sum(outputs==labels)
<ide>
<add>def copy_optimizer_params_to_model(named_params_model, named_params_optimizer):
<add> """ Utility function for optimize_on_cpu and 16-bits training.
<add> Copy the parameters optimized on CPU/RAM back to the model on GPU
<add> """
<add> for (name_opti, param_opti), (name_model, param_model) in zip(named_params_optimizer, named_params_model):
<add> if name_opti != name_model:
<add> logger.error("name_opti != name_model: {} {}".format(name_opti, name_model))
<add> raise ValueError
<add> param_model.data.copy_(param_opti.data)
<add>
<add>def set_optimizer_params_grad(named_params_optimizer, named_params_model, test_nan=False):
<add> """ Utility function for optimize_on_cpu and 16-bits training.
<add> Copy the gradient of the GPU parameters to the CPU/RAMM copy of the model
<add> """
<add> is_nan = False
<add> for (name_opti, param_opti), (name_model, param_model) in zip(named_params_optimizer, named_params_model):
<add> if name_opti != name_model:
<add> logger.error("name_opti != name_model: {} {}".format(name_opti, name_model))
<add> raise ValueError
<add> if test_nan and torch.isnan(param_model.grad).sum() > 0:
<add> is_nan = True
<add> if param_opti.grad is None:
<add> param_opti.grad = torch.nn.Parameter(param_opti.data.new().resize_(*param_opti.data.size()))
<add> param_opti.grad.data.copy_(param_model.grad.data)
<add> return is_nan
<add>
<ide> def main():
<ide> parser = argparse.ArgumentParser()
<ide>
<ide> def main():
<ide> type=int,
<ide> default=1,
<ide> help="Number of updates steps to accumualte before performing a backward/update pass.")
<add> parser.add_argument('--optimize_on_cpu',
<add> default=False,
<add> action='store_true',
<add> help="Whether to perform optimization and keep the optimizer averages on CPU")
<add> parser.add_argument('--fp16',
<add> default=False,
<add> action='store_true',
<add> help="Whether to use 16-bit float precision instead of 32-bit")
<add> parser.add_argument('--loss_scale',
<add> type=float, default=128,
<add> help='Loss scaling, positive power of 2 values can improve fp16 convergence.')
<add>
<ide> args = parser.parse_args()
<ide>
<ide> processors = {
<ide> def main():
<ide> n_gpu = 1
<ide> # Initializes the distributed backend which will take care of sychronizing nodes/GPUs
<ide> torch.distributed.init_process_group(backend='nccl')
<add> if args.fp16:
<add> logger.info("16-bits training currently not supported in distributed training")
<add> args.fp16 = False # (see https://github.com/pytorch/pytorch/pull/13496)
<ide> logger.info("device %s n_gpu %d distributed training %r", device, n_gpu, bool(args.local_rank != -1))
<ide>
<ide> if args.gradient_accumulation_steps < 1:
<ide> def main():
<ide> num_train_steps = int(
<ide> len(train_examples) / args.train_batch_size / args.gradient_accumulation_steps * args.num_train_epochs)
<ide>
<add> # Prepare model
<ide> model = BertForSequenceClassification(bert_config, len(label_list))
<ide> if args.init_checkpoint is not None:
<ide> model.bert.load_state_dict(torch.load(args.init_checkpoint, map_location='cpu'))
<add> if args.fp16:
<add> model.half()
<ide> model.to(device)
<del>
<ide> if args.local_rank != -1:
<ide> model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank],
<ide> output_device=args.local_rank)
<ide> elif n_gpu > 1:
<ide> model = torch.nn.DataParallel(model)
<ide>
<add> # Prepare optimizer
<add> if args.fp16:
<add> param_optimizer = [(n, param.clone().detach().to('cpu').float().requires_grad_()) \
<add> for n, param in model.named_parameters()]
<add> elif args.optimize_on_cpu:
<add> param_optimizer = [(n, param.clone().detach().to('cpu').requires_grad_()) \
<add> for n, param in model.named_parameters()]
<add> else:
<add> param_optimizer = list(model.named_parameters())
<ide> no_decay = ['bias', 'gamma', 'beta']
<del> optimizer_parameters = [
<del> {'params': [p for n, p in model.named_parameters() if n not in no_decay], 'weight_decay_rate': 0.01},
<del> {'params': [p for n, p in model.named_parameters() if n in no_decay], 'weight_decay_rate': 0.0}
<add> optimizer_grouped_parameters = [
<add> {'params': [p for n, p in param_optimizer if n not in no_decay], 'weight_decay_rate': 0.01},
<add> {'params': [p for n, p in param_optimizer if n in no_decay], 'weight_decay_rate': 0.0}
<ide> ]
<del>
<del> optimizer = BERTAdam(optimizer_parameters,
<add> optimizer = BERTAdam(optimizer_grouped_parameters,
<ide> lr=args.learning_rate,
<ide> warmup=args.warmup_proportion,
<ide> t_total=num_train_steps)
<ide> def main():
<ide> logger.info(" Num examples = %d", len(train_examples))
<ide> logger.info(" Batch size = %d", args.train_batch_size)
<ide> logger.info(" Num steps = %d", num_train_steps)
<del>
<ide> all_input_ids = torch.tensor([f.input_ids for f in train_features], dtype=torch.long)
<ide> all_input_mask = torch.tensor([f.input_mask for f in train_features], dtype=torch.long)
<ide> all_segment_ids = torch.tensor([f.segment_ids for f in train_features], dtype=torch.long)
<ide> all_label_ids = torch.tensor([f.label_id for f in train_features], dtype=torch.long)
<del>
<ide> train_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids)
<ide> if args.local_rank == -1:
<ide> train_sampler = RandomSampler(train_data)
<ide> def main():
<ide> loss, _ = model(input_ids, segment_ids, input_mask, label_ids)
<ide> if n_gpu > 1:
<ide> loss = loss.mean() # mean() to average on multi-gpu.
<add> if args.fp16 and args.loss_scale != 1.0:
<add> # rescale loss for fp16 training
<add> # see https://docs.nvidia.com/deeplearning/sdk/mixed-precision-training/index.html
<add> loss = loss * args.loss_scale
<ide> if args.gradient_accumulation_steps > 1:
<ide> loss = loss / args.gradient_accumulation_steps
<ide> loss.backward()
<ide> tr_loss += loss.item()
<ide> nb_tr_examples += input_ids.size(0)
<ide> nb_tr_steps += 1
<ide> if (step + 1) % args.gradient_accumulation_steps == 0:
<del> optimizer.step() # We have accumulated enought gradients
<add> if args.fp16 or args.optimize_on_cpu:
<add> if args.fp16 and args.loss_scale != 1.0:
<add> # scale down gradients for fp16 training
<add> for param in model.parameters():
<add> param.grad.data = param.grad.data / args.loss_scale
<add> is_nan = set_optimizer_params_grad(param_optimizer, model.named_parameters(), test_nan=True)
<add> if is_nan:
<add> logger.info("FP16 TRAINING: Nan in gradients, reducing loss scaling")
<add> args.loss_scale = args.loss_scale / 2
<add> model.zero_grad()
<add> continue
<add> optimizer.step()
<add> copy_optimizer_params_to_model(model.named_parameters(), param_optimizer)
<add> else:
<add> optimizer.step()
<ide> model.zero_grad()
<ide> global_step += 1
<ide>
<ide> if args.do_eval:
<ide> eval_examples = processor.get_dev_examples(args.data_dir)
<ide> eval_features = convert_examples_to_features(
<ide> eval_examples, label_list, args.max_seq_length, tokenizer)
<del>
<ide> logger.info("***** Running evaluation *****")
<ide> logger.info(" Num examples = %d", len(eval_examples))
<ide> logger.info(" Batch size = %d", args.eval_batch_size)
<del>
<ide> all_input_ids = torch.tensor([f.input_ids for f in eval_features], dtype=torch.long)
<ide> all_input_mask = torch.tensor([f.input_mask for f in eval_features], dtype=torch.long)
<ide> all_segment_ids = torch.tensor([f.segment_ids for f in eval_features], dtype=torch.long)
<ide> all_label_ids = torch.tensor([f.label_id for f in eval_features], dtype=torch.long)
<del>
<ide> eval_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids)
<ide> if args.local_rank == -1:
<ide> eval_sampler = SequentialSampler(eval_data)
<ide><path>run_squad.py
<ide> def _compute_softmax(scores):
<ide> probs.append(score / total_sum)
<ide> return probs
<ide>
<add>def copy_optimizer_params_to_model(named_params_model, named_params_optimizer):
<add> """ Utility function for optimize_on_cpu and 16-bits training.
<add> Copy the parameters optimized on CPU/RAM back to the model on GPU
<add> """
<add> for (name_opti, param_opti), (name_model, param_model) in zip(named_params_optimizer, named_params_model):
<add> if name_opti != name_model:
<add> logger.error("name_opti != name_model: {} {}".format(name_opti, name_model))
<add> raise ValueError
<add> param_model.data.copy_(param_opti.data)
<add>
<add>def set_optimizer_params_grad(named_params_optimizer, named_params_model, test_nan=False):
<add> """ Utility function for optimize_on_cpu and 16-bits training.
<add> Copy the gradient of the GPU parameters to the CPU/RAMM copy of the model
<add> """
<add> is_nan = False
<add> for (name_opti, param_opti), (name_model, param_model) in zip(named_params_optimizer, named_params_model):
<add> if name_opti != name_model:
<add> logger.error("name_opti != name_model: {} {}".format(name_opti, name_model))
<add> raise ValueError
<add> if test_nan and torch.isnan(param_model.grad).sum() > 0:
<add> is_nan = True
<add> if param_opti.grad is None:
<add> param_opti.grad = torch.nn.Parameter(param_opti.data.new().resize_(*param_opti.data.size()))
<add> param_opti.grad.data.copy_(param_model.grad.data)
<add> return is_nan
<ide>
<ide> def main():
<ide> parser = argparse.ArgumentParser()
<ide> def main():
<ide> default=False,
<ide> action='store_true',
<ide> help="Whether to use 16-bit float precision instead of 32-bit")
<del>
<add> parser.add_argument('--loss_scale',
<add> type=float, default=128,
<add> help='Loss scaling, positive power of 2 values can improve fp16 convergence.')
<ide>
<ide> args = parser.parse_args()
<ide>
<ide> def main():
<ide> n_gpu = 1
<ide> # Initializes the distributed backend which will take care of sychronizing nodes/GPUs
<ide> torch.distributed.init_process_group(backend='nccl')
<del> logger.info("device %s n_gpu %d distributed training %r", device, n_gpu, bool(args.local_rank != -1))
<add> if args.fp16:
<add> logger.info("16-bits training currently not supported in distributed training")
<add> args.fp16 = False # (see https://github.com/pytorch/pytorch/pull/13496)
<add> logger.info("device: {} n_gpu: {}, distributed training: {}, 16-bits trainiing: {}".format(
<add> device, n_gpu, bool(args.local_rank != -1), args.fp16))
<ide>
<ide> if args.gradient_accumulation_steps < 1:
<ide> raise ValueError("Invalid gradient_accumulation_steps parameter: {}, should be >= 1".format(
<ide> def main():
<ide> num_train_steps = int(
<ide> len(train_examples) / args.train_batch_size / args.gradient_accumulation_steps * args.num_train_epochs)
<ide>
<add> # Prepare model
<ide> model = BertForQuestionAnswering(bert_config)
<ide> if args.init_checkpoint is not None:
<ide> model.bert.load_state_dict(torch.load(args.init_checkpoint, map_location='cpu'))
<ide> if args.fp16:
<ide> model.half()
<del>
<del> if not args.optimize_on_cpu:
<del> model.to(device)
<del> no_decay = ['bias', 'gamma', 'beta']
<del> optimizer_parameters = [
<del> {'params': [p for n, p in model.named_parameters() if n not in no_decay], 'weight_decay_rate': 0.01},
<del> {'params': [p for n, p in model.named_parameters() if n in no_decay], 'weight_decay_rate': 0.0}
<del> ]
<del> optimizer = BERTAdam(optimizer_parameters,
<del> lr=args.learning_rate,
<del> warmup=args.warmup_proportion,
<del> t_total=num_train_steps)
<del>
<ide> model.to(device)
<ide> if args.local_rank != -1:
<ide> model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank],
<ide> output_device=args.local_rank)
<ide> elif n_gpu > 1:
<ide> model = torch.nn.DataParallel(model)
<ide>
<add> # Prepare optimizer
<add> if args.fp16:
<add> param_optimizer = [(n, param.clone().detach().to('cpu').float().requires_grad_()) \
<add> for n, param in model.named_parameters()]
<add> elif args.optimize_on_cpu:
<add> param_optimizer = [(n, param.clone().detach().to('cpu').requires_grad_()) \
<add> for n, param in model.named_parameters()]
<add> else:
<add> param_optimizer = list(model.named_parameters())
<add> no_decay = ['bias', 'gamma', 'beta']
<add> optimizer_grouped_parameters = [
<add> {'params': [p for n, p in param_optimizer if n not in no_decay], 'weight_decay_rate': 0.01},
<add> {'params': [p for n, p in param_optimizer if n in no_decay], 'weight_decay_rate': 0.0}
<add> ]
<add> optimizer = BERTAdam(optimizer_grouped_parameters,
<add> lr=args.learning_rate,
<add> warmup=args.warmup_proportion,
<add> t_total=num_train_steps)
<add>
<ide> global_step = 0
<ide> if args.do_train:
<ide> train_features = convert_examples_to_features(
<ide> def main():
<ide> logger.info(" Num split examples = %d", len(train_features))
<ide> logger.info(" Batch size = %d", args.train_batch_size)
<ide> logger.info(" Num steps = %d", num_train_steps)
<del>
<ide> all_input_ids = torch.tensor([f.input_ids for f in train_features], dtype=torch.long)
<ide> all_input_mask = torch.tensor([f.input_mask for f in train_features], dtype=torch.long)
<ide> all_segment_ids = torch.tensor([f.segment_ids for f in train_features], dtype=torch.long)
<ide> all_start_positions = torch.tensor([f.start_position for f in train_features], dtype=torch.long)
<ide> all_end_positions = torch.tensor([f.end_position for f in train_features], dtype=torch.long)
<del>
<del> if args.fp16:
<del> (all_input_ids, all_input_mask,
<del> all_segment_ids, all_start_positions,
<del> all_end_positions) = tuple(t.half() for t in (all_input_ids, all_input_mask, all_segment_ids,
<del> all_start_positions, all_end_positions))
<del>
<ide> train_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids,
<ide> all_start_positions, all_end_positions)
<ide> if args.local_rank == -1:
<ide> def main():
<ide> model.train()
<ide> for _ in trange(int(args.num_train_epochs), desc="Epoch"):
<ide> for step, batch in enumerate(tqdm(train_dataloader, desc="Iteration")):
<del> batch = tuple(t.to(device) for t in batch)
<add> if n_gpu == 1:
<add> batch = tuple(t.to(device) for t in batch) # multi-gpu does scattering it-self
<ide> input_ids, input_mask, segment_ids, start_positions, end_positions = batch
<ide> loss = model(input_ids, segment_ids, input_mask, start_positions, end_positions)
<ide> if n_gpu > 1:
<ide> loss = loss.mean() # mean() to average on multi-gpu.
<add> if args.fp16 and args.loss_scale != 1.0:
<add> # rescale loss for fp16 training
<add> # see https://docs.nvidia.com/deeplearning/sdk/mixed-precision-training/index.html
<add> loss = loss * args.loss_scale
<ide> if args.gradient_accumulation_steps > 1:
<ide> loss = loss / args.gradient_accumulation_steps
<ide> loss.backward()
<ide> if (step + 1) % args.gradient_accumulation_steps == 0:
<del> if args.optimize_on_cpu:
<del> model.to('cpu')
<del> optimizer.step() # We have accumulated enought gradients
<add> if args.fp16 or args.optimize_on_cpu:
<add> if args.fp16 and args.loss_scale != 1.0:
<add> # scale down gradients for fp16 training
<add> for param in model.parameters():
<add> param.grad.data = param.grad.data / args.loss_scale
<add> is_nan = set_optimizer_params_grad(param_optimizer, model.named_parameters(), test_nan=True)
<add> if is_nan:
<add> logger.info("FP16 TRAINING: Nan in gradients, reducing loss scaling")
<add> args.loss_scale = args.loss_scale / 2
<add> model.zero_grad()
<add> continue
<add> optimizer.step()
<add> copy_optimizer_params_to_model(model.named_parameters(), param_optimizer)
<add> else:
<add> optimizer.step()
<ide> model.zero_grad()
<del> if args.optimize_on_cpu:
<del> model.to(device)
<ide> global_step += 1
<ide>
<ide> if args.do_predict:
<ide> def main():
<ide> all_input_mask = torch.tensor([f.input_mask for f in eval_features], dtype=torch.long)
<ide> all_segment_ids = torch.tensor([f.segment_ids for f in eval_features], dtype=torch.long)
<ide> all_example_index = torch.arange(all_input_ids.size(0), dtype=torch.long)
<del> if args.fp16:
<del> (all_input_ids, all_input_mask,
<del> all_segment_ids, all_example_index) = tuple(t.half() for t in (all_input_ids, all_input_mask,
<del> all_segment_ids, all_example_index))
<del>
<ide> eval_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_example_index)
<ide> if args.local_rank == -1:
<ide> eval_sampler = SequentialSampler(eval_data)
| 4
|
Text
|
Text
|
use the rails binary when generating task
|
8f57b22025999e6911399d81b93ac145ec674bef
|
<ide><path>guides/source/command_line.md
<ide> The `tmp:` namespaced tasks will help you clear and create the `Rails.root/tmp`
<ide> ### Custom Rake Tasks
<ide>
<ide> Custom rake tasks have a `.rake` extension and are placed in
<del>`Rails.root/lib/tasks`. You can create these custom rake tasks with the `rails
<del>generate task` command.
<add>`Rails.root/lib/tasks`. You can create these custom rake tasks with the
<add>`bin/rails generate task` command.
<ide>
<ide> ```ruby
<ide> desc "I am short, but comprehensive description for my cool task"
| 1
|
Javascript
|
Javascript
|
remove unnecessary warnings
|
849e8328b596ce67720f33d73a1d57108e6de504
|
<ide><path>packages/react-dom/src/__tests__/ReactCompositeComponent-test.js
<ide> describe('ReactCompositeComponent', () => {
<ide> ReactDOM.render(<Component prop={123} />, container);
<ide> });
<ide>
<del> it('should warn about `setState` in getChildContext', () => {
<del> const container = document.createElement('div');
<del>
<del> let renderPasses = 0;
<del>
<del> class Component extends React.Component {
<del> state = {value: 0};
<del>
<del> getChildContext() {
<del> if (this.state.value === 0) {
<del> this.setState({value: 1});
<del> }
<del> }
<del>
<del> render() {
<del> renderPasses++;
<del> return <div />;
<del> }
<del> }
<del> Component.childContextTypes = {};
<del>
<del> let instance;
<del>
<del> expect(() => {
<del> instance = ReactDOM.render(<Component />, container);
<del> }).toErrorDev(
<del> 'Warning: setState(...): Cannot call setState() inside getChildContext()',
<del> );
<del>
<del> expect(renderPasses).toBe(2);
<del> expect(instance.state.value).toBe(1);
<del>
<del> // Test deduplication; (no additional warnings are expected).
<del> ReactDOM.unmountComponentAtNode(container);
<del> ReactDOM.render(<Component />, container);
<del> });
<del>
<ide> it('should cleanup even if render() fatals', () => {
<ide> class BadComponent extends React.Component {
<ide> render() {
<ide><path>packages/react-dom/src/__tests__/ReactDOMComponent-test.js
<ide> describe('ReactDOMComponent', () => {
<ide> );
<ide> });
<ide>
<del> it('should emit a warning once for a named custom component using shady DOM', () => {
<del> const defaultCreateElement = document.createElement.bind(document);
<del>
<del> try {
<del> document.createElement = element => {
<del> const container = defaultCreateElement(element);
<del> container.shadyRoot = {};
<del> return container;
<del> };
<del> class ShadyComponent extends React.Component {
<del> render() {
<del> return <polymer-component />;
<del> }
<del> }
<del> const node = document.createElement('div');
<del> expect(() => ReactDOM.render(<ShadyComponent />, node)).toErrorDev(
<del> 'ShadyComponent is using shady DOM. Using shady DOM with React can ' +
<del> 'cause things to break subtly.',
<del> );
<del> mountComponent({is: 'custom-shady-div2'});
<del> } finally {
<del> document.createElement = defaultCreateElement;
<del> }
<del> });
<del>
<del> it('should emit a warning once for an unnamed custom component using shady DOM', () => {
<del> const defaultCreateElement = document.createElement.bind(document);
<del>
<del> try {
<del> document.createElement = element => {
<del> const container = defaultCreateElement(element);
<del> container.shadyRoot = {};
<del> return container;
<del> };
<del>
<del> expect(() => mountComponent({is: 'custom-shady-div'})).toErrorDev(
<del> 'A component is using shady DOM. Using shady DOM with React can ' +
<del> 'cause things to break subtly.',
<del> );
<del>
<del> // No additional warnings are expected
<del> mountComponent({is: 'custom-shady-div2'});
<del> } finally {
<del> document.createElement = defaultCreateElement;
<del> }
<del> });
<del>
<ide> it('should treat menuitem as a void element but still create the closing tag', () => {
<ide> // menuitem is not implemented in jsdom, so this triggers the unknown warning error
<ide> const container = document.createElement('div');
<ide><path>packages/react-dom/src/client/ReactDOMComponent.js
<ide> * @flow
<ide> */
<ide>
<del>// TODO: direct imports like some-package/src/* are bad. Fix me.
<del>import {getCurrentFiberOwnerNameInDevOrNull} from 'react-reconciler/src/ReactCurrentFiber';
<ide> import {registrationNameModules} from 'legacy-events/EventPluginRegistry';
<ide> import {canUseDOM} from 'shared/ExecutionEnvironment';
<ide> import endsWith from 'shared/endsWith';
<ide> import {
<ide> import {legacyListenToEvent} from '../events/DOMLegacyEventPluginSystem';
<ide>
<ide> let didWarnInvalidHydration = false;
<del>let didWarnShadyDOM = false;
<ide> let didWarnScriptTags = false;
<ide>
<ide> const DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML';
<ide> export function setInitialProperties(
<ide> const isCustomComponentTag = isCustomComponent(tag, rawProps);
<ide> if (__DEV__) {
<ide> validatePropertiesInDevelopment(tag, rawProps);
<del> if (
<del> isCustomComponentTag &&
<del> !didWarnShadyDOM &&
<del> (domElement: any).shadyRoot
<del> ) {
<del> console.error(
<del> '%s is using shady DOM. Using shady DOM with React can ' +
<del> 'cause things to break subtly.',
<del> getCurrentFiberOwnerNameInDevOrNull() || 'A component',
<del> );
<del> didWarnShadyDOM = true;
<del> }
<ide> }
<ide>
<ide> // TODO: Make sure that we check isMounted before firing any of these events.
<ide> export function diffHydratedProperties(
<ide> suppressHydrationWarning = rawProps[SUPPRESS_HYDRATION_WARNING] === true;
<ide> isCustomComponentTag = isCustomComponent(tag, rawProps);
<ide> validatePropertiesInDevelopment(tag, rawProps);
<del> if (
<del> isCustomComponentTag &&
<del> !didWarnShadyDOM &&
<del> (domElement: any).shadyRoot
<del> ) {
<del> console.error(
<del> '%s is using shady DOM. Using shady DOM with React can ' +
<del> 'cause things to break subtly.',
<del> getCurrentFiberOwnerNameInDevOrNull() || 'A component',
<del> );
<del> didWarnShadyDOM = true;
<del> }
<ide> }
<ide>
<ide> // TODO: Make sure that we check isMounted before firing any of these events.
<ide><path>packages/react-reconciler/src/ReactCurrentFiber.js
<ide> import getComponentName from 'shared/getComponentName';
<ide>
<ide> const ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
<ide>
<del>type LifeCyclePhase = 'render' | 'getChildContext';
<del>
<ide> function describeFiber(fiber: Fiber): string {
<ide> switch (fiber.tag) {
<ide> case HostRoot:
<ide> export function getStackByFiberInDevAndProd(workInProgress: Fiber): string {
<ide> }
<ide>
<ide> export let current: Fiber | null = null;
<del>export let phase: LifeCyclePhase | null = null;
<add>export let isRendering: boolean = false;
<ide>
<ide> export function getCurrentFiberOwnerNameInDevOrNull(): string | null {
<ide> if (__DEV__) {
<ide> export function resetCurrentFiber() {
<ide> if (__DEV__) {
<ide> ReactDebugCurrentFrame.getCurrentStack = null;
<ide> current = null;
<del> phase = null;
<add> isRendering = false;
<ide> }
<ide> }
<ide>
<ide> export function setCurrentFiber(fiber: Fiber) {
<ide> if (__DEV__) {
<ide> ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackInDev;
<ide> current = fiber;
<del> phase = null;
<add> isRendering = false;
<ide> }
<ide> }
<ide>
<del>export function setCurrentPhase(lifeCyclePhase: LifeCyclePhase | null) {
<add>export function setIsRendering(rendering: boolean) {
<ide> if (__DEV__) {
<del> phase = lifeCyclePhase;
<add> isRendering = rendering;
<ide> }
<ide> }
<ide><path>packages/react-reconciler/src/ReactFiberBeginWork.js
<ide> import ReactStrictModeWarnings from './ReactStrictModeWarnings';
<ide> import {refineResolvedLazyComponent} from 'shared/ReactLazyComponent';
<ide> import {REACT_LAZY_TYPE, getIteratorFn} from 'shared/ReactSymbols';
<ide> import {
<del> setCurrentPhase,
<ide> getCurrentFiberOwnerNameInDevOrNull,
<ide> getCurrentFiberStackInDev,
<add> setIsRendering,
<ide> } from './ReactCurrentFiber';
<ide> import {startWorkTimer, cancelWorkTimer} from './ReactDebugFiberPerf';
<ide> import {
<ide> let didWarnAboutContextTypeOnFunctionComponent;
<ide> let didWarnAboutGetDerivedStateOnFunctionComponent;
<ide> let didWarnAboutFunctionRefs;
<ide> export let didWarnAboutReassigningProps;
<del>let didWarnAboutMaxDuration;
<ide> let didWarnAboutRevealOrder;
<ide> let didWarnAboutTailOptions;
<ide> let didWarnAboutDefaultPropsOnFunctionComponent;
<ide> if (__DEV__) {
<ide> didWarnAboutGetDerivedStateOnFunctionComponent = {};
<ide> didWarnAboutFunctionRefs = {};
<ide> didWarnAboutReassigningProps = false;
<del> didWarnAboutMaxDuration = false;
<ide> didWarnAboutRevealOrder = {};
<ide> didWarnAboutTailOptions = {};
<ide> didWarnAboutDefaultPropsOnFunctionComponent = {};
<ide> function updateForwardRef(
<ide> prepareToReadContext(workInProgress, renderExpirationTime);
<ide> if (__DEV__) {
<ide> ReactCurrentOwner.current = workInProgress;
<del> setCurrentPhase('render');
<add> setIsRendering(true);
<ide> nextChildren = renderWithHooks(
<ide> current,
<ide> workInProgress,
<ide> function updateForwardRef(
<ide> );
<ide> }
<ide> }
<del> setCurrentPhase(null);
<add> setIsRendering(false);
<ide> } else {
<ide> nextChildren = renderWithHooks(
<ide> current,
<ide> function updateFunctionComponent(
<ide> prepareToReadContext(workInProgress, renderExpirationTime);
<ide> if (__DEV__) {
<ide> ReactCurrentOwner.current = workInProgress;
<del> setCurrentPhase('render');
<add> setIsRendering(true);
<ide> nextChildren = renderWithHooks(
<ide> current,
<ide> workInProgress,
<ide> function updateFunctionComponent(
<ide> );
<ide> }
<ide> }
<del> setCurrentPhase(null);
<add> setIsRendering(false);
<ide> } else {
<ide> nextChildren = renderWithHooks(
<ide> current,
<ide> function updateBlock(
<ide> prepareToReadContext(workInProgress, renderExpirationTime);
<ide> if (__DEV__) {
<ide> ReactCurrentOwner.current = workInProgress;
<del> setCurrentPhase('render');
<add> setIsRendering(true);
<ide> nextChildren = renderWithHooks(
<ide> current,
<ide> workInProgress,
<ide> function updateBlock(
<ide> );
<ide> }
<ide> }
<del> setCurrentPhase(null);
<add> setIsRendering(false);
<ide> } else {
<ide> nextChildren = renderWithHooks(
<ide> current,
<ide> function finishClassComponent(
<ide> }
<ide> } else {
<ide> if (__DEV__) {
<del> setCurrentPhase('render');
<add> setIsRendering(true);
<ide> nextChildren = instance.render();
<ide> if (
<ide> debugRenderPhaseSideEffectsForStrictMode &&
<ide> workInProgress.mode & StrictMode
<ide> ) {
<ide> instance.render();
<ide> }
<del> setCurrentPhase(null);
<add> setIsRendering(false);
<ide> } else {
<ide> nextChildren = instance.render();
<ide> }
<ide> function updateSuspenseComponent(
<ide>
<ide> pushSuspenseContext(workInProgress, suspenseContext);
<ide>
<del> if (__DEV__) {
<del> if ('maxDuration' in nextProps) {
<del> if (!didWarnAboutMaxDuration) {
<del> didWarnAboutMaxDuration = true;
<del> console.error(
<del> 'maxDuration has been removed from React. ' +
<del> 'Remove the maxDuration prop.',
<del> );
<del> }
<del> }
<del> }
<del>
<ide> // This next part is a bit confusing. If the children timeout, we switch to
<ide> // showing the fallback children in place of the "primary" children.
<ide> // However, we don't want to delete the primary children because then their
<ide> function updateContextConsumer(
<ide> let newChildren;
<ide> if (__DEV__) {
<ide> ReactCurrentOwner.current = workInProgress;
<del> setCurrentPhase('render');
<add> setIsRendering(true);
<ide> newChildren = render(newValue);
<del> setCurrentPhase(null);
<add> setIsRendering(false);
<ide> } else {
<ide> newChildren = render(newValue);
<ide> }
<ide><path>packages/react-reconciler/src/ReactFiberContext.js
<ide> import getComponentName from 'shared/getComponentName';
<ide> import invariant from 'shared/invariant';
<ide> import checkPropTypes from 'prop-types/checkPropTypes';
<ide>
<del>import {setCurrentPhase, getCurrentFiberStackInDev} from './ReactCurrentFiber';
<add>import {getCurrentFiberStackInDev} from './ReactCurrentFiber';
<ide> import {startPhaseTimer, stopPhaseTimer} from './ReactDebugFiberPerf';
<ide> import {createCursor, push, pop} from './ReactFiberStack';
<ide>
<ide> function processChildContext(
<ide> }
<ide>
<ide> let childContext;
<del> if (__DEV__) {
<del> setCurrentPhase('getChildContext');
<del> }
<ide> startPhaseTimer(fiber, 'getChildContext');
<ide> childContext = instance.getChildContext();
<ide> stopPhaseTimer();
<del> if (__DEV__) {
<del> setCurrentPhase(null);
<del> }
<ide> for (let contextKey in childContext) {
<ide> invariant(
<ide> contextKey in childContextTypes,
<ide><path>packages/react-reconciler/src/ReactFiberReconciler.js
<ide> import {
<ide> import {createUpdate, enqueueUpdate} from './ReactUpdateQueue';
<ide> import {
<ide> getStackByFiberInDevAndProd,
<del> phase as ReactCurrentFiberPhase,
<add> isRendering as ReactCurrentFiberIsRendering,
<ide> current as ReactCurrentFiberCurrent,
<ide> } from './ReactCurrentFiber';
<ide> import {StrictMode} from './ReactTypeOfMode';
<ide> export function updateContainer(
<ide>
<ide> if (__DEV__) {
<ide> if (
<del> ReactCurrentFiberPhase === 'render' &&
<add> ReactCurrentFiberIsRendering &&
<ide> ReactCurrentFiberCurrent !== null &&
<ide> !didWarnAboutNestedUpdates
<ide> ) {
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.js
<ide> import {
<ide> import getComponentName from 'shared/getComponentName';
<ide> import ReactStrictModeWarnings from './ReactStrictModeWarnings';
<ide> import {
<del> phase as ReactCurrentDebugFiberPhaseInDEV,
<add> isRendering as ReactCurrentDebugFiberIsRenderingInDEV,
<ide> resetCurrentFiber as resetCurrentDebugFiberInDEV,
<ide> setCurrentFiber as setCurrentDebugFiberInDEV,
<ide> getStackByFiberInDevAndProd,
<ide> if (__DEV__ && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
<ide> }
<ide>
<ide> let didWarnAboutUpdateInRender = false;
<del>let didWarnAboutUpdateInGetChildContext = false;
<ide> function warnAboutRenderPhaseUpdatesInDEV(fiber) {
<ide> if (__DEV__) {
<ide> if ((executionContext & RenderContext) !== NoContext) {
<ide> function warnAboutRenderPhaseUpdatesInDEV(fiber) {
<ide> break;
<ide> }
<ide> case ClassComponent: {
<del> switch (ReactCurrentDebugFiberPhaseInDEV) {
<del> case 'getChildContext':
<del> if (didWarnAboutUpdateInGetChildContext) {
<del> return;
<del> }
<del> console.error(
<del> 'setState(...): Cannot call setState() inside getChildContext()',
<del> );
<del> didWarnAboutUpdateInGetChildContext = true;
<del> break;
<del> case 'render':
<del> if (didWarnAboutUpdateInRender) {
<del> return;
<del> }
<del> console.error(
<del> 'Cannot update during an existing state transition (such as ' +
<del> 'within `render`). Render methods should be a pure ' +
<del> 'function of props and state.',
<del> );
<del> didWarnAboutUpdateInRender = true;
<del> break;
<add> if (
<add> ReactCurrentDebugFiberIsRenderingInDEV &&
<add> !didWarnAboutUpdateInRender
<add> ) {
<add> console.error(
<add> 'Cannot update during an existing state transition (such as ' +
<add> 'within `render`). Render methods should be a pure ' +
<add> 'function of props and state.',
<add> );
<add> didWarnAboutUpdateInRender = true;
<add> break;
<ide> }
<del> break;
<ide> }
<ide> }
<ide> }
<ide><path>packages/react-reconciler/src/__tests__/ReactSuspenseWithNoopRenderer-test.internal.js
<ide> function loadModules({
<ide> }
<ide> }
<ide>
<del> it('warns if the deprecated maxDuration option is used', () => {
<del> function Foo() {
<del> return (
<del> <Suspense maxDuration={100} fallback="Loading...">
<del> <div />;
<del> </Suspense>
<del> );
<del> }
<del>
<del> ReactNoop.render(<Foo />);
<del>
<del> expect(() => Scheduler.unstable_flushAll()).toErrorDev([
<del> 'Warning: maxDuration has been removed from React. ' +
<del> 'Remove the maxDuration prop.' +
<del> '\n in Suspense (at **)' +
<del> '\n in Foo (at **)',
<del> ]);
<del> });
<del>
<ide> it('does not restart rendering for initial render', async () => {
<ide> function Bar(props) {
<ide> Scheduler.unstable_yieldValue('Bar');
| 9
|
Ruby
|
Ruby
|
implement `homebrew.args` compatibility layer
|
86359c4c91d8b4d2934828129a8de9cd310adf01
|
<ide><path>Library/Homebrew/compat.rb
<ide> # frozen_string_literal: true
<ide>
<add>require "compat/dependencies_helpers"
<add>require "compat/cli/parser"
<ide> require "compat/extend/nil"
<ide> require "compat/extend/string"
<ide> require "compat/formula"
<ide><path>Library/Homebrew/compat/cli/parser.rb
<add># frozen_string_literal: true
<add>
<add>module Homebrew
<add> module CLI
<add> class Parser
<add> module Compat
<add> module DeprecatedArgs
<add> def respond_to_missing?(*)
<add> super
<add> end
<add>
<add> def method_missing(method, *)
<add> if ![:debug?, :quiet?, :verbose?].include?(method) && !@printed_args_warning
<add> odeprecated "Homebrew.args", "`args = <command>_args.parse` and pass `args` along the call chain"
<add> @printed_args_warning = true
<add> end
<add>
<add> super
<add> end
<add> end
<add>
<add> def parse(*)
<add> args = super
<add> Homebrew.args = args.dup.extend(DeprecatedArgs)
<add> args
<add> end
<add> end
<add>
<add> prepend Compat
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/compat/dependencies_helpers.rb
<add># frozen_string_literal: true
<add>
<add>require "cli/args"
<add>
<add>module DependenciesHelpers
<add> module Compat
<add> def argv_includes_ignores(argv = nil)
<add> unless @printed_includes_ignores_warning
<add> odeprecated "Homebrew.argv_includes_ignores", "Homebrew.args_includes_ignores"
<add> @printed_includes_ignores_warning = true
<add> end
<add> args_includes_ignores(argv ? Homebrew::CLI::Args.new : Homebrew.args)
<add> end
<add> end
<add>
<add> prepend Compat
<add>end
| 3
|
Javascript
|
Javascript
|
fix branding violation memorycacheplugin
|
466e28b312b5a0305b546579f08c5e5d25c13470
|
<ide><path>lib/cache/MemoryCachePlugin.js
<ide> const Cache = require("../Cache");
<ide>
<ide> class MemoryCachePlugin {
<ide> /**
<del> * @param {Compiler} compiler Webpack compiler
<add> * @param {Compiler} compiler webpack compiler
<ide> * @returns {void}
<ide> */
<ide> apply(compiler) {
| 1
|
PHP
|
PHP
|
avoid fqcn in code.
|
dccf13e2c831c990e96d4c62a229f5ce3c2208ea
|
<ide><path>src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
<ide>
<ide> use Carbon\CarbonImmutable;
<ide> use Carbon\CarbonInterface;
<add>use DateTimeImmutable;
<ide> use DateTimeInterface;
<ide> use Illuminate\Contracts\Database\Eloquent\Castable;
<ide> use Illuminate\Contracts\Database\Eloquent\CastsInboundAttributes;
<ide> protected function asTimestamp($value)
<ide> */
<ide> protected function serializeDate(DateTimeInterface $date)
<ide> {
<del> return $date instanceof \DateTimeImmutable ?
<add> return $date instanceof DateTimeImmutable ?
<ide> CarbonImmutable::instance($date)->toJSON() :
<ide> Carbon::instance($date)->toJSON();
<ide> }
<ide><path>src/Illuminate/Routing/RouteDependencyResolverTrait.php
<ide> use ReflectionFunctionAbstract;
<ide> use ReflectionMethod;
<ide> use ReflectionParameter;
<add>use stdClass;
<ide>
<ide> trait RouteDependencyResolverTrait
<ide> {
<ide> public function resolveMethodDependencies(array $parameters, ReflectionFunctionA
<ide>
<ide> $values = array_values($parameters);
<ide>
<del> $skippableValue = new \stdClass;
<add> $skippableValue = new stdClass;
<ide>
<ide> foreach ($reflector->getParameters() as $key => $parameter) {
<ide> $instance = $this->transformDependency($parameter, $parameters, $skippableValue);
<ide><path>tests/Database/DatabaseEloquentSoftDeletesIntegrationTest.php
<ide> namespace Illuminate\Tests\Database;
<ide>
<ide> use BadMethodCallException;
<add>use Exception;
<ide> use Illuminate\Database\Capsule\Manager as DB;
<ide> use Illuminate\Database\Eloquent\Model as Eloquent;
<ide> use Illuminate\Database\Eloquent\SoftDeletes;
<ide> public function testForceDeleteDoesntUpdateExistsPropertyIfFailed()
<ide> public function newModelQuery()
<ide> {
<ide> return Mockery::spy(parent::newModelQuery(), function (Mockery\MockInterface $mock) {
<del> $mock->shouldReceive('forceDelete')->andThrow(new \Exception());
<add> $mock->shouldReceive('forceDelete')->andThrow(new Exception());
<ide> });
<ide> }
<ide> };
<ide> public function newModelQuery()
<ide>
<ide> try {
<ide> $user->forceDelete();
<del> } catch (\Exception $exception) {
<add> } catch (Exception $exception) {
<ide> }
<ide>
<ide> $this->assertTrue($user->exists);
<ide><path>tests/Foundation/Testing/DatabaseMigrationsTest.php
<ide> use Illuminate\Contracts\Console\Kernel;
<ide> use Illuminate\Foundation\Testing\DatabaseMigrations;
<ide> use Illuminate\Foundation\Testing\RefreshDatabaseState;
<add>use Mockery;
<ide> use PHPUnit\Framework\TestCase;
<add>use ReflectionMethod;
<ide>
<ide> class DatabaseMigrationsTest extends TestCase
<ide> {
<ide> protected function setUp(): void
<ide> 'beforeApplicationDestroyed',
<ide> ]);
<ide>
<del> $kernelObj = \Mockery::mock();
<add> $kernelObj = Mockery::mock();
<ide> $kernelObj->shouldReceive('setArtisan')
<ide> ->with(null);
<ide>
<ide> protected function setUp(): void
<ide>
<ide> private function __reflectAndSetupAccessibleForProtectedTraitMethod($methodName)
<ide> {
<del> $migrateFreshUsingReflection = new \ReflectionMethod(
<add> $migrateFreshUsingReflection = new ReflectionMethod(
<ide> get_class($this->traitObject),
<ide> $methodName
<ide> );
<ide><path>tests/Foundation/Testing/RefreshDatabaseTest.php
<ide> use Illuminate\Contracts\Console\Kernel;
<ide> use Illuminate\Foundation\Testing\RefreshDatabase;
<ide> use Illuminate\Foundation\Testing\RefreshDatabaseState;
<add>use Mockery;
<ide> use PHPUnit\Framework\TestCase;
<add>use ReflectionMethod;
<ide>
<ide> class RefreshDatabaseTest extends TestCase
<ide> {
<ide> protected function setUp(): void
<ide> 'beginDatabaseTransaction',
<ide> ]);
<ide>
<del> $kernelObj = \Mockery::mock();
<add> $kernelObj = Mockery::mock();
<ide> $kernelObj->shouldReceive('setArtisan')
<ide> ->with(null);
<ide>
<ide> protected function setUp(): void
<ide>
<ide> private function __reflectAndSetupAccessibleForProtectedTraitMethod($methodName)
<ide> {
<del> $migrateFreshUsingReflection = new \ReflectionMethod(
<add> $migrateFreshUsingReflection = new ReflectionMethod(
<ide> get_class($this->traitObject),
<ide> $methodName
<ide> );
<ide><path>tests/Foundation/Testing/Traits/CanConfigureMigrationCommandsTest.php
<ide>
<ide> use Illuminate\Foundation\Testing\Traits\CanConfigureMigrationCommands;
<ide> use PHPUnit\Framework\TestCase;
<add>use ReflectionMethod;
<ide>
<ide> class CanConfigureMigrationCommandsTest extends TestCase
<ide> {
<ide> protected function setup(): void
<ide>
<ide> private function __reflectAndSetupAccessibleForProtectedTraitMethod($methodName)
<ide> {
<del> $migrateFreshUsingReflection = new \ReflectionMethod(
<add> $migrateFreshUsingReflection = new ReflectionMethod(
<ide> get_class($this->traitObject),
<ide> $methodName
<ide> );
<ide><path>tests/Integration/Database/EloquentStrictLoadingTest.php
<ide> use Illuminate\Database\Schema\Blueprint;
<ide> use Illuminate\Support\Facades\Event;
<ide> use Illuminate\Support\Facades\Schema;
<add>use RuntimeException;
<ide>
<ide> class EloquentStrictLoadingTest extends DatabaseTestCase
<ide> {
<ide> public function testStrictModeWithCustomCallbackOnLazyLoading()
<ide>
<ide> public function testStrictModeWithOverriddenHandlerOnLazyLoading()
<ide> {
<del> $this->expectException(\RuntimeException::class);
<add> $this->expectException(RuntimeException::class);
<ide> $this->expectExceptionMessage('Violated');
<ide>
<ide> EloquentStrictLoadingTestModel1WithCustomHandler::create();
<ide> public function modelTwos()
<ide>
<ide> protected function handleLazyLoadingViolation($key)
<ide> {
<del> throw new \RuntimeException("Violated {$key}");
<add> throw new RuntimeException("Violated {$key}");
<ide> }
<ide> }
<ide>
<ide><path>tests/Support/SupportHelpersTest.php
<ide> use LogicException;
<ide> use Mockery as m;
<ide> use PHPUnit\Framework\TestCase;
<add>use ReflectionClass;
<ide> use RuntimeException;
<ide> use stdClass;
<ide> use Traversable;
<ide> public function testStr()
<ide> $this->assertTrue($stringable->isEmpty());
<ide>
<ide> $strAccessor = str();
<del> $this->assertTrue((new \ReflectionClass($strAccessor))->isAnonymous());
<add> $this->assertTrue((new ReflectionClass($strAccessor))->isAnonymous());
<ide> $this->assertSame($strAccessor->limit('string-value', 3), 'str...');
<ide>
<ide> $strAccessor = str();
<del> $this->assertTrue((new \ReflectionClass($strAccessor))->isAnonymous());
<add> $this->assertTrue((new ReflectionClass($strAccessor))->isAnonymous());
<ide> $this->assertSame((string) $strAccessor, '');
<ide> }
<ide>
| 8
|
Java
|
Java
|
introduce builder api for aot processor settings
|
eadb003a8d1973f54c1609bfc8da1bcf89eb9943
|
<ide><path>spring-context/src/main/java/org/springframework/context/aot/AbstractAotProcessor.java
<ide> import org.springframework.aot.hint.RuntimeHints;
<ide> import org.springframework.aot.nativex.FileNativeConfigurationWriter;
<ide> import org.springframework.lang.Nullable;
<add>import org.springframework.util.Assert;
<ide> import org.springframework.util.FileSystemUtils;
<ide>
<ide> /**
<ide> public abstract class AbstractAotProcessor {
<ide>
<ide> /**
<ide> * Create a new processor instance with the supplied {@linkplain Settings settings}.
<add> * @see Settings#builder()
<ide> */
<ide> protected AbstractAotProcessor(Settings settings) {
<ide> this.settings = settings;
<ide> protected void writeHints(RuntimeHints hints) {
<ide> /**
<ide> * Common settings for AOT processors.
<ide> */
<del> public static class Settings {
<add> public static final class Settings {
<ide>
<del> @Nullable
<del> private Path sourceOutput;
<add> private final Path sourceOutput;
<ide>
<del> @Nullable
<del> private Path resourceOutput;
<add> private final Path resourceOutput;
<ide>
<del> @Nullable
<del> private Path classOutput;
<add> private final Path classOutput;
<ide>
<del> @Nullable
<del> private String groupId;
<add> private final String groupId;
<ide>
<del> @Nullable
<del> private String artifactId;
<add> private final String artifactId;
<ide>
<ide>
<del> /**
<del> * Set the output directory for generated sources.
<del> * @param sourceOutput the location of generated sources
<del> * @return this settings object for method chaining
<del> */
<del> public Settings setSourceOutput(Path sourceOutput) {
<add> private Settings(Path sourceOutput, Path resourceOutput, Path classOutput, String groupId, String artifactId) {
<ide> this.sourceOutput = sourceOutput;
<del> return this;
<add> this.resourceOutput = resourceOutput;
<add> this.classOutput = classOutput;
<add> this.groupId = groupId;
<add> this.artifactId = artifactId;
<ide> }
<ide>
<add>
<ide> /**
<del> * Get the output directory for generated sources.
<add> * Create a new {@link Builder} for {@link Settings}.
<ide> */
<del> @Nullable
<del> public Path getSourceOutput() {
<del> return this.sourceOutput;
<add> public static Builder builder() {
<add> return new Builder();
<ide> }
<ide>
<add>
<ide> /**
<del> * Set the output directory for generated resources.
<del> * @param resourceOutput the location of generated resources
<del> * @return this settings object for method chaining
<add> * Get the output directory for generated sources.
<ide> */
<del> public Settings setResourceOutput(Path resourceOutput) {
<del> this.resourceOutput = resourceOutput;
<del> return this;
<add> public Path getSourceOutput() {
<add> return this.sourceOutput;
<ide> }
<ide>
<ide> /**
<ide> * Get the output directory for generated resources.
<ide> */
<del> @Nullable
<ide> public Path getResourceOutput() {
<ide> return this.resourceOutput;
<ide> }
<ide>
<del> /**
<del> * Set the output directory for generated classes.
<del> * @param classOutput the location of generated classes
<del> * @return this settings object for method chaining
<del> */
<del> public Settings setClassOutput(Path classOutput) {
<del> this.classOutput = classOutput;
<del> return this;
<del> }
<del>
<ide> /**
<ide> * Get the output directory for generated classes.
<ide> */
<del> @Nullable
<ide> public Path getClassOutput() {
<ide> return this.classOutput;
<ide> }
<ide>
<del> /**
<del> * Set the group ID of the application.
<del> * @param groupId the group ID of the application, used to locate
<del> * {@code native-image.properties}
<del> * @return this settings object for method chaining
<del> */
<del> public Settings setGroupId(String groupId) {
<del> this.groupId = groupId;
<del> return this;
<del> }
<del>
<ide> /**
<ide> * Get the group ID of the application.
<ide> */
<del> @Nullable
<ide> public String getGroupId() {
<ide> return this.groupId;
<ide> }
<ide>
<ide> /**
<del> * Set the artifact ID of the application.
<del> * @param artifactId the artifact ID of the application, used to locate
<del> * {@code native-image.properties}
<del> * @return this settings object for method chaining
<add> * Get the artifact ID of the application.
<ide> */
<del> public Settings setArtifactId(String artifactId) {
<del> this.artifactId = artifactId;
<del> return this;
<add> public String getArtifactId() {
<add> return this.artifactId;
<ide> }
<ide>
<add>
<ide> /**
<del> * Get the artifact ID of the application.
<add> * Fluent builder API for {@link Settings}.
<ide> */
<del> @Nullable
<del> public String getArtifactId() {
<del> return this.artifactId;
<add> public static final class Builder {
<add>
<add> @Nullable
<add> private Path sourceOutput;
<add>
<add> @Nullable
<add> private Path resourceOutput;
<add>
<add> @Nullable
<add> private Path classOutput;
<add>
<add> @Nullable
<add> private String groupId;
<add>
<add> @Nullable
<add> private String artifactId;
<add>
<add>
<add> private Builder() {
<add> // internal constructor
<add> }
<add>
<add>
<add> /**
<add> * Set the output directory for generated sources.
<add> * @param sourceOutput the location of generated sources
<add> * @return this builder for method chaining
<add> */
<add> public Builder sourceOutput(Path sourceOutput) {
<add> this.sourceOutput = sourceOutput;
<add> return this;
<add> }
<add>
<add> /**
<add> * Set the output directory for generated resources.
<add> * @param resourceOutput the location of generated resources
<add> * @return this builder for method chaining
<add> */
<add> public Builder resourceOutput(Path resourceOutput) {
<add> this.resourceOutput = resourceOutput;
<add> return this;
<add> }
<add>
<add> /**
<add> * Set the output directory for generated classes.
<add> * @param classOutput the location of generated classes
<add> * @return this builder for method chaining
<add> */
<add> public Builder classOutput(Path classOutput) {
<add> this.classOutput = classOutput;
<add> return this;
<add> }
<add>
<add> /**
<add> * Set the group ID of the application.
<add> * @param groupId the group ID of the application, used to locate
<add> * {@code native-image.properties}
<add> * @return this builder for method chaining
<add> */
<add> public Builder groupId(String groupId) {
<add> this.groupId = groupId;
<add> return this;
<add> }
<add>
<add> /**
<add> * Set the artifact ID of the application.
<add> * @param artifactId the artifact ID of the application, used to locate
<add> * {@code native-image.properties}
<add> * @return this builder for method chaining
<add> */
<add> public Builder artifactId(String artifactId) {
<add> this.artifactId = artifactId;
<add> return this;
<add> }
<add>
<add> /**
<add> * Build the {@link Settings} configured in this {@code Builder}.
<add> */
<add> public Settings build() {
<add> Assert.notNull(this.sourceOutput, "'sourceOutput' must not be null");
<add> Assert.notNull(this.resourceOutput, "'resourceOutput' must not be null");
<add> Assert.notNull(this.classOutput, "'classOutput' must not be null");
<add> Assert.hasText(this.groupId, "'groupId' must not be null or empty");
<add> Assert.hasText(this.artifactId, "'artifactId' must not be null or empty");
<add> return new Settings(this.sourceOutput, this.resourceOutput, this.classOutput,
<add> this.groupId, this.artifactId);
<add> }
<add>
<ide> }
<ide>
<ide> }
<ide><path>spring-context/src/test/java/org/springframework/context/aot/AotProcessorTests.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.context.aot;
<add>
<add>import java.nio.file.Path;
<add>
<add>import org.junit.jupiter.api.Test;
<add>import org.junit.jupiter.api.io.TempDir;
<add>
<add>import org.springframework.context.aot.AbstractAotProcessor.Settings;
<add>
<add>import static org.assertj.core.api.Assertions.assertThat;
<add>import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
<add>
<add>/**
<add> * Tests for {@link AbstractAotProcessor}, settings, and builder.
<add> *
<add> * @author Sam Brannen
<add> * @since 6.0
<add> */
<add>class AotProcessorTests {
<add>
<add> @Test
<add> void builderRejectsMissingSourceOutput() {
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(() -> Settings.builder().build())
<add> .withMessageContaining("'sourceOutput'");
<add> }
<add>
<add> @Test
<add> void builderRejectsMissingResourceOutput(@TempDir Path tempDir) {
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(() -> Settings.builder().sourceOutput(tempDir).build())
<add> .withMessageContaining("'resourceOutput'");
<add> }
<add>
<add> @Test
<add> void builderRejectsMissingClassOutput(@TempDir Path tempDir) {
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(() -> Settings.builder()
<add> .sourceOutput(tempDir)
<add> .resourceOutput(tempDir)
<add> .build())
<add> .withMessageContaining("'classOutput'");
<add> }
<add>
<add> @Test
<add> void builderRejectsMissingGroupdId(@TempDir Path tempDir) {
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(() -> Settings.builder()
<add> .sourceOutput(tempDir)
<add> .resourceOutput(tempDir)
<add> .classOutput(tempDir)
<add> .build())
<add> .withMessageContaining("'groupId'");
<add> }
<add>
<add> @Test
<add> void builderRejectsEmptyGroupdId(@TempDir Path tempDir) {
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(() -> Settings.builder()
<add> .sourceOutput(tempDir)
<add> .resourceOutput(tempDir)
<add> .classOutput(tempDir)
<add> .groupId(" ")
<add> .build())
<add> .withMessageContaining("'groupId'");
<add> }
<add>
<add> @Test
<add> void builderRejectsMissingArtifactId(@TempDir Path tempDir) {
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(() -> Settings.builder()
<add> .sourceOutput(tempDir)
<add> .resourceOutput(tempDir)
<add> .classOutput(tempDir)
<add> .groupId("my-group")
<add> .build())
<add> .withMessageContaining("'artifactId'");
<add> }
<add>
<add> @Test
<add> void builderRejectsEmptyArtifactId(@TempDir Path tempDir) {
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(() -> Settings.builder()
<add> .sourceOutput(tempDir)
<add> .resourceOutput(tempDir)
<add> .classOutput(tempDir)
<add> .groupId("my-group")
<add> .artifactId(" ")
<add> .build())
<add> .withMessageContaining("'artifactId'");
<add> }
<add>
<add> @Test
<add> void builderAcceptsRequiredSettings(@TempDir Path tempDir) {
<add> Settings settings = Settings.builder()
<add> .sourceOutput(tempDir)
<add> .resourceOutput(tempDir)
<add> .classOutput(tempDir)
<add> .groupId("my-group")
<add> .artifactId("my-artifact")
<add> .build();
<add> assertThat(settings).isNotNull();
<add> assertThat(settings.getSourceOutput()).isEqualTo(tempDir);
<add> assertThat(settings.getResourceOutput()).isEqualTo(tempDir);
<add> assertThat(settings.getClassOutput()).isEqualTo(tempDir);
<add> assertThat(settings.getGroupId()).isEqualTo("my-group");
<add> assertThat(settings.getArtifactId()).isEqualTo("my-artifact");
<add> }
<add>
<add>}
<ide><path>spring-context/src/test/java/org/springframework/context/aot/ContextAotProcessorTests.java
<ide> private static class DemoContextAotProcessor extends ContextAotProcessor {
<ide>
<ide> private static Settings createSettings(Path sourceOutput, Path resourceOutput,
<ide> Path classOutput, String groupId, String artifactId) {
<del> return new Settings()
<del> .setSourceOutput(sourceOutput)
<del> .setResourceOutput(resourceOutput)
<del> .setClassOutput(classOutput)
<del> .setArtifactId(artifactId)
<del> .setGroupId(groupId);
<add> return Settings.builder()
<add> .sourceOutput(sourceOutput)
<add> .resourceOutput(resourceOutput)
<add> .classOutput(classOutput)
<add> .artifactId(artifactId)
<add> .groupId(groupId)
<add> .build();
<ide> }
<ide>
<ide> @Override
<ide><path>spring-test/src/test/java/org/springframework/test/context/aot/TestAotProcessorTests.java
<ide> private static class DemoTestAotProcessor extends TestAotProcessor {
<ide>
<ide> private static Settings createSettings(Path sourceOutput, Path resourceOutput, Path classOutput, String groupId,
<ide> String artifactId) {
<del> return new Settings()
<del> .setSourceOutput(sourceOutput)
<del> .setResourceOutput(resourceOutput)
<del> .setClassOutput(classOutput)
<del> .setArtifactId(artifactId)
<del> .setGroupId(groupId);
<add> return Settings.builder()
<add> .sourceOutput(sourceOutput)
<add> .resourceOutput(resourceOutput)
<add> .classOutput(classOutput)
<add> .artifactId(artifactId)
<add> .groupId(groupId)
<add> .build();
<ide> }
<ide> }
<ide>
| 4
|
Javascript
|
Javascript
|
add setnativeprops to sectionlist
|
ccb0899658f7796aefe67008fa36cd3f7331bec9
|
<ide><path>Libraries/Lists/SectionList.js
<ide> class SectionList<SectionT: SectionBase<any>> extends React.PureComponent<
<ide> }
<ide> }
<ide>
<add> setNativeProps(props: Object) {
<add> const listRef = this._wrapperListRef && this._wrapperListRef.getListRef();
<add> if (listRef) {
<add> listRef.setNativeProps(props);
<add> }
<add> }
<add>
<ide> render() {
<ide> const List = this.props.legacyImplementation
<ide> ? MetroListView
| 1
|
Go
|
Go
|
fix behavior of absolute paths in .dockerignore
|
1cde87c43abd100f4233e965e040e30a6bd34112
|
<ide><path>builder/dockerignore/dockerignore.go
<ide> func ReadAll(reader io.Reader) ([]string, error) {
<ide> if pattern == "" {
<ide> continue
<ide> }
<del> pattern = filepath.Clean(pattern)
<del> pattern = filepath.ToSlash(pattern)
<add> // normalize absolute paths to paths relative to the context
<add> // (taking care of '!' prefix)
<add> invert := pattern[0] == '!'
<add> if invert {
<add> pattern = strings.TrimSpace(pattern[1:])
<add> }
<add> if len(pattern) > 0 {
<add> pattern = filepath.Clean(pattern)
<add> pattern = filepath.ToSlash(pattern)
<add> if len(pattern) > 1 && pattern[0] == '/' {
<add> pattern = pattern[1:]
<add> }
<add> }
<add> if invert {
<add> pattern = "!" + pattern
<add> }
<add>
<ide> excludes = append(excludes, pattern)
<ide> }
<ide> if err := scanner.Err(); err != nil {
<ide><path>builder/dockerignore/dockerignore_test.go
<ide> func TestReadAll(t *testing.T) {
<ide> }
<ide>
<ide> diName := filepath.Join(tmpDir, ".dockerignore")
<del> content := fmt.Sprintf("test1\n/test2\n/a/file/here\n\nlastfile")
<add> content := fmt.Sprintf("test1\n/test2\n/a/file/here\n\nlastfile\n# this is a comment\n! /inverted/abs/path\n!\n! \n")
<ide> err = ioutil.WriteFile(diName, []byte(content), 0777)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> func TestReadAll(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<add> if len(di) != 7 {
<add> t.Fatalf("Expected 5 entries, got %v", len(di))
<add> }
<ide> if di[0] != "test1" {
<ide> t.Fatal("First element is not test1")
<ide> }
<del> if di[1] != "/test2" {
<del> t.Fatal("Second element is not /test2")
<add> if di[1] != "test2" { // according to https://docs.docker.com/engine/reference/builder/#dockerignore-file, /foo/bar should be treated as foo/bar
<add> t.Fatal("Second element is not test2")
<ide> }
<del> if di[2] != "/a/file/here" {
<del> t.Fatal("Third element is not /a/file/here")
<add> if di[2] != "a/file/here" { // according to https://docs.docker.com/engine/reference/builder/#dockerignore-file, /foo/bar should be treated as foo/bar
<add> t.Fatal("Third element is not a/file/here")
<ide> }
<ide> if di[3] != "lastfile" {
<ide> t.Fatal("Fourth element is not lastfile")
<ide> }
<add> if di[4] != "!inverted/abs/path" {
<add> t.Fatal("Fifth element is not !inverted/abs/path")
<add> }
<add> if di[5] != "!" {
<add> t.Fatalf("Sixth element is not !, but %s", di[5])
<add> }
<add> if di[6] != "!" {
<add> t.Fatalf("Sixth element is not !, but %s", di[6])
<add> }
<ide> }
| 2
|
Text
|
Text
|
add changelog entry
|
c8dcc19cf9e40c4387bfc197bc118da16c8469c3
|
<ide><path>actionpack/CHANGELOG.md
<ide> ## Rails 3.2.0 (unreleased) ##
<ide>
<add>* Depends on rack ~> 1.4.0 *Santiago Pastorino*
<add>
<ide> * Add :gzip option to `caches_page`. The default option can be configured globally using `page_cache_compression` *Andrey Sitnik*
<ide>
<ide> * The ShowExceptions middleware now accepts a exceptions application that is responsible to render an exception when the application fails. The application is invoked with a copy of the exception in `env["action_dispatch.exception"]` and with the PATH_INFO rewritten to the status code. *José Valim*
| 1
|
Text
|
Text
|
update 5.0 release notes
|
ec50f9239bfbb91ef02cd333ca518ec04715a8c3
|
<ide><path>guides/source/5_0_release_notes.md
<ide> Please refer to the [Changelog][action-mailer] for detailed changes.
<ide> * Template lookup now respects default locale and I18n fallbacks.
<ide> ([commit](https://github.com/rails/rails/commit/ecb1981b))
<ide>
<add>* Template can use fragment cache like ActionView template.
<add> ([Pull Request](https://github.com/rails/rails/pull/22825))
<add>
<ide> * Added `_mailer` suffix to mailers created via generator, following the same
<ide> naming convention used in controllers and jobs.
<ide> ([Pull Request](https://github.com/rails/rails/pull/18074))
<ide> Please refer to the [Changelog][action-mailer] for detailed changes.
<ide> the mailer queue name.
<ide> ([Pull Request](https://github.com/rails/rails/pull/18587))
<ide>
<add>* Added `config.action_mailer.perform_caching` configuration to determine whether your templates should perform caching or not.
<add> ([Pull Request](https://github.com/rails/rails/pull/22825))
<add>
<ide>
<ide> Active Record
<ide> -------------
| 1
|
Javascript
|
Javascript
|
fix rmsync error swallowing
|
f9447b71a6b458adbb265f8a5fd38ebf41bc97a4
|
<ide><path>lib/internal/fs/rimraf.js
<ide> function _unlinkSync(path, options) {
<ide> i < tries &&
<ide> options.retryDelay > 0) {
<ide> sleep(i * options.retryDelay);
<add> } else if (err.code === 'ENOENT') {
<add> // The file is already gone.
<add> return;
<add> } else if (i === tries) {
<add> throw err;
<ide> }
<ide> }
<ide> }
<ide> function _rmdirSync(path, options, originalErr) {
<ide> } catch (err) {
<ide> if (err.code === 'ENOENT')
<ide> return;
<del> if (err.code === 'ENOTDIR')
<del> throw originalErr;
<add> if (err.code === 'ENOTDIR') {
<add> throw originalErr || err;
<add> }
<ide>
<ide> if (notEmptyErrorCodes.has(err.code)) {
<ide> // Removing failed. Try removing all children and then retrying the
<ide> function _rmdirSync(path, options, originalErr) {
<ide> i < tries &&
<ide> options.retryDelay > 0) {
<ide> sleep(i * options.retryDelay);
<add> } else if (err.code === 'ENOENT') {
<add> // The file is already gone.
<add> return;
<add> } else if (i === tries) {
<add> throw err;
<ide> }
<ide> }
<ide> }
<ide> }
<add>
<add> throw originalErr || err;
<ide> }
<ide> }
<ide>
<ide><path>test/parallel/test-fs-mkdir-recursive-eaccess.js
<ide> function makeDirectoryReadOnly(dir) {
<ide> let accessErrorCode = 'EACCES';
<ide> if (common.isWindows) {
<ide> accessErrorCode = 'EPERM';
<del> execSync(`icacls ${dir} /inheritance:r`);
<del> execSync(`icacls ${dir} /deny "everyone":W`);
<add> execSync(`icacls ${dir} /deny "everyone:(OI)(CI)(DE,DC,AD,WD)"`);
<ide> } else {
<ide> fs.chmodSync(dir, '444');
<ide> }
<ide> function makeDirectoryReadOnly(dir) {
<ide>
<ide> function makeDirectoryWritable(dir) {
<ide> if (common.isWindows) {
<del> execSync(`icacls ${dir} /grant "everyone":W`);
<add> execSync(`icacls ${dir} /remove:d "everyone"`);
<ide> }
<ide> }
<ide>
<ide><path>test/parallel/test-fs-open-no-close.js
<ide> const debuglog = (arg) => {
<ide> const tmpdir = require('../common/tmpdir');
<ide> tmpdir.refresh();
<ide>
<del>{
<del> fs.open(`${tmpdir.path}/dummy`, 'wx+', common.mustCall((err, fd) => {
<del> debuglog('fs open() callback');
<del> assert.ifError(err);
<del> }));
<del> debuglog('waiting for callback');
<del>}
<add>let openFd;
<add>
<add>fs.open(`${tmpdir.path}/dummy`, 'wx+', common.mustCall((err, fd) => {
<add> debuglog('fs open() callback');
<add> assert.ifError(err);
<add> openFd = fd;
<add>}));
<add>debuglog('waiting for callback');
<add>
<add>process.on('beforeExit', common.mustCall(() => {
<add> if (openFd) {
<add> fs.closeSync(openFd);
<add> }
<add>}));
<ide><path>test/parallel/test-fs-promises-file-handle-read-worker.js
<ide> if (isMainThread || !workerData) {
<ide> transferList: [handle]
<ide> });
<ide> });
<del> fs.promises.open(file, 'r').then((handle) => {
<del> fs.createReadStream(null, { fd: handle });
<del> assert.throws(() => {
<del> new Worker(__filename, {
<del> workerData: { handle },
<del> transferList: [handle]
<add> fs.promises.open(file, 'r').then(async (handle) => {
<add> try {
<add> fs.createReadStream(null, { fd: handle });
<add> assert.throws(() => {
<add> new Worker(__filename, {
<add> workerData: { handle },
<add> transferList: [handle]
<add> });
<add> }, {
<add> code: 25,
<ide> });
<del> }, {
<del> code: 25,
<del> });
<add> } finally {
<add> await handle.close();
<add> }
<ide> });
<ide> } else {
<ide> let output = '';
<ide><path>test/parallel/test-fs-promises-file-handle-readFile.js
<ide> async function doReadAndCancel() {
<ide> {
<ide> const filePathForHandle = path.resolve(tmpDir, 'dogs-running.txt');
<ide> const fileHandle = await open(filePathForHandle, 'w+');
<del> const buffer = Buffer.from('Dogs running'.repeat(10000), 'utf8');
<del> fs.writeFileSync(filePathForHandle, buffer);
<del> const signal = AbortSignal.abort();
<del> await assert.rejects(readFile(fileHandle, { signal }), {
<del> name: 'AbortError'
<del> });
<del> await fileHandle.close();
<add> try {
<add> const buffer = Buffer.from('Dogs running'.repeat(10000), 'utf8');
<add> fs.writeFileSync(filePathForHandle, buffer);
<add> const signal = AbortSignal.abort();
<add> await assert.rejects(readFile(fileHandle, { signal }), {
<add> name: 'AbortError'
<add> });
<add> } finally {
<add> await fileHandle.close();
<add> }
<ide> }
<ide>
<ide> // Signal aborted on first tick
<ide><path>test/parallel/test-fs-promises-file-handle-writeFile.js
<ide> async function validateWriteFile() {
<ide> async function doWriteAndCancel() {
<ide> const filePathForHandle = path.resolve(tmpDir, 'dogs-running.txt');
<ide> const fileHandle = await open(filePathForHandle, 'w+');
<del> const buffer = Buffer.from('dogs running'.repeat(512 * 1024), 'utf8');
<del> const controller = new AbortController();
<del> const { signal } = controller;
<del> process.nextTick(() => controller.abort());
<del> await assert.rejects(writeFile(fileHandle, buffer, { signal }), {
<del> name: 'AbortError'
<del> });
<add> try {
<add> const buffer = Buffer.from('dogs running'.repeat(512 * 1024), 'utf8');
<add> const controller = new AbortController();
<add> const { signal } = controller;
<add> process.nextTick(() => controller.abort());
<add> await assert.rejects(writeFile(fileHandle, buffer, { signal }), {
<add> name: 'AbortError'
<add> });
<add> } finally {
<add> await fileHandle.close();
<add> }
<ide> }
<ide>
<ide> validateWriteFile()
<ide><path>test/parallel/test-fs-promises.js
<ide> async function getHandle(dest) {
<ide> return open(dest, 'r+');
<ide> }
<ide>
<add>async function executeOnHandle(dest, func) {
<add> let handle;
<add> try {
<add> handle = await getHandle(dest);
<add> await func(handle);
<add> } finally {
<add> if (handle) {
<add> await handle.close();
<add> }
<add> }
<add>}
<add>
<ide> {
<ide> async function doTest() {
<ide> tmpdir.refresh();
<ide> async function getHandle(dest) {
<ide>
<ide> // handle is object
<ide> {
<del> const handle = await getHandle(dest);
<del> assert.strictEqual(typeof handle, 'object');
<del> await handle.close();
<add> await executeOnHandle(dest, async (handle) => {
<add> assert.strictEqual(typeof handle, 'object');
<add> });
<ide> }
<ide>
<ide> // file stats
<ide> {
<del> const handle = await getHandle(dest);
<del> let stats = await handle.stat();
<del> verifyStatObject(stats);
<del> assert.strictEqual(stats.size, 35);
<add> await executeOnHandle(dest, async (handle) => {
<add> let stats = await handle.stat();
<add> verifyStatObject(stats);
<add> assert.strictEqual(stats.size, 35);
<ide>
<del> await handle.truncate(1);
<add> await handle.truncate(1);
<ide>
<del> stats = await handle.stat();
<del> verifyStatObject(stats);
<del> assert.strictEqual(stats.size, 1);
<add> stats = await handle.stat();
<add> verifyStatObject(stats);
<add> assert.strictEqual(stats.size, 1);
<ide>
<del> stats = await stat(dest);
<del> verifyStatObject(stats);
<add> stats = await stat(dest);
<add> verifyStatObject(stats);
<ide>
<del> stats = await handle.stat();
<del> verifyStatObject(stats);
<add> stats = await handle.stat();
<add> verifyStatObject(stats);
<ide>
<del> await handle.datasync();
<del> await handle.sync();
<del> await handle.close();
<add> await handle.datasync();
<add> await handle.sync();
<add> });
<ide> }
<ide>
<ide> // Test fs.read promises when length to read is zero bytes
<ide> {
<ide> const dest = path.resolve(tmpDir, 'test1.js');
<del> const handle = await getHandle(dest);
<del> const buf = Buffer.from('DAWGS WIN');
<del> const bufLen = buf.length;
<del> await handle.write(buf);
<del> const ret = await handle.read(Buffer.alloc(bufLen), 0, 0, 0);
<del> assert.strictEqual(ret.bytesRead, 0);
<del>
<del> await unlink(dest);
<del> await handle.close();
<add> await executeOnHandle(dest, async (handle) => {
<add> const buf = Buffer.from('DAWGS WIN');
<add> const bufLen = buf.length;
<add> await handle.write(buf);
<add> const ret = await handle.read(Buffer.alloc(bufLen), 0, 0, 0);
<add> assert.strictEqual(ret.bytesRead, 0);
<add>
<add> await unlink(dest);
<add> });
<ide> }
<ide>
<ide> // Use fallback buffer allocation when input not buffer
<ide> {
<del> const handle = await getHandle(dest);
<del> const ret = await handle.read(0, 0, 0, 0);
<del> assert.strictEqual(ret.buffer.length, 16384);
<add> await executeOnHandle(dest, async (handle) => {
<add> const ret = await handle.read(0, 0, 0, 0);
<add> assert.strictEqual(ret.buffer.length, 16384);
<add> });
<ide> }
<ide>
<ide> // Bytes written to file match buffer
<ide> {
<del> const handle = await getHandle(dest);
<del> const buf = Buffer.from('hello fsPromises');
<del> const bufLen = buf.length;
<del> await handle.write(buf);
<del> const ret = await handle.read(Buffer.alloc(bufLen), 0, bufLen, 0);
<del> assert.strictEqual(ret.bytesRead, bufLen);
<del> assert.deepStrictEqual(ret.buffer, buf);
<del> await handle.close();
<add> await executeOnHandle(dest, async (handle) => {
<add> const buf = Buffer.from('hello fsPromises');
<add> const bufLen = buf.length;
<add> await handle.write(buf);
<add> const ret = await handle.read(Buffer.alloc(bufLen), 0, bufLen, 0);
<add> assert.strictEqual(ret.bytesRead, bufLen);
<add> assert.deepStrictEqual(ret.buffer, buf);
<add> });
<ide> }
<ide>
<ide> // Truncate file to specified length
<ide> {
<del> const handle = await getHandle(dest);
<del> const buf = Buffer.from('hello FileHandle');
<del> const bufLen = buf.length;
<del> await handle.write(buf, 0, bufLen, 0);
<del> const ret = await handle.read(Buffer.alloc(bufLen), 0, bufLen, 0);
<del> assert.strictEqual(ret.bytesRead, bufLen);
<del> assert.deepStrictEqual(ret.buffer, buf);
<del> await truncate(dest, 5);
<del> assert.deepStrictEqual((await readFile(dest)).toString(), 'hello');
<del> await handle.close();
<add> await executeOnHandle(dest, async (handle) => {
<add> const buf = Buffer.from('hello FileHandle');
<add> const bufLen = buf.length;
<add> await handle.write(buf, 0, bufLen, 0);
<add> const ret = await handle.read(Buffer.alloc(bufLen), 0, bufLen, 0);
<add> assert.strictEqual(ret.bytesRead, bufLen);
<add> assert.deepStrictEqual(ret.buffer, buf);
<add> await truncate(dest, 5);
<add> assert.deepStrictEqual((await readFile(dest)).toString(), 'hello');
<add> });
<ide> }
<ide>
<ide> // Invalid change of ownership
<ide> {
<del> const handle = await getHandle(dest);
<add> await executeOnHandle(dest, async (handle) => {
<add> await chmod(dest, 0o666);
<add> await handle.chmod(0o666);
<ide>
<del> await chmod(dest, 0o666);
<del> await handle.chmod(0o666);
<add> await chmod(dest, (0o10777));
<add> await handle.chmod(0o10777);
<ide>
<del> await chmod(dest, (0o10777));
<del> await handle.chmod(0o10777);
<del>
<del> if (!common.isWindows) {
<del> await chown(dest, process.getuid(), process.getgid());
<del> await handle.chown(process.getuid(), process.getgid());
<del> }
<del>
<del> assert.rejects(
<del> async () => {
<del> await chown(dest, 1, -2);
<del> },
<del> {
<del> code: 'ERR_OUT_OF_RANGE',
<del> name: 'RangeError',
<del> message: 'The value of "gid" is out of range. ' +
<del> 'It must be >= -1 && <= 4294967295. Received -2'
<del> });
<del>
<del> assert.rejects(
<del> async () => {
<del> await handle.chown(1, -2);
<del> },
<del> {
<del> code: 'ERR_OUT_OF_RANGE',
<del> name: 'RangeError',
<del> message: 'The value of "gid" is out of range. ' +
<del> 'It must be >= -1 && <= 4294967295. Received -2'
<del> });
<add> if (!common.isWindows) {
<add> await chown(dest, process.getuid(), process.getgid());
<add> await handle.chown(process.getuid(), process.getgid());
<add> }
<ide>
<del> await handle.close();
<add> await assert.rejects(
<add> async () => {
<add> await chown(dest, 1, -2);
<add> },
<add> {
<add> code: 'ERR_OUT_OF_RANGE',
<add> name: 'RangeError',
<add> message: 'The value of "gid" is out of range. ' +
<add> 'It must be >= -1 && <= 4294967295. Received -2'
<add> });
<add>
<add> await assert.rejects(
<add> async () => {
<add> await handle.chown(1, -2);
<add> },
<add> {
<add> code: 'ERR_OUT_OF_RANGE',
<add> name: 'RangeError',
<add> message: 'The value of "gid" is out of range. ' +
<add> 'It must be >= -1 && <= 4294967295. Received -2'
<add> });
<add> });
<ide> }
<ide>
<ide> // Set modification times
<ide> {
<del> const handle = await getHandle(dest);
<del>
<del> await utimes(dest, new Date(), new Date());
<del>
<del> try {
<del> await handle.utimes(new Date(), new Date());
<del> } catch (err) {
<del> // Some systems do not have futimes. If there is an error,
<del> // expect it to be ENOSYS
<del> common.expectsError({
<del> code: 'ENOSYS',
<del> name: 'Error'
<del> })(err);
<del> }
<del>
<del> await handle.close();
<add> await executeOnHandle(dest, async (handle) => {
<add>
<add> await utimes(dest, new Date(), new Date());
<add>
<add> try {
<add> await handle.utimes(new Date(), new Date());
<add> } catch (err) {
<add> // Some systems do not have futimes. If there is an error,
<add> // expect it to be ENOSYS
<add> common.expectsError({
<add> code: 'ENOSYS',
<add> name: 'Error'
<add> })(err);
<add> }
<add> });
<ide> }
<ide>
<ide> // Set modification times with lutimes
<ide> async function getHandle(dest) {
<ide>
<ide> // Regression test for https://github.com/nodejs/node/issues/38168
<ide> {
<del> const handle = await getHandle(dest);
<del>
<del> assert.rejects(
<del> async () => handle.write('abc', 0, 'hex'),
<del> {
<del> code: 'ERR_INVALID_ARG_VALUE',
<del> message: /'encoding' is invalid for data of length 3/
<del> }
<del> );
<add> await executeOnHandle(dest, async (handle) => {
<add> await assert.rejects(
<add> async () => handle.write('abc', 0, 'hex'),
<add> {
<add> code: 'ERR_INVALID_ARG_VALUE',
<add> message: /'encoding' is invalid for data of length 3/
<add> }
<add> );
<ide>
<del> const ret = await handle.write('abcd', 0, 'hex');
<del> assert.strictEqual(ret.bytesWritten, 2);
<del> await handle.close();
<add> const ret = await handle.write('abcd', 0, 'hex');
<add> assert.strictEqual(ret.bytesWritten, 2);
<add> });
<ide> }
<ide>
<ide> // Test prototype methods calling with contexts other than FileHandle
<ide> {
<del> const handle = await getHandle(dest);
<del> assert.rejects(() => handle.stat.call({}), {
<del> code: 'ERR_INTERNAL_ASSERTION',
<del> message: /handle must be an instance of FileHandle/
<add> await executeOnHandle(dest, async (handle) => {
<add> await assert.rejects(() => handle.stat.call({}), {
<add> code: 'ERR_INTERNAL_ASSERTION',
<add> message: /handle must be an instance of FileHandle/
<add> });
<ide> });
<del> await handle.close();
<ide> }
<ide> }
<ide>
<ide><path>test/parallel/test-fs-read-stream-pos.js
<ide> fs.writeFileSync(file, '');
<ide>
<ide> let counter = 0;
<ide>
<del>setInterval(() => {
<add>const writeInterval = setInterval(() => {
<ide> counter = counter + 1;
<ide> const line = `hello at ${counter}\n`;
<ide> fs.writeFileSync(file, line, { flag: 'a' });
<ide> let isLow = false;
<ide> let cur = 0;
<ide> let stream;
<ide>
<del>setInterval(() => {
<add>const readInterval = setInterval(() => {
<ide> if (stream) return;
<ide>
<ide> stream = fs.createReadStream(file, {
<ide> setInterval(() => {
<ide> return false;
<ide> });
<ide> assert.strictEqual(brokenLines.length, 0);
<del> process.exit();
<add> exitTest();
<ide> return;
<ide> }
<ide> if (chunk.length !== hwm) {
<ide> setInterval(() => {
<ide> }, 10);
<ide>
<ide> // Time longer than 90 seconds to exit safely
<del>setTimeout(() => {
<del> process.exit();
<add>const endTimer = setTimeout(() => {
<add> exitTest();
<ide> }, 90000);
<add>
<add>const exitTest = () => {
<add> clearInterval(readInterval);
<add> clearInterval(writeInterval);
<add> clearTimeout(endTimer);
<add> if (stream && !stream.destroyed) {
<add> stream.on('close', () => {
<add> process.exit();
<add> });
<add> stream.destroy();
<add> } else {
<add> process.exit();
<add> }
<add>};
<ide><path>test/parallel/test-fs-rm.js
<ide> const tmpdir = require('../common/tmpdir');
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide> const path = require('path');
<add>const { execSync } = require('child_process');
<add>
<ide> const { validateRmOptionsSync } = require('internal/fs/utils');
<ide>
<ide> tmpdir.refresh();
<ide> function removeAsync(dir) {
<ide> message: /^The value of "options\.maxRetries" is out of range\./
<ide> });
<ide> }
<add>
<add>{
<add> // IBMi has a different access permission mechanism
<add> // This test should not be run as `root`
<add> if (!common.isIBMi && (common.isWindows || process.getuid() !== 0)) {
<add> function makeDirectoryReadOnly(dir, mode) {
<add> let accessErrorCode = 'EACCES';
<add> if (common.isWindows) {
<add> accessErrorCode = 'EPERM';
<add> execSync(`icacls ${dir} /deny "everyone:(OI)(CI)(DE,DC)"`);
<add> } else {
<add> fs.chmodSync(dir, mode);
<add> }
<add> return accessErrorCode;
<add> }
<add>
<add> function makeDirectoryWritable(dir) {
<add> if (fs.existsSync(dir)) {
<add> if (common.isWindows) {
<add> execSync(`icacls ${dir} /remove:d "everyone"`);
<add> } else {
<add> fs.chmodSync(dir, 0o777);
<add> }
<add> }
<add> }
<add>
<add> {
<add> // Check that deleting a file that cannot be accessed using rmsync throws
<add> // https://github.com/nodejs/node/issues/38683
<add> const dirname = nextDirPath();
<add> const filePath = path.join(dirname, 'text.txt');
<add> try {
<add> fs.mkdirSync(dirname, { recursive: true });
<add> fs.writeFileSync(filePath, 'hello');
<add> const code = makeDirectoryReadOnly(dirname, 0o444);
<add> assert.throws(() => {
<add> fs.rmSync(filePath, { force: true });
<add> }, {
<add> code,
<add> name: 'Error',
<add> });
<add> } finally {
<add> makeDirectoryWritable(dirname);
<add> }
<add> }
<add>
<add> {
<add> // Check endless recursion.
<add> // https://github.com/nodejs/node/issues/34580
<add> const dirname = nextDirPath();
<add> fs.mkdirSync(dirname, { recursive: true });
<add> const root = fs.mkdtempSync(path.join(dirname, 'fs-'));
<add> const middle = path.join(root, 'middle');
<add> fs.mkdirSync(middle);
<add> fs.mkdirSync(path.join(middle, 'leaf')); // Make `middle` non-empty
<add> try {
<add> const code = makeDirectoryReadOnly(middle, 0o555);
<add> try {
<add> assert.throws(() => {
<add> fs.rmSync(root, { recursive: true });
<add> }, {
<add> code,
<add> name: 'Error',
<add> });
<add> } catch (err) {
<add> // Only fail the test if the folder was not deleted.
<add> // as in some cases rmSync succesfully deletes read-only folders.
<add> if (fs.existsSync(root)) {
<add> throw err;
<add> }
<add> }
<add> } finally {
<add> makeDirectoryWritable(middle);
<add> }
<add> }
<add> }
<add>}
| 9
|
Java
|
Java
|
add retry for flaky test (suspected tomcat issue)
|
0d42a1bd7fdd44b000873edd6cbbb35697fddc4a
|
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/socket/AbstractWebSocketIntegrationTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import java.lang.annotation.RetentionPolicy;
<ide> import java.lang.annotation.Target;
<ide> import java.net.URI;
<del>import java.net.URISyntaxException;
<ide> import java.util.LinkedHashMap;
<ide> import java.util.Map;
<ide> import java.util.stream.Stream;
<ide> private HttpHandler createHttpHandler() {
<ide> return WebHttpHandlerBuilder.applicationContext(context).build();
<ide> }
<ide>
<del> protected URI getUrl(String path) throws URISyntaxException {
<del> return new URI("ws://localhost:" + this.port + path);
<add> protected URI getUrl(String path) {
<add> return URI.create("ws://localhost:" + this.port + path);
<ide> }
<ide>
<ide> protected abstract Class<?> getWebConfigClass();
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/socket/WebSocketIntegrationTests.java
<ide> import reactor.core.publisher.Mono;
<ide> import reactor.core.publisher.MonoProcessor;
<ide> import reactor.core.publisher.ReplayProcessor;
<add>import reactor.util.retry.Retry;
<ide>
<ide> import org.springframework.context.annotation.Bean;
<ide> import org.springframework.context.annotation.Configuration;
<ide> import org.springframework.web.reactive.socket.client.WebSocketClient;
<ide> import org.springframework.web.server.WebFilter;
<ide> import org.springframework.web.testfixture.http.server.reactive.bootstrap.HttpServer;
<add>import org.springframework.web.testfixture.http.server.reactive.bootstrap.TomcatHttpServer;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide>
<ide> protected Class<?> getWebConfigClass() {
<ide> void echo(WebSocketClient client, HttpServer server, Class<?> serverConfigClass) throws Exception {
<ide> startServer(client, server, serverConfigClass);
<ide>
<add> if (server instanceof TomcatHttpServer) {
<add> Mono.fromRunnable(this::testEcho)
<add> .retryWhen(Retry.max(3).filter(ex -> ex instanceof IllegalStateException))
<add> .block();
<add> }
<add> else {
<add> testEcho();
<add> }
<add> }
<add>
<add> private void testEcho() {
<ide> int count = 100;
<ide> Flux<String> input = Flux.range(1, count).map(index -> "msg-" + index);
<ide> ReplayProcessor<Object> output = ReplayProcessor.create(count);
<del>
<ide> this.client.execute(getUrl("/echo"), session -> session
<ide> .send(input.map(session::textMessage))
<ide> .thenMany(session.receive().take(count).map(WebSocketMessage::getPayloadAsText))
<ide> .subscribeWith(output)
<ide> .then())
<ide> .block(TIMEOUT);
<del>
<del> assertThat(output.collectList().block(TIMEOUT)).isEqualTo(input.collectList().block(TIMEOUT));
<add> assertThat(output.isTerminated()).isTrue();
<add> assertThat(output.collectList().block()).isEqualTo(input.collectList().block());
<ide> }
<ide>
<ide> @ParameterizedWebSocketTest
| 2
|
Python
|
Python
|
remove unused `amsgrad` argument in sgd
|
330eb89a9a94e2621cfa03e813e3d252e91ee15a
|
<ide><path>keras/optimizers/optimizer_experimental/sgd.py
<ide> def __init__(
<ide> learning_rate=0.01,
<ide> momentum=0.0,
<ide> nesterov=False,
<del> amsgrad=False,
<ide> weight_decay=None,
<ide> clipnorm=None,
<ide> clipvalue=None,
| 1
|
PHP
|
PHP
|
remove pointless comparison
|
ad09b910ee27fadc0c3bcfe94c94ecc0c65dfd7f
|
<ide><path>lib/Cake/Controller/Component/CookieComponent.php
<ide> protected function _implode(array $array) {
<ide> */
<ide> protected function _explode($string) {
<ide> $first = substr($string, 0, 1);
<del> if ($first !== false && $first === '{' || $first === '[') {
<add> if ($first === '{' || $first === '[') {
<ide> $ret = json_decode($string, true);
<ide> return ($ret != null) ? $ret : $string;
<ide> }
| 1
|
Javascript
|
Javascript
|
fix semantic error
|
cf459052b41705522d8614a58e8eaf953efd9b7e
|
<ide><path>lib/Parser.js
<ide> Parser.prototype.enterObjectPattern = function enterObjectPattern(pattern, onIde
<ide> };
<ide>
<ide> Parser.prototype.enterArrayPattern = function enterArrayPattern(pattern, onIdent) {
<del> for(var elementIndex = 0, len = pattern.properties.length; elementIndex < len; elementIndex++) {
<add> for(var elementIndex = 0, len = pattern.elements.length; elementIndex < len; elementIndex++) {
<ide> var element = pattern.elements[elementIndex];
<ide> this.enterPattern(element, onIdent);
<ide> }
| 1
|
Javascript
|
Javascript
|
fix a little error with colorspace (#373)
|
a5d5f144bceb83e0153391d26bed741a02dc82de
|
<ide><path>pdf.js
<ide> var ColorSpace = (function() {
<ide> constructor.parse = function colorspace_parse(cs, xref, res) {
<ide> if (IsName(cs)) {
<ide> var colorSpaces = res.get('ColorSpace');
<del> if (colorSpaces) {
<add> if (colorSpaces && colorSpaces.get) {
<ide> var refcs = colorSpaces.get(cs.name);
<ide> if (refcs)
<ide> cs = refcs;
| 1
|
Ruby
|
Ruby
|
remove the default parameter and updated comment
|
a4a33fbb0a2375bfb13795148c17d460f3c5338d
|
<ide><path>lib/arel/visitors/dot.rb
<ide> def visit_String o
<ide>
<ide> def visit_Hash o
<ide> o.each_with_index do |pair, i|
<del> edge("pair_#{i}") { visit pair, a }
<add> edge("pair_#{i}") { visit pair }
<ide> end
<ide> end
<ide>
<ide> def visit_edge o, method
<ide> edge(method) { visit o.send(method) }
<ide> end
<ide>
<del> def visit o = nil
<add> def visit o
<ide> if node = @seen[o.object_id]
<ide> @edge_stack.last.to = node
<ide> return
<ide><path>lib/arel/visitors/oracle.rb
<ide> def order_hacks o
<ide> # Previous version with join and split broke ORDER BY clause
<ide> # if it contained functions with several arguments (separated by ',').
<ide> #
<del> # orders = o.orders.map { |x| visit x, a }.join(', ').split(',')
<add> # orders = o.orders.map { |x| visit x }.join(', ').split(',')
<ide> orders = o.orders.map do |x|
<ide> string = visit x
<ide> if string.include?(',')
| 2
|
Python
|
Python
|
use assertin, asertgreater, etc
|
131b0dd93f3e1793d98bda797e7d8388df774b71
|
<ide><path>celery/tests/app/test_schedules.py
<ide> def test_eq(self):
<ide> self.crontab(month_of_year='1'),
<ide> self.crontab(month_of_year='2'),
<ide> )
<del> self.assertFalse(object() == self.crontab(minute='1'))
<del> self.assertFalse(self.crontab(minute='1') == object())
<add> self.assertNotEqual(object(), self.crontab(minute='1'))
<add> self.assertNotEqual(self.crontab(minute='1'), object())
<ide> self.assertNotEqual(crontab(month_of_year='1'), schedule(10))
<ide>
<ide>
<ide><path>celery/tests/bin/test_multi.py
<ide> def test_parse(self, gethostname):
<ide> names = list(it)
<ide>
<ide> def assert_line_in(name, args):
<del> self.assertIn(name, [tup[0] for tup in names])
<add> self.assertIn(name, {tup[0] for tup in names})
<ide> argv = None
<ide> for item in names:
<ide> if item[0] == name:
<ide> def test_shutdown_nodes(self, slepp, gethostname, Pidfile):
<ide> self.assertEqual(len(sigs), 2)
<ide> self.assertIn(
<ide> ('foo@e.com', 10, signal.SIGTERM),
<del> [tup[0] for tup in sigs],
<add> {tup[0] for tup in sigs},
<ide> )
<ide> self.assertIn(
<ide> ('bar@e.com', 11, signal.SIGTERM),
<del> [tup[0] for tup in sigs],
<add> {tup[0] for tup in sigs},
<ide> )
<ide> self.t.signal_node.return_value = False
<ide> self.assertTrue(callback.called)
<ide><path>celery/tests/bin/test_worker.py
<ide> class test_Worker(WorkerAppCase):
<ide> def test_queues_string(self):
<ide> w = self.app.Worker()
<ide> w.setup_queues('foo,bar,baz')
<del> self.assertTrue('foo' in self.app.amqp.queues)
<add> self.assertIn('foo', self.app.amqp.queues)
<ide>
<ide> @disable_stdouts
<ide> def test_cpu_count(self):
<ide><path>celery/tests/concurrency/test_prefork.py
<ide> def test_start(self):
<ide> pool = TaskPool(10)
<ide> pool.start()
<ide> self.assertTrue(pool._pool.started)
<del> self.assertTrue(pool._pool._state == asynpool.RUN)
<add> self.assertEqual(pool._pool._state, asynpool.RUN)
<ide>
<ide> _pool = pool._pool
<ide> pool.stop()
<ide><path>celery/tests/events/test_state.py
<ide> def test_task_states(self):
<ide>
<ide> # RECEIVED
<ide> next(r)
<del> self.assertTrue(r.tid in r.state.tasks)
<add> self.assertIn(r.tid, r.state.tasks)
<ide> task = r.state.tasks[r.tid]
<ide> self.assertEqual(task.state, states.RECEIVED)
<ide> self.assertTrue(task.received)
<ide><path>celery/tests/tasks/test_result.py
<ide> def test_iterdeps(self):
<ide> list(x.iterdeps(intermediate=True))
<ide>
<ide> def test_eq_not_implemented(self):
<del> self.assertFalse(self.app.AsyncResult('1') == object())
<add> self.assertNotEqual(self.app.AsyncResult('1'), object())
<ide>
<ide> @depends_on_current_app
<ide> def test_reduce(self):
<ide> def test_resultset_repr(self):
<ide> [self.app.AsyncResult(t) for t in ['1', '2', '3']])))
<ide>
<ide> def test_eq_other(self):
<del> self.assertFalse(self.app.ResultSet(
<del> [self.app.AsyncResult(t) for t in [1, 3, 3]]) == 1)
<add> self.assertNotEqual(
<add> self.app.ResultSet([self.app.AsyncResult(t)
<add> for t in [1, 3, 3]]),
<add> 1,
<add> )
<ide> rs1 = self.app.ResultSet([self.app.AsyncResult(1)])
<ide> rs2 = self.app.ResultSet([self.app.AsyncResult(1)])
<del> self.assertTrue(rs1 == rs2)
<add> self.assertEqual(rs1, rs2)
<ide>
<ide> def test_get(self):
<ide> x = self.app.ResultSet([self.app.AsyncResult(t) for t in [1, 2, 3]])
<ide> def test_len(self):
<ide> self.assertEqual(len(self.ts), self.size)
<ide>
<ide> def test_eq_other(self):
<del> self.assertFalse(self.ts == 1)
<add> self.assertNotEqual(self.ts, 1)
<ide>
<ide> @depends_on_current_app
<ide> def test_pickleable(self):
<ide><path>celery/tests/tasks/test_states.py
<ide> from __future__ import absolute_import, unicode_literals
<ide>
<del>from celery.states import state
<ide> from celery import states
<add>
<ide> from celery.tests.case import Case
<ide>
<ide>
<ide> class test_state_precedence(Case):
<ide>
<ide> def test_gt(self):
<del> self.assertGreater(state(states.SUCCESS),
<del> state(states.PENDING))
<del> self.assertGreater(state(states.FAILURE),
<del> state(states.RECEIVED))
<del> self.assertGreater(state(states.REVOKED),
<del> state(states.STARTED))
<del> self.assertGreater(state(states.SUCCESS),
<del> state('CRASHED'))
<del> self.assertGreater(state(states.FAILURE),
<del> state('CRASHED'))
<del> self.assertFalse(state(states.REVOKED) > state('CRASHED'))
<add> self.assertGreater(
<add> states.state(states.SUCCESS), states.state(states.PENDING),
<add> )
<add> self.assertGreater(
<add> states.state(states.FAILURE), states.state(states.RECEIVED),
<add> )
<add> self.assertGreater(
<add> states.state(states.REVOKED), states.state(states.STARTED),
<add> )
<add> self.assertGreater(
<add> states.state(states.SUCCESS), states.state('CRASHED'),
<add> )
<add> self.assertGreater(
<add> states.state(states.FAILURE), states.state('CRASHED'),
<add> )
<add> self.assertLessEqual(
<add> states.state(states.REVOKED), states.state('CRASHED'),
<add> )
<ide>
<ide> def test_lt(self):
<del> self.assertLess(state(states.PENDING), state(states.SUCCESS))
<del> self.assertLess(state(states.RECEIVED), state(states.FAILURE))
<del> self.assertLess(state(states.STARTED), state(states.REVOKED))
<del> self.assertLess(state('CRASHED'), state(states.SUCCESS))
<del> self.assertLess(state('CRASHED'), state(states.FAILURE))
<del> self.assertTrue(state(states.REVOKED) < state('CRASHED'))
<del> self.assertTrue(state(states.REVOKED) <= state('CRASHED'))
<del> self.assertTrue(state('CRASHED') >= state(states.REVOKED))
<add> self.assertLess(
<add> states.state(states.PENDING), states.state(states.SUCCESS),
<add> )
<add> self.assertLess(
<add> states.state(states.RECEIVED), states.state(states.FAILURE),
<add> )
<add> self.assertLess(
<add> states.state(states.STARTED), states.state(states.REVOKED),
<add> )
<add> self.assertLess(
<add> states.state('CRASHED'), states.state(states.SUCCESS),
<add> )
<add> self.assertLess(
<add> states.state('CRASHED'), states.state(states.FAILURE),
<add> )
<add> self.assertLess(
<add> states.state(states.REVOKED), states.state('CRASHED'),
<add> )
<add> self.assertLessEqual(
<add> states.state(states.REVOKED), states.state('CRASHED'),
<add> )
<add> self.assertGreaterEqual(
<add> states.state('CRASHED'), states.state(states.REVOKED),
<add> )
<ide><path>celery/tests/utils/test_saferef.py
<ide> def test_in(self):
<ide>
<ide> """
<ide> for t in self.ts[:50]:
<del> self.assertTrue(safe_ref(t.x) in self.ss)
<add> self.assertIn(safe_ref(t.x), self.ss)
<ide>
<ide> def test_valid(self):
<ide> """test_value
| 8
|
Javascript
|
Javascript
|
publicize more dock methods
|
cabeeca8b6ca7b324c3a551d4b6eaea397f0aeb4
|
<ide><path>src/dock.js
<ide> module.exports = class Dock {
<ide> this.setState({draggingItem})
<ide> }
<ide>
<add> // Extended: Show the dock and focus its active {Pane}.
<ide> activate () {
<ide> this.getActivePane().activate()
<ide> }
<ide>
<add> // Extended: Show the dock without focusing it.
<ide> show () {
<ide> this.setState({visible: true})
<ide> }
<ide>
<add> // Extended: Hide the dock and activate the {WorkspaceCenter} if the dock was
<add> // was previously focused.
<ide> hide () {
<ide> this.setState({visible: false})
<ide> this.didHide()
<ide> }
<ide>
<add> // Extended: Toggle the dock's visiblity without changing the {Workspace}'s
<add> // active pane container.
<ide> toggle () {
<ide> this.setState({visible: !this.state.visible})
<ide> }
<ide>
<add> // Extended: Check if the dock is visible.
<add> //
<add> // Returns a {Boolean}.
<ide> isVisible () {
<ide> return this.state.visible
<ide> }
| 1
|
Ruby
|
Ruby
|
expose casks in tap.to_hash for tap-info --json
|
2c86e7e12794ffbd464a539273cd042187822ab4
|
<ide><path>Library/Homebrew/tap.rb
<ide> def to_hash
<ide> "formula_names" => formula_names,
<ide> "formula_files" => formula_files.map(&:to_s),
<ide> "command_files" => command_files.map(&:to_s),
<add> "cask_files" => cask_files.map(&:to_s),
<ide> "pinned" => pinned?,
<ide> }
<ide>
| 1
|
Javascript
|
Javascript
|
use reference check only when not using trackby
|
d7dc14dc0cdeb9c187d227e19acc8aca7df9d740
|
<ide><path>src/ng/directive/ngOptions.js
<ide> var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> // Check to see if the value has changed due to the update to the options
<ide> if (!ngModelCtrl.$isEmpty(previousValue)) {
<ide> var nextValue = selectCtrl.readValue();
<del> if (ngOptions.trackBy && !equals(previousValue, nextValue) ||
<del> previousValue !== nextValue) {
<add> if (ngOptions.trackBy ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
<ide> ngModelCtrl.$setViewValue(nextValue);
<ide> ngModelCtrl.$render();
<ide> }
<ide><path>test/ng/directive/ngOptionsSpec.js
<ide> describe('ngOptions', function() {
<ide>
<ide> });
<ide>
<add> it('should not set view value again if the tracked property of the model has not changed when using trackBy', function() {
<add>
<add> createSelect({
<add> 'ng-model': 'selected',
<add> 'ng-options': 'item for item in arr track by item.id'
<add> });
<add>
<add> scope.$apply(function() {
<add> scope.selected = {id: 10, label: 'ten'};
<add> });
<add>
<add> spyOn(element.controller('ngModel'), '$setViewValue');
<add>
<add> scope.$apply(function() {
<add> scope.arr[0] = {id: 10, label: 'ten'};
<add> });
<add>
<add> expect(element.controller('ngModel').$setViewValue).not.toHaveBeenCalled();
<add> });
<add>
<ide> it('should not re-render if a property of the model is changed when not using trackBy', function() {
<ide>
<ide> createSelect({
| 2
|
Ruby
|
Ruby
|
remove xcode 7 on 10.10 warning
|
a8476c0dbe016719fbca2327cd93ebb386b4fdff
|
<ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def check_xcode_select_path
<ide> end
<ide> end
<ide>
<del> # Xcode 7 lacking the 10.10 SDK is forcing sysroot to be declared
<del> # nil on 10.10 & breaking compiles. CLT is workaround.
<del> def check_sdk_path_not_nil_yosemite
<del> if MacOS.version == :yosemite && !MacOS::CLT.installed? && MacOS::Xcode.installed? && MacOS.sdk_path.nil?
<del> <<-EOS.undent
<del> Xcode 7 lacks the 10.10 SDK which can cause some builds to fail.
<del> We recommend installing the Command Line Tools with:
<del> xcode-select --install
<del> to resolve this issue.
<del> EOS
<del> end
<del> end
<del>
<ide> def check_user_path_1
<ide> $seen_prefix_bin = false
<ide> $seen_prefix_sbin = false
| 1
|
Python
|
Python
|
keep order in np.sort and np.partition copy
|
f0e6e0143c4a43e0bb9dcad7c567ffaa51d7a281
|
<ide><path>numpy/core/fromnumeric.py
<ide> def partition(a, kth, axis=-1, kind='introselect', order=None):
<ide> a = asanyarray(a).flatten()
<ide> axis = 0
<ide> else:
<del> a = asanyarray(a).copy()
<add> a = asanyarray(a).copy(order="K")
<ide> a.partition(kth, axis=axis, kind=kind, order=order)
<ide> return a
<ide>
<ide> def sort(a, axis=-1, kind='quicksort', order=None):
<ide> a = asanyarray(a).flatten()
<ide> axis = 0
<ide> else:
<del> a = asanyarray(a).copy()
<add> a = asanyarray(a).copy(order="K")
<ide> a.sort(axis, kind, order)
<ide> return a
<ide>
| 1
|
Text
|
Text
|
clarify use of `loading` property
|
d6f5ebf773f28026e230885b783c611510688c43
|
<ide><path>docs/advanced-features/dynamic-import.md
<ide> If you are not using React 18, you can use the `loading` attribute in place of t
<ide>
<ide> ```jsx
<ide> const DynamicHeader = dynamic(() => import('../components/header'), {
<del> loading: () => <header />,
<add> loading: () => <div>Loading...</div>,
<ide> })
<ide> ```
<ide>
| 1
|
Python
|
Python
|
add references to einops and opt_einsum
|
35c67f6d33aa82d1ee8bd4fbdc5b925ef560de2a
|
<ide><path>numpy/core/einsumfunc.py
<ide> def einsum(*operands, out=None, optimize=False, **kwargs):
<ide> --------
<ide> einsum_path, dot, inner, outer, tensordot, linalg.multi_dot
<ide>
<add> einops:
<add> similar verbose interface is provided by
<add> `einops <https://github.com/arogozhnikov/einops>`_ package to cover
<add> additional operations: transpose, reshape/flatten, repeat/tile,
<add> squeeze/unsqueeze and reductions.
<add>
<add> opt_einsum:
<add> `opt_einsum <https://optimized-einsum.readthedocs.io/en/stable/>`_
<add> optimizes contraction order for einsum-like expressions
<add> in backend-agnostic manner.
<add>
<ide> Notes
<ide> -----
<ide> .. versionadded:: 1.6.0
| 1
|
PHP
|
PHP
|
remove extra spacing
|
28e60c2f5ddfdee35564833ac36d0f13450690e7
|
<ide><path>src/Illuminate/Routing/Route.php
<ide> public function bindParameters(Request $request)
<ide> // compile that and get the parameter matches for this domain. We will then
<ide> // merge them into this parameters array so that this array is completed.
<ide> $params = $this->matchToKeys(
<del>
<ide> array_slice($this->bindPathParameters($request), 1)
<del>
<ide> );
<ide>
<ide> // If the route has a regular expression for the host part of the URI, we will
| 1
|
Text
|
Text
|
remove semicolons according code style
|
dcaa0c626f87016f0d8a80e0c119709b2a00b476
|
<ide><path>docs/FAQ.md
<ide> const mapStateToProps = (state) => {
<ide> return {
<ide> objects: state.objectIds.map(id => state.objects[id])
<ide> }
<del>};
<add>}
<ide> ```
<ide>
<ide> Even though the array might contain the exact same object references each time, the array itself is a different reference, so the shallow equality check fails and React Redux would re-render the wrapped component.
<ide><path>docs/api/README.md
<ide> Every function described above is a top-level export. You can import any of them
<ide> #### ES6
<ide>
<ide> ```js
<del>import { createStore } from 'redux';
<add>import { createStore } from 'redux'
<ide> ```
<ide>
<ide> #### ES5 (CommonJS)
<ide>
<ide> ```js
<del>var createStore = require('redux').createStore;
<add>var createStore = require('redux').createStore
<ide> ```
<ide>
<ide> #### ES5 (UMD build)
<ide>
<ide> ```js
<del>var createStore = Redux.createStore;
<add>var createStore = Redux.createStore
<ide> ```
<ide><path>docs/api/applyMiddleware.md
<ide> export default connect(
<ide> ```js
<ide> let middleware = [ a, b ]
<ide> if (process.env.NODE_ENV !== 'production') {
<del> let c = require('some-debug-middleware');
<del> let d = require('another-debug-middleware');
<del> middleware = [ ...middleware, c, d ];
<add> let c = require('some-debug-middleware')
<add> let d = require('another-debug-middleware')
<add> middleware = [ ...middleware, c, d ]
<ide> }
<ide>
<ide> const store = createStore(
<ide><path>docs/recipes/WritingTests.md
<ide> import thunk from 'redux-thunk'
<ide> import * as actions from '../../actions/counter'
<ide> import * as types from '../../constants/ActionTypes'
<ide> import nock from 'nock'
<del>import expect from 'expect'; // You can use any testing library
<add>import expect from 'expect' // You can use any testing library
<ide>
<ide> const middlewares = [ thunk ]
<ide> const mockStore = configureMockStore(middlewares)
<ide> const dispatchWithStoreOf = (storeData, action) => {
<ide> const dispatch = singleDispatch(createFakeStore(storeData))(actionAttempt => dispatched = actionAttempt)
<ide> dispatch(action)
<ide> return dispatched
<del>};
<add>}
<ide>
<ide> describe('middleware', () => {
<ide> it('should dispatch if store is empty', () => {
| 4
|
Mixed
|
Javascript
|
validate the input data to be of expected types
|
fb6df3bfac8ca38a7012eabf0563d7a799ce1acc
|
<ide><path>doc/api/fs.md
<ide> This happens when:
<ide> <!-- YAML
<ide> added: v0.0.2
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/31030
<add> description: The `buffer` parameter won't coerce unsupported input to
<add> strings anymore.
<ide> - version: v10.10.0
<ide> pr-url: https://github.com/nodejs/node/pull/22150
<ide> description: The `buffer` parameter can now be any `TypedArray` or a
<ide> the end of the file.
<ide> <!-- YAML
<ide> added: v0.11.5
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/31030
<add> description: The `string` parameter won't coerce unsupported input to
<add> strings anymore.
<ide> - version: v10.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/12562
<ide> description: The `callback` parameter is no longer optional. Not passing
<ide> details.
<ide> <!-- YAML
<ide> added: v0.1.29
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/31030
<add> description: The `data` parameter won't coerce unsupported input to
<add> strings anymore.
<ide> - version: v10.10.0
<ide> pr-url: https://github.com/nodejs/node/pull/22150
<ide> description: The `data` parameter can now be any `TypedArray` or a
<ide> to contain only `', World'`.
<ide> <!-- YAML
<ide> added: v0.1.29
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/31030
<add> description: The `data` parameter won't coerce unsupported input to
<add> strings anymore.
<ide> - version: v10.10.0
<ide> pr-url: https://github.com/nodejs/node/pull/22150
<ide> description: The `data` parameter can now be any `TypedArray` or a
<ide> this API: [`fs.writeFile()`][].
<ide> <!-- YAML
<ide> added: v0.1.21
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/31030
<add> description: The `buffer` parameter won't coerce unsupported input to
<add> strings anymore.
<ide> - version: v10.10.0
<ide> pr-url: https://github.com/nodejs/node/pull/22150
<ide> description: The `buffer` parameter can now be any `TypedArray` or a
<ide> this API: [`fs.write(fd, buffer...)`][].
<ide> <!-- YAML
<ide> added: v0.11.5
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/31030
<add> description: The `string` parameter won't coerce unsupported input to
<add> strings anymore.
<ide> - version: v7.2.0
<ide> pr-url: https://github.com/nodejs/node/pull/7856
<ide> description: The `position` parameter is optional now.
<ide> This function does not work on AIX versions before 7.1, it will resolve the
<ide> #### `filehandle.write(buffer[, offset[, length[, position]]])`
<ide> <!-- YAML
<ide> added: v10.0.0
<add>changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/31030
<add> description: The `buffer` parameter won't coerce unsupported input to
<add> buffers anymore.
<ide> -->
<ide>
<ide> * `buffer` {Buffer|Uint8Array}
<ide> the end of the file.
<ide> #### `filehandle.write(string[, position[, encoding]])`
<ide> <!-- YAML
<ide> added: v10.0.0
<add>changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/31030
<add> description: The `string` parameter won't coerce unsupported input to
<add> strings anymore.
<ide> -->
<ide>
<ide> * `string` {string}
<ide> added: v10.0.0
<ide> * Returns: {Promise}
<ide>
<ide> Write `string` to the file. If `string` is not a string, then
<del>the value will be coerced to one.
<add>an exception will be thrown.
<ide>
<ide> The `Promise` is resolved with an object containing a `bytesWritten` property
<ide> identifying the number of bytes written, and a `buffer` property containing
<ide> the end of the file.
<ide> #### `filehandle.writeFile(data, options)`
<ide> <!-- YAML
<ide> added: v10.0.0
<add>changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/31030
<add> description: The `data` parameter won't coerce unsupported input to
<add> strings anymore.
<ide> -->
<ide>
<ide> * `data` {string|Buffer|Uint8Array}
<ide> The `atime` and `mtime` arguments follow these rules:
<ide> ### `fsPromises.writeFile(file, data[, options])`
<ide> <!-- YAML
<ide> added: v10.0.0
<add>changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/31030
<add> description: The `data` parameter won't coerce unsupported input to
<add> strings anymore.
<ide> -->
<ide>
<ide> * `file` {string|Buffer|URL|FileHandle} filename or `FileHandle`
<ide><path>lib/fs.js
<ide> const {
<ide> validateOffsetLengthWrite,
<ide> validatePath,
<ide> validateRmdirOptions,
<add> validateStringAfterArrayBufferView,
<ide> warnOnNonPortableTemplate
<ide> } = require('internal/fs/utils');
<ide> const {
<ide> function write(fd, buffer, offset, length, position, callback) {
<ide>
<ide> validateInt32(fd, 'fd', 0);
<ide>
<del> const req = new FSReqCallback();
<del> req.oncomplete = wrapper;
<del>
<ide> if (isArrayBufferView(buffer)) {
<ide> callback = maybeCallback(callback || position || length || offset);
<ide> if (offset == null || typeof offset === 'function') {
<ide> function write(fd, buffer, offset, length, position, callback) {
<ide> if (typeof position !== 'number')
<ide> position = null;
<ide> validateOffsetLengthWrite(offset, length, buffer.byteLength);
<add>
<add> const req = new FSReqCallback();
<add> req.oncomplete = wrapper;
<ide> return binding.writeBuffer(fd, buffer, offset, length, position, req);
<ide> }
<ide>
<del> if (typeof buffer !== 'string')
<del> buffer += '';
<add> validateStringAfterArrayBufferView(buffer, 'buffer');
<add>
<ide> if (typeof position !== 'function') {
<ide> if (typeof offset === 'function') {
<ide> position = offset;
<ide> function write(fd, buffer, offset, length, position, callback) {
<ide> length = 'utf8';
<ide> }
<ide> callback = maybeCallback(position);
<add>
<add> const req = new FSReqCallback();
<add> req.oncomplete = wrapper;
<ide> return binding.writeString(fd, buffer, offset, length, req);
<ide> }
<ide>
<ide> function writeSync(fd, buffer, offset, length, position) {
<ide> result = binding.writeBuffer(fd, buffer, offset, length, position,
<ide> undefined, ctx);
<ide> } else {
<del> if (typeof buffer !== 'string')
<del> buffer += '';
<add> validateStringAfterArrayBufferView(buffer, 'buffer');
<add>
<ide> if (offset === undefined)
<ide> offset = null;
<ide> result = binding.writeString(fd, buffer, offset, length,
<ide> function writeFile(path, data, options, callback) {
<ide> options = getOptions(options, { encoding: 'utf8', mode: 0o666, flag: 'w' });
<ide> const flag = options.flag || 'w';
<ide>
<add> if (!isArrayBufferView(data)) {
<add> validateStringAfterArrayBufferView(data, 'data');
<add> data = Buffer.from(data, options.encoding || 'utf8');
<add> }
<add>
<ide> if (isFd(path)) {
<del> writeFd(path, true);
<add> const isUserFd = true;
<add> writeAll(path, isUserFd, data, 0, data.byteLength, null, callback);
<ide> return;
<ide> }
<ide>
<ide> fs.open(path, flag, options.mode, (openErr, fd) => {
<ide> if (openErr) {
<ide> callback(openErr);
<ide> } else {
<del> writeFd(fd, false);
<add> const isUserFd = false;
<add> const position = /a/.test(flag) ? null : 0;
<add> writeAll(fd, isUserFd, data, 0, data.byteLength, position, callback);
<ide> }
<ide> });
<del>
<del> function writeFd(fd, isUserFd) {
<del> const buffer = isArrayBufferView(data) ?
<del> data : Buffer.from('' + data, options.encoding || 'utf8');
<del> const position = (/a/.test(flag) || isUserFd) ? null : 0;
<del>
<del> writeAll(fd, isUserFd, buffer, 0, buffer.byteLength, position, callback);
<del> }
<ide> }
<ide>
<ide> function writeFileSync(path, data, options) {
<ide> options = getOptions(options, { encoding: 'utf8', mode: 0o666, flag: 'w' });
<add>
<add> if (!isArrayBufferView(data)) {
<add> validateStringAfterArrayBufferView(data, 'data');
<add> data = Buffer.from(data, options.encoding || 'utf8');
<add> }
<add>
<ide> const flag = options.flag || 'w';
<ide>
<ide> const isUserFd = isFd(path); // File descriptor ownership
<ide> const fd = isUserFd ? path : fs.openSync(path, flag, options.mode);
<ide>
<del> if (!isArrayBufferView(data)) {
<del> data = Buffer.from('' + data, options.encoding || 'utf8');
<del> }
<ide> let offset = 0;
<ide> let length = data.byteLength;
<ide> let position = (/a/.test(flag) || isUserFd) ? null : 0;
<ide><path>lib/internal/fs/promises.js
<ide> const {
<ide> ERR_INVALID_ARG_VALUE,
<ide> ERR_METHOD_NOT_IMPLEMENTED
<ide> } = require('internal/errors').codes;
<del>const { isUint8Array } = require('internal/util/types');
<add>const { isArrayBufferView } = require('internal/util/types');
<ide> const { rimrafPromises } = require('internal/fs/rimraf');
<ide> const {
<ide> copyObject,
<ide> const {
<ide> validateOffsetLengthRead,
<ide> validateOffsetLengthWrite,
<ide> validateRmdirOptions,
<add> validateStringAfterArrayBufferView,
<ide> warnOnNonPortableTemplate
<ide> } = require('internal/fs/utils');
<ide> const { opendir } = require('internal/fs/dir');
<ide> function validateFileHandle(handle) {
<ide> }
<ide>
<ide> async function writeFileHandle(filehandle, data, options) {
<del> let buffer = isUint8Array(data) ?
<del> data : Buffer.from('' + data, options.encoding || 'utf8');
<del> let remaining = buffer.length;
<add> if (!isArrayBufferView(data)) {
<add> validateStringAfterArrayBufferView(data, 'data');
<add> data = Buffer.from(data, options.encoding || 'utf8');
<add> }
<add> let remaining = data.length;
<ide> if (remaining === 0) return;
<ide> do {
<ide> const { bytesWritten } =
<del> await write(filehandle, buffer, 0,
<del> MathMin(16384, buffer.length));
<add> await write(filehandle, data, 0,
<add> MathMin(16384, data.length));
<ide> remaining -= bytesWritten;
<del> buffer = buffer.slice(bytesWritten);
<add> data = data.slice(bytesWritten);
<ide> } while (remaining > 0);
<ide> }
<ide>
<ide> async function write(handle, buffer, offset, length, position) {
<ide> if (buffer.length === 0)
<ide> return { bytesWritten: 0, buffer };
<ide>
<del> if (isUint8Array(buffer)) {
<add> if (isArrayBufferView(buffer)) {
<ide> if (offset == null) {
<ide> offset = 0;
<ide> } else {
<ide> async function write(handle, buffer, offset, length, position) {
<ide> return { bytesWritten, buffer };
<ide> }
<ide>
<del> if (typeof buffer !== 'string')
<del> buffer += '';
<add> validateStringAfterArrayBufferView(buffer, 'buffer');
<ide> const bytesWritten = (await binding.writeString(handle.fd, buffer, offset,
<ide> length, kUsePromises)) || 0;
<ide> return { bytesWritten, buffer };
<ide><path>lib/internal/fs/utils.js
<ide> const getValidMode = hideStackFrames((mode, type) => {
<ide> 'mode', `an integer >= ${min} && <= ${max}`, mode);
<ide> });
<ide>
<add>const validateStringAfterArrayBufferView = hideStackFrames((buffer, name) => {
<add> if (typeof buffer !== 'string') {
<add> throw new ERR_INVALID_ARG_TYPE(
<add> name,
<add> ['string', 'Buffer', 'TypedArray', 'DataView'],
<add> buffer
<add> );
<add> }
<add>});
<add>
<ide> module.exports = {
<ide> assertEncoding,
<ide> BigIntStats, // for testing
<ide> module.exports = {
<ide> validateOffsetLengthWrite,
<ide> validatePath,
<ide> validateRmdirOptions,
<add> validateStringAfterArrayBufferView,
<ide> warnOnNonPortableTemplate
<ide> };
<ide><path>test/parallel/test-fs-append-file-sync.js
<ide> const fileData3 = fs.readFileSync(filename3);
<ide>
<ide> assert.strictEqual(buf.length + currentFileData.length, fileData3.length);
<ide>
<del>// Test that appendFile accepts numbers.
<ide> const filename4 = join(tmpdir.path, 'append-sync4.txt');
<ide> fs.writeFileSync(filename4, currentFileData, { mode: m });
<ide>
<del>fs.appendFileSync(filename4, num, { mode: m });
<add>[
<add> true, false, 0, 1, Infinity, () => {}, {}, [], undefined, null
<add>].forEach((value) => {
<add> assert.throws(
<add> () => fs.appendFileSync(filename4, value, { mode: m }),
<add> { message: /data/, code: 'ERR_INVALID_ARG_TYPE' }
<add> );
<add>});
<add>fs.appendFileSync(filename4, `${num}`, { mode: m });
<ide>
<ide> // Windows permissions aren't Unix.
<ide> if (!common.isWindows) {
<ide><path>test/parallel/test-fs-append-file.js
<ide> const tmpdir = require('../common/tmpdir');
<ide>
<ide> const currentFileData = 'ABCD';
<ide>
<del>const n = 220;
<ide> const s = '南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、' +
<ide> '广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。' +
<ide> '南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。' +
<ide> const throwNextTick = (e) => { process.nextTick(() => { throw e; }); };
<ide> .catch(throwNextTick);
<ide> }
<ide>
<del>// Test that appendFile accepts numbers (callback API).
<del>{
<del> const filename = join(tmpdir.path, 'append-numbers.txt');
<del> fs.writeFileSync(filename, currentFileData);
<del>
<del> const m = 0o600;
<del> fs.appendFile(filename, n, { mode: m }, common.mustCall((e) => {
<del> assert.ifError(e);
<del>
<del> // Windows permissions aren't Unix.
<del> if (!common.isWindows) {
<del> const st = fs.statSync(filename);
<del> assert.strictEqual(st.mode & 0o700, m);
<del> }
<del>
<del> fs.readFile(filename, common.mustCall((e, buffer) => {
<del> assert.ifError(e);
<del> assert.strictEqual(Buffer.byteLength(String(n)) + currentFileData.length,
<del> buffer.length);
<del> }));
<del> }));
<del>}
<del>
<del>// Test that appendFile accepts numbers (promises API).
<del>{
<del> const filename = join(tmpdir.path, 'append-numbers-promises.txt');
<del> fs.writeFileSync(filename, currentFileData);
<del>
<del> const m = 0o600;
<del> fs.promises.appendFile(filename, n, { mode: m })
<del> .then(common.mustCall(() => {
<del> // Windows permissions aren't Unix.
<del> if (!common.isWindows) {
<del> const st = fs.statSync(filename);
<del> assert.strictEqual(st.mode & 0o700, m);
<del> }
<del>
<del> return fs.promises.readFile(filename);
<del> }))
<del> .then((buffer) => {
<del> assert.strictEqual(Buffer.byteLength(String(n)) + currentFileData.length,
<del> buffer.length);
<del> })
<del> .catch(throwNextTick);
<del>}
<add>// Test that appendFile does not accept numbers (callback API).
<add>[false, 5, {}, [], null, undefined].forEach((data) => {
<add> const errObj = {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> message: /"data"|"buffer"/
<add> };
<add> assert.throws(
<add> () => fs.appendFile('foobar', data, common.mustNotCall()),
<add> errObj
<add> );
<add> assert.throws(() => fs.appendFileSync('foobar', data), errObj);
<add> assert.rejects(fs.promises.appendFile('foobar', data), errObj);
<add>});
<ide>
<ide> // Test that appendFile accepts file descriptors (callback API).
<ide> {
<ide><path>test/parallel/test-fs-buffertype-writesync.js
<ide> 'use strict';
<ide> require('../common');
<ide>
<del>// This test ensures that writeSync does support inputs which
<del>// are then correctly converted into string buffers.
<add>// This test ensures that writeSync throws for invalid data input.
<ide>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<del>const path = require('path');
<ide>
<del>const tmpdir = require('../common/tmpdir');
<del>
<del>const filePath = path.join(tmpdir.path, 'test_buffer_type');
<del>const v = [true, false, 0, 1, Infinity, () => {}, {}, [], undefined, null];
<del>
<del>tmpdir.refresh();
<del>
<del>v.forEach((value) => {
<del> const fd = fs.openSync(filePath, 'w');
<del> fs.writeSync(fd, value);
<del> assert.strictEqual(fs.readFileSync(filePath).toString(), String(value));
<del> fs.closeSync(fd);
<add>[
<add> true, false, 0, 1, Infinity, () => {}, {}, [], undefined, null
<add>].forEach((value) => {
<add> assert.throws(
<add> () => fs.writeSync(1, value),
<add> { message: /"buffer"/, code: 'ERR_INVALID_ARG_TYPE' }
<add> );
<ide> });
<ide><path>test/parallel/test-fs-promises-file-handle-write.js
<ide> async function validateNonStringValuesWrite() {
<ide> const fileHandle = await open(filePathForHandle, 'w+');
<ide> const nonStringValues = [123, {}, new Map()];
<ide> for (const nonStringValue of nonStringValues) {
<del> await fileHandle.write(nonStringValue);
<add> await assert.rejects(
<add> fileHandle.write(nonStringValue),
<add> { message: /"buffer"/, code: 'ERR_INVALID_ARG_TYPE' }
<add> );
<ide> }
<ide>
<del> const readFileData = fs.readFileSync(filePathForHandle);
<del> const expected = ['123', '[object Object]', '[object Map]'].join('');
<del> assert.deepStrictEqual(Buffer.from(expected, 'utf8'), readFileData);
<del>
<ide> await fileHandle.close();
<ide> }
<ide>
<ide><path>test/parallel/test-fs-promises.js
<ide> async function getHandle(dest) {
<ide> {
<ide> const dir = path.join(tmpDir, nextdir(), nextdir());
<ide> await mkdir(path.dirname(dir));
<del> await writeFile(dir);
<add> await writeFile(dir, '');
<ide> assert.rejects(
<ide> mkdir(dir, { recursive: true }),
<ide> {
<ide> async function getHandle(dest) {
<ide> const file = path.join(tmpDir, nextdir(), nextdir());
<ide> const dir = path.join(file, nextdir(), nextdir());
<ide> await mkdir(path.dirname(file));
<del> await writeFile(file);
<add> await writeFile(file, '');
<ide> assert.rejects(
<ide> mkdir(dir, { recursive: true }),
<ide> {
<ide><path>test/parallel/test-fs-write-file.js
<ide> tmpdir.refresh();
<ide>
<ide> const filename = join(tmpdir.path, 'test.txt');
<ide>
<del>const n = 220;
<ide> const s = '南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、' +
<ide> '广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。' +
<ide> '南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。' +
<ide> fs.writeFile(filename2, buf, common.mustCall(function(e) {
<ide> }));
<ide> }));
<ide>
<del>// Test that writeFile accepts numbers.
<del>const filename3 = join(tmpdir.path, 'test3.txt');
<del>
<del>const m = 0o600;
<del>fs.writeFile(filename3, n, { mode: m }, common.mustCall(function(e) {
<del> assert.ifError(e);
<del>
<del> // Windows permissions aren't Unix.
<del> if (!common.isWindows) {
<del> const st = fs.statSync(filename3);
<del> assert.strictEqual(st.mode & 0o700, m);
<del> }
<del>
<del> fs.readFile(filename3, common.mustCall(function(e, buffer) {
<del> assert.ifError(e);
<del>
<del> assert.strictEqual(Buffer.byteLength(String(n)), buffer.length);
<del> }));
<del>}));
<del>
<ide> // Test that writeFile accepts file descriptors.
<ide> const filename4 = join(tmpdir.path, 'test4.txt');
<ide>
<ide><path>test/parallel/test-fs-write-string-coerce.js
<del>'use strict';
<del>const common = require('../common');
<del>const assert = require('assert');
<del>const path = require('path');
<del>const fs = require('fs');
<del>
<del>const tmpdir = require('../common/tmpdir');
<del>tmpdir.refresh();
<del>
<del>const fn = path.join(tmpdir.path, 'write-string-coerce.txt');
<del>const data = true;
<del>const expected = String(data);
<del>
<del>fs.open(fn, 'w', 0o644, common.mustCall(function(err, fd) {
<del> assert.ifError(err);
<del> console.log('open done');
<del> fs.write(fd, data, 0, 'utf8', common.mustCall(function(err, written) {
<del> console.log('write done');
<del> assert.ifError(err);
<del> assert.strictEqual(written, Buffer.byteLength(expected));
<del> fs.closeSync(fd);
<del> const found = fs.readFileSync(fn, 'utf8');
<del> console.log(`expected: "${expected}"`);
<del> console.log(`found: "${found}"`);
<del> fs.unlinkSync(fn);
<del> assert.strictEqual(found, expected);
<del> }));
<del>}));
<ide><path>test/parallel/test-fs-write.js
<ide> fs.open(fn3, 'w', 0o644, common.mustCall((err, fd) => {
<ide> }
<ide> );
<ide> });
<add>
<add>[false, 5, {}, [], null, undefined].forEach((data) => {
<add> assert.throws(
<add> () => fs.write(1, data, common.mustNotCall()),
<add> {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> message: /"buffer"/
<add> }
<add> );
<add> assert.throws(
<add> () => fs.writeSync(1, data),
<add> {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> message: /"buffer"/
<add> }
<add> );
<add>});
| 12
|
Ruby
|
Ruby
|
reset compiler when testing fails_with
|
bb8fcc89014de64d5faf7e8ac9a252144addb508
|
<ide><path>Library/Homebrew/test/test_formula.rb
<ide> def test_compiler_selection
<ide> cs = CompilerSelector.new(f)
<ide> cs.select_compiler
<ide> assert_equal MacOS.default_compiler, ENV.compiler
<add> ENV.send MacOS.default_compiler
<ide>
<ide> f = TestNoCompilerFailures.new
<ide> assert !(f.fails_with? :clang)
<ide> def test_compiler_selection
<ide> cs = CompilerSelector.new(f)
<ide> cs.select_compiler
<ide> assert_equal MacOS.default_compiler, ENV.compiler
<add> ENV.send MacOS.default_compiler
<ide>
<ide> f = TestLLVMFailure.new
<ide> assert !(f.fails_with? :clang)
<ide> def test_compiler_selection
<ide> when 0..210 then :gcc
<ide> else :clang
<ide> end
<add> ENV.send MacOS.default_compiler
<ide>
<ide> f = TestMixedCompilerFailures.new
<ide> assert f.fails_with? :clang
<ide> def test_compiler_selection
<ide> cs = CompilerSelector.new(f)
<ide> cs.select_compiler
<ide> assert_equal :llvm, ENV.compiler
<add> ENV.send MacOS.default_compiler
<ide>
<ide> f = TestMoreMixedCompilerFailures.new
<ide> assert !(f.fails_with? :clang)
<ide> def test_compiler_selection
<ide> cs = CompilerSelector.new(f)
<ide> cs.select_compiler
<ide> assert_equal :clang, ENV.compiler
<add> ENV.send MacOS.default_compiler
<ide>
<ide> f = TestEvenMoreMixedCompilerFailures.new
<ide> assert f.fails_with? :clang
<ide> def test_compiler_selection
<ide> cs = CompilerSelector.new(f)
<ide> cs.select_compiler
<ide> assert_equal :clang, ENV.compiler
<add> ENV.send MacOS.default_compiler
<ide>
<ide> f = TestBlockWithoutBuildCompilerFailure.new
<ide> assert f.fails_with? :clang
<ide> def test_compiler_selection
<ide> cs = CompilerSelector.new(f)
<ide> cs.select_compiler
<ide> assert_equal MacOS.default_compiler, ENV.compiler
<add> ENV.send MacOS.default_compiler
<ide> end
<ide> end
| 1
|
PHP
|
PHP
|
add assertion with empty chain
|
6f8b87eee17114f1cf0ff896db9fdcc31f0fc8f0
|
<ide><path>src/Illuminate/Support/Testing/Fakes/QueueFake.php
<ide> public function assertPushedWithChain($job, $expectedChain = [], $callback = nul
<ide> : $this->assertPushedWithChainOfClasses($job, $expectedChain, $callback);
<ide> }
<ide>
<add> /**
<add> * Assert if a job was pushed with empty chain based on a truth-test callback.
<add> *
<add> * @param string $job
<add> * @param callable|null $callback
<add> * @return void
<add> */
<add> public function assertPushedWithEmptyChain($job, $callback = null)
<add> {
<add> PHPUnit::assertTrue(
<add> $this->pushed($job, $callback)->isNotEmpty(),
<add> "The expected [{$job}] job was not pushed."
<add> );
<add>
<add> $this->assertPushedWithChainOfClasses($job, [], $callback);
<add> }
<add>
<ide> /**
<ide> * Assert if a job was pushed with chained jobs based on a truth-test callback.
<ide> *
<ide><path>tests/Support/SupportTestingQueueFakeTest.php
<ide> public function testAssertPushedWithChainUsingClassesOrObjectsArray()
<ide> ]);
<ide> }
<ide>
<add> public function testAssertPushedWithEmptyChain()
<add> {
<add> $this->fake->push(new JobWithChainStub([]));
<add>
<add> $this->fake->assertPushedWithEmptyChain(JobWithChainStub::class);
<add> }
<add>
<ide> public function testAssertPushedWithChainSameJobDifferentChains()
<ide> {
<ide> $this->fake->push(new JobWithChainStub([
| 2
|
Ruby
|
Ruby
|
hide the cxxstdlib data structure better
|
a5a2141a1569bada1397b0b369311deea2888630
|
<ide><path>Library/Homebrew/cxxstdlib.rb
<ide> def compatible_with?(other)
<ide> end
<ide>
<ide> def check_dependencies(formula, deps)
<del> unless formula.class.cxxstdlib.include? :skip
<add> unless formula.skip_cxxstdlib_check?
<ide> deps.each do |dep|
<ide> # Software is unlikely to link against anything from its
<ide> # buildtime deps, so it doesn't matter at all if they link
<ide><path>Library/Homebrew/formula.rb
<ide> def skip_clean? path
<ide> self.class.skip_clean_paths.include? to_check
<ide> end
<ide>
<add> def skip_cxxstdlib_check?
<add> self.class.cxxstdlib.include?(:skip)
<add> end
<add>
<ide> # yields self with current working directory set to the uncompressed tarball
<ide> def brew
<ide> validate_attributes :name, :version
| 2
|
PHP
|
PHP
|
condense isset calls
|
0d2713b16fa17f672d12b2f4fdda39c091496fbe
|
<ide><path>src/View/Helper/HtmlHelper.php
<ide> public function meta($type, $content = null, array $options = [])
<ide> } else {
<ide> $type = ['name' => $type, 'content' => $content];
<ide> }
<del> } elseif (isset($options['type']) && isset($types[$options['type']])) {
<add> } elseif (isset($options['type'], $types[$options['type']])) {
<ide> $type = $types[$options['type']];
<ide> unset($options['type']);
<ide> } else {
| 1
|
PHP
|
PHP
|
extract formattreelist() from findtreelist()
|
f64dfb9add68f1dc1ed1090430f700eb8fbcf092
|
<ide><path>src/ORM/Behavior/TreeBehavior.php
<ide> function ($field) {
<ide> */
<ide> public function findTreeList(Query $query, array $options)
<ide> {
<del> return $this->_scope($query)
<add> $results = $this->_scope($query)
<ide> ->find('threaded', [
<ide> 'parentField' => $this->config('parent'),
<ide> 'order' => [$this->config('left') => 'ASC']
<del> ])
<del> ->formatResults(function ($results) use ($options) {
<del> $options += [
<del> 'keyPath' => $this->_getPrimaryKey(),
<del> 'valuePath' => $this->_table->displayField(),
<del> 'spacer' => '_'
<del> ];
<del> return $results
<del> ->listNested()
<del> ->printer($options['valuePath'], $options['keyPath'], $options['spacer']);
<del> });
<add> ]);
<add> return $this->formatTreeList($results, $options);
<add> }
<add>
<add> /**
<add> * Formats query as a flat list where the keys are
<add> * the primary key for the table and the values are the display field for the table.
<add> * Values are prefixed to visually indicate relative depth in the tree.
<add> *
<add> * Available options are:
<add> *
<add> * - keyPath: A dot separated path to fetch the field to use for the array key, or a closure to
<add> * return the key out of the provided row.
<add> * - valuePath: A dot separated path to fetch the field to use for the array value, or a closure to
<add> * return the value out of the provided row.
<add> * - spacer: A string to be used as prefix for denoting the depth in the tree for each item
<add> *
<add> * @param \Cake\ORM\Query $query
<add> * @param array $options Array of options as described above
<add> * @return \Cake\ORM\Query
<add> */
<add> public function formatTreeList(Query $query, array $options = [])
<add> {
<add> return $query->formatResults(function ($results) use ($options) {
<add> $options += [
<add> 'keyPath' => $this->_getPrimaryKey(),
<add> 'valuePath' => $this->_table->displayField(),
<add> 'spacer' => '_'
<add> ];
<add> return $results
<add> ->listNested()
<add> ->printer($options['valuePath'], $options['keyPath'], $options['spacer']);
<add> });
<ide> }
<ide>
<ide> /**
| 1
|
Text
|
Text
|
update windows build instructions
|
2d07d6662c9b55ffd3bb8dc8b5163d07f147dd1e
|
<ide><path>docs/build-instructions/windows.md
<ide>
<ide> ## Why do I have to use GitHub for Windows?
<ide>
<del>You don't, You can use your existing Git! GitHub for Windows's Git Shell is just
<del>easier to set up. You need to have Posix tools in your `%PATH%` (i.e. `grep`,
<del>`sed`, et al.), which isn't the default configuration when you install Git. To
<del>fix this, you probably need to fiddle with your system PATH.
<add>You don't. You can use your existing Git! GitHub for Windows's Git Shell is just
<add>easier to set up.
<add>
<add>If you _prefer_ using your existing Git installation, make sure git's cmd directory is in your PATH env variable (e.g. `C:\Program Files (x86)\Git\cmd`) before you open your powershell or command window.
<add>Note that you may have to open your command window as administrator. For powershell that doesn't seem to always be the case, though.
<add>
<add>If none of this works, do install Github for Windows and use its Git shell. Makes life easier.
<add>
<ide>
<ide> ## Troubleshooting
<ide>
<ide> fix this, you probably need to fiddle with your system PATH.
<ide> * https://github.com/TooTallNate/node-gyp/issues/297
<ide> * https://code.google.com/p/gyp/issues/detail?id=393
<ide>
<add>* Other `node-gyp` errors on first build attempt, even though the right node and python versions are installed.
<add> * Do try the build command one more time, as experience shows it often works on second try in many of these cases.
<add>
<add>
<ide> ### Windows build error reports in atom/atom
<del>* Use [this search](https://github.com/atom/atom/search?q=label%3Abuild-error+label%3Awindows&type=Issues) to get a list of reports about build errors on Windows.
<add>* If all fails, use [this search](https://github.com/atom/atom/search?q=label%3Abuild-error+label%3Awindows&type=Issues) to get a list of reports about build errors on Windows, and see if yours has already been reported.
<add>
<add>* If it hasn't, please open a new issue with a print/screenshot of your Windows version, 32/64bit and build output, incl. the node and python versions.
| 1
|
Java
|
Java
|
fix import org.apache.http.protocol.httpcontext;
|
6d3066fbacfa88364177b288dff51045af117c25
|
<ide><path>rxjava-contrib/rxjava-apache-http/src/main/java/rx/apache/http/ObservableHttp.java
<ide> import org.apache.http.nio.client.HttpAsyncClient;
<ide> import org.apache.http.nio.client.methods.HttpAsyncMethods;
<ide> import org.apache.http.nio.protocol.HttpAsyncRequestProducer;
<del>import org.apache.http.protocol.Http.HttpContext;
<add>import org.apache.http.protocol.HttpContext;
<ide> import org.apache.http.protocol.BasicHttpContext;
<ide>
<ide> import rx.Observable;
| 1
|
Go
|
Go
|
fix panic on devicemapper initialization
|
f08989902374a517b1f8e5e0bfd3b4ea59e5ba27
|
<ide><path>daemon/graphdriver/devmapper/deviceset.go
<ide> func getDeviceUUID(device string) (string, error) {
<ide> }
<ide>
<ide> func (devices *DeviceSet) verifyBaseDeviceUUID(baseInfo *DevInfo) error {
<add> devices.Lock()
<add> defer devices.Unlock()
<add>
<ide> if err := devices.activateDeviceIfNeeded(baseInfo); err != nil {
<ide> return err
<ide> }
<ide> func (devices *DeviceSet) verifyBaseDeviceUUID(baseInfo *DevInfo) error {
<ide> }
<ide>
<ide> func (devices *DeviceSet) saveBaseDeviceUUID(baseInfo *DevInfo) error {
<add> devices.Lock()
<add> defer devices.Unlock()
<add>
<ide> if err := devices.activateDeviceIfNeeded(baseInfo); err != nil {
<ide> return err
<ide> }
| 1
|
Ruby
|
Ruby
|
use ivar accessors
|
856cebd9b45c40f361c62ca780ff8ef8976e64b9
|
<ide><path>Library/Homebrew/formula.rb
<ide> def initialize name='__UNKNOWN__', path=nil
<ide>
<ide> @active_spec = determine_active_spec
<ide> validate_attributes :url, :name, :version
<del> @downloader = download_strategy.new(name, @active_spec)
<add> @downloader = download_strategy.new(name, active_spec)
<ide>
<ide> # Combine DSL `option` and `def options`
<ide> options.each do |opt, desc|
<ide><path>Library/Homebrew/formula_support.rb
<ide> def initialize url=nil, version=nil
<ide> end
<ide>
<ide> def download_strategy
<del> @download_strategy ||= DownloadStrategyDetector.detect(@url, @using)
<add> @download_strategy ||= DownloadStrategyDetector.detect(url, using)
<ide> end
<ide>
<ide> def verify_download_integrity fn
<del> fn.verify_checksum @checksum
<add> fn.verify_checksum(checksum)
<ide> rescue ChecksumMissingError
<ide> opoo "Cannot verify package integrity"
<ide> puts "The formula did not provide a download checksum"
<ide> def version val=nil
<ide> end
<ide>
<ide> def mirror val
<del> @mirrors << val
<add> mirrors << val
<ide> end
<ide> end
<ide>
| 2
|
Text
|
Text
|
update details and add example [ci skip]
|
e9b68d4f4c02285bc83625101ea60d0a74d7c7cb
|
<ide><path>website/docs/usage/v3-1.md
<ide> annotations can be added via the [`Doc.spans`](/api/doc#spans) in the training
<ide> data under the key defined as
<ide> [`incorrect_spans_key`](/api/entityrecognizer#init) in the component config.
<ide>
<add>```python
<add>train_doc = nlp.make_doc("Barack Obama was born in Hawaii.")
<add># The doc.spans key can be defined in the config
<add>train_doc.spans["incorrect_spans"] = [
<add> Span(doc, 0, 2, label="ORG"),
<add> Span(doc, 5, 6, label="PRODUCT")
<add>]
<add>```
<add>
<ide> <!-- TODO: more details and/or example project? -->
<ide>
<ide> ### New pipeline packages for Catalan and Danish {#pipeline-packages}
<ide>
<del><!-- TODO: intro and update with final numbers -->
<add>spaCy v3.1 adds 5 new pipeline packages, including a new core family for Catalan
<add>and a new transformer-based pipeline for Danish using the
<add>[`danish-bert-botxo`](http://huggingface.co/Maltehb/danish-bert-botxo) weights.
<add>See the [models directory](/models) for an overview of all available trained
<add>pipelines and the [training guide](/usage/training) for details on how to train
<add>your own.
<add>
<add><!-- TODO: thank contributors and update with final numbers -->
<ide>
<ide> | Package | Language | Tagger | Parser | NER |
<ide> | ------------------------------------------------- | -------- | -----: | -----: | ---: |
| 1
|
Python
|
Python
|
fix xlnet & transfotests
|
b4a3a647448a1d54a9d130670344643a19a87d0d
|
<ide><path>tests/test_modeling_tf_transfo_xl.py
<ide> def test_lm_generate_transfo_xl_wt103(self):
<ide> 24,
<ide> 24,
<ide> 0,
<del> 29546,
<del> 40,
<del> 1092,
<del> 18,
<del> 8,
<del> 5854,
<del> 7,
<del> 1143,
<del> 2,
<del> 7,
<add> 33,
<ide> 1,
<del> 159,
<del> 99,
<del> 16,
<add> 1857,
<add> 2,
<ide> 1,
<ide> 1009,
<ide> 4,
<ide><path>tests/test_modeling_tf_xlnet.py
<ide> def test_lm_generate_xlnet_base_cased(self):
<ide> 9,
<ide> 4,
<ide> 3,
<del> 1722,
<del> 19,
<del> 24,
<del> 6348,
<del> 61,
<del> 977,
<del> 176,
<del> 1772,
<del> 33,
<del> 45,
<del> 970,
<del> 19,
<del> 4185,
<ide> 19,
<add> 12943,
<add> 4354,
<add> 153,
<ide> 27,
<ide> 442,
<ide> 22,
<ide><path>tests/test_modeling_transfo_xl.py
<ide> def test_lm_generate_transfo_xl_wt103(self):
<ide> # father initially slaps him for making such an accusation , Rasputin watches as the
<ide> # man is chased outside and beaten . Twenty years later , Rasputin sees a vision of
<ide> # the Virgin Mary , prompting him to become a priest . Rasputin quickly becomes famous ,
<add>
<ide> # with people , even a bishop , begging for his blessing . <eod> </s> <eos>
<ide>
<ide> expected_output_ids = [
<ide> def test_lm_generate_transfo_xl_wt103(self):
<ide> 24,
<ide> 24,
<ide> 0,
<del> 29546,
<del> 40,
<del> 1092,
<del> 18,
<del> 8,
<del> 5854,
<del> 7,
<del> 1143,
<del> 2,
<del> 7,
<add> 33,
<ide> 1,
<del> 159,
<del> 99,
<del> 16,
<add> 1857,
<add> 2,
<ide> 1,
<ide> 1009,
<ide> 4,
<ide><path>tests/test_modeling_xlnet.py
<ide> def prepare_config_and_inputs(self):
<ide>
<ide> input_ids_q = ids_tensor([self.batch_size, self.seq_length + 1], self.vocab_size)
<ide> perm_mask = torch.zeros(
<del> self.batch_size, self.seq_length + 1, self.seq_length + 1, dtype=torch.float, device=torch_device
<add> self.batch_size, self.seq_length + 1, self.seq_length + 1, dtype=torch.float, device=torch_device,
<ide> )
<ide> perm_mask[:, :, -1] = 1.0 # Previous tokens don't see last token
<ide> target_mapping = torch.zeros(
<del> self.batch_size, 1, self.seq_length + 1, dtype=torch.float, device=torch_device
<add> self.batch_size, 1, self.seq_length + 1, dtype=torch.float, device=torch_device,
<ide> )
<ide> target_mapping[:, 0, -1] = 1.0 # predict last token
<ide>
<ide> def create_and_check_xlnet_base_model(
<ide> self.parent.assertEqual(len(no_mems_outputs), 1)
<ide>
<ide> self.parent.assertListEqual(
<del> list(result["outputs"].size()), [self.batch_size, self.seq_length, self.hidden_size]
<add> list(result["outputs"].size()), [self.batch_size, self.seq_length, self.hidden_size],
<ide> )
<ide> self.parent.assertListEqual(
<ide> list(list(mem.size()) for mem in result["mems_1"]),
<ide> def create_and_check_xlnet_lm_head(
<ide>
<ide> self.parent.assertListEqual(list(result["loss_1"].size()), [])
<ide> self.parent.assertListEqual(
<del> list(result["all_logits_1"].size()), [self.batch_size, self.seq_length, self.vocab_size]
<add> list(result["all_logits_1"].size()), [self.batch_size, self.seq_length, self.vocab_size],
<ide> )
<ide> self.parent.assertListEqual(
<ide> list(list(mem.size()) for mem in result["mems_1"]),
<ide> def create_and_check_xlnet_lm_head(
<ide>
<ide> self.parent.assertListEqual(list(result["loss_2"].size()), [])
<ide> self.parent.assertListEqual(
<del> list(result["all_logits_2"].size()), [self.batch_size, self.seq_length, self.vocab_size]
<add> list(result["all_logits_2"].size()), [self.batch_size, self.seq_length, self.vocab_size],
<ide> )
<ide> self.parent.assertListEqual(
<ide> list(list(mem.size()) for mem in result["mems_2"]),
<ide> def create_and_check_xlnet_qa(
<ide> model.eval()
<ide>
<ide> outputs = model(input_ids_1)
<del> start_top_log_probs, start_top_index, end_top_log_probs, end_top_index, cls_logits, mems = outputs
<add> (start_top_log_probs, start_top_index, end_top_log_probs, end_top_index, cls_logits, mems,) = outputs
<ide>
<ide> outputs = model(
<ide> input_ids_1,
<ide> def create_and_check_xlnet_qa(
<ide>
<ide> total_loss, mems = outputs
<ide>
<del> outputs = model(input_ids_1, start_positions=sequence_labels, end_positions=sequence_labels)
<add> outputs = model(input_ids_1, start_positions=sequence_labels, end_positions=sequence_labels,)
<ide>
<ide> total_loss, mems = outputs
<ide>
<ide> def create_and_check_xlnet_qa(
<ide>
<ide> self.parent.assertListEqual(list(result["loss"].size()), [])
<ide> self.parent.assertListEqual(
<del> list(result["start_top_log_probs"].size()), [self.batch_size, model.config.start_n_top]
<add> list(result["start_top_log_probs"].size()), [self.batch_size, model.config.start_n_top],
<ide> )
<ide> self.parent.assertListEqual(
<del> list(result["start_top_index"].size()), [self.batch_size, model.config.start_n_top]
<add> list(result["start_top_index"].size()), [self.batch_size, model.config.start_n_top],
<ide> )
<ide> self.parent.assertListEqual(
<ide> list(result["end_top_log_probs"].size()),
<ide> def create_and_check_xlnet_token_classif(
<ide>
<ide> self.parent.assertListEqual(list(result["loss"].size()), [])
<ide> self.parent.assertListEqual(
<del> list(result["logits"].size()), [self.batch_size, self.seq_length, self.type_sequence_label_size]
<add> list(result["logits"].size()), [self.batch_size, self.seq_length, self.type_sequence_label_size],
<ide> )
<ide> self.parent.assertListEqual(
<ide> list(list(mem.size()) for mem in result["mems_1"]),
<ide> def create_and_check_xlnet_sequence_classif(
<ide>
<ide> self.parent.assertListEqual(list(result["loss"].size()), [])
<ide> self.parent.assertListEqual(
<del> list(result["logits"].size()), [self.batch_size, self.type_sequence_label_size]
<add> list(result["logits"].size()), [self.batch_size, self.type_sequence_label_size],
<ide> )
<ide> self.parent.assertListEqual(
<ide> list(list(mem.size()) for mem in result["mems_1"]),
<ide> def test_lm_generate_xlnet_base_cased(self):
<ide> 9,
<ide> 4,
<ide> 3,
<del> 1722,
<del> 19,
<del> 24,
<del> 6348,
<del> 61,
<del> 977,
<del> 176,
<del> 1772,
<del> 33,
<del> 45,
<del> 970,
<del> 19,
<del> 4185,
<ide> 19,
<add> 12943,
<add> 4354,
<add> 153,
<ide> 27,
<ide> 442,
<ide> 22,
<ide> def test_lm_generate_xlnet_base_cased(self):
<ide> # the men are forced to leave the monastery. Rasputin is forced to return to
<ide>
<ide> output_ids = model.generate(input_ids, max_length=200, do_sample=False)
<del>
<ide> self.assertListEqual(output_ids[0].tolist(), expected_output_ids)
| 4
|
PHP
|
PHP
|
remove unused command i added
|
ae16e5930eaa7d9e4518edea75740f1a7ee5a472
|
<ide><path>src/Illuminate/Database/Schema/Grammars/SQLiteGrammar.php
<ide> public function compileCreate(Blueprint $blueprint, Fluent $command)
<ide> );
<ide> }
<ide>
<del> /**
<del> * Compile a get all tables command.
<del> *
<del> * @param string $schema
<del> * @return string
<del> */
<del> public function compileGetAllTables()
<del> {
<del> return "select name from sqlite_master where type='table'";
<del> }
<del>
<ide> /**
<ide> * Get the foreign key syntax for a table creation statement.
<ide> *
| 1
|
Python
|
Python
|
add additional test cases for region argument
|
0805528a2bf4054036bd7a85b9b506695611c918
|
<ide><path>libcloud/test/compute/test_ovh.py
<ide> def setUp(self):
<ide> OvhMockHttp.type = None
<ide> self.driver = OvhNodeDriver(*OVH_PARAMS)
<ide>
<add> def test_region_argument(self):
<add> driver = OvhNodeDriver(*OVH_PARAMS)
<add> self.assertEqual(driver.connection.host, 'api.ovh.com')
<add>
<add> driver = OvhNodeDriver(*OVH_PARAMS, region=None)
<add> self.assertEqual(driver.connection.host, 'api.ovh.com')
<add>
<add> driver = OvhNodeDriver(*OVH_PARAMS, region='ca')
<add>
<add> driver = OvhNodeDriver(*OVH_PARAMS, region='eu')
<add> self.assertEqual(driver.connection.host, 'eu.api.ovh.com')
<add>
<add> driver = OvhNodeDriver(*OVH_PARAMS, region='ca')
<add> self.assertEqual(driver.connection.host, 'ca.api.ovh.com')
<add>
<ide> def test_list_nodes_invalid_region(self):
<ide> OvhNodeDriver.connectionCls.conn_class = LibcloudConnection
<ide> driver = OvhNodeDriver(*OVH_PARAMS, region='invalid')
| 1
|
Go
|
Go
|
add test coverage for seccomp implementation
|
137f86067cc1c9b30e5a59e73f91ed8876705b8f
|
<ide><path>daemon/seccomp_linux_test.go
<add>// +build linux,seccomp
<add>
<add>package daemon // import "github.com/docker/docker/daemon"
<add>
<add>import (
<add> "testing"
<add>
<add> coci "github.com/containerd/containerd/oci"
<add> config "github.com/docker/docker/api/types/container"
<add> "github.com/docker/docker/container"
<add> doci "github.com/docker/docker/oci"
<add> "github.com/docker/docker/profiles/seccomp"
<add> specs "github.com/opencontainers/runtime-spec/specs-go"
<add> "gotest.tools/v3/assert"
<add>)
<add>
<add>func TestWithSeccomp(t *testing.T) {
<add>
<add> type expected struct {
<add> daemon *Daemon
<add> c *container.Container
<add> inSpec coci.Spec
<add> outSpec coci.Spec
<add> err string
<add> comment string
<add> }
<add>
<add> for _, x := range []expected{
<add> {
<add> comment: "unconfined seccompProfile runs unconfined",
<add> daemon: &Daemon{
<add> seccompEnabled: true,
<add> },
<add> c: &container.Container{
<add> SeccompProfile: "unconfined",
<add> HostConfig: &config.HostConfig{
<add> Privileged: false,
<add> },
<add> },
<add> inSpec: doci.DefaultLinuxSpec(),
<add> outSpec: doci.DefaultLinuxSpec(),
<add> },
<add> {
<add> comment: "privileged container w/ custom profile runs unconfined",
<add> daemon: &Daemon{
<add> seccompEnabled: true,
<add> },
<add> c: &container.Container{
<add> SeccompProfile: "{ \"defaultAction\": \"SCMP_ACT_LOG\" }",
<add> HostConfig: &config.HostConfig{
<add> Privileged: true,
<add> },
<add> },
<add> inSpec: doci.DefaultLinuxSpec(),
<add> outSpec: doci.DefaultLinuxSpec(),
<add> },
<add> {
<add> comment: "privileged container w/ default runs unconfined",
<add> daemon: &Daemon{
<add> seccompEnabled: true,
<add> },
<add> c: &container.Container{
<add> SeccompProfile: "",
<add> HostConfig: &config.HostConfig{
<add> Privileged: true,
<add> },
<add> },
<add> inSpec: doci.DefaultLinuxSpec(),
<add> outSpec: doci.DefaultLinuxSpec(),
<add> },
<add> {
<add> comment: "privileged container w/ daemon profile runs unconfined",
<add> daemon: &Daemon{
<add> seccompEnabled: true,
<add> seccompProfile: []byte("{ \"defaultAction\": \"SCMP_ACT_ERRNO\" }"),
<add> },
<add> c: &container.Container{
<add> SeccompProfile: "",
<add> HostConfig: &config.HostConfig{
<add> Privileged: true,
<add> },
<add> },
<add> inSpec: doci.DefaultLinuxSpec(),
<add> outSpec: doci.DefaultLinuxSpec(),
<add> },
<add> {
<add> comment: "custom profile when seccomp is disabled returns error",
<add> daemon: &Daemon{
<add> seccompEnabled: false,
<add> },
<add> c: &container.Container{
<add> SeccompProfile: "{ \"defaultAction\": \"SCMP_ACT_ERRNO\" }",
<add> HostConfig: &config.HostConfig{
<add> Privileged: false,
<add> },
<add> },
<add> inSpec: doci.DefaultLinuxSpec(),
<add> outSpec: doci.DefaultLinuxSpec(),
<add> err: "seccomp is not enabled in your kernel, cannot run a custom seccomp profile",
<add> },
<add> {
<add> comment: "empty profile name loads default profile",
<add> daemon: &Daemon{
<add> seccompEnabled: true,
<add> },
<add> c: &container.Container{
<add> SeccompProfile: "",
<add> HostConfig: &config.HostConfig{
<add> Privileged: false,
<add> },
<add> },
<add> inSpec: doci.DefaultLinuxSpec(),
<add> outSpec: func() coci.Spec {
<add> s := doci.DefaultLinuxSpec()
<add> profile, _ := seccomp.GetDefaultProfile(&s)
<add> s.Linux.Seccomp = profile
<add> return s
<add> }(),
<add> },
<add> {
<add> comment: "load container's profile",
<add> daemon: &Daemon{
<add> seccompEnabled: true,
<add> },
<add> c: &container.Container{
<add> SeccompProfile: "{ \"defaultAction\": \"SCMP_ACT_ERRNO\" }",
<add> HostConfig: &config.HostConfig{
<add> Privileged: false,
<add> },
<add> },
<add> inSpec: doci.DefaultLinuxSpec(),
<add> outSpec: func() coci.Spec {
<add> s := doci.DefaultLinuxSpec()
<add> profile := &specs.LinuxSeccomp{
<add> DefaultAction: specs.LinuxSeccompAction("SCMP_ACT_ERRNO"),
<add> }
<add> s.Linux.Seccomp = profile
<add> return s
<add> }(),
<add> },
<add> {
<add> comment: "load daemon's profile",
<add> daemon: &Daemon{
<add> seccompEnabled: true,
<add> seccompProfile: []byte("{ \"defaultAction\": \"SCMP_ACT_ERRNO\" }"),
<add> },
<add> c: &container.Container{
<add> SeccompProfile: "",
<add> HostConfig: &config.HostConfig{
<add> Privileged: false,
<add> },
<add> },
<add> inSpec: doci.DefaultLinuxSpec(),
<add> outSpec: func() coci.Spec {
<add> s := doci.DefaultLinuxSpec()
<add> profile := &specs.LinuxSeccomp{
<add> DefaultAction: specs.LinuxSeccompAction("SCMP_ACT_ERRNO"),
<add> }
<add> s.Linux.Seccomp = profile
<add> return s
<add> }(),
<add> },
<add> {
<add> comment: "load prioritise container profile over daemon's",
<add> daemon: &Daemon{
<add> seccompEnabled: true,
<add> seccompProfile: []byte("{ \"defaultAction\": \"SCMP_ACT_ERRNO\" }"),
<add> },
<add> c: &container.Container{
<add> SeccompProfile: "{ \"defaultAction\": \"SCMP_ACT_LOG\" }",
<add> HostConfig: &config.HostConfig{
<add> Privileged: false,
<add> },
<add> },
<add> inSpec: doci.DefaultLinuxSpec(),
<add> outSpec: func() coci.Spec {
<add> s := doci.DefaultLinuxSpec()
<add> profile := &specs.LinuxSeccomp{
<add> DefaultAction: specs.LinuxSeccompAction("SCMP_ACT_LOG"),
<add> }
<add> s.Linux.Seccomp = profile
<add> return s
<add> }(),
<add> },
<add> } {
<add> t.Run(x.comment, func(t *testing.T) {
<add> opts := WithSeccomp(x.daemon, x.c)
<add> err := opts(nil, nil, nil, &x.inSpec)
<add>
<add> assert.DeepEqual(t, x.inSpec, x.outSpec)
<add> if x.err != "" {
<add> assert.Error(t, err, x.err)
<add> } else {
<add> assert.NilError(t, err)
<add> }
<add> })
<add> }
<add>}
| 1
|
PHP
|
PHP
|
return instance from eloquent setters
|
f59d8a8ca4a2ddc08415634f473d604ec7b4ffdd
|
<ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public function getVisible()
<ide> * Set the visible attributes for the model.
<ide> *
<ide> * @param array $visible
<del> * @return void
<add> * @return $this
<ide> */
<ide> public function setVisible(array $visible)
<ide> {
<ide> $this->visible = $visible;
<add>
<add> return $this;
<ide> }
<ide>
<ide> /**
<ide> public function addVisible($attributes = null)
<ide> * Set the accessors to append to model arrays.
<ide> *
<ide> * @param array $appends
<del> * @return void
<add> * @return $this
<ide> */
<ide> public function setAppends(array $appends)
<ide> {
<ide> $this->appends = $appends;
<add>
<add> return $this;
<ide> }
<ide>
<ide> /**
| 1
|
Go
|
Go
|
remove dead code
|
164d0bca63b74e6e0deeceee17b55c044f8d274e
|
<ide><path>daemon/container_unix.go
<ide> import (
<ide> "github.com/docker/docker/utils"
<ide> "github.com/docker/docker/volume"
<ide> "github.com/docker/libnetwork"
<del> "github.com/docker/libnetwork/drivers/bridge"
<ide> "github.com/docker/libnetwork/netlabel"
<ide> "github.com/docker/libnetwork/options"
<ide> "github.com/docker/libnetwork/types"
<ide> func (container *Container) buildCreateEndpointOptions(n libnetwork.Network) ([]
<ide> return createOptions, nil
<ide> }
<ide>
<del>func createNetwork(controller libnetwork.NetworkController, dnet string, driver string) (libnetwork.Network, error) {
<del> createOptions := []libnetwork.NetworkOption{}
<del> genericOption := options.Generic{}
<del>
<del> // Bridge driver is special due to legacy reasons
<del> if runconfig.NetworkMode(driver).IsBridge() {
<del> genericOption[netlabel.GenericData] = map[string]string{
<del> bridge.BridgeName: dnet,
<del> }
<del> networkOption := libnetwork.NetworkOptionGeneric(genericOption)
<del> createOptions = append(createOptions, networkOption)
<del> }
<del>
<del> return controller.NewNetwork(driver, dnet, createOptions...)
<del>}
<del>
<ide> func (container *Container) allocateNetwork() error {
<ide> updateSettings := false
<ide> if len(container.NetworkSettings.Networks) == 0 {
| 1
|
PHP
|
PHP
|
fix error code check
|
8e795a1e220ae089746b2e04580b6a32258a4504
|
<ide><path>src/Http/Client/Adapter/Curl.php
<ide> public function send(Request $request, array $options)
<ide> curl_close($ch);
<ide>
<ide> $status = 500;
<del> if ($error === 28) {
<add> if ($errorCode === 28) {
<ide> $status = 504;
<ide> }
<ide> throw new HttpException("cURL Error ({$errorCode}) {$error}", $status);
| 1
|
Javascript
|
Javascript
|
remove errant console.log
|
4f01b4b186368fe70cdd3853262f2b1856541b06
|
<ide><path>src/renderers/shared/reconciler/__tests__/ReactUpdates-test.js
<ide> describe('ReactUpdates', function() {
<ide> this.state = { showChild: true };
<ide> }
<ide> componentDidMount() {
<del> console.log('about to remove child via set state');
<ide> this.setState({ showChild: false });
<ide> }
<ide> render() {
| 1
|
Javascript
|
Javascript
|
use title - filename as document.title
|
025ee3f9afa255d021ab6f0c5f02a550496f94f0
|
<ide><path>web/viewer.js
<ide> var PDFView = {
<ide> pdfTitle = info['Title'];
<ide>
<ide> if (pdfTitle)
<del> document.title = pdfTitle;
<add> document.title = pdfTitle + ' - ' + document.title;
<ide> },
<ide>
<ide> setHash: function pdfViewSetHash(hash) {
| 1
|
Ruby
|
Ruby
|
freeze more strings
|
73528b6a08cb26e326300a1cb4b6743b6d25719c
|
<ide><path>Library/Homebrew/cask/exceptions.rb
<ide> def to_s
<ide> s << "\n" unless reason.end_with?("\n")
<ide> end
<ide>
<del> s
<add> s.freeze
<ide> end
<ide> end
<ide>
<ide> def to_s
<ide> s << "\n" unless reason.end_with?("\n")
<ide> end
<ide>
<del> s
<add> s.freeze
<ide> end
<ide> end
<ide>
<ide> def to_s
<ide> s << "\n" unless reason.end_with?("\n")
<ide> end
<ide>
<del> s
<add> s.freeze
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/cmd/gist-logs.rb
<ide> def brief_build_info(f)
<ide> s << "Host: #{hostname}\n"
<ide> end
<ide> s << "Build date: #{build_time_str}\n"
<del> s
<add> s.freeze
<ide> end
<ide>
<ide> # Causes some terminals to display secure password entry indicators
| 2
|
Python
|
Python
|
fix conllu2json converter to output all sentences
|
bdfb696677a7591ced018e7597c00929e97c6837
|
<ide><path>spacy/cli/converters/conllu2json.py
<ide> def conllu2json(input_data, n_sents=10, use_morphology=False, lang=None, **_):
<ide> doc = create_doc(sentences, i)
<ide> docs.append(doc)
<ide> sentences = []
<add> if sentences:
<add> doc = create_doc(sentences, i)
<add> docs.append(doc)
<ide> return docs
<ide>
<ide>
| 1
|
Javascript
|
Javascript
|
handle model updates when options are manipulated
|
47c15fbcc10f118170813021e8e605ffd263ad84
|
<ide><path>src/ng/directive/select.js
<ide> var SelectController =
<ide>
<ide> // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
<ide> self.ngModelCtrl = noopNgModelController;
<add> self.multiple = false;
<ide>
<ide> // The "unknown" option is one that is prepended to the list if the viewValue
<ide> // does not match any of the options. When it is rendered the value of the unknown
<ide> var SelectController =
<ide> }
<ide> var count = optionsMap.get(value) || 0;
<ide> optionsMap.put(value, count + 1);
<del> self.ngModelCtrl.$render();
<add> // Only render at the end of a digest. This improves render performance when many options
<add> // are added during a digest and ensures all relevant options are correctly marked as selected
<add> scheduleRender();
<ide> };
<ide>
<ide> // Tell the select control that an option, with the given value, has been removed
<ide> var SelectController =
<ide> };
<ide>
<ide>
<add> var renderScheduled = false;
<add> function scheduleRender() {
<add> if (renderScheduled) return;
<add> renderScheduled = true;
<add> $scope.$$postDigest(function() {
<add> renderScheduled = false;
<add> self.ngModelCtrl.$render();
<add> });
<add> }
<ide>
<ide> var updateScheduled = false;
<ide> function scheduleViewValueUpdate(renderAfter) {
<ide> var SelectController =
<ide> } else if (interpolateValueFn) {
<ide> // The value attribute is interpolated
<ide> optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
<add> var currentVal = self.readValue();
<add> var removal;
<add> var previouslySelected = optionElement.prop('selected');
<add> var removedVal;
<add>
<ide> if (isDefined(oldVal)) {
<ide> self.removeOption(oldVal);
<add> removal = true;
<add> removedVal = oldVal;
<ide> }
<ide> oldVal = newVal;
<ide> self.addOption(newVal, optionElement);
<add>
<add> if (removal && previouslySelected) {
<add> scheduleViewValueUpdate();
<add> }
<ide> });
<ide> } else if (interpolateTextFn) {
<ide> // The text content is interpolated
<ide> optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
<ide> optionAttrs.$set('value', newVal);
<add> var previouslySelected = optionElement.prop('selected');
<ide> if (oldVal !== newVal) {
<ide> self.removeOption(oldVal);
<ide> }
<ide> self.addOption(newVal, optionElement);
<add>
<add> if (oldVal && previouslySelected) {
<add> scheduleViewValueUpdate();
<add> }
<ide> });
<ide> } else {
<ide> // The value attribute is static
<ide> self.addOption(optionAttrs.value, optionElement);
<ide> }
<ide>
<add>
<add> var oldDisabled;
<add> optionAttrs.$observe('disabled', function(newVal) {
<add>
<add> // Since model updates will also select disabled options (like ngOptions),
<add> // we only have to handle options becoming disabled, not enabled
<add>
<add> if (newVal === 'true' || newVal && optionElement.prop('selected')) {
<add> if (self.multiple) {
<add> scheduleViewValueUpdate(true);
<add> } else {
<add> self.ngModelCtrl.$setViewValue(null);
<add> self.ngModelCtrl.$render();
<add> }
<add> oldDisabled = newVal;
<add> }
<add> });
<add>
<ide> optionElement.on('$destroy', function() {
<del> self.removeOption(optionAttrs.value);
<add> var currentValue = self.readValue();
<add> var removeValue = optionAttrs.value;
<add>
<add> self.removeOption(removeValue);
<ide> self.ngModelCtrl.$render();
<add>
<add> if (self.multiple && currentValue && currentValue.indexOf(removeValue) !== -1 ||
<add> currentValue === removeValue
<add> ) {
<add> // When multiple (selected) options are destroyed at the same time, we don't want
<add> // to run a model update for each of them. Instead, run a single update in the $$postDigest
<add> scheduleViewValueUpdate(true);
<add> }
<ide> });
<ide> };
<ide> }];
<ide> var selectDirective = function() {
<ide> // we have to add an extra watch since ngModel doesn't work well with arrays - it
<ide> // doesn't trigger rendering if only an item in the array changes.
<ide> if (attr.multiple) {
<add> selectCtrl.multiple = true;
<ide>
<ide> // Read value now needs to check each option to see if it is selected
<ide> selectCtrl.readValue = function readMultipleValue() {
<ide> var array = [];
<ide> forEach(element.find('option'), function(option) {
<del> if (option.selected) {
<add> if (option.selected && !option.disabled) {
<ide> var val = option.value;
<ide> array.push(val in selectCtrl.selectValueMap ? selectCtrl.selectValueMap[val] : val);
<ide> }
<ide><path>test/ng/directive/selectSpec.js
<ide> describe('select', function() {
<ide> scope.$apply(function() {
<ide> scope.robots.pop();
<ide> });
<del> expect(element).toEqualSelect([unknownValue('r2d2')], 'c3p0');
<del> expect(scope.robot).toBe('r2d2');
<add> expect(element).toEqualSelect([unknownValue(null)], 'c3p0');
<add> expect(scope.robot).toBe(null);
<ide>
<ide> scope.$apply(function() {
<ide> scope.robots.unshift('r2d2');
<ide> });
<add> expect(element).toEqualSelect([unknownValue(null)], 'r2d2', 'c3p0');
<add> expect(scope.robot).toBe(null);
<add>
<add> scope.$apply(function() {
<add> scope.robot = 'r2d2';
<add> });
<add>
<ide> expect(element).toEqualSelect(['r2d2'], 'c3p0');
<del> expect(scope.robot).toBe('r2d2');
<ide>
<ide> scope.$apply(function() {
<ide> delete scope.robots;
<ide> });
<del> expect(element).toEqualSelect([unknownValue('r2d2')]);
<del> expect(scope.robot).toBe('r2d2');
<add>
<add> expect(element).toEqualSelect([unknownValue(null)]);
<add> expect(scope.robot).toBe(null);
<ide> });
<ide> });
<ide>
<ide> describe('select', function() {
<ide>
<ide> });
<ide>
<add> });
<add>
<add> describe('updating the model and selection when option elements are manipulated', function() {
<add>
<add> they('should set the model to null when the currently selected option with $prop is removed',
<add> ['ngValue', 'interpolatedValue', 'interpolatedText'], function(prop) {
<add>
<add> var A = { name: 'A'}, B = { name: 'B'}, C = { name: 'C'};
<add>
<add> scope.options = [A, B, C];
<add> scope.obj = {};
<add>
<add> var optionString = '';
<add>
<add> switch (prop) {
<add> case 'ngValue':
<add> optionString = '<option ng-repeat="option in options" ng-value="option">{{$index}}</option>';
<add> break;
<add> case 'interpolatedValue':
<add> optionString = '<option ng-repeat="option in options" value="{{option.name}}">{{$index}}</option>';
<add> break;
<add> case 'interpolatedText':
<add> optionString = '<option ng-repeat="option in options">{{option.name}}</option>';
<add> break;
<add> }
<add>
<add> compile(
<add> '<select ng-model="obj.value">' +
<add> optionString +
<add> '</select>'
<add> );
<add>
<add> var optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(4);
<add> browserTrigger(optionElements.eq(0));
<add>
<add> optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(3);
<add> expect(scope.obj.value).toBe(prop === 'ngValue' ? A : 'A');
<add>
<add> scope.options.shift();
<add> scope.$digest();
<add>
<add> optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(3);
<add> expect(scope.obj.value).toBe(null);
<add> expect(element.val()).toBe('? object:null ?');
<add> });
<add>
<add>
<add> they('should set the model to null when the currently selected option with $prop changes its value',
<add> [
<add> 'ngValue',
<add> 'interpolatedValue',
<add> 'interpolatedText'
<add> ], function(prop) {
<add>
<add> var A = { name: 'A'}, B = { name: 'B'}, C = { name: 'C'};
<add>
<add> scope.options = [A, B, C];
<add> scope.obj = {};
<add>
<add> var optionString = '';
<add>
<add> switch (prop) {
<add> case 'ngValue':
<add> optionString = '<option ng-repeat="option in options" ng-value="option.name">{{$index}}</option>';
<add> break;
<add> case 'interpolatedValue':
<add> optionString = '<option ng-repeat="option in options" value="{{option.name}}">{{$index}}</option>';
<add> break;
<add> case 'interpolatedText':
<add> optionString = '<option ng-repeat="option in options">{{option.name}}</option>';
<add> break;
<add> }
<add>
<add> compile(
<add> '<select ng-model="obj.value">' +
<add> optionString +
<add> '</select>'
<add> );
<add>
<add> var optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(4);
<add> browserTrigger(optionElements.eq(0));
<add>
<add> optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(3);
<add> expect(scope.obj.value).toBe('A');
<add>
<add> A.name = 'X';
<add> scope.$digest();
<add>
<add> optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(4);
<add> expect(scope.obj.value).toBe(null);
<add> expect(element.val()).toBe('? string:A ?');
<add> });
<add>
<add>
<add> they('should set the model to null when the currently selected option with $prop is disabled',
<add> [
<add> 'ngValue',
<add> 'interpolatedValue',
<add> 'interpolatedText'
<add> ], function(prop) {
<add>
<add> var A = { name: 'A'}, B = { name: 'B'}, C = { name: 'C'};
<add>
<add> scope.options = [A, B, C];
<add> scope.obj = {};
<add>
<add> var optionString = '';
<add>
<add> switch (prop) {
<add> case 'ngValue':
<add> optionString = '<option ng-repeat="option in options" ng-disabled="option.disabled" ng-value="option.name">{{$index}}</option>';
<add> break;
<add> case 'interpolatedValue':
<add> optionString = '<option ng-repeat="option in options" ng-disabled="option.disabled" value="{{option.name}}">{{$index}}</option>';
<add> break;
<add> case 'interpolatedText':
<add> optionString = '<option ng-repeat="option in options" ng-disabled="option.disabled">{{option.name}}</option>';
<add> break;
<add> }
<add>
<add> compile(
<add> '<select ng-model="obj.value">' +
<add> optionString +
<add> '</select>'
<add> );
<add>
<add> var optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(4);
<add> browserTrigger(optionElements.eq(0));
<add>
<add> optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(3);
<add> expect(scope.obj.value).toBe('A');
<add>
<add> A.disabled = true;
<add> scope.$digest();
<add>
<add> optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(4);
<add> expect(scope.obj.value).toBe(null);
<add> expect(element.val()).toBe('? object:null ?');
<add> });
<add>
<add>
<add> they('should select a disabled option with $prop when the model is set to the matching value',
<add> [
<add> 'ngValue',
<add> 'interpolatedValue',
<add> 'interpolatedText'
<add> ], function(prop) {
<add>
<add> var A = { name: 'A'}, B = { name: 'B'}, C = { name: 'C'};
<add>
<add> scope.options = [A, B, C];
<add> scope.obj = {};
<add>
<add> var optionString = '';
<add>
<add> switch (prop) {
<add> case 'ngValue':
<add> optionString = '<option ng-repeat="option in options" ng-disabled="option.disabled" ng-value="option.name">{{$index}}</option>';
<add> break;
<add> case 'interpolatedValue':
<add> optionString = '<option ng-repeat="option in options" ng-disabled="option.disabled" value="{{option.name}}">{{$index}}</option>';
<add> break;
<add> case 'interpolatedText':
<add> optionString = '<option ng-repeat="option in options" ng-disabled="option.disabled">{{option.name}}</option>';
<add> break;
<add> }
<add>
<add> compile(
<add> '<select ng-model="obj.value">' +
<add> optionString +
<add> '</select>'
<add> );
<add>
<add> var optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(4);
<add> expect(optionElements[0].value).toEqual(unknownValue(undefined));
<add>
<add> B.disabled = true;
<add> scope.$digest();
<add>
<add> optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(4);
<add> expect(optionElements[0].value).toEqual(unknownValue(undefined));
<add>
<add> scope.obj.value = 'B';
<add> scope.$digest();
<add>
<add> optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(3);
<add> expect(scope.obj.value).toBe('B');
<add> // jQuery returns null for val() when the option is disabled, see
<add> // https://bugs.jquery.com/ticket/13097
<add> expect(element[0].value).toBe(prop === 'ngValue' ? 'string:B' : 'B');
<add> expect(optionElements.eq(1).prop('selected')).toBe(true);
<add> });
<add>
<add>
<add> they('should ignore an option with $prop that becomes enabled and does not match the model',
<add> [
<add> 'ngValue',
<add> 'interpolatedValue',
<add> 'interpolatedText'
<add> ], function(prop) {
<add>
<add> var A = { name: 'A'}, B = { name: 'B'}, C = { name: 'C'};
<add>
<add> scope.options = [A, B, C];
<add> scope.obj = {};
<add>
<add> var optionString = '';
<add>
<add> switch (prop) {
<add> case 'ngValue':
<add> optionString = '<option ng-repeat="option in options" ng-disabled="option.disabled" ng-value="option.name">{{$index}}</option>';
<add> break;
<add> case 'interpolatedValue':
<add> optionString = '<option ng-repeat="option in options" ng-disabled="option.disabled" value="{{option.name}}">{{$index}}</option>';
<add> break;
<add> case 'interpolatedText':
<add> optionString = '<option ng-repeat="option in options" ng-disabled="option.disabled">{{option.name}}</option>';
<add> break;
<add> }
<add>
<add> compile(
<add> '<select ng-model="obj.value">' +
<add> optionString +
<add> '</select>'
<add> );
<add>
<add> var optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(4);
<add> browserTrigger(optionElements.eq(0));
<add>
<add> optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(3);
<add> expect(scope.obj.value).toBe('A');
<add>
<add> A.disabled = true;
<add> scope.$digest();
<add>
<add> optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(4);
<add> expect(scope.obj.value).toBe(null);
<add> expect(element.val()).toBe('? object:null ?');
<add>
<add> A.disabled = false;
<add> scope.$digest();
<add>
<add> optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(4);
<add> expect(scope.obj.value).toBe(null);
<add> expect(element.val()).toBe('? object:null ?');
<add> });
<add>
<add>
<add> they('should select a newly added option with $prop when it matches the current model',
<add> [
<add> 'ngValue',
<add> 'interpolatedValue',
<add> 'interpolatedText'
<add> ], function(prop) {
<add>
<add> var A = { name: 'A'}, B = { name: 'B'}, C = { name: 'C'};
<add>
<add> scope.options = [A, B];
<add> scope.obj = {
<add> value: prop === 'ngValue' ? C : 'C'
<add> };
<add>
<add> var optionString = '';
<add>
<add> switch (prop) {
<add> case 'ngValue':
<add> optionString = '<option ng-repeat="option in options" ng-value="option">{{$index}}</option>';
<add> break;
<add> case 'interpolatedValue':
<add> optionString = '<option ng-repeat="option in options" value="{{option.name}}">{{$index}}</option>';
<add> break;
<add> case 'interpolatedText':
<add> optionString = '<option ng-repeat="option in options">{{option.name}}</option>';
<add> break;
<add> }
<add>
<add> compile(
<add> '<select ng-model="obj.value">' +
<add> optionString +
<add> '</select>'
<add> );
<add>
<add> var optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(3);
<add>
<add> scope.options.push(C);
<add> scope.$digest();
<add>
<add> optionElements = element.find('option');
<add> expect(element.val()).toBe(prop === 'ngValue' ? 'object:4' : 'C');
<add> expect(optionElements.length).toEqual(3);
<add> expect(optionElements[2].selected).toBe(true);
<add> expect(scope.obj.value).toEqual(prop === 'ngValue' ? {name: 'C', $$hashKey: 'object:4'} : 'C');
<add> });
<add>
<add>
<add> they('should keep selection and model when repeated options with track by are replaced with equal options',
<add> [
<add> 'ngValue',
<add> 'interpolatedValue',
<add> 'interpolatedText'
<add> ], function(prop) {
<add>
<add> var A = { name: 'A'}, B = { name: 'B'}, C = { name: 'C'};
<add>
<add> scope.options = [A, B, C];
<add> scope.obj = {
<add> value: 'C'
<add> };
<add>
<add> var optionString = '';
<add>
<add> switch (prop) {
<add> case 'ngValue':
<add> optionString = '<option ng-repeat="option in options track by option.name" ng-value="option.name">{{$index}}</option>';
<add> break;
<add> case 'interpolatedValue':
<add> optionString = '<option ng-repeat="option in options track by option.name" value="{{option.name}}">{{$index}}</option>';
<add> break;
<add> case 'interpolatedText':
<add> optionString = '<option ng-repeat="option in options track by option.name">{{option.name}}</option>';
<add> break;
<add> }
<add>
<add> compile(
<add> '<select ng-model="obj.value">' +
<add> optionString +
<add> '</select>'
<add> );
<add>
<add> var optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(3);
<add>
<add> scope.obj.value = 'C';
<add> scope.$digest();
<add>
<add> optionElements = element.find('option');
<add> expect(element.val()).toBe(prop === 'ngValue' ? 'string:C' : 'C');
<add> expect(optionElements.length).toEqual(3);
<add> expect(optionElements[2].selected).toBe(true);
<add> expect(scope.obj.value).toBe('C');
<add>
<add> scope.options = [
<add> {name: 'A'},
<add> {name: 'B'},
<add> {name: 'C'}
<add> ];
<add> scope.$digest();
<add>
<add> optionElements = element.find('option');
<add> expect(element.val()).toBe(prop === 'ngValue' ? 'string:C' : 'C');
<add> expect(optionElements.length).toEqual(3);
<add> expect(optionElements[2].selected).toBe(true);
<add> expect(scope.obj.value).toBe('C');
<add> });
<add>
<add> describe('when multiple', function() {
<add>
<add> they('should set the model to null when the currently selected option with $prop is removed',
<add> [
<add> 'ngValue',
<add> 'interpolatedValue',
<add> 'interpolatedText'
<add> ], function(prop) {
<add>
<add> var A = { name: 'A'}, B = { name: 'B'}, C = { name: 'C'};
<add>
<add> scope.options = [A, B, C];
<add> scope.obj = {};
<add>
<add> var optionString = '';
<add>
<add> switch (prop) {
<add> case 'ngValue':
<add> optionString = '<option ng-repeat="option in options" ng-value="option">{{$index}}</option>';
<add> break;
<add> case 'interpolatedValue':
<add> optionString = '<option ng-repeat="option in options" value="{{option.name}}">{{$index}}</option>';
<add> break;
<add> case 'interpolatedText':
<add> optionString = '<option ng-repeat="option in options">{{option.name}}</option>';
<add> break;
<add> }
<add>
<add> compile(
<add> '<select ng-model="obj.value" multiple>' +
<add> optionString +
<add> '</select>'
<add> );
<add>
<add> var ngModelCtrl = element.controller('ngModel');
<add> var ngModelCtrlSpy = spyOn(ngModelCtrl, '$setViewValue').and.callThrough();
<add>
<add> var optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(3);
<add>
<add> optionElements.eq(0).prop('selected', true);
<add> optionElements.eq(2).prop('selected', true);
<add> browserTrigger(element);
<add>
<add> optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(3);
<add> expect(scope.obj.value).toEqual(prop === 'ngValue' ? [A, C] : ['A', 'C']);
<add>
<add>
<add> ngModelCtrlSpy.calls.reset();
<add> scope.options.shift();
<add> scope.options.pop();
<add> scope.$digest();
<add>
<add> optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(1);
<add> expect(scope.obj.value).toEqual([]);
<add> expect(element.val()).toBe(null);
<add> expect(ngModelCtrlSpy).toHaveBeenCalledTimes(1);
<add> });
<add>
<add> they('should set the model to null when the currently selected option with $prop changes its value',
<add> [
<add> 'ngValue',
<add> 'interpolatedValue',
<add> 'interpolatedText'
<add> ], function(prop) {
<add>
<add> var A = { name: 'A'}, B = { name: 'B'}, C = { name: 'C'};
<add>
<add> scope.options = [A, B, C];
<add> scope.obj = {};
<add>
<add> var optionString = '';
<add>
<add> switch (prop) {
<add> case 'ngValue':
<add> optionString = '<option ng-repeat="option in options" ng-value="option.name">{{$index}}</option>';
<add> break;
<add> case 'interpolatedValue':
<add> optionString = '<option ng-repeat="option in options" value="{{option.name}}">{{$index}}</option>';
<add> break;
<add> case 'interpolatedText':
<add> optionString = '<option ng-repeat="option in options">{{option.name}}</option>';
<add> break;
<add> }
<add>
<add> compile(
<add> '<select ng-model="obj.value" multiple>' +
<add> optionString +
<add> '</select>'
<add> );
<add>
<add> var ngModelCtrl = element.controller('ngModel');
<add> var ngModelCtrlSpy = spyOn(ngModelCtrl, '$setViewValue').and.callThrough();
<add>
<add> var optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(3);
<add>
<add> optionElements.eq(0).prop('selected', true);
<add> optionElements.eq(2).prop('selected', true);
<add> browserTrigger(element);
<add>
<add> optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(3);
<add> expect(scope.obj.value).toEqual(['A', 'C']);
<add>
<add> ngModelCtrlSpy.calls.reset();
<add> A.name = 'X';
<add> C.name = 'Z';
<add> scope.$digest();
<add>
<add> optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(3);
<add> expect(scope.obj.value).toEqual([]);
<add> expect(element.val()).toBe(null);
<add> expect(ngModelCtrlSpy).toHaveBeenCalledTimes(1);
<add>
<add> });
<add>
<add> they('should set the model to null when the currently selected option with $prop becomes disabled',
<add> [
<add> 'ngValue',
<add> 'interpolatedValue',
<add> 'interpolatedText'
<add> ], function(prop) {
<add>
<add> var A = { name: 'A'}, B = { name: 'B'}, C = { name: 'C'}, D = { name: 'D'};
<add>
<add> scope.options = [A, B, C, D];
<add> scope.obj = {};
<add>
<add> var optionString = '';
<add>
<add> switch (prop) {
<add> case 'ngValue':
<add> optionString = '<option ng-repeat="option in options" ng-disabled="option.disabled" ng-value="option.name">{{$index}}</option>';
<add> break;
<add> case 'interpolatedValue':
<add> optionString = '<option ng-repeat="option in options" ng-disabled="option.disabled" value="{{option.name}}">{{$index}}</option>';
<add> break;
<add> case 'interpolatedText':
<add> optionString = '<option ng-repeat="option in options" ng-disabled="option.disabled">{{option.name}}</option>';
<add> break;
<add> }
<add>
<add> compile(
<add> '<select ng-model="obj.value" multiple>' +
<add> optionString +
<add> '</select>'
<add> );
<add>
<add> var ngModelCtrl = element.controller('ngModel');
<add> var ngModelCtrlSpy = spyOn(ngModelCtrl, '$setViewValue').and.callThrough();
<add>
<add> var optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(4);
<add>
<add> optionElements.eq(0).prop('selected', true);
<add> optionElements.eq(2).prop('selected', true);
<add> optionElements.eq(3).prop('selected', true);
<add> browserTrigger(element);
<add>
<add> optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(4);
<add> expect(scope.obj.value).toEqual(['A', 'C', 'D']);
<add>
<add> ngModelCtrlSpy.calls.reset();
<add> A.disabled = true;
<add> C.disabled = true;
<add> scope.$digest();
<add>
<add> optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(4);
<add> expect(scope.obj.value).toEqual(['D']);
<add> expect(element.val()).toEqual(prop === 'ngValue' ? ['string:D'] : ['D']);
<add> expect(ngModelCtrlSpy).toHaveBeenCalledTimes(1);
<add> });
<add>
<add>
<add> they('should select disabled options with $prop when the model is set to matching values',
<add> [
<add> 'ngValue',
<add> 'interpolatedValue',
<add> 'interpolatedText'
<add> ], function(prop) {
<add>
<add> var A = { name: 'A'}, B = { name: 'B'}, C = { name: 'C'}, D = {name: 'D'};
<add>
<add> scope.options = [A, B, C, D];
<add> scope.obj = {};
<add>
<add> var optionString = '';
<add>
<add> switch (prop) {
<add> case 'ngValue':
<add> optionString = '<option ng-repeat="option in options" ng-disabled="option.disabled" ng-value="option">{{$index}}</option>';
<add> break;
<add> case 'interpolatedValue':
<add> optionString = '<option ng-repeat="option in options" ng-disabled="option.disabled" value="{{option.name}}">{{$index}}</option>';
<add> break;
<add> case 'interpolatedText':
<add> optionString = '<option ng-repeat="option in options" ng-disabled="option.disabled">{{option.name}}</option>';
<add> break;
<add> }
<add>
<add> compile(
<add> '<select ng-model="obj.value" multiple>' +
<add> optionString +
<add> '</select>'
<add> );
<add>
<add> var optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(4);
<add> expect(element[0].value).toBe('');
<add>
<add> A.disabled = true;
<add> D.disabled = true;
<add> scope.$digest();
<add>
<add> optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(4);
<add> expect(element[0].value).toBe('');
<add>
<add> scope.obj.value = prop === 'ngValue' ? [A, C, D] : ['A', 'C', 'D'];
<add> scope.$digest();
<add>
<add> optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(4);
<add> expect(scope.obj.value).toEqual(prop === 'ngValue' ?
<add> [
<add> {name: 'A', $$hashKey: 'object:4', disabled: true},
<add> {name: 'C', $$hashKey: 'object:6'},
<add> {name: 'D', $$hashKey: 'object:7', disabled: true}
<add> ] :
<add> ['A', 'C', 'D']
<add> );
<add>
<add> expect(optionElements.eq(0).prop('selected')).toBe(true);
<add> expect(optionElements.eq(2).prop('selected')).toBe(true);
<add> expect(optionElements.eq(3).prop('selected')).toBe(true);
<add> });
<add>
<add> they('should select a newly added option with $prop when it matches the current model',
<add> [
<add> 'ngValue',
<add> 'interpolatedValue',
<add> 'interpolatedText'
<add> ], function(prop) {
<add>
<add> var A = { name: 'A'}, B = { name: 'B'}, C = { name: 'C'};
<add>
<add> scope.options = [A, B];
<add> scope.obj = {
<add> value: prop === 'ngValue' ? [B, C] : ['B', 'C']
<add> };
<add>
<add> var optionString = '';
<add>
<add> switch (prop) {
<add> case 'ngValue':
<add> optionString = '<option ng-repeat="option in options" ng-value="option">{{$index}}</option>';
<add> break;
<add> case 'interpolatedValue':
<add> optionString = '<option ng-repeat="option in options" value="{{option.name}}">{{$index}}</option>';
<add> break;
<add> case 'interpolatedText':
<add> optionString = '<option ng-repeat="option in options">{{option.name}}</option>';
<add> break;
<add> }
<add>
<add> compile(
<add> '<select ng-model="obj.value" multiple>' +
<add> optionString +
<add> '</select>'
<add> );
<add>
<add> var optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(2);
<add> expect(optionElements.eq(1).prop('selected')).toBe(true);
<add>
<add> scope.options.push(C);
<add> scope.$digest();
<add>
<add> optionElements = element.find('option');
<add> expect(element.val()).toEqual(prop === 'ngValue' ? ['object:4', 'object:5'] : ['B', 'C']);
<add> expect(optionElements.length).toEqual(3);
<add> expect(optionElements[1].selected).toBe(true);
<add> expect(optionElements[2].selected).toBe(true);
<add> expect(scope.obj.value).toEqual(prop === 'ngValue' ?
<add> [{ name: 'B', $$hashKey: 'object:4'},
<add> {name: 'C', $$hashKey: 'object:5'}] :
<add> ['B', 'C']);
<add> });
<add>
<add> they('should keep selection and model when a repeated options with track by are replaced with equal options',
<add> [
<add> 'ngValue',
<add> 'interpolatedValue',
<add> 'interpolatedText'
<add> ], function(prop) {
<add>
<add> var A = { name: 'A'}, B = { name: 'B'}, C = { name: 'C'};
<add>
<add> scope.options = [A, B, C];
<add> scope.obj = {
<add> value: 'C'
<add> };
<add>
<add> var optionString = '';
<add>
<add> switch (prop) {
<add> case 'ngValue':
<add> optionString = '<option ng-repeat="option in options track by option.name" ng-value="option.name">{{$index}}</option>';
<add> break;
<add> case 'interpolatedValue':
<add> optionString = '<option ng-repeat="option in options track by option.name" value="{{option.name}}">{{$index}}</option>';
<add> break;
<add> case 'interpolatedText':
<add> optionString = '<option ng-repeat="option in options track by option.name">{{option.name}}</option>';
<add> break;
<add> }
<add>
<add> compile(
<add> '<select ng-model="obj.value" multiple>' +
<add> optionString +
<add> '</select>'
<add> );
<add>
<add> var optionElements = element.find('option');
<add> expect(optionElements.length).toEqual(3);
<add>
<add> scope.obj.value = ['B', 'C'];
<add> scope.$digest();
<add>
<add> optionElements = element.find('option');
<add> expect(element.val()).toEqual(prop === 'ngValue' ? ['string:B', 'string:C'] : ['B', 'C']);
<add> expect(optionElements.length).toEqual(3);
<add> expect(optionElements[1].selected).toBe(true);
<add> expect(optionElements[2].selected).toBe(true);
<add> expect(scope.obj.value).toEqual(['B', 'C']);
<add>
<add> scope.options = [
<add> {name: 'A'},
<add> {name: 'B'},
<add> {name: 'C'}
<add> ];
<add> scope.$digest();
<add>
<add> optionElements = element.find('option');
<add> expect(element.val()).toEqual(prop === 'ngValue' ? ['string:B', 'string:C'] : ['B', 'C']);
<add> expect(optionElements.length).toEqual(3);
<add> expect(optionElements[1].selected).toBe(true);
<add> expect(optionElements[2].selected).toBe(true);
<add> expect(scope.obj.value).toEqual(['B', 'C']);
<add> });
<add>
<add> });
<ide>
<ide> });
<ide>
<add>
<ide> });
<ide> });
| 2
|
Java
|
Java
|
adjust some javadoc in emitters
|
34a0c6c0ff5191d4cb9e516bfda07e987498e380
|
<ide><path>src/main/java/io/reactivex/CompletableEmitter.java
<ide> import io.reactivex.functions.Cancellable;
<ide>
<ide> /**
<del> * Abstraction over a RxJava CompletableObserver that allows associating
<add> * Abstraction over an RxJava {@link CompletableObserver} that allows associating
<ide> * a resource with it.
<ide> * <p>
<ide> * All methods are safe to call from multiple threads.
<ide><path>src/main/java/io/reactivex/FlowableEmitter.java
<ide> import io.reactivex.functions.Cancellable;
<ide>
<ide> /**
<del> * Abstraction over a RxJava Subscriber that allows associating
<add> * Abstraction over a Reactive Streams {@link org.reactivestreams.Subscriber} that allows associating
<ide> * a resource with it and exposes the current number of downstream
<ide> * requested amount.
<ide> * <p>
<ide> * @param c the cancellable resource, null is allowed
<ide> */
<ide> void setCancellable(Cancellable c);
<add>
<ide> /**
<ide> * The current outstanding request amount.
<ide> * <p>This method is thread-safe.
<ide> * @return the serialized FlowableEmitter
<ide> */
<ide> FlowableEmitter<T> serialize();
<add>
<ide> /**
<ide> * Options to handle backpressure in the emitter.
<ide> */
<ide><path>src/main/java/io/reactivex/MaybeEmitter.java
<ide> import io.reactivex.functions.Cancellable;
<ide>
<ide> /**
<del> * Abstraction over a RxJava MaybeObserver that allows associating
<add> * Abstraction over an RxJava {@link MaybeObserver} that allows associating
<ide> * a resource with it.
<ide> * <p>
<ide> * All methods are safe to call from multiple threads.
<ide><path>src/main/java/io/reactivex/ObservableEmitter.java
<ide> import io.reactivex.functions.Cancellable;
<ide>
<ide> /**
<del> * Abstraction over a RxJava Observer that allows associating
<add> * Abstraction over an RxJava {@link Observer} that allows associating
<ide> * a resource with it.
<ide> * <p>
<ide> * The onNext, onError and onComplete methods should be called
<ide><path>src/main/java/io/reactivex/ObservableOnSubscribe.java
<ide>
<ide> /**
<ide> * A functional interface that has a {@code subscribe()} method that receives
<del> * an instance of a {@link ObservableEmitter} instance that allows pushing
<add> * an instance of an {@link ObservableEmitter} instance that allows pushing
<ide> * events in a cancellation-safe manner.
<ide> *
<ide> * @param <T> the value type pushed
<ide><path>src/main/java/io/reactivex/SingleEmitter.java
<ide> import io.reactivex.functions.Cancellable;
<ide>
<ide> /**
<del> * Abstraction over a RxJava SingleObserver that allows associating
<add> * Abstraction over an RxJava {@link SingleObserver} that allows associating
<ide> * a resource with it.
<ide> * <p>
<ide> * All methods are safe to call from multiple threads.
| 6
|
Text
|
Text
|
use serve_static_files in guides, take 2 [skip ci]
|
58b7567bdab8b7422c2ef1bb0996282ac2438f7f
|
<ide><path>guides/source/configuring.md
<ide> numbers. New applications filter out passwords by adding the following `config.f
<ide>
<ide> * `secrets.secret_key_base` is used for specifying a key which allows sessions for the application to be verified against a known secure key to prevent tampering. Applications get `secrets.secret_key_base` initialized to a random key present in `config/secrets.yml`.
<ide>
<del>* `config.serve_static_assets` configures Rails to serve static files. This option defaults to true, but in the production environment it is set to false because the server software (e.g. NGINX or Apache) used to run the application should serve static files instead. If you are running or testing your app in production mode using WEBrick (it is not recommended to use WEBrick in production) set the option to true. Otherwise, you won't be able use page caching and requests for files that exist under the public directory.
<add>* `config.serve_static_files` configures Rails to serve static files. This option defaults to true, but in the production environment it is set to false because the server software (e.g. NGINX or Apache) used to run the application should serve static files instead. If you are running or testing your app in production mode using WEBrick (it is not recommended to use WEBrick in production) set the option to true. Otherwise, you won't be able use page caching and requests for files that exist under the public directory.
<ide>
<ide> * `config.session_store` is usually set up in `config/initializers/session_store.rb` and specifies what class to use to store the session. Possible values are `:cookie_store` which is the default, `:mem_cache_store`, and `:disabled`. The last one tells Rails not to deal with sessions. Custom session stores can also be specified:
<ide>
<ide> The full set of methods that can be used in this block are as follows:
<ide> Every Rails application comes with a standard set of middleware which it uses in this order in the development environment:
<ide>
<ide> * `ActionDispatch::SSL` forces every request to be under HTTPS protocol. Will be available if `config.force_ssl` is set to `true`. Options passed to this can be configured by using `config.ssl_options`.
<del>* `ActionDispatch::Static` is used to serve static assets. Disabled if `config.serve_static_assets` is `false`.
<add>* `ActionDispatch::Static` is used to serve static assets. Disabled if `config.serve_static_files` is `false`.
<ide> * `Rack::Lock` wraps the app in mutex so it can only be called by a single thread at a time. Only enabled when `config.cache_classes` is `false`.
<ide> * `ActiveSupport::Cache::Strategy::LocalCache` serves as a basic memory backed cache. This cache is not thread safe and is intended only for serving as a temporary memory cache for a single thread.
<ide> * `Rack::Runtime` sets an `X-Runtime` header, containing the time (in seconds) taken to execute the request.
| 1
|
PHP
|
PHP
|
add tests for eloquent model push method
|
432c478936ba363a09b28c6487c6b3e13c651f86
|
<ide><path>tests/Database/DatabaseEloquentModelTest.php
<ide> public function testDeleteProperlyDeletesModel()
<ide> }
<ide>
<ide>
<add> public function testPushNoRelations()
<add> {
<add> $model = $this->getMock('EloquentModelStub', array('newQuery', 'updateTimestamps'));
<add> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<add> $query->shouldReceive('insertGetId')->once()->with(array('name' => 'taylor'), 'id')->andReturn(1);
<add> $model->expects($this->once())->method('newQuery')->will($this->returnValue($query));
<add> $model->expects($this->once())->method('updateTimestamps');
<add>
<add> $model->name = 'taylor';
<add> $model->exists = false;
<add>
<add> $this->assertTrue($model->push());
<add> $this->assertEquals(1, $model->id);
<add> $this->assertTrue($model->exists);
<add> }
<add>
<add>
<add> public function testPushEmptyOneRelation()
<add> {
<add> $model = $this->getMock('EloquentModelStub', array('newQuery', 'updateTimestamps'));
<add> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<add> $query->shouldReceive('insertGetId')->once()->with(array('name' => 'taylor'), 'id')->andReturn(1);
<add> $model->expects($this->once())->method('newQuery')->will($this->returnValue($query));
<add> $model->expects($this->once())->method('updateTimestamps');
<add>
<add> $model->name = 'taylor';
<add> $model->exists = false;
<add> $model->setRelation('relationOne', null);
<add>
<add> $this->assertTrue($model->push());
<add> $this->assertEquals(1, $model->id);
<add> $this->assertTrue($model->exists);
<add> $this->assertNull($model->relationOne);
<add> }
<add>
<add>
<add> public function testPushOneRelation()
<add> {
<add> $related1 = $this->getMock('EloquentModelStub', array('newQuery', 'updateTimestamps'));
<add> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<add> $query->shouldReceive('insertGetId')->once()->with(array('name' => 'related1'), 'id')->andReturn(2);
<add> $related1->expects($this->once())->method('newQuery')->will($this->returnValue($query));
<add> $related1->expects($this->once())->method('updateTimestamps');
<add> $related1->name = 'related1';
<add> $related1->exists = false;
<add>
<add> $model = $this->getMock('EloquentModelStub', array('newQuery', 'updateTimestamps'));
<add> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<add> $query->shouldReceive('insertGetId')->once()->with(array('name' => 'taylor'), 'id')->andReturn(1);
<add> $model->expects($this->once())->method('newQuery')->will($this->returnValue($query));
<add> $model->expects($this->once())->method('updateTimestamps');
<add>
<add> $model->name = 'taylor';
<add> $model->exists = false;
<add> $model->setRelation('relationOne', $related1);
<add>
<add> $this->assertTrue($model->push());
<add> $this->assertEquals(1, $model->id);
<add> $this->assertTrue($model->exists);
<add> $this->assertEquals(2, $model->relationOne->id);
<add> $this->assertTrue($model->relationOne->exists);
<add> $this->assertEquals(2, $related1->id);
<add> $this->assertTrue($related1->exists);
<add> }
<add>
<add>
<add> public function testPushEmptyManyRelation()
<add> {
<add> $model = $this->getMock('EloquentModelStub', array('newQuery', 'updateTimestamps'));
<add> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<add> $query->shouldReceive('insertGetId')->once()->with(array('name' => 'taylor'), 'id')->andReturn(1);
<add> $model->expects($this->once())->method('newQuery')->will($this->returnValue($query));
<add> $model->expects($this->once())->method('updateTimestamps');
<add>
<add> $model->name = 'taylor';
<add> $model->exists = false;
<add> $model->setRelation('relationMany', new Illuminate\Database\Eloquent\Collection(array()));
<add>
<add> $this->assertTrue($model->push());
<add> $this->assertEquals(1, $model->id);
<add> $this->assertTrue($model->exists);
<add> $this->assertEquals(0, count($model->relationMany));
<add> }
<add>
<add>
<add> public function testPushManyRelation()
<add> {
<add> $related1 = $this->getMock('EloquentModelStub', array('newQuery', 'updateTimestamps'));
<add> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<add> $query->shouldReceive('insertGetId')->once()->with(array('name' => 'related1'), 'id')->andReturn(2);
<add> $related1->expects($this->once())->method('newQuery')->will($this->returnValue($query));
<add> $related1->expects($this->once())->method('updateTimestamps');
<add> $related1->name = 'related1';
<add> $related1->exists = false;
<add>
<add> $related2 = $this->getMock('EloquentModelStub', array('newQuery', 'updateTimestamps'));
<add> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<add> $query->shouldReceive('insertGetId')->once()->with(array('name' => 'related2'), 'id')->andReturn(3);
<add> $related2->expects($this->once())->method('newQuery')->will($this->returnValue($query));
<add> $related2->expects($this->once())->method('updateTimestamps');
<add> $related2->name = 'related2';
<add> $related2->exists = false;
<add>
<add> $model = $this->getMock('EloquentModelStub', array('newQuery', 'updateTimestamps'));
<add> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<add> $query->shouldReceive('insertGetId')->once()->with(array('name' => 'taylor'), 'id')->andReturn(1);
<add> $model->expects($this->once())->method('newQuery')->will($this->returnValue($query));
<add> $model->expects($this->once())->method('updateTimestamps');
<add>
<add> $model->name = 'taylor';
<add> $model->exists = false;
<add> $model->setRelation('relationMany', new Illuminate\Database\Eloquent\Collection(array($related1, $related2)));
<add>
<add> $this->assertTrue($model->push());
<add> $this->assertEquals(1, $model->id);
<add> $this->assertTrue($model->exists);
<add> $this->assertEquals(2, count($model->relationMany));
<add> $this->assertEquals([2, 3], $model->relationMany->lists('id'));
<add> }
<add>
<add>
<ide> public function testNewQueryReturnsEloquentQueryBuilder()
<ide> {
<ide> $conn = m::mock('Illuminate\Database\Connection');
| 1
|
Javascript
|
Javascript
|
remove fallback function
|
0cb1a088233b663785cfb2ead478c40774b050f4
|
<ide><path>web/viewer.js
<ide> var PDFView = {
<ide> }
<ide> },
<ide>
<del> fallback: function pdfViewDownload() {
<del> var url = this.url.split('#')[0];
<del> if (!PDFJS.isFirefoxExtension)
<del> return; // can't do this with regular viewer
<del> FirefoxCom.request('fallback', url);
<del> },
<del>
<ide> navigateTo: function pdfViewNavigateTo(dest) {
<ide> if (typeof dest === 'string')
<ide> dest = this.destinations[dest];
| 1
|
Text
|
Text
|
add link to 7.0 release notes in upgrade guide
|
6dd25a899abf3a6216ad3e865282b3070e134b9a
|
<ide><path>guides/source/upgrading_ruby_on_rails.md
<ide> config.action_mailer.preview_paths << "#{Rails.root}/lib/mailer_previews"
<ide> Upgrading from Rails 6.1 to Rails 7.0
<ide> -------------------------------------
<ide>
<add>For more information on changes made to Rails 7.0 please see the [release notes](7_0_release_notes.html).
<add>
<ide> ### `ActionView::Helpers::UrlHelper#button_to` changed behavior
<ide>
<ide> Starting from Rails 7.0 `button_to` renders a `form` tag with `patch` HTTP verb if a persisted Active Record object is used to build button URL.
| 1
|
PHP
|
PHP
|
preserve keys in collection reverse
|
3b65a33206f426612d68eba7fb0e501833a1651d
|
<ide><path>src/Illuminate/Support/Collection.php
<ide> public function reject($callback)
<ide> /**
<ide> * Reverse items order.
<ide> *
<add> * @param bool $preserveKeys
<ide> * @return static
<ide> */
<del> public function reverse()
<add> public function reverse($preserveKeys = false)
<ide> {
<del> return new static(array_reverse($this->items));
<add> return new static(array_reverse($this->items, $preserveKeys));
<ide> }
<ide>
<ide> /**
<ide><path>tests/Support/SupportCollectionTest.php
<ide> public function testReverse()
<ide> $reversed = $data->reverse();
<ide>
<ide> $this->assertEquals(['alan', 'zaeed'], array_values($reversed->all()));
<add>
<add> $data = new Collection(['zaeed', 'alan']);
<add> $reversed = $data->reverse(true);
<add>
<add> $this->assertEquals([1 => 'alan', 0 => 'zaeed'], $reversed->all());
<ide> }
<ide>
<ide> public function testFlip()
| 2
|
Ruby
|
Ruby
|
add test for brew info --json=v1
|
a4020db526fc8476b4c8606a1f0c6473e1a197c8
|
<ide><path>Library/Homebrew/test/cmd/info_spec.rb
<ide> .to output(/testball: stable 0.1/).to_stdout
<ide> .and not_to_output.to_stderr
<ide> .and be_a_success
<add>
<add> expect { brew "info", "testball", "--json=v1" }
<add> .to output(/\{.+testball.+\}/).to_stdout
<add> .and not_to_output.to_stderr
<add> .and be_a_success
<ide> end
<ide> end
<ide>
| 1
|
Go
|
Go
|
fix docker run for 64 byte hex id
|
16e4c4e481aca8d5a99d5a4760b5d27bf5bbb9fd
|
<ide><path>api/client/create.go
<ide> func (cli *DockerCli) createContainer(config *container.Config, hostConfig *cont
<ide> defer containerIDFile.Close()
<ide> }
<ide>
<del> ref, err := reference.ParseNamed(config.Image)
<add> var trustedRef reference.Canonical
<add> _, ref, err := reference.ParseIDOrReference(config.Image)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<del> ref = reference.WithDefaultTag(ref)
<del>
<del> var trustedRef reference.Canonical
<add> if ref != nil {
<add> ref = reference.WithDefaultTag(ref)
<ide>
<del> if ref, ok := ref.(reference.NamedTagged); ok && isTrusted() {
<del> var err error
<del> trustedRef, err = cli.trustedReference(ref)
<del> if err != nil {
<del> return nil, err
<add> if ref, ok := ref.(reference.NamedTagged); ok && isTrusted() {
<add> var err error
<add> trustedRef, err = cli.trustedReference(ref)
<add> if err != nil {
<add> return nil, err
<add> }
<add> config.Image = trustedRef.String()
<ide> }
<del> config.Image = trustedRef.String()
<ide> }
<ide>
<ide> //create the container
<ide> response, err := cli.client.ContainerCreate(config, hostConfig, networkingConfig, name)
<ide>
<ide> //if image not found try to pull it
<ide> if err != nil {
<del> if client.IsErrImageNotFound(err) {
<add> if client.IsErrImageNotFound(err) && ref != nil {
<ide> fmt.Fprintf(cli.err, "Unable to find image '%s' locally\n", ref.String())
<ide>
<ide> // we don't want to write to stdout anything apart from container.ID
<ide><path>daemon/daemon.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/Sirupsen/logrus"
<del> "github.com/docker/distribution/digest"
<ide> "github.com/docker/docker/api"
<ide> "github.com/docker/docker/builder"
<ide> "github.com/docker/docker/container"
<ide> func (daemon *Daemon) ImageHistory(name string) ([]*types.ImageHistory, error) {
<ide> // GetImageID returns an image ID corresponding to the image referred to by
<ide> // refOrID.
<ide> func (daemon *Daemon) GetImageID(refOrID string) (image.ID, error) {
<del> // Treat as an ID
<del> if id, err := digest.ParseDigest(refOrID); err == nil {
<add> id, ref, err := reference.ParseIDOrReference(refOrID)
<add> if err != nil {
<add> return "", err
<add> }
<add> if id != "" {
<ide> if _, err := daemon.imageStore.Get(image.ID(id)); err != nil {
<ide> return "", ErrImageDoesNotExist{refOrID}
<ide> }
<ide> return image.ID(id), nil
<ide> }
<ide>
<del> // Treat it as a possible tag or digest reference
<del> if ref, err := reference.ParseNamed(refOrID); err == nil {
<del> if id, err := daemon.referenceStore.Get(ref); err == nil {
<del> return id, nil
<del> }
<del> if tagged, ok := ref.(reference.NamedTagged); ok {
<del> if id, err := daemon.imageStore.Search(tagged.Tag()); err == nil {
<del> for _, namedRef := range daemon.referenceStore.References(id) {
<del> if namedRef.Name() == ref.Name() {
<del> return id, nil
<del> }
<add> if id, err := daemon.referenceStore.Get(ref); err == nil {
<add> return id, nil
<add> }
<add> if tagged, ok := ref.(reference.NamedTagged); ok {
<add> if id, err := daemon.imageStore.Search(tagged.Tag()); err == nil {
<add> for _, namedRef := range daemon.referenceStore.References(id) {
<add> if namedRef.Name() == ref.Name() {
<add> return id, nil
<ide> }
<ide> }
<ide> }
<ide><path>image/tarexport/save.go
<ide> func (l *tarexporter) parseNames(names []string) (map[image.ID]*imageDescriptor,
<ide> }
<ide>
<ide> for _, name := range names {
<del> ref, err := reference.ParseNamed(name)
<add> id, ref, err := reference.ParseIDOrReference(name)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<add> if id != "" {
<add> _, err := l.is.Get(image.ID(id))
<add> if err != nil {
<add> return nil, err
<add> }
<add> addAssoc(image.ID(id), nil)
<add> continue
<add> }
<ide> if ref.Name() == string(digest.Canonical) {
<ide> imgID, err := l.is.Search(name)
<ide> if err != nil {
<ide><path>integration-cli/docker_cli_create_test.go
<ide> func (s *DockerSuite) TestCreateWithInvalidLogOpts(c *check.C) {
<ide> out, _ = dockerCmd(c, "ps", "-a")
<ide> c.Assert(out, checker.Not(checker.Contains), name)
<ide> }
<add>
<add>// #20972
<add>func (s *DockerSuite) TestCreate64ByteHexID(c *check.C) {
<add> out := inspectField(c, "busybox", "Id")
<add> imageID := strings.TrimPrefix(strings.TrimSpace(string(out)), "sha256:")
<add>
<add> dockerCmd(c, "create", imageID)
<add>}
<ide><path>reference/reference.go
<ide> func IsNameOnly(ref Named) bool {
<ide> return true
<ide> }
<ide>
<add>// ParseIDOrReference parses string for a image ID or a reference. ID can be
<add>// without a default prefix.
<add>func ParseIDOrReference(idOrRef string) (digest.Digest, Named, error) {
<add> if err := v1.ValidateID(idOrRef); err == nil {
<add> idOrRef = "sha256:" + idOrRef
<add> }
<add> if dgst, err := digest.ParseDigest(idOrRef); err == nil {
<add> return dgst, nil, nil
<add> }
<add> ref, err := ParseNamed(idOrRef)
<add> return "", ref, err
<add>}
<add>
<ide> // splitHostname splits a repository name to hostname and remotename string.
<ide> // If no valid hostname is found, the default hostname is used. Repository name
<ide> // needs to be already validated before.
| 5
|
Javascript
|
Javascript
|
fix a bug in determining if yarn is available
|
caa9ab19bfa975c159d34cd603205147586ddaa2
|
<ide><path>local-cli/util/yarn.js
<ide> */
<ide> 'use strict';
<ide>
<add>const execSync = require('child_process').execSync;
<ide> const fs = require('fs');
<ide> const path = require('path');
<ide> const semver = require('semver');
| 1
|
Ruby
|
Ruby
|
remove a circular dependency
|
6062017382304b0872b18d84620d33e8204d7078
|
<ide><path>activeresource/test/setter_trap.rb
<del>require 'abstract_unit'
<del>
<ide> class SetterTrap < ActiveSupport::BasicObject
<ide> class << self
<ide> def rollback_sets(obj)
| 1
|
PHP
|
PHP
|
remove dead code
|
870ec588b01a2a6890a5013be5029651760f8328
|
<ide><path>src/Http/ServerRequestFactory.php
<ide> public static function marshalUriFromServer(array $server, array $headers)
<ide> $uri = static::updatePath($base, $uri);
<ide> }
<ide>
<add> if (!$uri->getHost()) {
<add> $uri = $uri->withHost('localhost');
<add> }
<add>
<ide> // Splat on some extra attributes to save
<ide> // some method calls.
<ide> $uri->base = $base;
<ide><path>src/Routing/Router.php
<ide> public static function pushRequest(ServerRequest $request)
<ide> /**
<ide> * Store the request context for a given request.
<ide> *
<del> * @param \Cake\Http\ServerRequest|\Psr\Http\Message\ServerRequestInterface $request The request instance.
<add> * @param \Psr\Http\Message\ServerRequestInterface $request The request instance.
<ide> * @return void
<ide> * @throws InvalidArgumentException When parameter is an incorrect type.
<ide> */
<del> public static function setRequestContext($request)
<add> public static function setRequestContext(ServerRequestInterface $request)
<ide> {
<del> if ($request instanceof ServerRequest) {
<del> static::$_requestContext = [
<del> '_base' => $request->base,
<del> '_port' => $request->port(),
<del> '_scheme' => $request->scheme(),
<del> '_host' => $request->host()
<del> ];
<del>
<del> return;
<del> }
<del> if ($request instanceof ServerRequestInterface) {
<del> $uri = $request->getUri();
<del> static::$_requestContext = [
<del> '_base' => $request->getAttribute('base'),
<del> '_port' => $uri->getPort(),
<del> '_scheme' => $uri->getScheme(),
<del> '_host' => $uri->getHost(),
<del> ];
<del>
<del> return;
<del> }
<del> throw new InvalidArgumentException('Unknown request type received.');
<add> $uri = $request->getUri();
<add> static::$_requestContext = [
<add> '_base' => $request->getAttribute('base'),
<add> '_port' => $uri->getPort(),
<add> '_scheme' => $uri->getScheme(),
<add> '_host' => $uri->getHost(),
<add> ];
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Routing/RouterTest.php
<ide> public function testGenerationWithSslOption()
<ide> Router::connect('/:controller/:action/*');
<ide>
<ide> $request = new ServerRequest();
<del> $request->env('HTTP_HOST', 'localhost');
<ide> Router::pushRequest(
<ide> $request->addParams([
<ide> 'plugin' => null, 'controller' => 'images', 'action' => 'index'
<ide> public function testGenerateWithSslInSsl()
<ide> Router::connect('/:controller/:action/*');
<ide>
<ide> $request = new ServerRequest();
<del> $request->env('HTTP_HOST', 'localhost');
<ide> $request->env('HTTPS', 'on');
<ide> Router::pushRequest(
<ide> $request->addParams([
<ide> public function testSetRequestContextPsr()
<ide> $this->assertEquals('/subdir/pages/home', $result);
<ide> }
<ide>
<del> /**
<del> * Test setting the request context.
<del> *
<del> * @expectedException \InvalidArgumentException
<del> * @return void
<del> */
<del> public function testSetRequestContextInvalid()
<del> {
<del> Router::setRequestContext(new \stdClass);
<del> }
<del>
<ide> /**
<ide> * Test getting path specific middleware.
<ide> *
| 3
|
Javascript
|
Javascript
|
fix a flakey test
|
cd135d5e90c188d7cf06b7b455ceafb64d10b6a3
|
<ide><path>test/core/transition-test-transition.js
<ide> module.exports = {
<ide> d3.timer(function() {
<ide> cb(null, t1);
<ide> return true;
<del> });
<add> }, 50);
<ide> });
<ide> },
<ide> "decrements the lock's reference count": function(t1) {
| 1
|
Go
|
Go
|
simplify secret lookup on service create
|
dce2afbd81945056aa955079fac04e28ab96e703
|
<ide><path>cli/command/service/parse.go
<ide> func parseSecretString(secretString string) (string, string, error) {
<ide> // parseSecrets retrieves the secrets from the requested names and converts
<ide> // them to secret references to use with the spec
<ide> func parseSecrets(client client.APIClient, requestedSecrets []string) ([]*swarmtypes.SecretReference, error) {
<del> lookupSecretNames := []string{}
<del> neededSecrets := make(map[string]*swarmtypes.SecretReference)
<add> secretRefs := make(map[string]*swarmtypes.SecretReference)
<ide> ctx := context.Background()
<ide>
<del> neededLookup := map[string]string{}
<ide> for _, secret := range requestedSecrets {
<ide> n, t, err := parseSecretString(secret)
<ide> if err != nil {
<ide> func parseSecrets(client client.APIClient, requestedSecrets []string) ([]*swarmt
<ide> Target: t,
<ide> }
<ide>
<del> lookupSecretNames = append(lookupSecretNames, n)
<del> neededLookup[t] = n
<del> neededSecrets[t] = secretRef
<add> if _, exists := secretRefs[t]; exists {
<add> return nil, fmt.Errorf("duplicate secret target for %s not allowed", n)
<add> }
<add> secretRefs[t] = secretRef
<ide> }
<ide>
<ide> args := filters.NewArgs()
<del> for _, s := range lookupSecretNames {
<del> args.Add("names", s)
<add> for _, s := range secretRefs {
<add> args.Add("names", s.SecretName)
<ide> }
<ide>
<ide> secrets, err := client.SecretList(ctx, types.SecretListOptions{
<ide> func parseSecrets(client client.APIClient, requestedSecrets []string) ([]*swarmt
<ide>
<ide> addedSecrets := []*swarmtypes.SecretReference{}
<ide>
<del> for target, secretName := range neededLookup {
<del> id, ok := foundSecrets[secretName]
<del> if !ok {
<del> return nil, fmt.Errorf("secret not found: %s", secretName)
<del> }
<del>
<del> secretRef, ok := neededSecrets[target]
<add> for _, ref := range secretRefs {
<add> id, ok := foundSecrets[ref.SecretName]
<ide> if !ok {
<del> return nil, fmt.Errorf("secret reference not found: %s", secretName)
<add> return nil, fmt.Errorf("secret not found: %s", ref.SecretName)
<ide> }
<ide>
<ide> // set the id for the ref to properly assign in swarm
<ide> // since swarm needs the ID instead of the name
<del> secretRef.SecretID = id
<del> addedSecrets = append(addedSecrets, secretRef)
<add> ref.SecretID = id
<add> addedSecrets = append(addedSecrets, ref)
<ide> }
<ide>
<ide> return addedSecrets, nil
| 1
|
Javascript
|
Javascript
|
allow some right swipe
|
26a92220c2a6355afc0a54be4a7266da50f7c692
|
<ide><path>Libraries/Experimental/SwipeableRow/SwipeableRow.js
<ide> const emptyFunction = require('fbjs/lib/emptyFunction');
<ide> const CLOSED_LEFT_POSITION = 0;
<ide> // Minimum swipe distance before we recognize it as such
<ide> const HORIZONTAL_SWIPE_DISTANCE_THRESHOLD = 15;
<add>// Distance left of closed position to bounce back when right-swiping from closed
<add>const RIGHT_SWIPE_BOUNCE_BACK_DISTANCE = 30;
<add>// Factor to divide by to get slow speed; i.e. 4 means 1/4 of full speed
<add>const SLOW_SPEED_SWIPE_FACTOR = 4;
<add>/**
<add> * Max distance of right swipe to allow (right swipes do functionally nothing).
<add> * Must be multiplied by SLOW_SPEED_SWIPE_FACTOR because gestureState.dx tracks
<add> * how far the finger swipes, and not the actual animation distance.
<add>*/
<add>const RIGHT_SWIPE_THRESHOLD = 30 * SLOW_SPEED_SWIPE_FACTOR;
<ide> // Time, in milliseconds, of how long the animated swipe should be
<ide> const SWIPE_DURATION = 200;
<ide>
<ide> const SwipeableRow = React.createClass({
<ide> propTypes: {
<ide> isOpen: PropTypes.bool,
<ide> maxSwipeDistance: PropTypes.number.isRequired,
<del> onOpen: PropTypes.func,
<add> onOpen: PropTypes.func.isRequired,
<ide> onSwipeEnd: PropTypes.func.isRequired,
<ide> onSwipeStart: PropTypes.func.isRequired,
<ide> /**
<ide> const SwipeableRow = React.createClass({
<ide> return {
<ide> isOpen: false,
<ide> maxSwipeDistance: 0,
<add> onOpen: emptyFunction,
<ide> onSwipeEnd: emptyFunction,
<ide> onSwipeStart: emptyFunction,
<ide> swipeThreshold: 30,
<ide> const SwipeableRow = React.createClass({
<ide> },
<ide>
<ide> _handlePanResponderMove(event: Object, gestureState: Object): void {
<add> if (this._isSwipingExcessivelyRightFromClosedPosition(gestureState)) {
<add> return;
<add> }
<add>
<ide> this.props.onSwipeStart();
<ide>
<del> if (!this._isSwipingRightFromClosedPosition(gestureState)) {
<del> this.state.currentLeft.setValue(this._previousLeft + gestureState.dx);
<add> if (this._isSwipingRightFromClosed(gestureState)) {
<add> this._swipeSlowSpeed(gestureState);
<add> } else {
<add> this._swipeFullSpeed(gestureState);
<ide> }
<ide> },
<ide>
<del> _isSwipingRightFromClosedPosition(gestureState: Object): boolean {
<add> _isSwipingRightFromClosed(gestureState: Object): boolean {
<ide> return this._previousLeft === CLOSED_LEFT_POSITION && gestureState.dx > 0;
<ide> },
<ide>
<del> _onPanResponderTerminationRequest(event: Object, gestureState: Object): boolean {
<add> _swipeFullSpeed(gestureState: Object): void {
<add> this.state.currentLeft.setValue(this._previousLeft + gestureState.dx);
<add> },
<add>
<add> _swipeSlowSpeed(gestureState: Object): void {
<add> this.state.currentLeft.setValue(
<add> this._previousLeft + gestureState.dx / SLOW_SPEED_SWIPE_FACTOR,
<add> );
<add> },
<add>
<add> _isSwipingExcessivelyRightFromClosedPosition(gestureState: Object): boolean {
<add> /**
<add> * We want to allow a BIT of right swipe, to allow users to know that
<add> * swiping is available, but swiping right does not do anything
<add> * functionally.
<add> */
<add> return (
<add> this._isSwipingRightFromClosed(gestureState) &&
<add> gestureState.dx > RIGHT_SWIPE_THRESHOLD
<add> );
<add> },
<add>
<add> _onPanResponderTerminationRequest(
<add> event: Object,
<add> gestureState: Object,
<add> ): boolean {
<ide> return false;
<ide> },
<ide>
<del> _animateTo(toValue: number): void {
<add> _animateTo(toValue: number, callback: Function = emptyFunction): void {
<ide> Animated.timing(
<ide> this.state.currentLeft,
<ide> {
<ide> const SwipeableRow = React.createClass({
<ide> },
<ide> ).start(() => {
<ide> this._previousLeft = toValue;
<add> callback();
<ide> });
<ide> },
<ide>
<ide> const SwipeableRow = React.createClass({
<ide> this._animateTo(CLOSED_LEFT_POSITION);
<ide> },
<ide>
<add> _animateRightSwipeBounceBack(): void {
<add> /**
<add> * When swiping right, we want to bounce back past closed position on release
<add> * so users know they should swipe right to get content.
<add> */
<add> this._animateTo(
<add> -RIGHT_SWIPE_BOUNCE_BACK_DISTANCE,
<add> this._animateToClosedPosition,
<add> );
<add> },
<add>
<ide> // Ignore swipes due to user's finger moving slightly when tapping
<ide> _isValidSwipe(gestureState: Object): boolean {
<ide> return Math.abs(gestureState.dx) > HORIZONTAL_SWIPE_DISTANCE_THRESHOLD;
<ide> const SwipeableRow = React.createClass({
<ide> _handlePanResponderEnd(event: Object, gestureState: Object): void {
<ide> const horizontalDistance = gestureState.dx;
<ide>
<del> if (Math.abs(horizontalDistance) > this.props.swipeThreshold) {
<add> if (this._isSwipingRightFromClosed(gestureState)) {
<add> this.props.onOpen();
<add> this._animateRightSwipeBounceBack();
<add> } else if (Math.abs(horizontalDistance) > this.props.swipeThreshold) {
<add> // Overswiped
<add>
<ide> if (horizontalDistance < 0) {
<ide> // Swiped left
<del> this.props.onOpen && this.props.onOpen();
<add> this.props.onOpen();
<ide> this._animateToOpenPosition();
<ide> } else {
<ide> // Swiped right
<ide> this._animateToClosedPosition();
<ide> }
<ide> } else {
<add> // Swiping from closed but let go before fully
<add>
<ide> if (this._previousLeft === CLOSED_LEFT_POSITION) {
<ide> this._animateToClosedPosition();
<ide> } else {
| 1
|
Javascript
|
Javascript
|
simplify skeleton building
|
9e4849ace7b9e8ebfbda022f9f32e3bf18e68dee
|
<ide><path>examples/js/loaders/FBXLoader.js
<ide>
<ide> function bindSkeleton( FBXTree, skeletons, geometryMap, modelMap, connections, sceneGraph ) {
<ide>
<del> // Now with the bones created, we can update the skeletons and bind them to the skinned meshes.
<del> sceneGraph.updateMatrixWorld( true );
<del>
<del> var worldMatrices = new Map();
<del>
<del> // Put skeleton into bind pose.
<del> if ( 'Pose' in FBXTree.Objects ) {
<del>
<del> var BindPoseNode = FBXTree.Objects.Pose;
<del>
<del> for ( var nodeID in BindPoseNode ) {
<del>
<del> if ( BindPoseNode[ nodeID ].attrType === 'BindPose' ) {
<del>
<del> var poseNodes = BindPoseNode[ nodeID ].PoseNode;
<del>
<del> if ( Array.isArray( poseNodes ) ) {
<del>
<del> poseNodes.forEach( function ( node ) {
<del>
<del> var rawMatWrd = new THREE.Matrix4().fromArray( node.Matrix.a );
<del> worldMatrices.set( parseInt( node.Node ), rawMatWrd );
<del>
<del> } );
<del>
<del> } else {
<del>
<del> var rawMatWrd = new THREE.Matrix4().fromArray( poseNodes.Matrix.a );
<del> worldMatrices.set( parseInt( poseNodes.Node ), rawMatWrd );
<del>
<del> }
<del>
<del> }
<del>
<del> }
<del>
<del> }
<del>
<ide> for ( var ID in skeletons ) {
<ide>
<ide> var skeleton = skeletons[ ID ];
<ide>
<ide> skeleton.bones.forEach( function ( bone, i ) {
<ide>
<del> // if the bone's initial transform is set in a poseNode, copy that
<del> if ( worldMatrices.has( bone.ID ) ) {
<del>
<del> var mat = worldMatrices.get( bone.ID );
<del> bone.matrixWorld.copy( mat );
<del>
<del> }
<del> // otherwise use the transform from the rawBone
<del> else {
<del>
<del> bone.matrixWorld.copy( skeleton.rawBones[ i ].transformLink );
<del>
<del> }
<add> bone.matrixWorld.copy( skeleton.rawBones[ i ].transformLink );
<ide>
<ide> } );
<ide>
<del> // Now that skeleton is in bind pose, bind to model.
<ide> var parents = connections.get( parseInt( skeleton.ID ) ).parents;
<ide>
<ide> parents.forEach( function ( parent ) {
<ide>
<ide> }
<ide>
<del> //Skeleton is now bound, return objects to starting world positions.
<del> sceneGraph.updateMatrixWorld( true );
<del>
<ide> }
<ide>
<ide> function parseAnimations( FBXTree, connections ) {
<ide> // if the subnode already exists, append it
<ide> if ( nodeName in currentNode ) {
<ide>
<del> // special case Pose needs PoseNodes as an array
<del> if ( nodeName === 'PoseNode' ) {
<del>
<del> currentNode.PoseNode.push( node );
<del>
<del> } else if ( currentNode[ nodeName ].id !== undefined ) {
<add> if ( currentNode[ nodeName ].id !== undefined ) {
<ide>
<ide> currentNode[ nodeName ] = {};
<ide> currentNode[ nodeName ][ currentNode[ nodeName ].id ] = currentNode[ nodeName ];
<ide>
<ide> } else if ( nodeName !== 'Properties70' ) {
<ide>
<del> if ( nodeName === 'PoseNode' ) currentNode[ nodeName ] = [ node ];
<del> else currentNode[ nodeName ] = node;
<add> currentNode[ nodeName ] = node;
<ide>
<ide> }
<ide>
<ide>
<ide> }
<ide>
<del> } else {
<add> } else if ( node[ subNode.name ][ subNode.id ] === undefined ) {
<ide>
<del> if ( subNode.name === 'PoseNode' ) {
<del>
<del> if ( ! Array.isArray( node[ subNode.name ] ) ) {
<del>
<del> node[ subNode.name ] = [ node[ subNode.name ] ];
<del>
<del> }
<del>
<del> node[ subNode.name ].push( subNode );
<del>
<del> } else if ( node[ subNode.name ][ subNode.id ] === undefined ) {
<del>
<del> node[ subNode.name ][ subNode.id ] = subNode;
<del>
<del> }
<add> node[ subNode.name ][ subNode.id ] = subNode;
<ide>
<ide> }
<ide>
| 1
|
Go
|
Go
|
add container=lxc in default env
|
67f1e3f5ed4d3061e07e910e28ac866b7bb13e18
|
<ide><path>container.go
<ide> func (container *Container) Start(hostConfig *HostConfig) error {
<ide> params = append(params,
<ide> "-e", "HOME=/",
<ide> "-e", "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
<add> "-e", "container=lxc",
<ide> )
<ide>
<ide> for _, elem := range container.Config.Env {
| 1
|
Javascript
|
Javascript
|
transfer the key prop in clonewithprops
|
4a5a6ad733a546f933c8096932fb87b47bc335da
|
<ide><path>src/utils/__tests__/cloneWithProps-test.js
<ide> describe('cloneWithProps', function() {
<ide> console.warn = _warn;
<ide> }
<ide> });
<add>
<add> it('should transfer the key property', function() {
<add> var Component = React.createClass({
<add> render: function() {
<add> expect(this.props.key).toBe('xyz');
<add> return <div />;
<add> }
<add> });
<add>
<add> ReactTestUtils.renderIntoDocument(
<add> cloneWithProps(<Component />, {key: 'xyz'})
<add> );
<add> });
<ide> });
<ide><path>src/utils/cloneWithProps.js
<ide> function cloneWithProps(child, props) {
<ide> }
<ide> }
<ide>
<del> return child.constructor.ConvenienceConstructor(
<del> ReactPropTransferer.mergeProps(child.props, props)
<del> );
<add> var newProps = ReactPropTransferer.mergeProps(child.props, props);
<add> // ReactPropTransferer does not transfer the `key` prop so do it manually.
<add> if (props.key) {
<add> newProps.key = props.key;
<add> }
<add> return child.constructor.ConvenienceConstructor(newProps);
<ide> }
<ide>
<ide> module.exports = cloneWithProps;
| 2
|
Ruby
|
Ruby
|
add cppflag for ncurses flag under 10.6
|
e4a32736cd72836f3948ea4dd5f5aa97a784ff69
|
<ide><path>Library/Homebrew/brewkit.rb
<ide> def x11
<ide> def enable_warnings
<ide> remove_from_cflags '-w'
<ide> end
<add> # Snow Leopard defines an NCURSES value the opposite of most distros
<add> # See: http://bugs.python.org/issue6848
<add> def ncurses_define
<add> append 'CPPFLAGS', "-DNCURSES_OPAQUE=0"
<add> end
<ide> # returns the compiler we're using
<ide> def cc
<ide> ENV['CC'] or "gcc"
| 1
|
Go
|
Go
|
add deprecation warning for -t on pull
|
15e52ccaadea996b409e2f62bcbdb1a088619e35
|
<ide><path>api/client.go
<ide> func (cli *DockerCli) CmdPush(args ...string) error {
<ide> }
<ide>
<ide> func (cli *DockerCli) CmdPull(args ...string) error {
<del> cmd := cli.Subcmd("pull", "NAME", "Pull an image or a repository from the registry")
<del> tag := cmd.String([]string{"t", "-tag"}, "", "Download tagged image in repository")
<add> cmd := cli.Subcmd("pull", "NAME[:TAG]", "Pull an image or a repository from the registry")
<add> tag := cmd.String([]string{"#t", "#-tag"}, "", "Download tagged image in repository")
<ide> if err := cmd.Parse(args); err != nil {
<ide> return nil
<ide> }
| 1
|
PHP
|
PHP
|
add another integration test
|
28390c9e76f87dc61ec8e0352a22b32a212a7706
|
<ide><path>tests/Database/DatabaseEloquentIntegrationTests.php
<ide> public function setUp()
<ide> $table->integer('user_id');
<ide> $table->integer('friend_id');
<ide> });
<add>
<add> $this->schema()->create('posts', function($table) {
<add> $table->increments('id');
<add> $table->integer('user_id');
<add> $table->string('name');
<add> $table->timestamps();
<add> });
<ide> }
<ide>
<ide>
<ide> public function tearDown()
<ide> {
<ide> $this->schema()->drop('users');
<ide> $this->schema()->drop('friends');
<add> $this->schema()->drop('posts');
<ide> }
<ide>
<ide> /**
<ide> public function testHasOnSelfReferencingBelongsToManyRelationship()
<ide> $this->assertEquals('taylorotwell@gmail.com', $results->first()->email);
<ide> }
<ide>
<add>
<add> public function testBasicHasManyEagerLoading()
<add> {
<add> $user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
<add> $user->posts()->create(['name' => 'First Post']);
<add> $user = EloquentTestUser::with('posts')->where('email', 'taylorotwell@gmail.com')->first();
<add>
<add> $this->assertEquals('First Post', $user->posts->first()->name);
<add> }
<add>
<ide> /**
<ide> * Helpers...
<ide> */
<ide> class EloquentTestUser extends Eloquent {
<ide> public function friends() {
<ide> return $this->belongsToMany('EloquentTestUser', 'friends', 'user_id', 'friend_id');
<ide> }
<add> public function posts() {
<add> return $this->hasMany('EloquentTestPost', 'user_id');
<add> }
<add>}
<add>
<add>class EloquentTestPost extends Eloquent {
<add> protected $table = 'posts';
<add> protected $guarded = [];
<add> public function user() {
<add> return $this->belongsTo('EloquentTestUser', 'user_id');
<add> }
<ide> }
<ide>
<ide> /**
| 1
|
Python
|
Python
|
remove test of parser pickle
|
cd71b6b0a94c98966a7750f067eaa2dd044f5fec
|
<ide><path>spacy/tests/parser/test_parser_pickle.py
<ide> import io
<ide>
<ide>
<del>@pytest.mark.models
<del>def test_pickle(EN):
<del> file_ = io.BytesIO()
<del> cloudpickle.dump(EN.parser, file_)
<del>
<del> file_.seek(0)
<del>
<del> loaded = pickle.load(file_)
<del>
<add>#@pytest.mark.models
<add>#def test_pickle(EN):
<add># file_ = io.BytesIO()
<add># cloudpickle.dump(EN.parser, file_)
<add>#
<add># file_.seek(0)
<add>#
<add># loaded = pickle.load(file_)
<add>#
| 1
|
Go
|
Go
|
add updatesuffixarray and refactor truncindex
|
219b7ae8b526bb5e6d0e27176308db71438a002f
|
<ide><path>utils/utils.go
<ide> func NewTruncIndex(ids []string) (idx *TruncIndex) {
<ide> return
<ide> }
<ide>
<del>func (idx *TruncIndex) Add(id string) error {
<del> idx.Lock()
<del> defer idx.Unlock()
<add>func (idx *TruncIndex) addId(id string) error {
<ide> if strings.Contains(id, " ") {
<ide> return fmt.Errorf("Illegal character: ' '")
<ide> }
<ide> func (idx *TruncIndex) Add(id string) error {
<ide> }
<ide> idx.ids[id] = true
<ide> idx.bytes = append(idx.bytes, []byte(id+" ")...)
<add> return nil
<add>}
<add>
<add>func (idx *TruncIndex) Add(id string) error {
<add> idx.Lock()
<add> defer idx.Unlock()
<add> if err := idx.addId(id); err != nil {
<add> return err
<add> }
<ide> idx.index = suffixarray.New(idx.bytes)
<ide> return nil
<ide> }
<ide>
<add>func (idx *TruncIndex) AddWithoutSuffixarrayUpdate(id string) error {
<add> idx.Lock()
<add> defer idx.Unlock()
<add> return idx.addId(id)
<add>}
<add>
<add>func (idx *TruncIndex) UpdateSuffixarray() {
<add> idx.Lock()
<add> defer idx.Unlock()
<add> idx.index = suffixarray.New(idx.bytes)
<add>}
<add>
<ide> func (idx *TruncIndex) Delete(id string) error {
<ide> idx.Lock()
<ide> defer idx.Unlock()
| 1
|
Ruby
|
Ruby
|
use -v for python version
|
05772f8ccfa16ca27e75fa22b7e590241a19b03e
|
<ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def check_for_enthought_python
<ide>
<ide> def check_for_bad_python_symlink
<ide> return unless which "python"
<del> # Indeed Python --version outputs to stderr (WTF?)
<del> `python --version 2>&1` =~ /Python (\d+)\./
<add> # Indeed Python -V outputs to stderr (WTF?)
<add> `python -V 2>&1` =~ /Python (\d+)\./
<add> # This won't be the right warning if we matched nothing at all
<add> return if $1.nil?
<ide> unless $1 == "2" then <<-EOS.undent
<ide> python is symlinked to python#$1
<ide> This will confuse build scripts and in general lead to subtle breakage.
| 1
|
PHP
|
PHP
|
use single quotes where applicable
|
256ac763f4f5c9cd37a3831bd7df827ff46b387b
|
<ide><path>src/Collection/CollectionTrait.php
<ide> public function last()
<ide> public function takeLast(int $howMany): CollectionInterface
<ide> {
<ide> if ($howMany < 1) {
<del> throw new InvalidArgumentException("The takeLast method requires a number greater than 0.");
<add> throw new InvalidArgumentException('The takeLast method requires a number greater than 0.');
<ide> }
<ide>
<ide> $iterator = $this->optimizeUnwrap();
<ide><path>src/Command/I18nExtractCommand.php
<ide> protected function _extract(Arguments $args, ConsoleIo $io): void
<ide> $io->out();
<ide> if ($this->_countMarkerError) {
<ide> $io->err("{$this->_countMarkerError} marker error(s) detected.");
<del> $io->err(" => Use the --marker-error option to display errors.");
<add> $io->err(' => Use the --marker-error option to display errors.');
<ide> }
<ide>
<ide> $io->out('Done.');
<ide> protected function _writeHeader(string $domain): string
<ide> $output .= "#, fuzzy\n";
<ide> $output .= "msgid \"\"\n";
<ide> $output .= "msgstr \"\"\n";
<del> $output .= "\"Project-Id-Version: " . $projectIdVersion . "\\n\"\n";
<add> $output .= '"Project-Id-Version: ' . $projectIdVersion . "\\n\"\n";
<ide> $output .= '"POT-Creation-Date: ' . date('Y-m-d H:iO') . "\\n\"\n";
<ide> $output .= "\"PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\\n\"\n";
<ide> $output .= "\"Last-Translator: NAME <EMAIL@ADDRESS>\\n\"\n";
<ide><path>src/Console/CommandRunner.php
<ide> public function run(array $argv, ?ConsoleIo $io = null): int
<ide> $this->loadRoutes();
<ide>
<ide> if (empty($argv)) {
<del> throw new RuntimeException("Cannot run any commands. No arguments received.");
<add> throw new RuntimeException('Cannot run any commands. No arguments received.');
<ide> }
<ide> // Remove the root executable segment
<ide> array_shift($argv);
<ide><path>src/Controller/ControllerFactory.php
<ide> public function getControllerClass(ServerRequest $request): ?string
<ide> if ($firstChar !== strtoupper($firstChar)) {
<ide> deprecationWarning(
<ide> "The `{$prefix}` prefix did not start with an upper case character. " .
<del> "Routing prefixes should be defined as CamelCase values. " .
<del> "Prefix inflection will be removed in 5.0"
<add> 'Routing prefixes should be defined as CamelCase values. ' .
<add> 'Prefix inflection will be removed in 5.0'
<ide> );
<ide>
<ide> if (strpos($prefix, '/') === false) {
<ide><path>src/Database/Dialect/SqliteDialectTrait.php
<ide> protected function _transformFunctionExpression(FunctionExpression $expression):
<ide> case 'RAND':
<ide> $expression
<ide> ->setName('ABS')
<del> ->add(["RANDOM() % 1" => 'literal'], [], true);
<add> ->add(['RANDOM() % 1' => 'literal'], [], true);
<ide> break;
<ide> case 'CURRENT_DATE':
<ide> $expression->setName('DATE')->add(["'now'" => 'literal']);
<ide><path>src/Database/Type/BinaryUuidType.php
<ide> public function marshal($value)
<ide> */
<ide> protected function convertBinaryUuidToString($binary): string
<ide> {
<del> $string = unpack("H*", $binary);
<add> $string = unpack('H*', $binary);
<ide>
<ide> $string = preg_replace(
<del> "/([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})/",
<del> "$1-$2-$3-$4-$5",
<add> '/([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})/',
<add> '$1-$2-$3-$4-$5',
<ide> $string
<ide> );
<ide>
<ide> protected function convertStringToBinaryUuid($string): string
<ide> {
<ide> $string = str_replace('-', '', $string);
<ide>
<del> return pack("H*", $string);
<add> return pack('H*', $string);
<ide> }
<ide> }
<ide><path>src/Filesystem/File.php
<ide> protected static function _basename(string $path, ?string $ext = null): string
<ide> return $name;
<ide> }
<ide> $ext = preg_quote($ext);
<del> $new = preg_replace("/({$ext})$/u", "", $name);
<add> $new = preg_replace("/({$ext})$/u", '', $name);
<ide>
<ide> // basename of '/etc/.d' is '.d' not ''
<ide> return $new === '' ? $name : $new;
<ide><path>src/Http/Cookie/CookieCollection.php
<ide> public function addToRequest(RequestInterface $request, array $extraCookies = []
<ide> $cookies = array_merge($cookies, $extraCookies);
<ide> $cookiePairs = [];
<ide> foreach ($cookies as $key => $value) {
<del> $cookie = sprintf("%s=%s", rawurlencode($key), rawurlencode($value));
<add> $cookie = sprintf('%s=%s', rawurlencode($key), rawurlencode($value));
<ide> $size = strlen($cookie);
<ide> if ($size > 4096) {
<ide> triggerWarning(sprintf(
<ide><path>src/I18n/Date.php
<ide> class Date extends MutableDate implements I18nDateTimeInterface
<ide> * @var string|array|int
<ide> * @see \Cake\I18n\Time::i18nFormat()
<ide> */
<del> protected static $_jsonEncodeFormat = "yyyy-MM-dd";
<add> protected static $_jsonEncodeFormat = 'yyyy-MM-dd';
<ide>
<ide> /**
<ide> * The format to use when formatting a time using `Cake\I18n\Date::timeAgoInWords()`
<ide><path>src/I18n/FrozenDate.php
<ide> class FrozenDate extends ChronosDate implements I18nDateTimeInterface
<ide> * @var string|array|int
<ide> * @see \Cake\I18n\Time::i18nFormat()
<ide> */
<del> protected static $_jsonEncodeFormat = "yyyy-MM-dd";
<add> protected static $_jsonEncodeFormat = 'yyyy-MM-dd';
<ide>
<ide> /**
<ide> * The format to use when formatting a time using `Cake\I18n\Date::timeAgoInWords()`
<ide><path>src/ORM/Table.php
<ide> protected function checkAliasLengths(): void
<ide> }
<ide>
<ide> $maxLength = null;
<del> if (method_exists($this->getConnection()->getDriver(), "getMaxAliasLength")) {
<add> if (method_exists($this->getConnection()->getDriver(), 'getMaxAliasLength')) {
<ide> $maxLength = $this->getConnection()->getDriver()->getMaxAliasLength();
<ide> }
<ide> if ($maxLength === null) {
<ide> protected function checkAliasLengths(): void
<ide> if (strlen($table . '__' . $name) > $maxLength) {
<ide> $nameLength = $maxLength - 2;
<ide> throw new RuntimeException(
<del> "ORM queries generate field aliases using the table name/alias and column name. " .
<add> 'ORM queries generate field aliases using the table name/alias and column name. ' .
<ide> "The table alias `{$table}` and column `{$name}` create an alias longer than ({$nameLength}). " .
<del> "You must change the table schema in the database and shorten either the table or column " .
<del> "identifier so they fit within the database alias limits."
<add> 'You must change the table schema in the database and shorten either the table or column ' .
<add> 'identifier so they fit within the database alias limits.'
<ide> );
<ide> }
<ide> }
<ide><path>src/View/Helper/FormHelper.php
<ide> protected function setRequiredAndCustomValidity(string $fieldName, array $option
<ide> if ($this->getConfig('autoSetCustomValidity')) {
<ide> $options['data-validity-message'] = $message;
<ide> $options['oninvalid'] = "this.setCustomValidity(''); "
<del> . "if (!this.value) this.setCustomValidity(this.dataset.validityMessage)";
<add> . 'if (!this.value) this.setCustomValidity(this.dataset.validityMessage)';
<ide> $options['oninput'] = "this.setCustomValidity('')";
<ide> }
<ide> }
<ide><path>templates/Error/missing_action.php
<ide> * @license https://opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide> use Cake\Core\Configure;
<del>use Cake\Utility\Inflector;
<ide> use Cake\Core\Plugin;
<add>use Cake\Utility\Inflector;
<ide>
<ide> $namespace = Configure::read('App.namespace');
<ide> if (!empty($plugin)) {
<ide> $namespace = str_replace('/', '\\', $plugin);
<ide> }
<ide> $prefixNs = '';
<del>$prefix = isset($prefix) ? $prefix : '';
<del>if (!empty($prefix)) {
<add>$prefix = $prefix ?? '';
<add>if ($prefix) {
<ide> $prefix = array_map('Cake\Utility\Inflector::camelize', explode('/', $prefix));
<ide> $prefixNs = '\\' . implode('\\', $prefix);
<ide> $prefix = implode(DIRECTORY_SEPARATOR, $prefix) . DIRECTORY_SEPARATOR;
<ide> }
<ide>
<ide> if (empty($plugin)) {
<del> $path = APP_DIR . DIRECTORY_SEPARATOR . $type . DIRECTORY_SEPARATOR . $prefix . h($class) . '.php' ;
<add> $path = APP_DIR . DIRECTORY_SEPARATOR . $type . DIRECTORY_SEPARATOR . $prefix . h($class) . '.php';
<ide> } else {
<ide> $path = Plugin::classPath($plugin) . $type . DIRECTORY_SEPARATOR . $prefix . h($class) . '.php';
<ide> }
<ide> ?>
<ide> <p class="error">
<ide> <strong>Error</strong>
<del> <?= sprintf('Create <em>%s::%s()</em> in file: %s.', h($class), h($action), $path); ?>
<add> <?= sprintf('Create <em>%s::%s()</em> in file: %s.', h($class), h($action), $path); ?>
<ide> </p>
<ide>
<ide> <?php
<ide><path>templates/Error/missing_behavior.php
<ide> * @since 1.3.0
<ide> * @license https://opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>use Cake\Core\Plugin;
<ide> use Cake\Core\Configure;
<add>use Cake\Core\Plugin;
<ide>
<ide> $namespace = Configure::read('App.namespace');
<ide> if (!empty($plugin)) {
<ide><path>templates/Error/missing_component.php
<ide> * @since 0.10.0
<ide> * @license https://opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>use Cake\Core\Plugin;
<ide> use Cake\Core\Configure;
<add>use Cake\Core\Plugin;
<ide>
<ide> $namespace = Configure::read('App.namespace');
<ide> if (!empty($plugin)) {
<ide><path>templates/Error/missing_controller.php
<ide> * @since 0.10.0
<ide> * @license https://opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>use Cake\Core\Plugin;
<ide> use Cake\Core\Configure;
<add>use Cake\Core\Plugin;
<ide> use Cake\Utility\Inflector;
<ide>
<ide> $pluginDot = empty($plugin) ? null : $plugin . '.';
<ide> $namespace = str_replace('/', '\\', $plugin);
<ide> }
<ide> if (empty($plugin)) {
<del> $path = APP_DIR . DIRECTORY_SEPARATOR . 'Controller' . DIRECTORY_SEPARATOR . $prefixPath . h($class) . 'Controller.php' ;
<add> $path = APP_DIR . DIRECTORY_SEPARATOR . 'Controller' . DIRECTORY_SEPARATOR . $prefixPath . h($class) . 'Controller.php';
<ide> } else {
<ide> $path = Plugin::classPath($plugin) . 'Controller' . DIRECTORY_SEPARATOR . $prefixPath . h($class) . 'Controller.php';
<ide> }
<ide><path>templates/Error/missing_datasource_config.php
<ide> <?php
<ide> /**
<del> *
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> *
<ide><path>templates/Error/missing_helper.php
<ide> * @since 0.10.0
<ide> * @license https://opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>use Cake\Core\Plugin;
<ide> use Cake\Core\Configure;
<add>use Cake\Core\Plugin;
<ide>
<ide> $namespace = Configure::read('App.namespace');
<ide> if (!empty($plugin)) {
<ide><path>templates/Error/missing_route.php
<ide> * @license https://opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide>
<del>use Cake\Routing\Router;
<ide> use Cake\Error\Debugger;
<add>use Cake\Routing\Router;
<ide>
<ide> $this->layout = 'dev_error';
<ide>
<ide><path>templates/Error/missing_view.php
<ide> * @since 3.0.0
<ide> * @license https://opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>use Cake\Core\Plugin;
<ide> use Cake\Core\Configure;
<add>use Cake\Core\Plugin;
<add>
<ide> $namespace = Configure::read('App.namespace');
<ide>
<ide> $pluginPath = Configure::read('App.paths.plugins.0');
<ide><path>templates/element/auto_table_warning.php
<ide> * @license https://opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide> use Cake\ORM\TableRegistry;
<add>
<ide> $autoTables = TableRegistry::getTableLocator()->genericInstances();
<ide> if (!$autoTables) {
<ide> return;
<ide><path>templates/element/exception_stack_trace.php
<ide> * @link https://cakephp.org CakePHP(tm) Project
<ide> * @since 1.3.0
<ide> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> *
<add> * @var array $trace
<ide> */
<ide> use Cake\Error\Debugger;
<ide>
<ide><path>templates/element/exception_stack_trace_nav.php
<ide> * @link https://cakephp.org CakePHP(tm) Project
<ide> * @since 3.0.0
<ide> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> *
<add> * @var array $trace
<ide> */
<ide> use Cake\Error\Debugger;
<ide> ?>
<ide><path>templates/element/plugin_class_error.php
<ide> '<a href="https://book.cakephp.org/4/en/plugins.html#autoloading-plugin-classes">Plugins - autoloading plugin classes</a>'
<ide> );
<ide> endif;
<del>
<del>?>
<ide><path>tests/TestCase/Command/CompletionCommandTest.php
<ide> public function testSubCommandsCorePlugin()
<ide> $this->exec('completion subcommands schema_cache');
<ide> $this->assertExitCode(Command::CODE_SUCCESS);
<ide>
<del> $expected = "build clear";
<add> $expected = 'build clear';
<ide> $this->assertOutputContains($expected);
<ide> }
<ide>
<ide> public function testSubCommandsPlugin()
<ide> $this->exec('completion subcommands welcome');
<ide> $this->assertExitCode(Command::CODE_SUCCESS);
<ide>
<del> $expected = "say_hello";
<add> $expected = 'say_hello';
<ide> $this->assertOutputContains($expected);
<ide> }
<ide>
<ide> public function testSubCommandsPluginDotNotationBackwardCompatibility()
<ide> $this->exec('completion subcommands test_plugin_two.welcome');
<ide> $this->assertExitCode(Command::CODE_SUCCESS);
<ide>
<del> $expected = "say_hello";
<add> $expected = 'say_hello';
<ide> $this->assertOutputContains($expected);
<ide> }
<ide>
<ide> public function testSubCommandsPluginDotNotation()
<ide> $this->exec('completion subcommands test_plugin_two.example');
<ide> $this->assertExitCode(Command::CODE_SUCCESS);
<ide>
<del> $expected = "say_hello";
<add> $expected = 'say_hello';
<ide> $this->assertOutputContains($expected);
<ide> }
<ide>
<ide> public function testSubCommandsPluginDuplicateApp()
<ide> $this->exec('completion subcommands test_plugin.sample');
<ide> $this->assertExitCode(Command::CODE_SUCCESS);
<ide>
<del> $expected = "example";
<add> $expected = 'example';
<ide> $this->assertOutputContains($expected);
<ide> }
<ide>
<ide> public function testSubCommands()
<ide> $this->exec('completion subcommands schema_cache');
<ide> $this->assertExitCode(Command::CODE_SUCCESS);
<ide>
<del> $expected = "build clear";
<add> $expected = 'build clear';
<ide> $this->assertOutputContains($expected);
<ide> }
<ide>
<ide><path>tests/TestCase/Console/CommandRunnerTest.php
<ide> public function testRunInvalidCommandSuggestion()
<ide> "\n" .
<ide> "Other valid choices:\n" .
<ide> "\n" .
<del> "- help",
<add> '- help',
<ide> $messages
<ide> );
<ide> }
<ide><path>tests/TestCase/Console/ConsoleOptionParserTest.php
<ide> public function testOptionThatDoesNotExist()
<ide> "\n" .
<ide> "Other valid choices:\n" .
<ide> "\n" .
<del> "- help",
<add> '- help',
<ide> $e->getFullMessage()
<ide> );
<ide> }
<ide> public function testShortOptionThatDoesNotExist()
<ide> try {
<ide> $parser->parse(['-f']);
<ide> } catch (MissingOptionException $e) {
<del> $this->assertStringContainsString("Unknown short option `f`.", $e->getFullMessage());
<add> $this->assertStringContainsString('Unknown short option `f`.', $e->getFullMessage());
<ide> }
<ide> }
<ide>
<ide> public function testHelpUnknownSubcommand()
<ide> "\n" .
<ide> "Other valid choices:\n" .
<ide> "\n" .
<del> "- method",
<add> '- method',
<ide> $result
<ide> );
<ide> }
<ide><path>tests/TestCase/ExceptionsTest.php
<ide> public function testMissingTemplateExceptions()
<ide> $previous = new Exception();
<ide>
<ide> $error = new MissingTemplateException('view.ctp', ['path/a/', 'path/b/'], 100, $previous);
<del> $this->assertStringContainsString("Template file `view.ctp` could not be found", $error->getMessage());
<add> $this->assertStringContainsString('Template file `view.ctp` could not be found', $error->getMessage());
<ide> $this->assertStringContainsString('- `path/a/view.ctp`', $error->getMessage());
<ide> $this->assertSame($previous, $error->getPrevious());
<ide> $this->assertSame(100, $error->getCode());
<ide> public function testMissingTemplateExceptions()
<ide> $this->assertArrayHasKey('paths', $attributes);
<ide>
<ide> $error = new MissingLayoutException('default.ctp', ['path/a/', 'path/b/'], 100, $previous);
<del> $this->assertStringContainsString("Layout file `default.ctp` could not be found", $error->getMessage());
<add> $this->assertStringContainsString('Layout file `default.ctp` could not be found', $error->getMessage());
<ide> $this->assertStringContainsString('- `path/a/default.ctp`', $error->getMessage());
<ide> $this->assertSame($previous, $error->getPrevious());
<ide> $this->assertSame(100, $error->getCode());
<ide>
<ide> $error = new MissingElementException('view.ctp', ['path/a/', 'path/b/'], 100, $previous);
<del> $this->assertStringContainsString("Element file `view.ctp` could not be found", $error->getMessage());
<add> $this->assertStringContainsString('Element file `view.ctp` could not be found', $error->getMessage());
<ide> $this->assertStringContainsString('- `path/a/view.ctp`', $error->getMessage());
<ide> $this->assertSame($previous, $error->getPrevious());
<ide> $this->assertSame(100, $error->getCode());
<ide>
<ide> $error = new MissingCellTemplateException('Articles', 'view.ctp', ['path/a/', 'path/b/'], 100, $previous);
<del> $this->assertStringContainsString("Cell template file `view.ctp` could not be found", $error->getMessage());
<add> $this->assertStringContainsString('Cell template file `view.ctp` could not be found', $error->getMessage());
<ide> $this->assertStringContainsString('- `path/a/view.ctp`', $error->getMessage());
<ide> $this->assertSame($previous, $error->getPrevious());
<ide> $this->assertSame(100, $error->getCode());
<ide><path>tests/TestCase/Filesystem/FolderTest.php
<ide> public function testSortByName()
<ide> public function testIsRegisteredStreamWrapper()
<ide> {
<ide> foreach (stream_get_wrappers() as $wrapper) {
<del> $this->assertTrue(Folder::isRegisteredStreamWrapper($wrapper . "://path/to/file"));
<del> $this->assertFalse(Folder::isRegisteredStreamWrapper("bad." . $wrapper . "://path/to/file"));
<add> $this->assertTrue(Folder::isRegisteredStreamWrapper($wrapper . '://path/to/file'));
<add> $this->assertFalse(Folder::isRegisteredStreamWrapper('bad.' . $wrapper . '://path/to/file'));
<ide> }
<ide>
<ide> $wrapper = 'unit.test1-';
<del> $this->assertFalse(Folder::isRegisteredStreamWrapper($wrapper . "://path/to/file"));
<add> $this->assertFalse(Folder::isRegisteredStreamWrapper($wrapper . '://path/to/file'));
<ide> stream_wrapper_register($wrapper, self::class);
<del> $this->assertTrue(Folder::isRegisteredStreamWrapper($wrapper . "://path/to/file"));
<add> $this->assertTrue(Folder::isRegisteredStreamWrapper($wrapper . '://path/to/file'));
<ide> stream_wrapper_unregister($wrapper);
<ide> }
<ide> }
<ide><path>tests/TestCase/Http/Client/Adapter/StreamTest.php
<ide> public function testSendContextContentArrayFiles()
<ide>
<ide> $this->stream->send($request, []);
<ide> $result = $this->stream->contextOptions();
<del> $this->assertStringContainsString("Content-Type: multipart/form-data", $result['header']);
<add> $this->assertStringContainsString('Content-Type: multipart/form-data', $result['header']);
<ide> $this->assertStringContainsString("Connection: close\r\n", $result['header']);
<del> $this->assertStringContainsString("User-Agent: CakePHP", $result['header']);
<add> $this->assertStringContainsString('User-Agent: CakePHP', $result['header']);
<ide> $this->assertStringContainsString('name="upload"', $result['content']);
<ide> $this->assertStringContainsString('filename="VERSION.txt"', $result['content']);
<ide> }
<ide><path>tests/TestCase/Http/Cookie/CookieTest.php
<ide> public function invalidNameProvider()
<ide> ["no\rnewline"],
<ide> ["no\nnewline"],
<ide> ["no\ttab"],
<del> ["no,comma"],
<del> ["no;semi"],
<add> ['no,comma'],
<add> ['no;semi'],
<ide> ];
<ide> }
<ide>
<ide><path>tests/TestCase/Http/ServerTest.php
<ide> public function testRunClosesSessionIfServerRequestUsed()
<ide> $this->assertSame(
<ide> 200,
<ide> $res->getStatusCode(),
<del> "Application was expected to be executed"
<add> 'Application was expected to be executed'
<ide> );
<ide> $this->assertSame(
<ide> 'source header',
<ide> $res->getHeaderLine('X-testing'),
<del> "Application was expected to be executed"
<add> 'Application was expected to be executed'
<ide> );
<ide> }
<ide>
<ide> public function testRunDoesNotCloseSessionIfServerRequestNotUsed()
<ide> $this->assertSame(
<ide> 200,
<ide> $res->getStatusCode(),
<del> "Application was expected to be executed"
<add> 'Application was expected to be executed'
<ide> );
<ide> $this->assertSame(
<ide> 'source header',
<ide> $res->getHeaderLine('X-testing'),
<del> "Application was expected to be executed"
<add> 'Application was expected to be executed'
<ide> );
<ide> }
<ide>
<ide><path>tests/TestCase/I18n/Parser/PoFileParserTest.php
<ide> public function testParseContextOnSomeMessages()
<ide> $this->assertSame('En resolved', __('Resolved'));
<ide> $this->assertSame('En resolved - context', __x('Pay status', 'Resolved'));
<ide> $this->assertSame("I've", __x('origin', $key, [1]));
<del> $this->assertSame("We are", __x('origin', $key, [3]));
<add> $this->assertSame('We are', __x('origin', $key, [3]));
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Mailer/Transport/SmtpTransportTest.php
<ide> public function testSendMessageTooBigOnWindows()
<ide> $this->socket->expects($this->at(8))->method('write')->with("DATA\r\n");
<ide> $this->socket->expects($this->at(9))->method('read')->will($this->returnValue("354 OK\r\n"));
<ide> $this->socket->expects($this->at(10))->method('write')->with($this->stringContains('First Line'));
<del> $this->socket->expects($this->at(11))->method('read')->will($this->returnValue("Message size too large"));
<add> $this->socket->expects($this->at(11))->method('read')->will($this->returnValue('Message size too large'));
<ide>
<ide> $this->expectException(SocketException::class);
<ide> $this->expectExceptionMessage('Message size too large');
<ide><path>tests/TestCase/ORM/Behavior/TranslateBehaviorShadowTableTest.php
<ide> public function testFindWithAssociations()
<ide>
<ide> $result = $query->firstOrFail();
<ide>
<del> $this->assertNotNull($result->author, "There should be an author for article 1.");
<add> $this->assertNotNull($result->author, 'There should be an author for article 1.');
<ide> $expected = [
<ide> 'id' => 1,
<ide> 'name' => 'mariano',
<ide> public function testFindWithBTMAssociations()
<ide>
<ide> $result = $query->firstOrFail();
<ide>
<del> $this->assertCount(2, $result->tags, "There should be two translated tags.");
<add> $this->assertCount(2, $result->tags, 'There should be two translated tags.');
<ide>
<ide> $expected = [
<ide> 'id' => 1,
<ide> public function testSaveWithAccessibleFalse()
<ide> $article = $table->get(1);
<ide> $article->translation('xyz')->title = 'XYZ title';
<ide>
<del> $this->assertNotFalse($table->save($article), "The save should succeed");
<add> $this->assertNotFalse($table->save($article), 'The save should succeed');
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/ORM/TableTest.php
<ide> public function testSetSchemaLongIdentifiers()
<ide> $nameLength = $maxAlias - 2;
<ide> $this->expectException(RuntimeException::class);
<ide> $this->expectExceptionMessage(
<del> "ORM queries generate field aliases using the table name/alias and column name. " .
<add> 'ORM queries generate field aliases using the table name/alias and column name. ' .
<ide> "The table alias `very_long_alias_name` and column `this_is_invalid_because_it_is_very_very_very_long` create an alias longer than ({$nameLength}). " .
<del> "You must change the table schema in the database and shorten either the table or column " .
<del> "identifier so they fit within the database alias limits."
<add> 'You must change the table schema in the database and shorten either the table or column ' .
<add> 'identifier so they fit within the database alias limits.'
<ide> );
<ide> }
<ide> $this->assertNotNull($table->setSchema($schema));
<ide><path>tests/TestCase/Routing/Route/RouteTest.php
<ide> public function testMatchWithExplicitGet()
<ide> 'controller' => 'Articles',
<ide> 'action' => 'foo',
<ide> ]);
<del> $this->assertEquals("/anything", $result);
<add> $this->assertEquals('/anything', $result);
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/TestSuite/IntegrationTestTraitTest.php
<ide> public function testExceptionsInMiddlewareJsonView()
<ide>
<ide> $this->configApplication(Configure::read('App.namespace') . '\ApplicationWithExceptionsInMiddleware', null);
<ide>
<del> $this->_request['headers'] = [ "Accept" => "application/json" ];
<add> $this->_request['headers'] = [ 'Accept' => 'application/json' ];
<ide> $this->get('/json_response/api_get_data');
<ide> $this->assertResponseCode(403);
<ide> $this->assertHeader('Content-Type', 'application/json');
<ide><path>tests/TestCase/Utility/XmlTest.php
<ide> public function tearDown(): void
<ide> public function testExceptionChainingForInvalidInput()
<ide> {
<ide> try {
<del> $value = "invalid-xml-input<<";
<add> $value = 'invalid-xml-input<<';
<ide> Xml::build($value);
<ide> $this->fail('This line should not be executed because of exception above.');
<ide> } catch (XmlException $exception) {
<ide><path>tests/TestCase/View/CellTest.php
<ide> public function testCellManualRenderError()
<ide> $this->assertNotNull($e);
<ide> $message = $e->getMessage();
<ide> $this->assertStringContainsString(
<del> str_replace('/', DS, "Cell template file `cell/Articles/foo_bar.php` could not be found."),
<add> str_replace('/', DS, 'Cell template file `cell/Articles/foo_bar.php` could not be found.'),
<ide> $message
<ide> );
<ide> $this->assertStringContainsString('The following paths', $message);
<ide><path>tests/TestCase/View/Helper/HtmlHelperTest.php
<ide> public function testDiv()
<ide> $expected = ['div' => ['class' => 'class-name'], '<text>', '/div'];
<ide> $this->assertHtml($expected, $result);
<ide>
<del> $evilKey = "><script>alert(1)</script>";
<add> $evilKey = '><script>alert(1)</script>';
<ide> $options = [$evilKey => 'some value'];
<ide> $result = $this->Html->div('class-name', '', $options);
<ide> $expected = '<div ><script>alert(1)</script>="some value" class="class-name"></div>';
<ide><path>tests/TestCase/View/StringTemplateTest.php
<ide> public function testFormatAttributes()
<ide> $result
<ide> );
<ide>
<del> $evilKey = "><script>alert(1)</script>";
<add> $evilKey = '><script>alert(1)</script>';
<ide> $attrs = [$evilKey => 'some value'];
<ide>
<ide> $result = $this->template->formatAttributes($attrs);
<ide><path>tests/TestCase/View/ViewTest.php
<ide> public function testGetLayoutFileNameDirectoryTraversal()
<ide> public function testMissingTemplate()
<ide> {
<ide> $this->expectException(\Cake\View\Exception\MissingTemplateException::class);
<del> $this->expectExceptionMessage("Template file `does_not_exist.php` could not be found");
<add> $this->expectExceptionMessage('Template file `does_not_exist.php` could not be found');
<ide> $this->expectExceptionMessage('The following paths were searched');
<ide> $this->expectExceptionMessage('- `' . ROOT . DS . 'templates' . DS . 'does_not_exist.php`');
<ide> $viewOptions = ['plugin' => null,
<ide> public function testMissingTemplate()
<ide> public function testMissingLayout()
<ide> {
<ide> $this->expectException(\Cake\View\Exception\MissingLayoutException::class);
<del> $this->expectExceptionMessage("Layout file `whatever.php` could not be found");
<add> $this->expectExceptionMessage('Layout file `whatever.php` could not be found');
<ide> $this->expectExceptionMessage('The following paths were searched');
<ide> $this->expectExceptionMessage('- `' . ROOT . DS . 'templates' . DS . 'layout' . DS . 'whatever.php`');
<ide> $viewOptions = ['plugin' => null,
<ide> public function testPrefixElement()
<ide> public function testElementMissing()
<ide> {
<ide> $this->expectException(\Cake\View\Exception\MissingElementException::class);
<del> $this->expectExceptionMessage("Element file `non_existent_element.php` could not be found");
<add> $this->expectExceptionMessage('Element file `non_existent_element.php` could not be found');
<ide>
<ide> $this->View->element('non_existent_element');
<ide> }
<ide> public function testElementMissing()
<ide> public function testElementMissingPluginElement()
<ide> {
<ide> $this->expectException(\Cake\View\Exception\MissingElementException::class);
<del> $this->expectExceptionMessage("Element file `TestPlugin.nope.php` could not be found");
<add> $this->expectExceptionMessage('Element file `TestPlugin.nope.php` could not be found');
<ide>
<ide> $this->View->element('TestPlugin.nope');
<ide> }
<ide><path>tests/test_app/TestApp/Middleware/ThrowsExceptionMiddleware.php
<ide> class ThrowsExceptionMiddleware
<ide> {
<ide> public function __invoke($req, $res, $next)
<ide> {
<del> throw new ForbiddenException("Sample Message");
<add> throw new ForbiddenException('Sample Message');
<ide> }
<ide> }
| 44
|
Python
|
Python
|
fix typo in the test case name
|
ff38804195258385dff1ebe339ceddb6fd442f93
|
<ide><path>keras/engine/functional_utils_test.py
<ide>
<ide> class FunctionalModelSlideTest(keras_parameterized.TestCase):
<ide>
<del> def testfind_nodes_by_inputs_and_outputs(self):
<add> def test_find_nodes_by_inputs_and_outputs(self):
<ide> inputs = input_layer_lib.Input((10,))
<ide> unconnected_inputs = input_layer_lib.Input((10,))
<ide> x = layers.Dense(8)(inputs)
<ide> def testfind_nodes_by_inputs_and_outputs(self):
<ide> functional_utils.find_nodes_by_inputs_and_outputs(
<ide> [inputs, unconnected_inputs], output)
<ide>
<del> def testfind_nodes_by_inputs_and_outputs_with_complicated_network(self):
<add> def test_find_nodes_by_inputs_and_outputs_with_complicated_network(self):
<ide> input1 = input_layer_lib.Input((10,))
<ide> input2 = input_layer_lib.Input((10,))
<ide> input3 = input_layer_lib.Input((10,))
| 1
|
Mixed
|
Javascript
|
add null check in readable.from
|
2cd79700c028f99f76f5b124b30009a838019b2b
|
<ide><path>doc/api/stream.md
<ide> added:
<ide> -->
<ide>
<ide> * `iterable` {Iterable} Object implementing the `Symbol.asyncIterator` or
<del> `Symbol.iterator` iterable protocol.
<add> `Symbol.iterator` iterable protocol. Emits an 'error' event if a null
<add> value is passed.
<ide> * `options` {Object} Options provided to `new stream.Readable([options])`.
<ide> By default, `Readable.from()` will set `options.objectMode` to `true`, unless
<ide> this is explicitly opted out by setting `options.objectMode` to `false`.
<ide><path>lib/internal/streams/from.js
<ide> const {
<ide> const { Buffer } = require('buffer');
<ide>
<ide> const {
<del> ERR_INVALID_ARG_TYPE
<add> ERR_INVALID_ARG_TYPE,
<add> ERR_STREAM_NULL_VALUES
<ide> } = require('internal/errors').codes;
<ide>
<ide> function from(Readable, iterable, opts) {
<ide> function from(Readable, iterable, opts) {
<ide> needToClose = false;
<ide> const { value, done } = await iterator.next();
<ide> needToClose = !done;
<del> const resolved = await value;
<ide> if (done) {
<ide> readable.push(null);
<ide> } else if (readable.destroyed) {
<ide> await close();
<del> } else if (readable.push(resolved)) {
<del> next();
<ide> } else {
<del> reading = false;
<add> const res = await value;
<add> if (res === null) {
<add> reading = false;
<add> throw new ERR_STREAM_NULL_VALUES();
<add> } else if (readable.push(res)) {
<add> next();
<add> } else {
<add> reading = false;
<add> }
<ide> }
<ide> } catch (err) {
<ide> readable.destroy(err);
<ide><path>test/parallel/test-readable-from-iterator-closing.js
<ide> async function closeAfterNullYielded() {
<ide> const finallyMustCall = mustCall();
<ide> const dataMustCall = mustCall(3);
<ide>
<del> function* infiniteGenerate() {
<add> function* generate() {
<ide> try {
<ide> yield 'a';
<ide> yield 'a';
<ide> yield 'a';
<del> while (true) yield null;
<ide> } finally {
<ide> finallyMustCall();
<ide> }
<ide> }
<ide>
<del> const stream = Readable.from(infiniteGenerate());
<add> const stream = Readable.from(generate());
<ide>
<ide> stream.on('data', (chunk) => {
<ide> dataMustCall();
<ide><path>test/parallel/test-stream-readable-next-no-null.js
<add>'use strict';
<add>const { mustNotCall, expectsError } = require('../common');
<add>const { Readable } = require('stream');
<add>
<add>async function* generate() {
<add> yield null;
<add>}
<add>
<add>const stream = Readable.from(generate());
<add>
<add>stream.on('error', expectsError({
<add> code: 'ERR_STREAM_NULL_VALUES',
<add> name: 'TypeError',
<add> message: 'May not write null values to stream'
<add>}));
<add>
<add>stream.on('data', mustNotCall((chunk) => {}));
<add>
<add>stream.on('end', mustNotCall());
| 4
|
Javascript
|
Javascript
|
fix some warnings/errors
|
ec565ddd9c536aa7f7441e89f03ea08e23de1a42
|
<ide><path>docs/app/src/search.js
<ide> angular.module('search', [])
<ide> }
<ide>
<ide> // Create the lunr index
<del> var index = lunr(/* @this */ function() {
<add> var index = lunr(/** @this */ function() {
<ide> this.ref('path');
<ide> this.field('titleWords', {boost: 50});
<ide> this.field('members', { boost: 40});
<ide><path>docs/config/index.js
<ide> module.exports = new Package('angularjs', [
<ide> parseTagsProcessor.tagDefinitions.push(require('./tag-defs/tutorial-step'));
<ide> parseTagsProcessor.tagDefinitions.push(require('./tag-defs/sortOrder'));
<ide> parseTagsProcessor.tagDefinitions.push(require('./tag-defs/installation'));
<add> parseTagsProcessor.tagDefinitions.push(require('./tag-defs/this'));
<ide> })
<ide>
<ide>
<ide><path>docs/config/tag-defs/this.js
<add>'use strict';
<add>
<add>module.exports = {
<add> name: 'this'
<add>};
<ide><path>docs/gulpfile.js
<ide> var getMergedEslintConfig = function(filepath) {
<ide> strict: 'off',
<ide> // Generated examples may miss the final EOL; ignore that.
<ide> 'eol-last': 'off',
<add> // Generated files use the system's default linebreak style (e.g. CRLF on Windows)
<add> 'linebreak-style': 'off',
<ide> // While alerts would be bad to have in the library or test code,
<ide> // they're perfectly fine in examples.
<ide> 'no-alert': 'off',
<ide><path>src/apis.js
<ide> HashMap.prototype = {
<ide> }
<ide> };
<ide>
<del>var $$HashMapProvider = [/* @this */function() {
<add>var $$HashMapProvider = [/** @this */function() {
<ide> this.$get = [function() {
<ide> return HashMap;
<ide> }];
<ide><path>src/auto/injector.js
<ide> function createInjector(modulesToLoad, strictDi) {
<ide> }
<ide>
<ide> function enforceReturnValue(name, factory) {
<del> return /* @this */ function enforcedReturnValue() {
<add> return /** @this */ function enforcedReturnValue() {
<ide> var result = instanceInjector.invoke(factory, this);
<ide> if (isUndefined(result)) {
<ide> throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
<ide><path>src/jqLite.js
<ide> function jqLiteWrapNode(node, wrapper) {
<ide>
<ide>
<ide> // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
<del>var jqLiteContains = window.Node.prototype.contains || /* @this */ function(arg) {
<add>var jqLiteContains = window.Node.prototype.contains || /** @this */ function(arg) {
<ide> // eslint-disable-next-line no-bitwise
<ide> return !!(this.compareDocumentPosition(arg) & 16);
<ide> };
<ide> forEach({
<ide>
<ide>
<ide> // Provider for private $$jqLite service
<del>/* @this */
<add>/** @this */
<ide> function $$jqLiteProvider() {
<ide> this.$get = function $$jqLite() {
<ide> return extend(JQLite, {
<ide><path>src/ng/animate.js
<ide> function prepareAnimateOptions(options) {
<ide> : {};
<ide> }
<ide>
<del>var $$CoreAnimateJsProvider = /* @this */ function() {
<add>var $$CoreAnimateJsProvider = /** @this */ function() {
<ide> this.$get = noop;
<ide> };
<ide>
<ide> // this is prefixed with Core since it conflicts with
<ide> // the animateQueueProvider defined in ngAnimate/animateQueue.js
<del>var $$CoreAnimateQueueProvider = /* @this */ function() {
<add>var $$CoreAnimateQueueProvider = /** @this */ function() {
<ide> var postDigestQueue = new HashMap();
<ide> var postDigestElements = [];
<ide>
<ide> var $$CoreAnimateQueueProvider = /* @this */ function() {
<ide> *
<ide> * To see the functional implementation check out `src/ngAnimate/animate.js`.
<ide> */
<del>var $AnimateProvider = ['$provide', /* @this */ function($provide) {
<add>var $AnimateProvider = ['$provide', /** @this */ function($provide) {
<ide> var provider = this;
<ide>
<ide> this.$$registeredAnimations = Object.create(null);
<ide><path>src/ng/animateRunner.js
<ide> 'use strict';
<ide>
<del>var $$AnimateAsyncRunFactoryProvider = /* @this */ function() {
<add>var $$AnimateAsyncRunFactoryProvider = /** @this */ function() {
<ide> this.$get = ['$$rAF', function($$rAF) {
<ide> var waitQueue = [];
<ide>
<ide> var $$AnimateAsyncRunFactoryProvider = /* @this */ function() {
<ide> }];
<ide> };
<ide>
<del>var $$AnimateRunnerFactoryProvider = /* @this */ function() {
<add>var $$AnimateRunnerFactoryProvider = /** @this */ function() {
<ide> this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$$isDocumentHidden', '$timeout',
<ide> function($q, $sniffer, $$animateAsyncRun, $$isDocumentHidden, $timeout) {
<ide>
<ide><path>src/ng/browser.js
<ide> function Browser(window, document, $log, $sniffer) {
<ide>
<ide> }
<ide>
<del>/* @this */
<add>/** @this */
<ide> function $BrowserProvider() {
<ide> this.$get = ['$window', '$log', '$sniffer', '$document',
<ide> function($window, $log, $sniffer, $document) {
<ide><path>src/ng/compile.js
<ide> var _UNINITIALIZED_VALUE = new UNINITIALIZED_VALUE();
<ide> * @description
<ide> */
<ide> $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
<del>/* @this */
<add>/** @this */
<ide> function $CompileProvider($provide, $$sanitizeUriProvider) {
<ide> var hasDirectives = {},
<ide> Suffix = 'Directive',
<ide> function $CompileProvider($provide, $$sanitizeUriProvider) {
<ide> function factory($injector) {
<ide> function makeInjectable(fn) {
<ide> if (isFunction(fn) || isArray(fn)) {
<del> return /* @this */ function(tElement, tAttrs) {
<add> return /** @this */ function(tElement, tAttrs) {
<ide> return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});
<ide> };
<ide> } else {
<ide> function $CompileProvider($provide, $$sanitizeUriProvider) {
<ide> if (eager) {
<ide> return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
<ide> }
<del> return /* @this */ function lazyCompilation() {
<add> return /** @this */ function lazyCompilation() {
<ide> if (!compiled) {
<ide> compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
<ide>
<ide><path>src/ng/cookieReader.js
<ide> function $$CookieReader($document) {
<ide>
<ide> $$CookieReader.$inject = ['$document'];
<ide>
<del>/* @this */
<add>/** @this */
<ide> function $$CookieReaderProvider() {
<ide> this.$get = $$CookieReader;
<ide> }
<ide><path>src/ng/directive/input.js
<ide> function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
<ide> }
<ide> };
<ide>
<del> element.on('keydown', /* @this */ function(event) {
<add> element.on('keydown', /** @this */ function(event) {
<ide> var key = event.keyCode;
<ide>
<ide> // ignore
<ide> function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
<ide> // For these event types, when native validators are present and the browser supports the type,
<ide> // check for validity changes on various DOM events.
<ide> if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) {
<del> element.on(PARTIAL_VALIDATION_EVENTS, /* @this */ function(ev) {
<add> element.on(PARTIAL_VALIDATION_EVENTS, /** @this */ function(ev) {
<ide> if (!timeout) {
<ide> var validity = this[VALIDITY_STATE_PROPERTY];
<ide> var origBadInput = validity.badInput;
<ide><path>src/ng/directive/ngModel.js
<ide> is set to `true`. The parse error is stored in `ngModel.$error.parse`.
<ide> *
<ide> */
<ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
<del> /* @this */ function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
<add> /** @this */ function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
<ide> this.$viewValue = Number.NaN;
<ide> this.$modelValue = Number.NaN;
<ide> this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
<ide><path>src/ng/directive/select.js
<ide> var noopNgModelController = { $setViewValue: noop, $render: noop };
<ide> * added `<option>` elements, perhaps by an `ngRepeat` directive.
<ide> */
<ide> var SelectController =
<del> ['$element', '$scope', /* @this */ function($element, $scope) {
<add> ['$element', '$scope', /** @this */ function($element, $scope) {
<ide>
<ide> var self = this,
<ide> optionsMap = new HashMap();
<ide><path>src/ng/filter.js
<ide> </example>
<ide> */
<ide> $FilterProvider.$inject = ['$provide'];
<del>/* @this */
<add>/** @this */
<ide> function $FilterProvider($provide) {
<ide> var suffix = 'Filter';
<ide>
<ide><path>src/ng/forceReflow.js
<ide> 'use strict';
<ide>
<del>var $$ForceReflowProvider = /* @this */ function() {
<add>var $$ForceReflowProvider = /** @this */ function() {
<ide> this.$get = ['$document', function($document) {
<ide> return function(domNode) {
<ide> //the line below will force the browser to perform a repaint so
<ide><path>src/ng/http.js
<ide> function serializeValue(v) {
<ide> }
<ide>
<ide>
<del>/* @this */
<add>/** @this */
<ide> function $HttpParamSerializerProvider() {
<ide> /**
<ide> * @ngdoc service
<ide> function $HttpParamSerializerProvider() {
<ide> };
<ide> }
<ide>
<del>/* @this */
<add>/** @this */
<ide> function $HttpParamSerializerJQLikeProvider() {
<ide> /**
<ide> * @ngdoc service
<ide><path>src/ng/interpolate.js
<ide> function $InterpolateProvider() {
<ide> expressions: expressions,
<ide> $$watchDelegate: function(scope, listener) {
<ide> var lastValue;
<del> return scope.$watchGroup(parseFns, /* @this */ function interpolateFnWatcher(values, oldValues) {
<add> return scope.$watchGroup(parseFns, /** @this */ function interpolateFnWatcher(values, oldValues) {
<ide> var currValue = compute(values);
<ide> if (isFunction(listener)) {
<ide> listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
<ide><path>src/ng/interval.js
<ide> 'use strict';
<ide>
<del>/* @this */
<add>/** @this */
<ide> function $IntervalProvider() {
<ide> this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser',
<ide> function($rootScope, $window, $q, $$q, $browser) {
<ide><path>src/ng/jsonpCallbacks.js
<ide> * Override this service if you wish to customise where the callbacks are stored and
<ide> * how they vary compared to the requested url.
<ide> */
<del>var $jsonpCallbacksProvider = /* @this */ function() {
<add>var $jsonpCallbacksProvider = /** @this */ function() {
<ide> this.$get = ['$window', function($window) {
<ide> var callbacks = $window.angular.callbacks;
<ide> var callbackMap = {};
<ide><path>src/ng/location.js
<ide> forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], fun
<ide>
<ide>
<ide> function locationGetter(property) {
<del> return /* @this */ function() {
<add> return /** @this */ function() {
<ide> return this[property];
<ide> };
<ide> }
<ide>
<ide>
<ide> function locationGetterSetter(property, preprocess) {
<del> return /* @this */ function(value) {
<add> return /** @this */ function(value) {
<ide> if (isUndefined(value)) {
<ide> return this[property];
<ide> }
<ide><path>src/ng/q.js
<ide> function $QProvider() {
<ide> };
<ide> }
<ide>
<del>/* @this */
<add>/** @this */
<ide> function $$QProvider() {
<ide> var errorOnUnhandledRejections = true;
<ide> this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
<ide><path>src/ng/raf.js
<ide> 'use strict';
<ide>
<del>/* @this */
<add>/** @this */
<ide> function $$RAFProvider() { //rAF
<ide> this.$get = ['$window', '$timeout', function($window, $timeout) {
<ide> var requestAnimationFrame = $window.requestAnimationFrame ||
<ide><path>src/ng/testability.js
<ide> 'use strict';
<ide>
<del>/* @this */
<add>/** @this */
<ide> function $$TestabilityProvider() {
<ide> this.$get = ['$rootScope', '$browser', '$location',
<ide> function($rootScope, $browser, $location) {
<ide><path>src/ng/timeout.js
<ide> 'use strict';
<ide>
<del>/* @this */
<add>/** @this */
<ide> function $TimeoutProvider() {
<ide> this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
<ide> function($rootScope, $browser, $q, $$q, $exceptionHandler) {
<ide><path>src/ngAnimate/animateCss.js
<ide> function registerRestorableStyles(backup, node, properties) {
<ide> });
<ide> }
<ide>
<del>var $AnimateCssProvider = ['$animateProvider', /* @this */ function($animateProvider) {
<add>var $AnimateCssProvider = ['$animateProvider', /** @this */ function($animateProvider) {
<ide> var gcsLookup = createLocalCacheLookup();
<ide> var gcsStaggerLookup = createLocalCacheLookup();
<ide>
<ide><path>src/ngAnimate/animateCssDriver.js
<ide> 'use strict';
<ide>
<del>var $$AnimateCssDriverProvider = ['$$animationProvider', /* @this */ function($$animationProvider) {
<add>var $$AnimateCssDriverProvider = ['$$animationProvider', /** @this */ function($$animationProvider) {
<ide> $$animationProvider.drivers.push('$$animateCssDriver');
<ide>
<ide> var NG_ANIMATE_SHIM_CLASS_NAME = 'ng-animate-shim';
<ide><path>src/ngAnimate/animateJs.js
<ide> // TODO(matsko): add documentation
<ide> // by the time...
<ide>
<del>var $$AnimateJsProvider = ['$animateProvider', /* @this */ function($animateProvider) {
<add>var $$AnimateJsProvider = ['$animateProvider', /** @this */ function($animateProvider) {
<ide> this.$get = ['$injector', '$$AnimateRunner', '$$jqLite',
<ide> function($injector, $$AnimateRunner, $$jqLite) {
<ide>
<ide><path>src/ngAnimate/animateJsDriver.js
<ide> 'use strict';
<ide>
<del>var $$AnimateJsDriverProvider = ['$$animationProvider', /* @this */ function($$animationProvider) {
<add>var $$AnimateJsDriverProvider = ['$$animationProvider', /** @this */ function($$animationProvider) {
<ide> $$animationProvider.drivers.push('$$animateJsDriver');
<ide> this.$get = ['$$animateJs', '$$AnimateRunner', function($$animateJs, $$AnimateRunner) {
<ide> return function initDriverFn(animationDetails) {
<ide><path>src/ngAnimate/animateQueue.js
<ide>
<ide> var NG_ANIMATE_ATTR_NAME = 'data-ng-animate';
<ide> var NG_ANIMATE_PIN_DATA = '$ngAnimatePin';
<del>var $$AnimateQueueProvider = ['$animateProvider', /* @this */ function($animateProvider) {
<add>var $$AnimateQueueProvider = ['$animateProvider', /** @this */ function($animateProvider) {
<ide> var PRE_DIGEST_STATE = 1;
<ide> var RUNNING_STATE = 2;
<ide> var ONE_SPACE = ' ';
<ide> var $$AnimateQueueProvider = ['$animateProvider', /* @this */ function($animateP
<ide> }
<ide>
<ide> // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
<del> var contains = window.Node.prototype.contains || /* @this */ function(arg) {
<add> var contains = window.Node.prototype.contains || /** @this */ function(arg) {
<ide> // eslint-disable-next-line no-bitwise
<ide> return this === arg || !!(this.compareDocumentPosition(arg) & 16);
<ide> };
<ide><path>src/ngAnimate/animation.js
<ide>
<ide> /* exported $$AnimationProvider */
<ide>
<del>var $$AnimationProvider = ['$animateProvider', /* @this */ function($animateProvider) {
<add>var $$AnimationProvider = ['$animateProvider', /** @this */ function($animateProvider) {
<ide> var NG_ANIMATE_REF_ATTR = 'ng-animate-ref';
<ide>
<ide> var drivers = this.drivers = [];
<ide><path>src/ngCookies/cookieWriter.js
<ide> function $$CookieWriter($document, $log, $browser) {
<ide>
<ide> $$CookieWriter.$inject = ['$document', '$log', '$browser'];
<ide>
<del>angular.module('ngCookies').provider('$$cookieWriter', /* @this */ function $$CookieWriterProvider() {
<add>angular.module('ngCookies').provider('$$cookieWriter', /** @this */ function $$CookieWriterProvider() {
<ide> this.$get = $$CookieWriter;
<ide> });
<ide><path>src/ngCookies/cookies.js
<ide> angular.module('ngCookies', ['ng']).
<ide> * @description
<ide> * Use `$cookiesProvider` to change the default behavior of the {@link ngCookies.$cookies $cookies} service.
<ide> * */
<del> provider('$cookies', [/* @this */function $CookiesProvider() {
<add> provider('$cookies', [/** @this */function $CookiesProvider() {
<ide> /**
<ide> * @ngdoc property
<ide> * @name $cookiesProvider#defaults
<ide><path>src/ngMock/angular-mocks.js
<ide> angular.mock.$RootScopeDecorator = ['$delegate', function($delegate) {
<ide>
<ide> var initialized = false;
<ide>
<del> module.$$beforeAllHook(/* @this */ function() {
<add> module.$$beforeAllHook(/** @this */ function() {
<ide> if (injectorState.shared) {
<ide> injectorState.sharedError = Error("sharedInjector() cannot be called inside a context that has already called sharedInjector()");
<ide> throw injectorState.sharedError;
<ide><path>src/ngScenario/Describe.js
<ide> angular.scenario.Describe = function(descName, parent) {
<ide> var beforeEachFns = this.beforeEachFns;
<ide> this.setupBefore = function() {
<ide> if (parent) parent.setupBefore.call(this);
<del> angular.forEach(beforeEachFns, /* @this */ function(fn) { fn.call(this); }, this);
<add> angular.forEach(beforeEachFns, /** @this */ function(fn) { fn.call(this); }, this);
<ide> };
<ide>
<ide> /**
<ide> * Calls all after functions.
<ide> */
<ide> var afterEachFns = this.afterEachFns;
<ide> this.setupAfter = function() {
<del> angular.forEach(afterEachFns, /* @this */ function(fn) { fn.call(this); }, this);
<add> angular.forEach(afterEachFns, /** @this */ function(fn) { fn.call(this); }, this);
<ide> if (parent) parent.setupAfter.call(this);
<ide> };
<ide> };
<ide><path>src/ngScenario/Runner.js
<ide> angular.scenario.Runner = function($window) {
<ide> beforeEach: this.beforeEach,
<ide> afterEach: this.afterEach
<ide> };
<del> angular.forEach(this.api, angular.bind(this, /* @this */ function(fn, key) {
<add> angular.forEach(this.api, angular.bind(this, /** @this */ function(fn, key) {
<ide> this.$window[key] = angular.bind(this, fn);
<ide> }));
<ide> };
<ide> angular.scenario.Runner.prototype.on = function(eventName, listener) {
<ide> */
<ide> angular.scenario.Runner.prototype.describe = function(name, body) {
<ide> var self = this;
<del> this.currentDescribe.describe(name, /* @this */ function() {
<add> this.currentDescribe.describe(name, /** @this */ function() {
<ide> var parentDescribe = self.currentDescribe;
<ide> self.currentDescribe = this;
<ide> try {
<ide> angular.scenario.Runner.prototype.describe = function(name, body) {
<ide> */
<ide> angular.scenario.Runner.prototype.ddescribe = function(name, body) {
<ide> var self = this;
<del> this.currentDescribe.ddescribe(name, /* @this */ function() {
<add> this.currentDescribe.ddescribe(name, /** @this */ function() {
<ide> var parentDescribe = self.currentDescribe;
<ide> self.currentDescribe = this;
<ide> try {
<ide> angular.scenario.Runner.prototype.run = function(application) {
<ide> return scope.dsl[key].apply(scope, arguments);
<ide> };
<ide> });
<del> runner.run(spec, /* @this */ function() {
<add> runner.run(spec, /** @this */ function() {
<ide> runner.$destroy();
<ide> specDone.apply(this, arguments);
<ide> });
<ide><path>src/ngScenario/Scenario.js
<ide> angular.scenario.output = angular.scenario.output || function(name, fn) {
<ide> angular.scenario.dsl = angular.scenario.dsl || function(name, fn) {
<ide> angular.scenario.dsl[name] = function() {
<ide> // The dsl binds `this` for us when calling chained functions
<del> /* @this */
<add> /** @this */
<ide> function executeStatement(statement, args) {
<ide> var result = statement.apply(this, args);
<ide> if (angular.isFunction(result) || result instanceof angular.scenario.Future) {
<ide> angular.scenario.dsl = angular.scenario.dsl || function(name, fn) {
<ide> return chain;
<ide> }
<ide> var statement = fn.apply(this, arguments);
<del> return /* @this */ function() {
<add> return /** @this */ function() {
<ide> return executeStatement.call(this, statement, arguments);
<ide> };
<ide> };
<ide><path>src/ngScenario/SpecRunner.js
<ide> angular.scenario.SpecRunner.prototype.addFuture = function(name, behavior, line)
<ide> angular.scenario.SpecRunner.prototype.addFutureAction = function(name, behavior, line) {
<ide> var self = this;
<ide> var NG = /\[ng\\:/;
<del> return this.addFuture(name, /* @this */ function(done) {
<add> return this.addFuture(name, /** @this */ function(done) {
<ide> this.application.executeAction(function($window, $document) {
<ide>
<ide> //TODO(esprehn): Refactor this so it doesn't need to be in here.
<ide><path>src/ngScenario/matchers.js
<ide> * Matchers for implementing specs. Follows the Jasmine spec conventions.
<ide> */
<ide>
<del>angular.scenario.matcher('toEqual', /* @this */ function(expected) {
<add>angular.scenario.matcher('toEqual', /** @this */ function(expected) {
<ide> return angular.equals(this.actual, expected);
<ide> });
<ide>
<del>angular.scenario.matcher('toBe', /* @this */ function(expected) {
<add>angular.scenario.matcher('toBe', /** @this */ function(expected) {
<ide> return this.actual === expected;
<ide> });
<ide>
<del>angular.scenario.matcher('toBeDefined', /* @this */ function() {
<add>angular.scenario.matcher('toBeDefined', /** @this */ function() {
<ide> return angular.isDefined(this.actual);
<ide> });
<ide>
<del>angular.scenario.matcher('toBeTruthy', /* @this */ function() {
<add>angular.scenario.matcher('toBeTruthy', /** @this */ function() {
<ide> return this.actual;
<ide> });
<ide>
<del>angular.scenario.matcher('toBeFalsy', /* @this */ function() {
<add>angular.scenario.matcher('toBeFalsy', /** @this */ function() {
<ide> return !this.actual;
<ide> });
<ide>
<del>angular.scenario.matcher('toMatch', /* @this */ function(expected) {
<add>angular.scenario.matcher('toMatch', /** @this */ function(expected) {
<ide> return new RegExp(expected).test(this.actual);
<ide> });
<ide>
<del>angular.scenario.matcher('toBeNull', /* @this */ function() {
<add>angular.scenario.matcher('toBeNull', /** @this */ function() {
<ide> return this.actual === null;
<ide> });
<ide>
<del>angular.scenario.matcher('toContain', /* @this */ function(expected) {
<add>angular.scenario.matcher('toContain', /** @this */ function(expected) {
<ide> return includes(this.actual, expected);
<ide> });
<ide>
<del>angular.scenario.matcher('toBeLessThan', /* @this */ function(expected) {
<add>angular.scenario.matcher('toBeLessThan', /** @this */ function(expected) {
<ide> return this.actual < expected;
<ide> });
<ide>
<del>angular.scenario.matcher('toBeGreaterThan', /* @this */ function(expected) {
<add>angular.scenario.matcher('toBeGreaterThan', /** @this */ function(expected) {
<ide> return this.actual > expected;
<ide> });
| 40
|
Text
|
Text
|
fix stateful rnns faq link
|
70ffba0766b5671fa9f2d08aa5a19fa24021bd3f
|
<ide><path>docs/templates/getting-started/sequential-model-guide.md
<ide> A stateful recurrent model is one for which the internal states (memories) obtai
<ide> of samples are reused as initial states for the samples of the next batch. This allows to process longer sequences
<ide> while keeping computational complexity manageable.
<ide>
<del>[You can read more about stateful RNNs in the FAQ.](/faq/#how-can-i-use-stateful-rnns)
<add>[You can read more about stateful RNNs in the FAQ.](/getting-started/faq/#how-can-i-use-stateful-rnns)
<ide>
<ide> ```python
<ide> from keras.models import Sequential
| 1
|
Text
|
Text
|
modify the text
|
dd5e85779722d4042b494559d1859e966709e660
|
<ide><path>guide/english/mathematics/algebra/intro-to-rationalizing-the-denominator/index.md
<ide> title: Intro to Rationalizing the Denominator
<ide> ---
<ide> ## Intro to Rationalizing the Denominator
<ide>
<del>If you can't express the denominator of a fraction in the form of a/b, where a and b are integers, then the denominator is irrational. To simplify the fraction we should rationalize the denominator. Rationalizing the denominator can aid you in solving certain equations. There are a couple ways to do this.
<add>If a number couldn't be expressed in p/q form where p,q are real numbers and q in non-zero, the number is said to be an irrational number .To simplify the fraction we should rationalize the denominator. Rationalizing the denominator can aid you to simplify certain equations. This could be done by the following listed methods -
<ide>
<ide> ### Multiplying by a Root
<ide> We can multiply the top and bottom by a root. Notice that we are multiplying the fraction by root 2 divided by itself which is just another way or writing 1.
| 1
|
Python
|
Python
|
fix undefined names
|
b7f9cbdc834fdde3f7c2ebf93698d3918faa8929
|
<ide><path>spacy/lang/ga/irish_morphology_helpers.py
<ide> # coding: utf8
<ide> from __future__ import unicode_literals
<ide>
<del>class IrishMorph:
<del> consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z']
<del> broad_vowels = ['a', 'á', 'o', 'ó', 'u', 'ú']
<del> slender_vowels = ['e', 'é', 'i', 'í']
<del> vowels = broad_vowels + slender_vowels
<add>consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z']
<add>broad_vowels = ['a', 'á', 'o', 'ó', 'u', 'ú']
<add>slender_vowels = ['e', 'é', 'i', 'í']
<add>vowels = broad_vowels + slender_vowels
<ide>
<del> def ends_dentals(word):
<del> if word != "" and word[-1] in ['d', 'n', 't', 's']:
<del> return True
<del> else:
<del> return False
<add>def ends_dentals(word):
<add> if word != "" and word[-1] in ['d', 'n', 't', 's']:
<add> return True
<add> else:
<add> return False
<ide>
<del> def devoice(word):
<del> if len(word) > 2 and word[-2] == 's' and word[-1] == 'd':
<del> return word[:-1] + 't'
<del> else:
<del> return word
<add>def devoice(word):
<add> if len(word) > 2 and word[-2] == 's' and word[-1] == 'd':
<add> return word[:-1] + 't'
<add> else:
<add> return word
<ide>
<del> def ends_with_vowel(word):
<del> return word != "" and word[-1] in vowels
<add>def ends_with_vowel(word):
<add> return word != "" and word[-1] in vowels
<ide>
<del> def starts_with_vowel(word):
<del> return word != "" and word[0] in vowels
<del>
<del> def deduplicate(word):
<del> if len(word) > 2 and word[-2] == word[-1] and word[-1] in consonants:
<del> return word[:-1]
<del> else:
<del> return word
<add>def starts_with_vowel(word):
<add> return word != "" and word[0] in vowels
<ide>
<add>def deduplicate(word):
<add> if len(word) > 2 and word[-2] == word[-1] and word[-1] in consonants:
<add> return word[:-1]
<add> else:
<add> return word
| 1
|
Ruby
|
Ruby
|
fix unstated usage of pathname
|
812136a0b23787aa0e81c28d0bbc71a9ccf0f6ea
|
<ide><path>railties/lib/rails/engine.rb
<del>require 'active_support/core_ext/module/delegation'
<ide> require 'rails/railtie'
<add>require 'active_support/core_ext/module/delegation'
<add>require 'pathname'
<ide>
<ide> module Rails
<ide> class Engine < Railtie
| 1
|
Javascript
|
Javascript
|
add tests for oneoftype with shape
|
f88936977fadaf41050af22b0a6115479021e711
|
<ide><path>src/core/__tests__/ReactPropTypes-test.js
<ide> describe('Union Types', function() {
<ide> [],
<ide> 'Invalid prop `testProp` supplied to `testComponent`.'
<ide> );
<add>
<add> var checker = PropTypes.oneOfType([
<add> PropTypes.shape({a: PropTypes.number.isRequired}),
<add> PropTypes.shape({b: PropTypes.number.isRequired})
<add> ]);
<add> typeCheckFail(
<add> checker,
<add> {c: 1},
<add> 'Invalid prop `testProp` supplied to `testComponent`.'
<add> );
<ide> });
<ide>
<ide> it('should not warn if one of the types are valid', function() {
<ide> describe('Union Types', function() {
<ide> typeCheckPass(checker, null);
<ide> typeCheckPass(checker, 'foo');
<ide> typeCheckPass(checker, 123);
<add>
<add> checker = PropTypes.oneOfType([
<add> PropTypes.shape({a: PropTypes.number.isRequired}),
<add> PropTypes.shape({b: PropTypes.number.isRequired})
<add> ]);
<add> typeCheckPass(checker, {a: 1});
<add> typeCheckPass(checker, {b: 1});
<ide> });
<ide>
<ide> it("should be implicitly optional and not warn without values", function() {
<ide> describe('Shape Types', function() {
<ide> );
<ide> });
<ide>
<add> it("should warn for the first required type", function() {
<add> typeCheckFail(
<add> PropTypes.shape({
<add> key: PropTypes.number.isRequired,
<add> secondKey: PropTypes.number.isRequired
<add> }),
<add> {},
<add> 'Required prop `key` was not specified in `testComponent`.'
<add> );
<add> });
<add>
<ide> it("should warn for invalid key types", function() {
<ide> typeCheckFail(PropTypes.shape({key: PropTypes.number}),
<ide> {key: 'abc'},
| 1
|
Javascript
|
Javascript
|
add new accesstoken utils
|
2f944b3aed45e92dee2b2c34a77061528a7be1a9
|
<ide><path>api-server/server/utils/getSetAccessToken.js
<add>import jwt from 'jsonwebtoken';
<add>import { isBefore } from 'date-fns';
<add>
<add>import { jwtSecret as _jwtSecret } from '../../../config/secrets';
<add>
<add>export const authHeaderNS = 'X-fcc-access-token';
<add>export const jwtCookieNS = 'jwt_access_token';
<add>
<add>export function createCookieConfig(req) {
<add> return {
<add> signed: !!req.signedCookies,
<add> domain: process.env.COOKIE_DOMAIN || 'localhost'
<add> };
<add>}
<add>
<add>export function setAccessTokenToResponse(
<add> { accessToken },
<add> req,
<add> res,
<add> jwtSecret = _jwtSecret
<add>) {
<add> const cookieConfig = {
<add> ...createCookieConfig(req),
<add> maxAge: accessToken.ttl || 77760000000
<add> };
<add> const jwtAccess = jwt.sign({ accessToken }, jwtSecret);
<add> res.cookie(jwtCookieNS, jwtAccess, cookieConfig);
<add> res.cookie('access_token', accessToken.id, cookieConfig);
<add> res.cookie('userId', accessToken.userId, cookieConfig);
<add> return;
<add>}
<add>
<add>export function getAccessTokenFromRequest(req, jwtSecret = _jwtSecret) {
<add> const maybeToken =
<add> (req.headers && req.headers[authHeaderNS]) ||
<add> (req.signedCookies && req.signedCookies[jwtCookieNS]) ||
<add> (req.cookie && req.cookie[jwtCookieNS]);
<add> if (!maybeToken) {
<add> return {
<add> accessToken: null,
<add> error: errorTypes.noTokenFound
<add> };
<add> }
<add> let token;
<add> try {
<add> token = jwt.verify(maybeToken, jwtSecret);
<add> } catch (err) {
<add> return { accessToken: null, error: errorTypes.invalidToken };
<add> }
<add>
<add> const { accessToken } = token;
<add> const { created, ttl } = accessToken;
<add> const valid = isBefore(Date.now(), Date.parse(created) + ttl);
<add> if (!valid) {
<add> return {
<add> accessToken: null,
<add> error: errorTypes.expiredToken
<add> };
<add> }
<add> return { accessToken, error: '', jwt: maybeToken };
<add>}
<add>
<add>export function removeCookies(req, res) {
<add> const config = createCookieConfig(req);
<add> res.clearCookie(jwtCookieNS, config);
<add> res.clearCookie('access_token', config);
<add> res.clearCookie('userId', config);
<add> res.clearCookie('_csrf', config);
<add> return;
<add>}
<add>
<add>export const errorTypes = {
<add> noTokenFound: 'No token found',
<add> invalidToken: 'Invalid token',
<add> expiredToken: 'Token timed out'
<add>};
<ide><path>api-server/server/utils/getSetAccessToken.test.js
<add>/* global describe it expect */
<add>import {
<add> getAccessTokenFromRequest,
<add> errorTypes,
<add> setAccessTokenToResponse,
<add> removeCookies
<add>} from './getSetAccessToken';
<add>import { mockReq, mockRes } from 'sinon-express-mock';
<add>import jwt from 'jsonwebtoken';
<add>
<add>describe('getSetAccessToken', () => {
<add> const validJWTSecret = 'this is a super secret string';
<add> const invalidJWTSecret = 'This is not correct secret';
<add> const now = new Date(Date.now());
<add> const theBeginningOfTime = new Date(0);
<add> const accessToken = {
<add> id: '123abc',
<add> userId: '456def',
<add> ttl: 60000,
<add> created: now
<add> };
<add>
<add> describe('getAccessTokenFromRequest', () => {
<add> it('return `no token` error if no token is found', () => {
<add> const req = mockReq({ headers: {}, cookie: {} });
<add> const result = getAccessTokenFromRequest(req, validJWTSecret);
<add> expect(result.error).toEqual(errorTypes.noTokenFound);
<add> });
<add>
<add> describe('cookies', () => {
<add> it('returns `invalid token` error for malformed tokens', () => {
<add> const invalidJWT = jwt.sign({ accessToken }, invalidJWTSecret);
<add> // eslint-disable-next-line camelcase
<add> const req = mockReq({ cookie: { jwt_access_token: invalidJWT } });
<add> const result = getAccessTokenFromRequest(req, validJWTSecret);
<add>
<add> expect(result.error).toEqual(errorTypes.invalidToken);
<add> });
<add>
<add> it('returns `expired token` error for expired tokens', () => {
<add> const invalidJWT = jwt.sign(
<add> { accessToken: { ...accessToken, created: theBeginningOfTime } },
<add> validJWTSecret
<add> );
<add> // eslint-disable-next-line camelcase
<add> const req = mockReq({ cookie: { jwt_access_token: invalidJWT } });
<add> const result = getAccessTokenFromRequest(req, validJWTSecret);
<add>
<add> expect(result.error).toEqual(errorTypes.expiredToken);
<add> });
<add>
<add> it('returns a valid access token with no errors ', () => {
<add> expect.assertions(2);
<add> const validJWT = jwt.sign({ accessToken }, validJWTSecret);
<add> // eslint-disable-next-line camelcase
<add> const req = mockReq({ cookie: { jwt_access_token: validJWT } });
<add> const result = getAccessTokenFromRequest(req, validJWTSecret);
<add>
<add> expect(result.error).toBeFalsy();
<add> expect(result.accessToken).toEqual({
<add> ...accessToken,
<add> created: accessToken.created.toISOString()
<add> });
<add> });
<add>
<add> it('returns the signed jwt if found', () => {
<add> const validJWT = jwt.sign({ accessToken }, validJWTSecret);
<add> // eslint-disable-next-line camelcase
<add> const req = mockReq({ cookie: { jwt_access_token: validJWT } });
<add> const result = getAccessTokenFromRequest(req, validJWTSecret);
<add>
<add> expect(result.jwt).toEqual(validJWT);
<add> });
<add> });
<add>
<add> describe('Auth headers', () => {
<add> it('returns `invalid token` error for malformed tokens', () => {
<add> const invalidJWT = jwt.sign({ accessToken }, invalidJWTSecret);
<add> // eslint-disable-next-line camelcase
<add> const req = mockReq({ headers: { 'X-fcc-access-token': invalidJWT } });
<add> const result = getAccessTokenFromRequest(req, validJWTSecret);
<add>
<add> expect(result.error).toEqual(errorTypes.invalidToken);
<add> });
<add>
<add> it('returns `expired token` error for expired tokens', () => {
<add> const invalidJWT = jwt.sign(
<add> { accessToken: { ...accessToken, created: theBeginningOfTime } },
<add> validJWTSecret
<add> );
<add> // eslint-disable-next-line camelcase
<add> const req = mockReq({ headers: { 'X-fcc-access-token': invalidJWT } });
<add> const result = getAccessTokenFromRequest(req, validJWTSecret);
<add>
<add> expect(result.error).toEqual(errorTypes.expiredToken);
<add> });
<add>
<add> it('returns a valid access token with no errors ', () => {
<add> expect.assertions(2);
<add> const validJWT = jwt.sign({ accessToken }, validJWTSecret);
<add> // eslint-disable-next-line camelcase
<add> const req = mockReq({ headers: { 'X-fcc-access-token': validJWT } });
<add> const result = getAccessTokenFromRequest(req, validJWTSecret);
<add>
<add> expect(result.error).toBeFalsy();
<add> expect(result.accessToken).toEqual({
<add> ...accessToken,
<add> created: accessToken.created.toISOString()
<add> });
<add> });
<add>
<add> it('returns the signed jwt if found', () => {
<add> const validJWT = jwt.sign({ accessToken }, validJWTSecret);
<add> // eslint-disable-next-line camelcase
<add> const req = mockReq({ headers: { 'X-fcc-access-token': validJWT } });
<add> const result = getAccessTokenFromRequest(req, validJWTSecret);
<add>
<add> expect(result.jwt).toEqual(validJWT);
<add> });
<add> });
<add> });
<add>
<add> describe('setAccessTokenToResponse', () => {
<add> it('sets three cookies in the response', () => {
<add> expect.assertions(3);
<add> const req = mockReq();
<add> const res = mockRes();
<add>
<add> const expectedJWT = jwt.sign({ accessToken }, validJWTSecret);
<add>
<add> setAccessTokenToResponse({ accessToken }, req, res, validJWTSecret);
<add>
<add> expect(res.cookie.getCall(0).args).toEqual([
<add> 'jwt_access_token',
<add> expectedJWT,
<add> {
<add> signed: false,
<add> domain: 'localhost',
<add> maxAge: accessToken.ttl
<add> }
<add> ]);
<add> expect(res.cookie.getCall(1).args).toEqual([
<add> 'access_token',
<add> accessToken.id,
<add> {
<add> signed: false,
<add> domain: 'localhost',
<add> maxAge: accessToken.ttl
<add> }
<add> ]);
<add> expect(res.cookie.getCall(2).args).toEqual([
<add> 'userId',
<add> accessToken.userId,
<add> {
<add> signed: false,
<add> domain: 'localhost',
<add> maxAge: accessToken.ttl
<add> }
<add> ]);
<add> });
<add> });
<add>
<add> describe('removeCookies', () => {
<add> it('removes four cookies set in the lifetime of an authenticated session', () => {
<add> // expect.assertions(4);
<add> const req = mockReq();
<add> const res = mockRes();
<add>
<add> removeCookies(req, res);
<add>
<add> expect(res.clearCookie.getCall(0).args).toEqual([
<add> 'jwt_access_token',
<add> {
<add> signed: false,
<add> domain: 'localhost'
<add> }
<add> ]);
<add> expect(res.clearCookie.getCall(1).args).toEqual([
<add> 'access_token',
<add> {
<add> signed: false,
<add> domain: 'localhost'
<add> }
<add> ]);
<add> expect(res.clearCookie.getCall(2).args).toEqual([
<add> 'userId',
<add> {
<add> signed: false,
<add> domain: 'localhost'
<add> }
<add> ]);
<add> expect(res.clearCookie.getCall(3).args).toEqual([
<add> '_csrf',
<add> {
<add> signed: false,
<add> domain: 'localhost'
<add> }
<add> ]);
<add> });
<add> });
<add>});
| 2
|
Ruby
|
Ruby
|
fix ares tests under jruby. [tom.enebo@gmail.com]
|
fc042435a6f571684314d60e9605e3331b7435f9
|
<ide><path>activeresource/test/base_test.rb
<ide> def test_respond_to
<ide> assert matz.respond_to?(:name)
<ide> assert matz.respond_to?(:name=)
<ide> assert matz.respond_to?(:name?)
<del> assert !matz.respond_to?(:java)
<add> assert !matz.respond_to?(:super_scalable_stuff)
<ide> end
<ide>
<ide> def test_find_by_id_with_custom_prefix
| 1
|
Javascript
|
Javascript
|
increase coverage for internal/errors.js
|
44d486500de528fa955f9126d7b82cef0deb0ab8
|
<ide><path>test/parallel/test-internal-errors.js
<ide> assert.strictEqual(errors.message('ERR_INVALID_ARG_TYPE',
<ide> assert.strictEqual(errors.message('ERR_INVALID_ARG_TYPE',
<ide> ['a', 'b', null]),
<ide> 'The "a" argument must be of type b. Received type null');
<add>assert.strictEqual(errors.message('ERR_INVALID_ARG_TYPE', ['a', 'not b']),
<add> 'The "a" argument must not be of type b');
<add>assert.strictEqual(errors.message('ERR_INVALID_ARG_TYPE', ['a.b', 'not c']),
<add> 'The "a.b" property must not be of type c');
<add>assert.strictEqual(
<add> errors.message('ERR_INVALID_ARG_TYPE', ['first argument', 'c']),
<add> 'The first argument must be of type c');
<add>assert.strictEqual(
<add> errors.message('ERR_INVALID_ARG_TYPE', [['a', 'b', 'c'], 'not d']),
<add> 'The "a", "b", "c" arguments must not be of type d');
<ide>
<ide> // Test ERR_INVALID_URL_SCHEME
<ide> assert.strictEqual(errors.message('ERR_INVALID_URL_SCHEME', ['file']),
| 1
|
Javascript
|
Javascript
|
exclude tests that are only failing on edge
|
7efed006327df7e6f0784b54e856f0a4e87331e5
|
<ide><path>test/ng/animateRunnerSpec.js
<ide> describe('$$AnimateRunner', function() {
<ide> expect(status).toBe(true);
<ide> }));
<ide>
<del> it('should break the chian when a function evaluates to false',
<add> it('should break the chain when a function evaluates to false',
<ide> inject(function($$rAF, $$AnimateRunner) {
<ide>
<ide> var runner1 = new $$AnimateRunner();
<ide><path>test/ng/directive/inputSpec.js
<ide> describe('input', function() {
<ide> var helper = {}, $compile, $rootScope, $browser, $sniffer, $timeout, $q;
<ide>
<add> // UA sniffing to exclude Edge from some date input tests
<add> var isEdge = /\bEdge\//.test(window.navigator.userAgent);
<add>
<ide> generateInputCompilerHelper(helper);
<ide>
<ide> beforeEach(inject(function(_$compile_, _$rootScope_, _$browser_, _$sniffer_, _$timeout_, _$q_) {
<ide> describe('input', function() {
<ide> expect($rootScope.form.alias.$error.month).toBeTruthy();
<ide> });
<ide>
<del> it('should allow four or more digits in year', function() {
<del> var inputElm = helper.compileInput('<input type="month" ng-model="value" ng-model-options="{timezone: \'UTC\'}"/>');
<ide>
<del> helper.changeInputValueTo('10123-03');
<del> expect(+$rootScope.value).toBe(Date.UTC(10123, 2, 1, 0, 0, 0));
<add> if (!isEdge) {
<add> it('should allow four or more digits in year', function() {
<add> var inputElm = helper.compileInput('<input type="month" ng-model="value" ng-model-options="{timezone: \'UTC\'}"/>');
<ide>
<del> $rootScope.$apply(function() {
<del> $rootScope.value = new Date(Date.UTC(20456, 3, 1, 0, 0, 0));
<del> });
<del> expect(inputElm.val()).toBe('20456-04');
<del> });
<add> helper.changeInputValueTo('10123-03');
<add> expect(+$rootScope.value).toBe(Date.UTC(10123, 2, 1, 0, 0, 0));
<ide>
<add> $rootScope.$apply(function() {
<add> $rootScope.value = new Date(Date.UTC(20456, 3, 1, 0, 0, 0));
<add> });
<add> expect(inputElm.val()).toBe('20456-04');
<add> });
<add> }
<ide>
<ide> it('should only change the month of a bound date', function() {
<ide> var inputElm = helper.compileInput('<input type="month" ng-model="value" ng-model-options="{timezone: \'UTC\'}" />');
<ide> describe('input', function() {
<ide> expect(inputElm).toBeValid();
<ide> });
<ide>
<del> it('should allow four or more digits in year', function() {
<del> var inputElm = helper.compileInput('<input type="week" ng-model="value" ng-model-options="{timezone: \'UTC\'}"/>');
<add> if (!isEdge) {
<add> it('should allow four or more digits in year', function() {
<add> var inputElm = helper.compileInput('<input type="week" ng-model="value" ng-model-options="{timezone: \'UTC\'}"/>');
<ide>
<del> helper.changeInputValueTo('10123-W03');
<del> expect(+$rootScope.value).toBe(Date.UTC(10123, 0, 21));
<add> helper.changeInputValueTo('10123-W03');
<add> expect(+$rootScope.value).toBe(Date.UTC(10123, 0, 21));
<ide>
<del> $rootScope.$apply(function() {
<del> $rootScope.value = new Date(Date.UTC(20456, 0, 28));
<add> $rootScope.$apply(function() {
<add> $rootScope.value = new Date(Date.UTC(20456, 0, 28));
<add> });
<add> expect(inputElm.val()).toBe('20456-W04');
<ide> });
<del> expect(inputElm.val()).toBe('20456-W04');
<del> });
<add> }
<ide>
<ide> it('should use UTC if specified in the options', function() {
<ide> var inputElm = helper.compileInput('<input type="week" ng-model="value" ng-model-options="{timezone: \'UTC\'}" />');
<ide> describe('input', function() {
<ide> expect(+$rootScope.value).toBe(+new Date(2000, 0, 1, 1, 2, 0));
<ide> });
<ide>
<del> it('should allow four or more digits in year', function() {
<del> var inputElm = helper.compileInput('<input type="datetime-local" ng-model="value" />');
<ide>
<del> helper.changeInputValueTo('10123-01-01T01:02');
<del> expect(+$rootScope.value).toBe(+new Date(10123, 0, 1, 1, 2, 0));
<add> if (!isEdge) {
<add> it('should allow four or more digits in year', function() {
<add> var inputElm = helper.compileInput('<input type="datetime-local" ng-model="value" />');
<add>
<add> helper.changeInputValueTo('10123-01-01T01:02');
<add> expect(+$rootScope.value).toBe(+new Date(10123, 0, 1, 1, 2, 0));
<add>
<add> $rootScope.$apply(function() {
<add> $rootScope.value = new Date(20456, 1, 1, 1, 2, 0);
<add> });
<add> expect(inputElm.val()).toBe('20456-02-01T01:02:00.000');
<add> }
<add> );
<add> }
<ide>
<del> $rootScope.$apply(function() {
<del> $rootScope.value = new Date(20456, 1, 1, 1, 2, 0);
<del> });
<del> expect(inputElm.val()).toBe('20456-02-01T01:02:00.000');
<del> }
<del> );
<ide>
<ide> it('should label parse errors as `datetimelocal`', function() {
<ide> var inputElm = helper.compileInput('<input type="datetime-local" ng-model="val" name="alias" />', {
<ide> describe('input', function() {
<ide> }
<ide> );
<ide>
<del> it('should allow four or more digits in year', function() {
<del> var inputElm = helper.compileInput('<input type="date" ng-model="value" ng-model-options="{timezone: \'UTC\'}" />');
<del>
<del> helper.changeInputValueTo('10123-01-01');
<del> expect(+$rootScope.value).toBe(Date.UTC(10123, 0, 1, 0, 0, 0));
<add> if (!isEdge) {
<add> it('should allow four or more digits in year', function() {
<add> var inputElm = helper.compileInput('<input type="date" ng-model="value" ng-model-options="{timezone: \'UTC\'}" />');
<ide>
<del> $rootScope.$apply(function() {
<del> $rootScope.value = new Date(Date.UTC(20456, 1, 1, 0, 0, 0));
<del> });
<del> expect(inputElm.val()).toBe('20456-02-01');
<del> }
<del> );
<add> helper.changeInputValueTo('10123-01-01');
<add> expect(+$rootScope.value).toBe(Date.UTC(10123, 0, 1, 0, 0, 0));
<ide>
<add> $rootScope.$apply(function() {
<add> $rootScope.value = new Date(Date.UTC(20456, 1, 1, 0, 0, 0));
<add> });
<add> expect(inputElm.val()).toBe('20456-02-01');
<add> }
<add> );
<add> }
<ide>
<ide> it('should label parse errors as `date`', function() {
<ide> var inputElm = helper.compileInput('<input type="date" ng-model="val" name="alias" />', {
<ide> describe('input', function() {
<ide> });
<ide>
<ide> expect(inputElm[0].value).toBe('');
<del> // Support: IE 9-11
<add> // Support: IE 9-11, Edge
<ide> // In IE it is not possible to remove the `value` attribute from an input element.
<del> if (!msie) {
<add> if (!msie && !isEdge) {
<ide> expect(inputElm[0].getAttribute('value')).toBeNull();
<add> } else {
<add> // Support: IE 9-11, Edge
<add> // This will fail if the Edge bug gets fixed
<add> expect(inputElm[0].getAttribute('value')).toBe('something');
<ide> }
<ide> });
<ide>
| 2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.