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
|
---|---|---|---|---|---|
Go | Go | fix panic due to mismatched types | c09fe6a7c15ac25c031d0df43d041e4dbb4dbe34 | <ide><path>libnetwork/options/options.go
<ide> func (e CannotSetFieldError) Error() string {
<ide> return fmt.Sprintf("cannot set field %q of type %q", e.Field, e.Type)
<ide> }
<ide>
<add>// TypeMismatchError is the error returned when the type of the generic value
<add>// for a field mismatches the type of the destination structure.
<add>type TypeMismatchError struct {
<add> Field string
<add> ExpectType string
<add> ActualType string
<add>}
<add>
<add>func (e TypeMismatchError) Error() string {
<add> return fmt.Sprintf("type mismatch, field %s require type %v, actual type %v", e.Field, e.ExpectType, e.ActualType)
<add>}
<add>
<ide> // Generic is an basic type to store arbitrary settings.
<ide> type Generic map[string]interface{}
<ide>
<ide> func GenerateFromModel(options Generic, model interface{}) (interface{}, error)
<ide> if !field.CanSet() {
<ide> return nil, CannotSetFieldError{name, resType.String()}
<ide> }
<add> if reflect.TypeOf(value) != field.Type() {
<add> return nil, TypeMismatchError{name, field.Type().String(), reflect.TypeOf(value).String()}
<add> }
<ide> field.Set(reflect.ValueOf(value))
<ide> }
<ide>
<ide><path>libnetwork/options/options_test.go
<ide> func TestFieldCannotBeSet(t *testing.T) {
<ide> t.Fatalf("expected %q in error message, got %s", expected, err.Error())
<ide> }
<ide> }
<add>
<add>func TestTypeMismatchError(t *testing.T) {
<add> type Model struct{ Foo int }
<add> _, err := GenerateFromModel(Generic{"Foo": "bar"}, Model{})
<add>
<add> if _, ok := err.(TypeMismatchError); !ok {
<add> t.Fatalf("expected TypeMismatchError, got %#v", err)
<add> } else if expected := "type mismatch"; !strings.Contains(err.Error(), expected) {
<add> t.Fatalf("expected %q in error message, got %s", expected, err.Error())
<add> }
<add>} | 2 |
Python | Python | simplify fix for rate == 0 in financial.pmt | a9a80fc4a5ed8fb2faba1e1102121468a905c908 | <ide><path>numpy/lib/financial.py
<ide> def pmt(rate, nper, pv, fv=0, when='end'):
<ide> """
<ide> when = _convert_when(when)
<ide> (rate, nper, pv, fv, when) = map(np.asarray, [rate, nper, pv, fv, when])
<del> temp = (1+rate)**nper
<del> miter = np.broadcast(rate, nper, pv, fv, when)
<del> zer = np.zeros(miter.shape)
<del> fact = np.zeros(miter.shape)
<del> numerator = (1 + rate * when) * ( temp - 1)
<del> np.divide(numerator, rate, where = ( rate!= 0), out= fact)
<del> factforZeroRate = nper + zer
<del> np.copyto(fact, factforZeroRate, where = (rate==0))
<add> temp = (1 + rate)**nper
<add> mask = (rate == 0.0)
<add> np.copyto(rate, 1.0, where=mask)
<add> z = np.zeros(np.broadcast(rate, nper, pv, fv, when).shape)
<add> fact = np.where(mask != z, nper + z, (1 + rate*when)*(temp - 1)/rate + z)
<ide> return -(fv + pv*temp) / fact
<ide>
<ide> def nper(rate, pmt, pv, fv=0, when='end'): | 1 |
Java | Java | introduce unit tests for gh-29275 | 66989434b41c06a610be1b32f4ebcabbc707bfa3 | <ide><path>spring-core/src/test/java/org/springframework/core/io/ResourceTests.java
<ide> void readableChannelProvidesContent() throws Exception {
<ide> }
<ide> }
<ide>
<add> @Test
<add> void urlAndUriAreNormalizedWhenCreatedFromFile() throws Exception {
<add> Path path = Path.of("src/test/resources/scanned-resources/resource#test1.txt").toAbsolutePath();
<add> assertUrlAndUriBehavior(new FileSystemResource(path.toFile()));
<add> }
<add>
<add> @Test
<add> void urlAndUriAreNormalizedWhenCreatedFromPath() throws Exception {
<add> Path path = Path.of("src/test/resources/scanned-resources/resource#test1.txt").toAbsolutePath();
<add> assertUrlAndUriBehavior(new FileSystemResource(path));
<add> }
<add>
<add> /**
<add> * The following assertions serve as regression tests for the lack of the
<add> * "authority component" (//) in the returned URI/URL. For example, we are
<add> * expecting file:/my/path (or file:/C:/My/Path) instead of file:///my/path.
<add> */
<add> private void assertUrlAndUriBehavior(Resource resource) throws IOException {
<add> assertThat(resource.getURL().toString()).matches("^file:\\/[^\\/].+test1\\.txt$");
<add> assertThat(resource.getURI().toString()).matches("^file:\\/[^\\/].+test1\\.txt$");
<add> }
<ide> }
<ide>
<ide> @Nested | 1 |
Java | Java | fix double spel evaluation of parameter | 519799e1cf414615ef0a7a26d5dde0478a47b96d | <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/MethodReference.java
<ide> protected ValueRef getValueRef(ExpressionState state) throws EvaluationException
<ide> throwIfNotNullSafe(getArgumentTypes(arguments));
<ide> return ValueRef.NullValueRef.instance;
<ide> }
<del> return new MethodValueRef(state);
<add> return new MethodValueRef(state, arguments);
<ide> }
<ide>
<ide> @Override
<ide> private class MethodValueRef implements ValueRef {
<ide>
<ide> private final Object[] arguments;
<ide>
<del> public MethodValueRef(ExpressionState state) {
<add> public MethodValueRef(ExpressionState state, Object[] arguments) {
<ide> this.evaluationContext = state.getEvaluationContext();
<ide> this.value = state.getActiveContextObject().getValue();
<ide> this.targetType = state.getActiveContextObject().getTypeDescriptor();
<del> this.arguments = getArguments(state);
<add> this.arguments = arguments;
<ide> }
<ide>
<ide> @Override
<ide><path>spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java
<ide> import java.util.List;
<ide> import java.util.Map;
<ide> import java.util.Properties;
<add>import java.util.concurrent.atomic.AtomicInteger;
<ide>
<ide> import org.junit.Rule;
<ide> import org.junit.Test;
<ide> public void SPR11348() {
<ide> assertEquals("two", list.get(1));
<ide> }
<ide>
<add> @Test
<add> public void SPR11445_simple() {
<add> StandardEvaluationContext context = new StandardEvaluationContext(new Spr11445Class());
<add> Expression expr = new SpelExpressionParser().parseRaw("echo(parameter())");
<add> assertEquals(1, expr.getValue(context));
<add> }
<add>
<add> @Test
<add> public void SPR11445_beanReference() {
<add> StandardEvaluationContext context = new StandardEvaluationContext();
<add> context.setBeanResolver(new Spr11445Class());
<add> Expression expr = new SpelExpressionParser().parseRaw("@bean.echo(@bean.parameter())");
<add> assertEquals(1, expr.getValue(context));
<add> }
<add>
<add> static class Spr11445Class implements BeanResolver {
<add>
<add> private final AtomicInteger counter = new AtomicInteger();
<add>
<add> public int echo(int invocation) {
<add> return invocation;
<add> }
<add>
<add> public int parameter() {
<add> return counter.incrementAndGet();
<add> }
<add>
<add> @Override
<add> public Object resolve(EvaluationContext context, String beanName) throws AccessException {
<add> return beanName.equals("bean") ? this : null;
<add> }
<add> }
<add>
<ide> @Test
<ide> public void SPR11494() {
<ide> Expression exp = new SpelExpressionParser().parseExpression("T(java.util.Arrays).asList('a','b')"); | 2 |
Javascript | Javascript | use new bufferattribute.applymatrix4() method | 94526d96484269b6c503719fda2c89725bbde77f | <ide><path>examples/js/loaders/FBXLoader.js
<ide> THREE.FBXLoader = ( function () {
<ide>
<ide> var positionAttribute = new THREE.Float32BufferAttribute( buffers.vertex, 3 );
<ide>
<del> preTransform.applyToBufferAttribute( positionAttribute );
<add> positionAttribute.applyMatrix4( preTransform );
<ide>
<ide> geo.setAttribute( 'position', positionAttribute );
<ide>
<ide> THREE.FBXLoader = ( function () {
<ide> var positionAttribute = new THREE.Float32BufferAttribute( morphBuffers.vertex, 3 );
<ide> positionAttribute.name = name || morphGeoNode.attrName;
<ide>
<del> preTransform.applyToBufferAttribute( positionAttribute );
<add> positionAttribute.applyMatrix4( preTransform );
<ide>
<ide> parentGeo.morphAttributes.position.push( positionAttribute );
<ide>
<ide><path>examples/jsm/loaders/FBXLoader.js
<ide> var FBXLoader = ( function () {
<ide>
<ide> var positionAttribute = new Float32BufferAttribute( buffers.vertex, 3 );
<ide>
<del> preTransform.applyToBufferAttribute( positionAttribute );
<add> positionAttribute.applyMatrix4( preTransform );
<ide>
<ide> geo.setAttribute( 'position', positionAttribute );
<ide>
<ide> var FBXLoader = ( function () {
<ide> var positionAttribute = new Float32BufferAttribute( morphBuffers.vertex, 3 );
<ide> positionAttribute.name = name || morphGeoNode.attrName;
<ide>
<del> preTransform.applyToBufferAttribute( positionAttribute );
<add> positionAttribute.applyMatrix4( preTransform );
<ide>
<ide> parentGeo.morphAttributes.position.push( positionAttribute );
<ide> | 2 |
Python | Python | remove unused default_params (issue ) | 28e3e1a745953e330bf2ee363fa38cb8550f0b52 | <ide><path>celery/backends/redis.py
<ide> You need to install the redis library in order to use \
<ide> the Redis result store backend."""
<ide>
<del>default_params = {
<del> 'host': 'localhost',
<del> 'port': 6379,
<del> 'db': 0,
<del> 'password': None,
<del>}
<del>
<ide>
<ide> class RedisBackend(KeyValueStoreBackend):
<ide> """Redis task result store.""" | 1 |
Javascript | Javascript | add origin for used named chunks | 89fb178917b113287088f739a0ee4254d85c420b | <ide><path>lib/Chunk.js
<ide> Chunk.prototype.addBlock = function(block) {
<ide> return true;
<ide> };
<ide>
<add>Chunk.prototype.addOrigin = function(module, loc) {
<add> this.origins.push({module: module, loc: loc, name: this.name});
<add>};
<add>
<ide> Chunk.prototype.remove = function(reason) {
<ide> // console.log("remove " + this.toString());
<ide> this.modules.slice().forEach(function(m) {
<ide><path>lib/Compilation.js
<ide> Compilation.prototype.seal = function seal(callback) {
<ide>
<ide> Compilation.prototype.addChunk = function addChunk(name, module, loc) {
<ide> if(name) {
<del> if(Object.prototype.hasOwnProperty.call(this.namedChunks, name))
<del> return this.namedChunks[name];
<add> if(Object.prototype.hasOwnProperty.call(this.namedChunks, name)) {
<add> var chunk = this.namedChunks[name];
<add> if(module) chunk.addOrigin(module, loc);
<add> return chunk;
<add> }
<ide> }
<ide> var chunk = new Chunk(name, module, loc);
<ide> this.chunks.push(chunk); | 2 |
Ruby | Ruby | fix typo in image_tag documentation | 98c3586415150e90cea49003a0be6c5eef84a370 | <ide><path>actionview/lib/action_view/helpers/asset_tag_helper.rb
<ide> def favicon_link_tag(source='favicon.ico', options={})
<ide> # ==== Options
<ide> #
<ide> # You can add HTML attributes using the +options+. The +options+ supports
<del> # three additional keys for convenience and conformance:
<add> # two additional keys for convenience and conformance:
<ide> #
<ide> # * <tt>:alt</tt> - If no alt text is given, the file name part of the
<ide> # +source+ is used (capitalized and without the extension) | 1 |
Ruby | Ruby | add missing require to use set | 060ca6abce737b1c2ad53f2427ccaee7142d7cf9 | <ide><path>activemodel/lib/active_model/mass_assignment_security/permission_set.rb
<add>require 'set'
<ide> require 'active_model/mass_assignment_security/sanitizer'
<ide>
<ide> module ActiveModel
<ide> def deny?(key)
<ide> end
<ide> end
<ide> end
<del>end
<ide>\ No newline at end of file
<add>end | 1 |
Text | Text | update javascript capitalization | 26e857b6ab8c3f75f9ef17480ece7bb4318d2057 | <ide><path>client/src/pages/learn/javascript-algorithms-and-data-structures/basic-data-structures/index.md
<ide> superBlock: JavaScript Algorithms and Data Structures
<ide> ---
<ide> ## Introduction to the Basic Data Structure Challenges
<ide>
<del>Data can be stored and accessed in many different ways, both in Javascript and other languages. This section will teach you how to manipulate arrays, as well as access and copy the information within them. It will also teach you how to manipulate and access the data within Javascript objects, using both dot and bracket notation. When you're done with this section, you should understand the basic properties and differences between arrays and objects, as well as how to choose which to use for a given purpose.
<add>Data can be stored and accessed in many different ways, both in JavaScript and other languages. This section will teach you how to manipulate arrays, as well as access and copy the information within them. It will also teach you how to manipulate and access the data within JavaScript objects, using both dot and bracket notation. When you're done with this section, you should understand the basic properties and differences between arrays and objects, as well as how to choose which to use for a given purpose. | 1 |
Text | Text | add geoffreybooth to collaborators | 3bcb2e17f81ad08b94eb541560fc01fded154e0b | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> **Wyatt Preul** <[email protected]>
<ide> * [gengjiawen](https://github.com/gengjiawen) -
<ide> **Jiawen Geng** <[email protected]>
<add>* [GeoffreyBooth](https://github.com/geoffreybooth) -
<add>**Geoffrey Booth** <[email protected]> (he/him)
<ide> * [gibfahn](https://github.com/gibfahn) -
<ide> **Gibson Fahnestock** <[email protected]> (he/him)
<ide> * [gireeshpunathil](https://github.com/gireeshpunathil) - | 1 |
Javascript | Javascript | fix lint issues | 22679069f87b1ff0ca50ddbcd43fe76d3a4ffee4 | <ide><path>lib/RuntimeTemplate.js
<ide>
<ide> const Template = require("./Template");
<ide>
<add>/**
<add> * @typedef CommentOptions
<add> * @property {string=} request
<add> * @property {string=} chunkName
<add> * @property {string=} chunkReason
<add> * @property {string=} message
<add> * @property {string=} exportName
<add> */
<add>
<ide> module.exports = class RuntimeTemplate {
<ide> constructor(outputOptions, requestShortener) {
<ide> this.outputOptions = outputOptions || {};
<ide> this.requestShortener = requestShortener;
<ide> }
<ide>
<del> /**
<del> * @typedef CommentOptions
<del> * @property {string=} request
<del> * @property {string=} chunkName
<del> * @property {string=} chunkReason
<del> * @property {string=} message
<del> * @property {string=} exportName
<del> */
<ide> comment(
<ide> /** @type {CommentOptions} */ {
<ide> request,
<ide><path>lib/util/SortableSet.js
<ide> class SortableSet extends Set {
<ide> return super.clear();
<ide> }
<ide>
<del> /**
<del> * @param {(a: any, b: any) => number} sortFn - function to sort the set
<del> * @returns {void}
<del> */
<del> sortWith(sortFn) {
<add> sortWith(/** @type {(a: any, b: any) => number} */ sortFn) {
<ide> if (this.size === 0 || sortFn === this._lastActiveSortFn) {
<ide> // already sorted - nothing to do
<ide> return; | 2 |
Javascript | Javascript | increase coverage for stream writable | 8de858b96d94cfbfe420a2fe1c95023e3aa92590 | <ide><path>test/parallel/test-stream-writable-final-throw.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const {
<add> Duplex,
<add>} = require('stream');
<add>
<add>{
<add> class Foo extends Duplex {
<add> _final(callback) {
<add> throw new Error('fhqwhgads');
<add> }
<add>
<add> _read() {}
<add> }
<add>
<add> const foo = new Foo();
<add> foo._write = common.mustCall((chunk, encoding, cb) => {
<add> cb();
<add> });
<add> foo.end('test', common.expectsError({ message: 'fhqwhgads' }));
<add> foo.on('error', common.mustCall());
<add>} | 1 |
Go | Go | use new image as base of next command | 74b9e851f6f407ede9d46ab4960e5e134ff666c7 | <ide><path>builder.go
<ide> func (builder *Builder) Build(dockerfile io.Reader, stdout io.Writer) error {
<ide> tmpImages[base.Id] = struct{}{}
<ide>
<ide> fmt.Fprintf(stdout, "===> %s\n", base.ShortId())
<add>
<add> // use the base as the new image
<add> image = base
<add>
<ide> break
<ide> case "copy":
<ide> if image == nil { | 1 |
Go | Go | fix some minor wording / issues | 263e28a830c7c0ba573f8bb6aa37bee1c3956d22 | <ide><path>integration/container/stop_linux_test.go
<ide> func TestStopContainerWithTimeout(t *testing.T) {
<ide>
<ide> func TestDeleteDevicemapper(t *testing.T) {
<ide> skip.If(t, testEnv.DaemonInfo.Driver != "devicemapper")
<del> skip.If(t, testEnv.IsRemoteDaemon, "cannot start daemon on remote test run")
<add> skip.If(t, testEnv.IsRemoteDaemon)
<ide>
<ide> defer setupTest(t)()
<ide> client := testEnv.APIClient()
<ide><path>internal/test/fakestorage/storage.go
<ide> func New(t testingT, dir string, modifiers ...func(*fakecontext.Fake) error) Fak
<ide> ctx := fakecontext.New(t, dir, modifiers...)
<ide> switch {
<ide> case testEnv.IsRemoteDaemon() && strings.HasPrefix(request.DaemonHost(), "unix:///"):
<del> t.Skip(fmt.Sprintf("e2e run : daemon is remote but docker host points to a unix socket"))
<add> t.Skip("e2e run : daemon is remote but docker host points to a unix socket")
<ide> case testEnv.IsLocalDaemon():
<ide> return newLocalFakeStorage(ctx)
<ide> default: | 2 |
Ruby | Ruby | fix wherechain docs to mention only not | 0c3998782b455c81a0cb857a7bd4c90c5ab2e821 | <ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> module QueryMethods
<ide> extend ActiveSupport::Concern
<ide>
<ide> # WhereChain objects act as placeholder for queries in which #where does not have any parameter.
<del> # In this case, #where must be chained with either #not, #like, or #not_like to return a new relation.
<add> # In this case, #where must be chained with #not to return a new relation.
<ide> class WhereChain
<ide> def initialize(scope)
<ide> @scope = scope | 1 |
Javascript | Javascript | improve comparison coverage to 100% | 2f11fe3663a0f23831b36ef92699d3f358e8a277 | <ide><path>test/parallel/test-assert-deep.js
<ide> assertNotDeepOrStrict(new Set([1, 2, 3, 4]), new Set([1, 2, 3]));
<ide> assertDeepAndStrictEqual(new Set(['1', '2', '3']), new Set(['1', '2', '3']));
<ide> assertDeepAndStrictEqual(new Set([[1, 2], [3, 4]]), new Set([[3, 4], [1, 2]]));
<ide> assertNotDeepOrStrict(new Set([{ a: 0 }]), new Set([{ a: 1 }]));
<add>assertNotDeepOrStrict(new Set([Symbol()]), new Set([Symbol()]));
<ide>
<ide> {
<ide> const a = [ 1, 2 ];
<ide> assertDeepAndStrictEqual(-0, -0);
<ide> Object.defineProperty(obj2, Symbol(), { value: 1 });
<ide> assertOnlyDeepEqual(obj1, obj3);
<ide> assertDeepAndStrictEqual(obj1, obj2);
<add> obj2[Symbol()] = true;
<add> assertOnlyDeepEqual(obj1, obj2);
<ide> // TypedArrays have a fast path. Test for this as well.
<ide> const a = new Uint8Array(4);
<ide> const b = new Uint8Array(4); | 1 |
Javascript | Javascript | use callback to properly propagate error | cc7cec25c5fc2fdb8e055e25162c4b231f19e287 | <ide><path>lib/net.js
<ide> Socket.prototype._writeGeneric = function(writev, data, encoding, cb) {
<ide> this._pendingEncoding = '';
<ide>
<ide> if (!this._handle) {
<del> this.destroy(new ERR_SOCKET_CLOSED(), cb);
<add> cb(new ERR_SOCKET_CLOSED());
<ide> return false;
<ide> }
<ide> | 1 |
Go | Go | use pkg/mount to support more flags in dm.mountopt | 9a64f2bbb3d8fed35bb094c73dac54a13dcf7369 | <ide><path>daemon/graphdriver/devmapper/deviceset.go
<ide> import (
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/daemon/graphdriver"
<ide> "github.com/docker/docker/pkg/devicemapper"
<add> "github.com/docker/docker/pkg/mount"
<ide> "github.com/docker/docker/pkg/parsers"
<ide> "github.com/docker/docker/pkg/units"
<ide> "github.com/opencontainers/runc/libcontainer/label"
<ide> func (devices *DeviceSet) MountDevice(hash, path, mountLabel string) error {
<ide> options = joinMountOptions(options, devices.mountOptions)
<ide> options = joinMountOptions(options, label.FormatMountLabel("", mountLabel))
<ide>
<del> if err := syscall.Mount(info.DevName(), path, fstype, syscall.MS_MGC_VAL, options); err != nil {
<add> if err := mount.Mount(info.DevName(), path, fstype, options); err != nil {
<ide> return fmt.Errorf("Error mounting '%s' on '%s': %s", info.DevName(), path, err)
<ide> }
<ide> | 1 |
PHP | PHP | trim $sql before checking for select | 9aeea2fcc3362076a946adcb9d072ccd8fb28bca | <ide><path>lib/Cake/Model/Datasource/Database/Sqlserver.php
<ide> public function lastAffected($source = null) {
<ide> */
<ide> protected function _execute($sql, $params = array(), $prepareOptions = array()) {
<ide> $this->_lastAffected = false;
<add> $sql = trim($sql);
<ide> if (strncasecmp($sql, 'SELECT', 6) === 0 || preg_match('/^EXEC(?:UTE)?\s/mi', $sql) > 0) {
<ide> $prepareOptions += array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL);
<ide> return parent::_execute($sql, $params, $prepareOptions); | 1 |
Python | Python | add more indexing tests | 8a836c53d85f63831e51e7aac9a2f77fdf25ef9f | <ide><path>numpy/core/tests/test_indexing.py
<ide> # but hopefully NumPy indexing can be changed to be more systematic
<ide> # at some point in the future.
<ide>
<del>def test_boolean_indexing():
<del> # Indexing a 2-dimensional array with a length-1 array of 'True'
<del> a = np.array([[ 0., 0., 0.]])
<del> b = np.array([ True], dtype=bool)
<del> assert_equal(a[b], a)
<del>
<del> a[b] = 1.
<del> assert_equal(a, [[1., 1., 1.]])
<add>class TestIndexing(TestCase):
<add>
<add> def test_none_index(self):
<add> # `None` index adds newaxis
<add> a = np.array([1, 2, 3])
<add> assert_equal(a[None], a[np.newaxis])
<add> assert_equal(a[None].ndim, a.ndim + 1)
<add>
<add> def test_empty_tuple_index(self):
<add> # Empty tuple index creates a view
<add> a = np.array([1, 2, 3])
<add> assert_equal(a[()], a)
<add> assert_(a[()].base is a)
<add>
<add> def _test_empty_list_index(self):
<add> # Empty list index (is buggy!)
<add> a = np.array([1, 2, 3])
<add> assert_equal(a[[]], a)
<add>
<add> def test_empty_array_index(self):
<add> # Empty array index is illegal
<add> a = np.array([1, 2, 3])
<add> b = np.array([])
<add> assert_raises(IndexError, a.__getitem__, b)
<add>
<add> def test_ellipsis_index(self):
<add> # Ellipsis index does not create a view
<add> a = np.array([[1, 2, 3],
<add> [4 ,5, 6],
<add> [7, 8, 9]])
<add> assert_equal(a[...], a)
<add> assert_(a[...] is a)
<add>
<add> # Slicing with ellipsis can skip an
<add> # arbitrary number of dimensions
<add> assert_equal(a[0, ...], a[0])
<add> assert_equal(a[0, ...], a[0, :])
<add> assert_equal(a[..., 0], a[:, 0])
<add>
<add> # Slicing with ellipsis always results
<add> # in an array, not a scalar
<add> assert_equal(a[0, ..., 1], np.array(2))
<add>
<add> def test_single_int_index(self):
<add> # Single integer index selects one row
<add> a = np.array([[1, 2, 3],
<add> [4 ,5, 6],
<add> [7, 8, 9]])
<add>
<add> assert_equal(a[0], [1, 2, 3])
<add> assert_equal(a[-1], [7, 8, 9])
<add>
<add> # Index out of bounds produces IndexError
<add> assert_raises(IndexError, a.__getitem__, 1<<30)
<add> # Index overflow produces ValueError
<add> assert_raises(ValueError, a.__getitem__, 1<<64)
<add>
<add> def _test_single_bool_index(self):
<add> # Single boolean index (is buggy?)
<add> a = np.array([[1, 2, 3],
<add> [4 ,5, 6],
<add> [7, 8, 9]])
<add>
<add> # Python boolean converts to integer (invalid?)
<add> assert_equal(a[True], a[1])
<add>
<add> # NumPy zero-dimensional boolean array (*crashes*)
<add> assert_equal(a[np.array(True)], a) # what should be the behaviour?
<add> assert_equal(a[np.array(False)], []) # what should be the behaviour?
<add>
<add> def test_boolean_indexing(self):
<add> # Indexing a 2-dimensional array with a length-1 array of 'True'
<add> a = np.array([[ 0., 0., 0.]])
<add> b = np.array([ True], dtype=bool)
<add> assert_equal(a[b], a)
<add>
<add> a[b] = 1.
<add> assert_equal(a, [[1., 1., 1.]])
<ide>
<ide> if __name__ == "__main__":
<ide> run_module_suite() | 1 |
Ruby | Ruby | fix syntax error | 91b139aca293bea1aa926c5301754e8603c9275e | <ide><path>Library/Homebrew/utils/github.rb
<ide> def query_string(*main_params, **qualifiers)
<ide> if value.is_a? Array
<ide> value.each { |v| params_list << format_parameter(key, v) }
<ide> else
<del> params_list << format_parameter(key, v)
<add> params_list << format_parameter(key, value)
<ide> end
<ide> end
<ide> | 1 |
Ruby | Ruby | handle missing environment from non empty config | 283a2edec2f8ccdf90fb58025608f02a63948fa0 | <ide><path>activerecord/lib/active_record/connection_handling.rb
<ide> def raw_merged_into_default
<ide> # the connection URL. This hash responds to any string key with
<ide> # resolved connection information.
<ide> def default_url_hash
<del> if @raw_config.blank?
<del> Hash.new do |hash, key|
<del> hash[key] = if key.is_a? String
<del> ActiveRecord::ConnectionAdapters::ConnectionSpecification::ConnectionUrlResolver.new(@url).to_hash
<del> else
<del> nil
<del> end
<add> Hash.new do |hash, key|
<add> hash[key] = if key.is_a? String
<add> ActiveRecord::ConnectionAdapters::ConnectionSpecification::ConnectionUrlResolver.new(@url).to_hash
<add> else
<add> nil
<ide> end
<del> else
<del> {}
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/connection_adapters/connection_handler_test.rb
<ide> def teardown
<ide> ENV["DATABASE_URL"] = @previous_database_url
<ide> end
<ide>
<add> def test_environment_does_not_exist_in_config_url_does_exist
<add> ENV['DATABASE_URL'] = "postgres://localhost/foo"
<add> config = { "not_production" => { "adapter" => "not_postgres", "database" => "not_foo" } }
<add> actual = klass.new(config).resolve
<add> expect_prod = { "adapter"=>"postgresql", "database"=>"foo", "host"=>"localhost" }
<add> assert_equal expect_prod, actual["production"]
<add> end
<add>
<ide> def test_string_connection
<ide> config = { "production" => "postgres://localhost/foo" }
<ide> actual = klass.new(config).resolve
<ide> def test_blank_with_database_url
<ide> assert_equal nil, actual[:test]
<ide> end
<ide>
<del> def test_sting_with_database_url
<del> ENV['DATABASE_URL'] = "NOT-POSTGRES://localhost/NOT_FOO"
<del>
<del> config = { "production" => "postgres://localhost/foo" }
<del> actual = klass.new(config).resolve
<del>
<del> expected = { "production" =>
<del> { "adapter" => "postgresql",
<del> "database" => "foo",
<del> "host" => "localhost"
<del> }
<del> }
<del> assert_equal expected, actual
<del> end
<del>
<ide> def test_url_sub_key_with_database_url
<ide> ENV['DATABASE_URL'] = "NOT-POSTGRES://localhost/NOT_FOO"
<ide> | 2 |
Javascript | Javascript | use common.fixtures module in test-preload | 0d38e6d01f110bd0ac373da6c6e781d4826be83e | <ide><path>test/parallel/test-preload.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>const fixtures = require('../common/fixtures');
<ide> // Refs: https://github.com/nodejs/node/pull/2253
<ide> if (common.isSunOS)
<ide> common.skip('unreliable on SunOS');
<ide>
<ide> const assert = require('assert');
<del>const path = require('path');
<ide> const childProcess = require('child_process');
<ide>
<ide> const nodeBinary = process.argv[0];
<ide> const preloadOption = (preloads) => {
<ide> return option;
<ide> };
<ide>
<del>const fixture = (name) => path.join(common.fixturesDir, name);
<del>
<del>const fixtureA = fixture('printA.js');
<del>const fixtureB = fixture('printB.js');
<del>const fixtureC = fixture('printC.js');
<del>const fixtureD = fixture('define-global.js');
<del>const fixtureThrows = fixture('throws_error4.js');
<add>const fixtureA = fixtures.path('printA.js');
<add>const fixtureB = fixtures.path('printB.js');
<add>const fixtureC = fixtures.path('printC.js');
<add>const fixtureD = fixtures.path('define-global.js');
<add>const fixtureThrows = fixtures.path('throws_error4.js');
<ide>
<ide> // test preloading a single module works
<ide> childProcess.exec(`"${nodeBinary}" ${preloadOption([fixtureA])} "${fixtureB}"`,
<ide> interactive.stdin.write('a\n');
<ide> interactive.stdin.write('process.exit()\n');
<ide>
<ide> childProcess.exec(
<del> `"${nodeBinary}" --require "${fixture('cluster-preload.js')}" "${
<del> fixture('cluster-preload-test.js')}"`,
<add> `"${nodeBinary}" --require "${fixtures.path('cluster-preload.js')}" "${
<add> fixtures.path('cluster-preload-test.js')}"`,
<ide> function(err, stdout, stderr) {
<ide> assert.ifError(err);
<ide> assert.ok(/worker terminated with code 43/.test(stdout));
<ide> }
<ide> );
<ide>
<ide> // https://github.com/nodejs/node/issues/1691
<del>process.chdir(common.fixturesDir);
<add>process.chdir(fixtures.fixturesDir);
<ide> childProcess.exec(
<ide> `"${nodeBinary}" --expose_natives_as=v8natives --require ` +
<del> `"${fixture('cluster-preload.js')}" cluster-preload-test.js`,
<add> `"${fixtures.path('cluster-preload.js')}" cluster-preload-test.js`,
<ide> function(err, stdout, stderr) {
<ide> assert.ifError(err);
<ide> assert.ok(/worker terminated with code 43/.test(stdout)); | 1 |
Ruby | Ruby | simplify merge call on polymorphic helpers | e2ae787b36e32627974a0d448694c0067327fed7 | <ide><path>actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
<ide> module PolymorphicRoutes
<ide> #
<ide> def polymorphic_url(record_or_hash_or_array, options = {})
<ide> if Hash === record_or_hash_or_array
<del> options = record_or_hash_or_array.dup.merge!(options)
<add> options = record_or_hash_or_array.merge(options)
<ide> record = options.delete :id
<ide> return polymorphic_url record, options
<ide> end
<ide> def polymorphic_url(record_or_hash_or_array, options = {})
<ide> # <tt>polymorphic_url</tt> with <tt>routing_type: :path</tt>.
<ide> def polymorphic_path(record_or_hash_or_array, options = {})
<ide> if Hash === record_or_hash_or_array
<del> options = record_or_hash_or_array.dup.merge!(options)
<add> options = record_or_hash_or_array.merge(options)
<ide> record = options.delete :id
<ide> return polymorphic_path record, options
<ide> end | 1 |
Ruby | Ruby | improve performance of integration tests | 1fb9e6eff71eb84b6cb620282c15b7b89d8e70c1 | <ide><path>actionpack/lib/action_dispatch/routing/route_set.rb
<ide> def url_helpers(supports_path = true)
<ide> # Rails.application.routes.url_helpers.url_for(args)
<ide> @_routes = routes
<ide> class << self
<del> delegate :url_for, :optimize_routes_generation?, to: '@_routes'
<add> def url_for(options)
<add> @_routes.url_for(options)
<add> end
<add>
<add> def optimize_routes_generation?
<add> @_routes.optimize_routes_generation?
<add> end
<add>
<ide> attr_reader :_routes
<ide> def url_options; {}; end
<ide> end | 1 |
Python | Python | add disjoint set | 01601e6382e92b5a3806fb3a44357460dff97ee7 | <ide><path>data_structures/disjoint_set/disjoint_set.py
<add>"""
<add> disjoint set
<add> Reference: https://en.wikipedia.org/wiki/Disjoint-set_data_structure
<add>"""
<add>
<add>
<add>class Node:
<add> def __init__(self, data):
<add> self.data = data
<add>
<add>
<add>def make_set(x):
<add> """
<add> make x as a set.
<add> """
<add> # rank is the distance from x to its' parent
<add> # root's rank is 0
<add> x.rank = 0
<add> x.parent = x
<add>
<add>
<add>def union_set(x, y):
<add> """
<add> union two sets.
<add> set with bigger rank should be parent, so that the
<add> disjoint set tree will be more flat.
<add> """
<add> x, y = find_set(x), find_set(y)
<add> if x.rank > y.rank:
<add> y.parent = x
<add> else:
<add> x.parent = y
<add> if x.rank == y.rank:
<add> y.rank += 1
<add>
<add>
<add>def find_set(x):
<add> """
<add> return the parent of x
<add> """
<add> if x != x.parent:
<add> x.parent = find_set(x.parent)
<add> return x.parent
<add>
<add>
<add>def find_python_set(node: Node) -> set:
<add> """
<add> Return a Python Standard Library set that contains i.
<add> """
<add> sets = ({0, 1, 2}, {3, 4, 5})
<add> for s in sets:
<add> if node.data in s:
<add> return s
<add> raise ValueError(f"{node.data} is not in {sets}")
<add>
<add>
<add>def test_disjoint_set():
<add> """
<add> >>> test_disjoint_set()
<add> """
<add> vertex = [Node(i) for i in range(6)]
<add> for v in vertex:
<add> make_set(v)
<add>
<add> union_set(vertex[0], vertex[1])
<add> union_set(vertex[1], vertex[2])
<add> union_set(vertex[3], vertex[4])
<add> union_set(vertex[3], vertex[5])
<add>
<add> for node0 in vertex:
<add> for node1 in vertex:
<add> if find_python_set(node0).isdisjoint(find_python_set(node1)):
<add> assert find_set(node0) != find_set(node1)
<add> else:
<add> assert find_set(node0) == find_set(node1)
<add>
<add>
<add>if __name__ == "__main__":
<add> test_disjoint_set() | 1 |
Python | Python | add regression test for decimalfield mapping | 7d79cf35b7be01b175d8c25276a4414e8144a16b | <ide><path>tests/test_model_serializer.py
<ide>
<ide> from rest_framework import serializers
<ide> from rest_framework.compat import DurationField as ModelDurationField
<del>from rest_framework.compat import unicode_repr
<add>from rest_framework.compat import DecimalValidator, unicode_repr
<ide>
<ide>
<ide> def dedent(blocktext):
<ide> class Meta:
<ide> }]
<ide>
<ide> assert serializer.data == expected
<add>
<add>
<add>class DecimalFieldModel(models.Model):
<add> decimal_field = models.DecimalField(
<add> max_digits=3,
<add> decimal_places=1,
<add> validators=[MinValueValidator(1), MaxValueValidator(3)]
<add> )
<add>
<add>
<add>class TestDecimalFieldMappings(TestCase):
<add> @pytest.mark.skipif(DecimalValidator is not None,
<add> reason='DecimalValidator is available in Django 1.9+')
<add> def test_decimal_field_has_no_decimal_validator(self):
<add> """
<add> Test that a DecimalField has no validators before Django 1.9.
<add> """
<add> class TestSerializer(serializers.ModelSerializer):
<add> class Meta:
<add> model = DecimalFieldModel
<add>
<add> serializer = TestSerializer()
<add>
<add> assert len(serializer.fields['decimal_field'].validators) == 0
<add>
<add> @pytest.mark.skipif(DecimalValidator is None,
<add> reason='DecimalValidator is available in Django 1.9+')
<add> def test_decimal_field_has_decimal_validator(self):
<add> """
<add> Test that a DecimalField has DecimalValidator in Django 1.9+.
<add> """
<add> class TestSerializer(serializers.ModelSerializer):
<add> class Meta:
<add> model = DecimalFieldModel
<add>
<add> serializer = TestSerializer()
<add>
<add> assert len(serializer.fields['decimal_field'].validators) == 2 | 1 |
Python | Python | update undici cpe in vuln checking script | 994081f9147e92d0b31cdc508e24273a4108b59d | <ide><path>tools/dep_checker/dependencies.py
<ide> def get_cpe(self) -> Optional[str]:
<ide> version=vp.get_libuv_version(), cpe=CPE(vendor="libuv_project", product="libuv")
<ide> ),
<ide> "undici": Dependency(
<del> version=vp.get_undici_version(), cpe=None, keyword="undici", npm_name="undici"
<add> version=vp.get_undici_version(),
<add> cpe=CPE(vendor="nodejs", product="undici"),
<add> npm_name="undici",
<ide> ),
<ide> "OpenSSL": Dependency(
<ide> version=vp.get_openssl_version(), cpe=CPE(vendor="openssl", product="openssl") | 1 |
Text | Text | add issue contributing section | a647c39acfac136acdd841b5a2faaae46b67425d | <ide><path>CONTRIBUTING.md
<ide> # CONTRIBUTING
<ide>
<add>## ISSUE CONTRIBUTIONS
<add>
<add>When opening new issues or commenting on existing issues on this repository
<add>please make sure discussions are related to concrete technical issues with the
<add>`iojs` software.
<add>
<add>Discussion of non-technical topics including subjects like intellectual
<add>property, trademark and high level project questions should move to the
<add>[node-forward discussion repository][] instead.
<add>
<add>## CODE CONTRIBUTIONS
<add>
<ide> The node.js project welcomes new contributors. This document will guide you
<ide> through the process.
<ide>
<ide> not send out notifications when you add commits.
<ide> [node.js mailing list]: http://groups.google.com/group/nodejs
<ide> [IRC]: http://webchat.freenode.net/?channels=node.js
<ide> [project maintainers]: https://github.com/joyent/node/wiki/Project-Organization
<add>[node-forward discussion repository]: https://github.com/node-forward/discussions/issues | 1 |
Javascript | Javascript | remove error allowance in debugger test | 938ab0e2675f0551b71af43ae3f9746436ff1a74 | <ide><path>test/sequential/test-debugger-exceptions.js
<ide> const path = require('path');
<ide> })
<ide> // Making sure it will die by default:
<ide> .then(() => cli.command('c'))
<del> // TODO: Remove FATAL ERROR once node doesn't show a FATAL ERROR anymore.
<del> .then(() => cli.waitFor(/disconnect|FATAL ERROR/))
<add> .then(() => cli.waitFor(/disconnect/))
<ide>
<ide> // Next run: With `breakOnException` it pauses in both places.
<ide> .then(() => cli.stepCommand('r'))
<ide> const path = require('path');
<ide> assert.deepStrictEqual(cli.breakInfo, { filename: script, line: 1 });
<ide> })
<ide> .then(() => cli.command('c'))
<del> // TODO: Remove FATAL ERROR once node doesn't show a FATAL ERROR anymore
<del> .then(() => cli.waitFor(/disconnect|FATAL ERROR/))
<del>
<add> .then(() => cli.waitFor(/disconnect/))
<ide> .then(() => cli.quit())
<ide> .then(null, onFatal);
<ide> } | 1 |
Text | Text | add dev report for may 1st | 67ac02d4a6c093f9c796dd4ddd1a185bde63b460 | <ide><path>reports/2017-05-01.md
<add># Development Report for May 01, 2017
<add>
<add>This is the 1st report, since the Moby project was announced at DockerCon. Thank you to everyone that stayed an extra day to attend the summit on Thursday.
<add>
<add>## Daily Meeting
<add>
<add>A daily meeting is hosted on [slack](dockercommunity.slack.com) every business day at 9am PST on the channel `#moby-project`.
<add>During this meeting, we are talking about the [tasks](https://github.com/moby/moby/issues/32867) needed to be done for splitting moby and docker.
<add>
<add>## Topics discussed last week
<add>
<add>### The moby tool
<add>
<add>The moby tool currently lives at [https://github.com/moby/tool](https://github.com/moby/tool), it's only a temporary place and will soon be merged in [https://github.com/moby/moby](https://github.com/moby/moby).
<add>
<add>### The CLI split
<add>
<add>Ongoing work to split the Docker CLI into [https://github.com/docker/cli](https://github.com/docker/cli) is happening [here](https://github.com/moby/moby/pull/32694).
<add>We are almost done, it should be merged soon.
<add>
<add>### Mailing list
<add>
<add>Slack works great for synchronous communication, but we need to place for async discussion. A mailing list is currently being setup.
<add>
<add>#### Find a good and non-confusing home for the remaining monolith
<add>
<add>Lots of discussion and progress made on this topic, see [here](https://github.com/moby/moby/issues/32871). The work will start this week.
<add>
<add>## Componentization
<add>
<add>So far only work on the builder happened regarding the componentization effort.
<add>
<add>### builder
<add>
<add>The builder dev report can be found [here](builder/2017-05-01.md)
<ide><path>reports/builder/2017-05-01.md
<add># Development Report for May 01, 2017
<add>
<add>### buildkit
<add>
<add>As part of the goals of [Moby](https://github.com/moby/moby#transitioning-to-moby) to split the current platform into reusable components and to provide a future vision for the builder component new [buildkit proposal](https://github.com/moby/moby/issues/32925) was opened with early design draft.
<add>
<add>Buildkit is a library providing the core essentials of running a build process using isolated sandboxed commands. It is designed for extensibility and customization. Buildkit supports multiple build declaration formats(frontends) and multiple ways for outputting build results(not just docker images). It doesn't make decisions for a specific worker, snapshot or exporter implementations.
<add>
<add>It is designed to help find the most efficient way to process build tasks and intelligently cache them for repeated invocations.
<add>
<add>### Quality: Dependency interface switch
<add>
<add>To improve quality and performance, a new [proposal was made for switching the dependency interface](https://github.com/moby/moby/issues/32904) for current builder package. That should fix the current problems with data leakage and conflicts caused by daemon state cleanup scripts.
<add>
<add>@dnephin is in progress of refactoring current builder code to logical areas as a preparation work for updating this interface.
<add>
<add>Merged as part of this effort:
<add>
<add>- [Refactor Dockerfile.parser and directive](https://github.com/moby/moby/pull/32580)
<add>- [Refactor builder dispatch state](https://github.com/moby/moby/pull/32600)
<add>- [Use a bytes.Buffer for shell_words string concat](https://github.com/moby/moby/pull/32601)
<add>- [Refactor `Builder.commit()`](https://github.com/moby/moby/pull/32772)
<add>- [Remove b.escapeToken, create ShellLex](https://github.com/moby/moby/pull/32858)
<add>
<add>### New feature: Long running session
<add>
<add>PR for [adding long-running session between daemon and cli](https://github.com/moby/moby/pull/32677) that enabled advanced features like incremental context send, build credentials from the client, ssh forwarding etc. is looking for initial design review. It is currently open if features implemented on top of it would use a specific transport implementation on the wire or a generic interface(current implementation). @tonistiigi is working on adding persistent cache capabilities that are currently missing from that PR. It also needs to be figured out how the [cli split](https://github.com/moby/moby/pull/32694) will affect features like this.
<add>
<add>### Proposals for new Dockerfile features that need design feedback:
<add>
<add>[Add IMPORT/EXPORT commands to Dockerfile](https://github.com/moby/moby/issues/32100)
<add>
<add>[Add `DOCKEROS/DOCKERARCH` default ARG to Dockerfile](https://github.com/moby/moby/issues/32487)
<add>
<add>[Add support for `RUN --mount`](https://github.com/moby/moby/issues/32507)
<add>
<add>These proposals have gotten mostly positive feedback for now. We will leave them open for a couple of more weeks and then decide what actions to take in a maintainers meeting. Also, if you are interested in implementing any of them, leave a comment on the specific issues.
<add>
<add>### Other new builder features currently in code-review:
<add>
<add>[`docker build --iidfile` to capture the ID of the build result](https://github.com/moby/moby/pull/32406)
<add>
<add>[Allow builds from any git remote ref](https://github.com/moby/moby/pull/32502)
<add>
<add>### Backlog:
<add>
<add>[Build secrets](https://github.com/moby/moby/pull/30637) will be brought up again in next maintainer's meeting to evaluate how to move on with this, if any other proposals have changed the objective and if we should wait for swarm secrets to be available first. | 2 |
Text | Text | fix typo in changelog | 81503e597bbddfe210a627eaddea827ad0e01e44 | <ide><path>CHANGELOG.md
<ide>
<ide> * [[`b3cbd13340`](https://github.com/nodejs/node/commit/b3cbd13340)] - **buffer**: fix assertion error in WeakCallback (Fedor Indutny) [#3329](https://github.com/nodejs/node/pull/3329)
<ide> * [[`102cb7288c`](https://github.com/nodejs/node/commit/102cb7288c)] - **doc**: label v4.2.0 as LTS in changelog heading (Rod Vagg) [#3343](https://github.com/nodejs/node/pull/3343)
<del>* [[`c245a199a7`](https://github.com/nodejs/node/commit/c245a199a7)] - **lib**: fix undefined timeout regression (Ryan Graham) [#3331](https://github.com/nodejs/node/pull/3331
<add>* [[`c245a199a7`](https://github.com/nodejs/node/commit/c245a199a7)] - **lib**: fix undefined timeout regression (Ryan Graham) [#3331](https://github.com/nodejs/node/pull/3331)
<ide>
<ide> ## 2015-10-07, Version 4.2.0 'Argon' (LTS), @jasnell
<ide> | 1 |
Ruby | Ruby | remove some old cruft | bb91beabbde29a52bb2851884eaa90636aff0b95 | <ide><path>actionpack/lib/action_view/paths.rb
<ide> def unshift(*objs)
<ide> end
<ide>
<ide> def find(path, details = {}, prefix = nil, partial = false)
<del> # template_path = path.sub(/^\//, '')
<ide> template_path = path
<ide>
<ide> each do |load_path|
<ide> def find(path, details = {}, prefix = nil, partial = false)
<ide> end
<ide> end
<ide>
<del> # TODO: Have a fallback absolute path?
<del> extension = details[:formats] || []
<ide> raise ActionView::MissingTemplate.new(self, "#{prefix}/#{path} - #{details.inspect} - partial: #{!!partial}")
<ide> end
<ide> | 1 |
Mixed | Python | allow string argument for disable/enable/exclude | 8fc0efc502da2f02076575e0887cb585d0e0f391 | <ide><path>spacy/__init__.py
<ide> def load(
<ide> name: Union[str, Path],
<ide> *,
<ide> vocab: Union[Vocab, bool] = True,
<del> disable: Iterable[str] = util.SimpleFrozenList(),
<del> enable: Iterable[str] = util.SimpleFrozenList(),
<del> exclude: Iterable[str] = util.SimpleFrozenList(),
<add> disable: Union[str, Iterable[str]] = util.SimpleFrozenList(),
<add> enable: Union[str, Iterable[str]] = util.SimpleFrozenList(),
<add> exclude: Union[str, Iterable[str]] = util.SimpleFrozenList(),
<ide> config: Union[Dict[str, Any], Config] = util.SimpleFrozenDict(),
<ide> ) -> Language:
<ide> """Load a spaCy model from an installed package or a local path.
<ide>
<ide> name (str): Package name or model path.
<ide> vocab (Vocab): A Vocab object. If True, a vocab is created.
<del> disable (Iterable[str]): Names of pipeline components to disable. Disabled
<add> disable (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to disable. Disabled
<ide> pipes will be loaded but they won't be run unless you explicitly
<ide> enable them by calling nlp.enable_pipe.
<del> enable (Iterable[str]): Names of pipeline components to enable. All other
<add> enable (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to enable. All other
<ide> pipes will be disabled (but can be enabled later using nlp.enable_pipe).
<del> exclude (Iterable[str]): Names of pipeline components to exclude. Excluded
<add> exclude (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to exclude. Excluded
<ide> components won't be loaded.
<ide> config (Dict[str, Any] / Config): Config overrides as nested dict or dict
<ide> keyed by section values in dot notation.
<ide><path>spacy/language.py
<ide> def select_pipes(
<ide> """
<ide> if enable is None and disable is None:
<ide> raise ValueError(Errors.E991)
<del> if disable is not None and isinstance(disable, str):
<add> if isinstance(disable, str):
<ide> disable = [disable]
<ide> if enable is not None:
<ide> if isinstance(enable, str):
<ide> def from_config(
<ide> config: Union[Dict[str, Any], Config] = {},
<ide> *,
<ide> vocab: Union[Vocab, bool] = True,
<del> disable: Iterable[str] = SimpleFrozenList(),
<del> enable: Iterable[str] = SimpleFrozenList(),
<del> exclude: Iterable[str] = SimpleFrozenList(),
<add> disable: Union[str, Iterable[str]] = SimpleFrozenList(),
<add> enable: Union[str, Iterable[str]] = SimpleFrozenList(),
<add> exclude: Union[str, Iterable[str]] = SimpleFrozenList(),
<ide> meta: Dict[str, Any] = SimpleFrozenDict(),
<ide> auto_fill: bool = True,
<ide> validate: bool = True,
<ide> def from_config(
<ide>
<ide> config (Dict[str, Any] / Config): The loaded config.
<ide> vocab (Vocab): A Vocab object. If True, a vocab is created.
<del> disable (Iterable[str]): Names of pipeline components to disable.
<add> disable (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to disable.
<ide> Disabled pipes will be loaded but they won't be run unless you
<ide> explicitly enable them by calling nlp.enable_pipe.
<del> enable (Iterable[str]): Names of pipeline components to enable. All other
<add> enable (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to enable. All other
<ide> pipes will be disabled (and can be enabled using `nlp.enable_pipe`).
<del> exclude (Iterable[str]): Names of pipeline components to exclude.
<add> exclude (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to exclude.
<ide> Excluded components won't be loaded.
<ide> meta (Dict[str, Any]): Meta overrides for nlp.meta.
<ide> auto_fill (bool): Automatically fill in missing values in config based
<ide> def from_config(
<ide>
<ide> DOCS: https://spacy.io/api/language#from_config
<ide> """
<add> if isinstance(disable, str):
<add> disable = [disable]
<add> if isinstance(enable, str):
<add> enable = [enable]
<add> if isinstance(exclude, str):
<add> exclude = [exclude]
<ide> if auto_fill:
<ide> config = Config(
<ide> cls.default_config, section_order=CONFIG_SECTION_ORDER
<ide> def to_disk(
<ide>
<ide> @staticmethod
<ide> def _resolve_component_status(
<del> disable: Iterable[str], enable: Iterable[str], pipe_names: Collection[str]
<add> disable: Union[str, Iterable[str]],
<add> enable: Union[str, Iterable[str]],
<add> pipe_names: Iterable[str],
<ide> ) -> Tuple[str, ...]:
<ide> """Derives whether (1) `disable` and `enable` values are consistent and (2)
<ide> resolves those to a single set of disabled components. Raises an error in
<ide> case of inconsistency.
<ide>
<del> disable (Iterable[str]): Names of components or serialization fields to disable.
<del> enable (Iterable[str]): Names of pipeline components to enable.
<add> disable (Union[str, Iterable[str]]): Name(s) of component(s) or serialization fields to disable.
<add> enable (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to enable.
<ide> pipe_names (Iterable[str]): Names of all pipeline components.
<ide>
<ide> RETURNS (Tuple[str, ...]): Names of components to exclude from pipeline w.r.t.
<ide> specified includes and excludes.
<ide> """
<ide>
<del> if disable is not None and isinstance(disable, str):
<add> if isinstance(disable, str):
<ide> disable = [disable]
<ide> to_disable = disable
<ide>
<ide> if enable:
<add> if isinstance(enable, str):
<add> enable = [enable]
<ide> to_disable = [
<ide> pipe_name for pipe_name in pipe_names if pipe_name not in enable
<ide> ]
<ide><path>spacy/tests/pipeline/test_pipe_methods.py
<ide> def test_load_disable_enable() -> None:
<ide> base_nlp.to_disk(tmp_dir)
<ide> to_disable = ["parser", "tagger"]
<ide> to_enable = ["tagger", "parser"]
<add> single_str = "tagger"
<ide>
<ide> # Setting only `disable`.
<ide> nlp = spacy.load(tmp_dir, disable=to_disable)
<ide> def test_load_disable_enable() -> None:
<ide> ]
<ide> )
<ide>
<add> # Loading with a string representing one component
<add> nlp = spacy.load(tmp_dir, exclude=single_str)
<add> assert single_str not in nlp.component_names
<add>
<add> nlp = spacy.load(tmp_dir, disable=single_str)
<add> assert single_str in nlp.component_names
<add> assert single_str not in nlp.pipe_names
<add> assert nlp._disabled == {single_str}
<add> assert nlp.disabled == [single_str]
<add>
<ide> # Testing consistent enable/disable combination.
<ide> nlp = spacy.load(
<ide> tmp_dir,
<ide><path>spacy/util.py
<ide> def load_model(
<ide> name: Union[str, Path],
<ide> *,
<ide> vocab: Union["Vocab", bool] = True,
<del> disable: Iterable[str] = SimpleFrozenList(),
<del> enable: Iterable[str] = SimpleFrozenList(),
<del> exclude: Iterable[str] = SimpleFrozenList(),
<add> disable: Union[str, Iterable[str]] = SimpleFrozenList(),
<add> enable: Union[str, Iterable[str]] = SimpleFrozenList(),
<add> exclude: Union[str, Iterable[str]] = SimpleFrozenList(),
<ide> config: Union[Dict[str, Any], Config] = SimpleFrozenDict(),
<ide> ) -> "Language":
<ide> """Load a model from a package or data path.
<ide>
<ide> name (str): Package name or model path.
<ide> vocab (Vocab / True): Optional vocab to pass in on initialization. If True,
<ide> a new Vocab object will be created.
<del> disable (Iterable[str]): Names of pipeline components to disable.
<del> enable (Iterable[str]): Names of pipeline components to enable. All others will be disabled.
<del> exclude (Iterable[str]): Names of pipeline components to exclude.
<add> disable (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to disable.
<add> enable (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to enable. All others will be disabled.
<add> exclude (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to exclude.
<ide> config (Dict[str, Any] / Config): Config overrides as nested dict or dict
<ide> keyed by section values in dot notation.
<ide> RETURNS (Language): The loaded nlp object.
<ide> def load_model_from_package(
<ide> name: str,
<ide> *,
<ide> vocab: Union["Vocab", bool] = True,
<del> disable: Iterable[str] = SimpleFrozenList(),
<del> enable: Iterable[str] = SimpleFrozenList(),
<del> exclude: Iterable[str] = SimpleFrozenList(),
<add> disable: Union[str, Iterable[str]] = SimpleFrozenList(),
<add> enable: Union[str, Iterable[str]] = SimpleFrozenList(),
<add> exclude: Union[str, Iterable[str]] = SimpleFrozenList(),
<ide> config: Union[Dict[str, Any], Config] = SimpleFrozenDict(),
<ide> ) -> "Language":
<ide> """Load a model from an installed package.
<ide>
<ide> name (str): The package name.
<ide> vocab (Vocab / True): Optional vocab to pass in on initialization. If True,
<ide> a new Vocab object will be created.
<del> disable (Iterable[str]): Names of pipeline components to disable. Disabled
<add> disable (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to disable. Disabled
<ide> pipes will be loaded but they won't be run unless you explicitly
<ide> enable them by calling nlp.enable_pipe.
<del> enable (Iterable[str]): Names of pipeline components to enable. All other
<add> enable (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to enable. All other
<ide> pipes will be disabled (and can be enabled using `nlp.enable_pipe`).
<del> exclude (Iterable[str]): Names of pipeline components to exclude. Excluded
<add> exclude (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to exclude. Excluded
<ide> components won't be loaded.
<ide> config (Dict[str, Any] / Config): Config overrides as nested dict or dict
<ide> keyed by section values in dot notation.
<ide> def load_model_from_path(
<ide> *,
<ide> meta: Optional[Dict[str, Any]] = None,
<ide> vocab: Union["Vocab", bool] = True,
<del> disable: Iterable[str] = SimpleFrozenList(),
<del> enable: Iterable[str] = SimpleFrozenList(),
<del> exclude: Iterable[str] = SimpleFrozenList(),
<add> disable: Union[str, Iterable[str]] = SimpleFrozenList(),
<add> enable: Union[str, Iterable[str]] = SimpleFrozenList(),
<add> exclude: Union[str, Iterable[str]] = SimpleFrozenList(),
<ide> config: Union[Dict[str, Any], Config] = SimpleFrozenDict(),
<ide> ) -> "Language":
<ide> """Load a model from a data directory path. Creates Language class with
<ide> def load_model_from_path(
<ide> meta (Dict[str, Any]): Optional model meta.
<ide> vocab (Vocab / True): Optional vocab to pass in on initialization. If True,
<ide> a new Vocab object will be created.
<del> disable (Iterable[str]): Names of pipeline components to disable. Disabled
<add> disable (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to disable. Disabled
<ide> pipes will be loaded but they won't be run unless you explicitly
<ide> enable them by calling nlp.enable_pipe.
<del> enable (Iterable[str]): Names of pipeline components to enable. All other
<add> enable (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to enable. All other
<ide> pipes will be disabled (and can be enabled using `nlp.enable_pipe`).
<del> exclude (Iterable[str]): Names of pipeline components to exclude. Excluded
<add> exclude (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to exclude. Excluded
<ide> components won't be loaded.
<ide> config (Dict[str, Any] / Config): Config overrides as nested dict or dict
<ide> keyed by section values in dot notation.
<ide> def load_model_from_config(
<ide> *,
<ide> meta: Dict[str, Any] = SimpleFrozenDict(),
<ide> vocab: Union["Vocab", bool] = True,
<del> disable: Iterable[str] = SimpleFrozenList(),
<del> enable: Iterable[str] = SimpleFrozenList(),
<del> exclude: Iterable[str] = SimpleFrozenList(),
<add> disable: Union[str, Iterable[str]] = SimpleFrozenList(),
<add> enable: Union[str, Iterable[str]] = SimpleFrozenList(),
<add> exclude: Union[str, Iterable[str]] = SimpleFrozenList(),
<ide> auto_fill: bool = False,
<ide> validate: bool = True,
<ide> ) -> "Language":
<ide> def load_model_from_config(
<ide> meta (Dict[str, Any]): Optional model meta.
<ide> vocab (Vocab / True): Optional vocab to pass in on initialization. If True,
<ide> a new Vocab object will be created.
<del> disable (Iterable[str]): Names of pipeline components to disable. Disabled
<add> disable (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to disable. Disabled
<ide> pipes will be loaded but they won't be run unless you explicitly
<ide> enable them by calling nlp.enable_pipe.
<del> enable (Iterable[str]): Names of pipeline components to enable. All other
<add> enable (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to enable. All other
<ide> pipes will be disabled (and can be enabled using `nlp.enable_pipe`).
<del> exclude (Iterable[str]): Names of pipeline components to exclude. Excluded
<add> exclude (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to exclude. Excluded
<ide> components won't be loaded.
<ide> auto_fill (bool): Whether to auto-fill config with missing defaults.
<ide> validate (bool): Whether to show config validation errors.
<ide> def load_model_from_init_py(
<ide> init_file: Union[Path, str],
<ide> *,
<ide> vocab: Union["Vocab", bool] = True,
<del> disable: Iterable[str] = SimpleFrozenList(),
<del> enable: Iterable[str] = SimpleFrozenList(),
<del> exclude: Iterable[str] = SimpleFrozenList(),
<add> disable: Union[str, Iterable[str]] = SimpleFrozenList(),
<add> enable: Union[str, Iterable[str]] = SimpleFrozenList(),
<add> exclude: Union[str, Iterable[str]] = SimpleFrozenList(),
<ide> config: Union[Dict[str, Any], Config] = SimpleFrozenDict(),
<ide> ) -> "Language":
<ide> """Helper function to use in the `load()` method of a model package's
<ide> __init__.py.
<ide>
<ide> vocab (Vocab / True): Optional vocab to pass in on initialization. If True,
<ide> a new Vocab object will be created.
<del> disable (Iterable[str]): Names of pipeline components to disable. Disabled
<add> disable (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to disable. Disabled
<ide> pipes will be loaded but they won't be run unless you explicitly
<ide> enable them by calling nlp.enable_pipe.
<del> enable (Iterable[str]): Names of pipeline components to enable. All other
<add> enable (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to enable. All other
<ide> pipes will be disabled (and can be enabled using `nlp.enable_pipe`).
<del> exclude (Iterable[str]): Names of pipeline components to exclude. Excluded
<add> exclude (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to exclude. Excluded
<ide> components won't be loaded.
<ide> config (Dict[str, Any] / Config): Config overrides as nested dict or dict
<ide> keyed by section values in dot notation.
<ide><path>website/docs/api/language.md
<ide> spaCy loads a model under the hood based on its
<ide> > nlp = Language.from_config(config)
<ide> > ```
<ide>
<del>| Name | Description |
<del>| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
<del>| `config` | The loaded config. ~~Union[Dict[str, Any], Config]~~ |
<del>| _keyword-only_ | |
<del>| `vocab` | A `Vocab` object. If `True`, a vocab is created using the default language data settings. ~~Vocab~~ |
<del>| `disable` | Names of pipeline components to [disable](/usage/processing-pipelines#disabling). Disabled pipes will be loaded but they won't be run unless you explicitly enable them by calling [`nlp.enable_pipe`](/api/language#enable_pipe). ~~List[str]~~ |
<del>| `exclude` | Names of pipeline components to [exclude](/usage/processing-pipelines#disabling). Excluded components won't be loaded. ~~List[str]~~ |
<del>| `meta` | [Meta data](/api/data-formats#meta) overrides. ~~Dict[str, Any]~~ |
<del>| `auto_fill` | Whether to automatically fill in missing values in the config, based on defaults and function argument annotations. Defaults to `True`. ~~bool~~ |
<del>| `validate` | Whether to validate the component config and arguments against the types expected by the factory. Defaults to `True`. ~~bool~~ |
<del>| **RETURNS** | The initialized object. ~~Language~~ |
<add>| Name | Description |
<add>| ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
<add>| `config` | The loaded config. ~~Union[Dict[str, Any], Config]~~ |
<add>| _keyword-only_ | |
<add>| `vocab` | A `Vocab` object. If `True`, a vocab is created using the default language data settings. ~~Vocab~~ |
<add>| `disable` | Name(s) of pipeline component(s) to [disable](/usage/processing-pipelines#disabling). Disabled pipes will be loaded but they won't be run unless you explicitly enable them by calling [`nlp.enable_pipe`](/api/language#enable_pipe). ~~Union[str, Iterable[str]]~~ |
<add>| `enable` <Tag variant="new">3.4</Tag> | Name(s) of pipeline component(s) to [enable](/usage/processing-pipelines#disabling). All other pipes will be disabled, but can be enabled again using [`nlp.enable_pipe`](/api/language#enable_pipe). ~~Union[str, Iterable[str]]~~ |
<add>| `exclude` | Name(s) of pipeline component(s) to [exclude](/usage/processing-pipelines#disabling). Excluded components won't be loaded. ~~Union[str, Iterable[str]]~~ |
<add>| `meta` | [Meta data](/api/data-formats#meta) overrides. ~~Dict[str, Any]~~ |
<add>| `auto_fill` | Whether to automatically fill in missing values in the config, based on defaults and function argument annotations. Defaults to `True`. ~~bool~~ |
<add>| `validate` | Whether to validate the component config and arguments against the types expected by the factory. Defaults to `True`. ~~bool~~ |
<add>| **RETURNS** | The initialized object. ~~Language~~ |
<ide>
<ide> ## Language.component {#component tag="classmethod" new="3"}
<ide>
<ide> As of spaCy v3.0, the `disable_pipes` method has been renamed to `select_pipes`:
<ide> | Name | Description |
<ide> | -------------- | ------------------------------------------------------------------------------------------------------ |
<ide> | _keyword-only_ | |
<del>| `disable` | Name(s) of pipeline components to disable. ~~Optional[Union[str, Iterable[str]]]~~ |
<del>| `enable` | Name(s) of pipeline components that will not be disabled. ~~Optional[Union[str, Iterable[str]]]~~ |
<add>| `disable` | Name(s) of pipeline component(s) to disable. ~~Optional[Union[str, Iterable[str]]]~~ |
<add>| `enable` | Name(s) of pipeline component(s) that will not be disabled. ~~Optional[Union[str, Iterable[str]]]~~ |
<ide> | **RETURNS** | The disabled pipes that can be restored by calling the object's `.restore()` method. ~~DisabledPipes~~ |
<ide>
<ide> ## Language.get_factory_meta {#get_factory_meta tag="classmethod" new="3"}
<ide><path>website/docs/api/top-level.md
<ide> specified separately using the new `exclude` keyword argument.
<ide> > nlp = spacy.load("en_core_web_sm", exclude=["parser", "tagger"])
<ide> > ```
<ide>
<del>| Name | Description |
<del>| ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
<del>| `name` | Pipeline to load, i.e. package name or path. ~~Union[str, Path]~~ |
<del>| _keyword-only_ | |
<del>| `vocab` | Optional shared vocab to pass in on initialization. If `True` (default), a new `Vocab` object will be created. ~~Union[Vocab, bool]~~ |
<del>| `disable` | Names of pipeline components to [disable](/usage/processing-pipelines#disabling). Disabled pipes will be loaded but they won't be run unless you explicitly enable them by calling [nlp.enable_pipe](/api/language#enable_pipe). ~~List[str]~~ |
<del>| `enable` | Names of pipeline components to [enable](/usage/processing-pipelines#disabling). All other pipes will be disabled. ~~List[str]~~ |
<del>| `exclude` <Tag variant="new">3</Tag> | Names of pipeline components to [exclude](/usage/processing-pipelines#disabling). Excluded components won't be loaded. ~~List[str]~~ |
<del>| `config` <Tag variant="new">3</Tag> | Optional config overrides, either as nested dict or dict keyed by section value in dot notation, e.g. `"components.name.value"`. ~~Union[Dict[str, Any], Config]~~ |
<del>| **RETURNS** | A `Language` object with the loaded pipeline. ~~Language~~ |
<add>| Name | Description |
<add>| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
<add>| `name` | Pipeline to load, i.e. package name or path. ~~Union[str, Path]~~ |
<add>| _keyword-only_ | |
<add>| `vocab` | Optional shared vocab to pass in on initialization. If `True` (default), a new `Vocab` object will be created. ~~Union[Vocab, bool]~~ |
<add>| `disable` | Name(s) of pipeline component(s) to [disable](/usage/processing-pipelines#disabling). Disabled pipes will be loaded but they won't be run unless you explicitly enable them by calling [nlp.enable_pipe](/api/language#enable_pipe). ~~Union[str, Iterable[str]]~~ |
<add>| `enable` <Tag variant="new">3.4</Tag> | Name(s) of pipeline component(s) to [enable](/usage/processing-pipelines#disabling). All other pipes will be disabled. ~~Union[str, Iterable[str]]~~ |
<add>| `exclude` <Tag variant="new">3</Tag> | Name(s) of pipeline component(s) to [exclude](/usage/processing-pipelines#disabling). Excluded components won't be loaded. ~~Union[str, Iterable[str]]~~ |
<add>| `config` <Tag variant="new">3</Tag> | Optional config overrides, either as nested dict or dict keyed by section value in dot notation, e.g. `"components.name.value"`. ~~Union[Dict[str, Any], Config]~~ |
<add>| **RETURNS** | A `Language` object with the loaded pipeline. ~~Language~~ |
<ide>
<ide> Essentially, `spacy.load()` is a convenience wrapper that reads the pipeline's
<ide> [`config.cfg`](/api/data-formats#config), uses the language and pipeline
<ide> and create a `Language` object. The model data will then be loaded in via
<ide> > nlp = util.load_model("/path/to/data")
<ide> > ```
<ide>
<del>| Name | Description |
<del>| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
<del>| `name` | Package name or path. ~~str~~ |
<del>| _keyword-only_ | |
<del>| `vocab` | Optional shared vocab to pass in on initialization. If `True` (default), a new `Vocab` object will be created. ~~Union[Vocab, bool]~~ |
<del>| `disable` | Names of pipeline components to [disable](/usage/processing-pipelines#disabling). Disabled pipes will be loaded but they won't be run unless you explicitly enable them by calling [`nlp.enable_pipe`](/api/language#enable_pipe). ~~List[str]~~ |
<del>| `exclude` <Tag variant="new">3</Tag> | Names of pipeline components to [exclude](/usage/processing-pipelines#disabling). Excluded components won't be loaded. ~~List[str]~~ |
<del>| `config` <Tag variant="new">3</Tag> | Config overrides as nested dict or flat dict keyed by section values in dot notation, e.g. `"nlp.pipeline"`. ~~Union[Dict[str, Any], Config]~~ |
<del>| **RETURNS** | `Language` class with the loaded pipeline. ~~Language~~ |
<add>| Name | Description |
<add>| ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
<add>| `name` | Package name or path. ~~str~~ |
<add>| _keyword-only_ | |
<add>| `vocab` | Optional shared vocab to pass in on initialization. If `True` (default), a new `Vocab` object will be created. ~~Union[Vocab, bool]~~ |
<add>| `disable` | Name(s) of pipeline component(s) to [disable](/usage/processing-pipelines#disabling). Disabled pipes will be loaded but they won't be run unless you explicitly enable them by calling [`nlp.enable_pipe`](/api/language#enable_pipe). ~~Union[str, Iterable[str]]~~ |
<add>| `enable` <Tag variant="new">3.4</Tag> | Name(s) of pipeline component(s) to [enable](/usage/processing-pipelines#disabling). All other pipes will be disabled, but can be enabled again using [`nlp.enable_pipe`](/api/language#enable_pipe). ~~Union[str, Iterable[str]]~~ |
<add>| `exclude` | Name(s) of pipeline component(s) to [exclude](/usage/processing-pipelines#disabling). Excluded components won't be loaded. ~~Union[str, Iterable[str]]~~ |
<add>| `config` <Tag variant="new">3</Tag> | Config overrides as nested dict or flat dict keyed by section values in dot notation, e.g. `"nlp.pipeline"`. ~~Union[Dict[str, Any], Config]~~ |
<add>| **RETURNS** | `Language` class with the loaded pipeline. ~~Language~~ |
<ide>
<ide> ### util.load_model_from_init_py {#util.load_model_from_init_py tag="function" new="2"}
<ide>
<ide> A helper function to use in the `load()` method of a pipeline package's
<ide> > return load_model_from_init_py(__file__, **overrides)
<ide> > ```
<ide>
<del>| Name | Description |
<del>| ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
<del>| `init_file` | Path to package's `__init__.py`, i.e. `__file__`. ~~Union[str, Path]~~ |
<del>| _keyword-only_ | |
<del>| `vocab` <Tag variant="new">3</Tag> | Optional shared vocab to pass in on initialization. If `True` (default), a new `Vocab` object will be created. ~~Union[Vocab, bool]~~ |
<del>| `disable` | Names of pipeline components to [disable](/usage/processing-pipelines#disabling). Disabled pipes will be loaded but they won't be run unless you explicitly enable them by calling [nlp.enable_pipe](/api/language#enable_pipe). ~~List[str]~~ |
<del>| `exclude` <Tag variant="new">3</Tag> | Names of pipeline components to [exclude](/usage/processing-pipelines#disabling). Excluded components won't be loaded. ~~List[str]~~ |
<del>| `config` <Tag variant="new">3</Tag> | Config overrides as nested dict or flat dict keyed by section values in dot notation, e.g. `"nlp.pipeline"`. ~~Union[Dict[str, Any], Config]~~ |
<del>| **RETURNS** | `Language` class with the loaded pipeline. ~~Language~~ |
<add>| Name | Description |
<add>| ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
<add>| `init_file` | Path to package's `__init__.py`, i.e. `__file__`. ~~Union[str, Path]~~ |
<add>| _keyword-only_ | |
<add>| `vocab` <Tag variant="new">3</Tag> | Optional shared vocab to pass in on initialization. If `True` (default), a new `Vocab` object will be created. ~~Union[Vocab, bool]~~ |
<add>| `disable` | Name(s) of pipeline component(s) to [disable](/usage/processing-pipelines#disabling). Disabled pipes will be loaded but they won't be run unless you explicitly enable them by calling [`nlp.enable_pipe`](/api/language#enable_pipe). ~~Union[str, Iterable[str]]~~ |
<add>| `enable` <Tag variant="new">3.4</Tag> | Name(s) of pipeline component(s) to [enable](/usage/processing-pipelines#disabling). All other pipes will be disabled, but can be enabled again using [`nlp.enable_pipe`](/api/language#enable_pipe). ~~Union[str, Iterable[str]]~~ |
<add>| `exclude` <Tag variant="new">3</Tag> | Name(s) of pipeline component(s) to [exclude](/usage/processing-pipelines#disabling). Excluded components won't be loaded. ~~Union[str, Iterable[str]]~~ |
<add>| `config` <Tag variant="new">3</Tag> | Config overrides as nested dict or flat dict keyed by section values in dot notation, e.g. `"nlp.pipeline"`. ~~Union[Dict[str, Any], Config]~~ |
<add>| **RETURNS** | `Language` class with the loaded pipeline. ~~Language~~ |
<ide>
<ide> ### util.load_config {#util.load_config tag="function" new="3"}
<ide> | 6 |
Ruby | Ruby | use tap object | 70d31838c61b0aaeb76827b26cb461069c9dff8c | <ide><path>Library/Homebrew/cmd/test-bot.rb
<ide> module Homebrew
<ide> EMAIL_SUBJECT_FILE = "brew-test-bot.#{MacOS.cat}.email.txt"
<ide> BYTES_IN_1_MEGABYTE = 1024*1024
<ide>
<add> def resolve_test_tap
<add> tap = ARGV.value("tap")
<add> return Tap.new(*tap_args(tap)) if tap
<add>
<add> if ENV["UPSTREAM_BOT_PARAMS"]
<add> bot_argv = ENV["UPSTREAM_BOT_PARAMS"].split " "
<add> bot_argv.extend HomebrewArgvExtension
<add> tap = bot_argv.value("tap")
<add> return Tap.new(*tap_args(tap)) if tap
<add> end
<add>
<add> if git_url = ENV["UPSTREAM_GIT_URL"] || ENV["GIT_URL"]
<add> # Also can get tap from Jenkins GIT_URL.
<add> url_path = git_url.sub(%r{^https?://github\.com/}, "").chomp("/")
<add> HOMEBREW_TAP_ARGS_REGEX =~ url_path
<add> return Tap.new($1, $3) if $1 && $3 && $3 != "homebrew"
<add> end
<add>
<add> # return nil means we are testing core repo.
<add> end
<add>
<ide> def homebrew_git_repo(tap = nil)
<ide> if tap
<del> user, repo = tap.split "/"
<del> HOMEBREW_LIBRARY/"Taps/#{user}/homebrew-#{repo}"
<add> tap.path
<ide> else
<ide> HOMEBREW_REPOSITORY
<ide> end
<ide> def homebrew
<ide> return if @skip_homebrew
<ide> test "brew", "tests"
<ide> if @tap
<del> test "brew", "readall", @tap
<add> test "brew", "readall", @tap.name
<ide> else
<ide> test "brew", "tests", "--no-compat"
<ide> readall_args = ["--aliases"]
<ide> def formulae
<ide> end
<ide>
<ide> def head_only_tap?(formula)
<del> formula.head && formula.devel.nil? && formula.stable.nil? && formula.tap == "homebrew/homebrew-head-only"
<add> formula.head && formula.devel.nil? && formula.stable.nil? && formula.tap.name == "homebrew/head-only"
<ide> end
<ide>
<ide> def devel_only_tap?(formula)
<del> formula.devel && formula.stable.nil? && formula.tap == "homebrew/homebrew-devel-only"
<add> formula.devel && formula.stable.nil? && formula.tap.name == "homebrew/devel-only"
<ide> end
<ide>
<ide> def run
<ide> def test_bot_ci_reset_and_update
<ide> end
<ide>
<ide> def test_bot
<del> tap = ARGV.value("tap")
<del>
<del> if !tap && ENV["UPSTREAM_BOT_PARAMS"]
<del> bot_argv = ENV["UPSTREAM_BOT_PARAMS"].split " "
<del> bot_argv.extend HomebrewArgvExtension
<del> tap ||= bot_argv.value("tap")
<del> end
<del>
<del> tap.gsub!(/homebrew\/homebrew-/i, "Homebrew/") if tap
<del>
<del> git_url = ENV["UPSTREAM_GIT_URL"] || ENV["GIT_URL"]
<del> if !tap && git_url
<del> # Also can get tap from Jenkins GIT_URL.
<del> url_path = git_url.gsub(%r{^https?://github\.com/}, "").gsub(%r{/$}, "")
<del> HOMEBREW_TAP_ARGS_REGEX =~ url_path
<del> tap = "#{$1}/#{$3}" if $1 && $3
<del> end
<add> tap = resolve_test_tap
<add> repository = Homebrew.homebrew_git_repo tap
<ide>
<ide> if Pathname.pwd == HOMEBREW_PREFIX && ARGV.include?("--cleanup")
<ide> odie "cannot use --cleanup from HOMEBREW_PREFIX as it will delete all output."
<ide> def test_bot
<ide>
<ide> test_bot_ci_reset_and_update if ARGV.include? "--ci-reset-and-update"
<ide>
<del> repository = Homebrew.homebrew_git_repo tap
<del>
<ide> # Tap repository if required, this is done before everything else
<ide> # because Formula parsing and/or git commit hash lookup depends on it.
<del> if tap && !repository.directory?
<del> safe_system "brew", "tap", tap
<add> if tap && !tap.installed?
<add> safe_system "brew", "tap", tap.name
<ide> end
<ide>
<ide> if ARGV.include? "--ci-upload"
<ide> def test_bot
<ide>
<ide> if pr
<ide> pull_pr = if tap
<del> user, repo = tap.split "/"
<del> "https://github.com/#{user}/homebrew-#{repo}/pull/#{pr}"
<add> "https://github.com/#{tap.user}/homebrew-#{tap.repo}/pull/#{pr}"
<ide> else
<ide> pr
<ide> end
<ide> def test_bot
<ide> bottle_args << "--keep-old" if ARGV.include? "--keep-old"
<ide> safe_system "brew", "bottle", *bottle_args
<ide>
<del> remote_repo = tap ? tap.tr("/", "-") : "homebrew"
<del>
<add> remote_repo = tap ? "homebrew-#{tap.repo}" : "homebrew"
<ide> remote = "[email protected]:BrewTestBot/#{remote_repo}.git"
<ide> tag = pr ? "pr-#{pr}" : "testing-#{number}"
<ide> safe_system "git", "push", "--force", remote, "master:master", ":refs/tags/#{tag}"
<ide>
<del> bintray_repo = Bintray.repository(tap)
<add> bintray_repo = Bintray.repository(tap.name)
<ide> bintray_repo_url = "https://api.bintray.com/packages/homebrew/#{bintray_repo}"
<ide> formula_packaged = {}
<ide> | 1 |
Python | Python | add type hinting for mongo provider | 46cdb0e08045f84029ac727cbaf6040acd592810 | <ide><path>airflow/providers/mongo/hooks/mongo.py
<ide> # under the License.
<ide> """Hook for Mongo DB"""
<ide> from ssl import CERT_NONE
<add>from types import TracebackType
<add>from typing import List, Optional, Type
<ide>
<add>import pymongo
<ide> from pymongo import MongoClient, ReplaceOne
<ide>
<ide> from airflow.hooks.base_hook import BaseHook
<ide> class MongoHook(BaseHook):
<ide> """
<ide> conn_type = 'mongo'
<ide>
<del> def __init__(self, conn_id='mongo_default', *args, **kwargs):
<add> def __init__(self, conn_id: str = 'mongo_default', *args, **kwargs) -> None:
<ide>
<ide> super().__init__()
<ide> self.mongo_conn_id = conn_id
<ide> def __init__(self, conn_id='mongo_default', *args, **kwargs):
<ide> def __enter__(self):
<ide> return self
<ide>
<del> def __exit__(self, exc_type, exc_val, exc_tb):
<add> def __exit__(self,
<add> exc_type: Optional[Type[BaseException]],
<add> exc_val: Optional[BaseException],
<add> exc_tb: Optional[TracebackType]) -> None:
<ide> if self.client is not None:
<ide> self.close_conn()
<ide>
<del> def get_conn(self):
<add> def get_conn(self) -> MongoClient:
<ide> """
<ide> Fetches PyMongo Client
<ide> """
<ide> def close_conn(self) -> None:
<ide> client.close()
<ide> self.client = None
<ide>
<del> def get_collection(self, mongo_collection, mongo_db=None):
<add> def get_collection(self,
<add> mongo_collection: str,
<add> mongo_db: Optional[str] = None) -> pymongo.collection.Collection:
<ide> """
<ide> Fetches a mongo collection object for querying.
<ide>
<ide> Uses connection schema as DB unless specified.
<ide> """
<ide> mongo_db = mongo_db if mongo_db is not None else self.connection.schema
<del> mongo_conn = self.get_conn()
<add> mongo_conn: MongoClient = self.get_conn()
<ide>
<ide> return mongo_conn.get_database(mongo_db).get_collection(mongo_collection)
<ide>
<del> def aggregate(self, mongo_collection, aggregate_query, mongo_db=None, **kwargs):
<add> def aggregate(self,
<add> mongo_collection: str,
<add> aggregate_query: list,
<add> mongo_db: Optional[str] = None,
<add> **kwargs) -> pymongo.command_cursor.CommandCursor:
<ide> """
<ide> Runs an aggregation pipeline and returns the results
<ide> https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.aggregate
<ide> def aggregate(self, mongo_collection, aggregate_query, mongo_db=None, **kwargs):
<ide>
<ide> return collection.aggregate(aggregate_query, **kwargs)
<ide>
<del> def find(self, mongo_collection, query, find_one=False, mongo_db=None, **kwargs):
<add> def find(self,
<add> mongo_collection: str,
<add> query: dict,
<add> find_one: bool = False,
<add> mongo_db: Optional[str] = None,
<add> **kwargs) -> pymongo.cursor.Cursor:
<ide> """
<ide> Runs a mongo find query and returns the results
<ide> https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find
<ide> def find(self, mongo_collection, query, find_one=False, mongo_db=None, **kwargs)
<ide> else:
<ide> return collection.find(query, **kwargs)
<ide>
<del> def insert_one(self, mongo_collection, doc, mongo_db=None, **kwargs):
<add> def insert_one(self,
<add> mongo_collection: str,
<add> doc: dict,
<add> mongo_db: Optional[str] = None,
<add> **kwargs) -> pymongo.results.InsertOneResult:
<ide> """
<ide> Inserts a single document into a mongo collection
<ide> https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_one
<ide> def insert_one(self, mongo_collection, doc, mongo_db=None, **kwargs):
<ide>
<ide> return collection.insert_one(doc, **kwargs)
<ide>
<del> def insert_many(self, mongo_collection, docs, mongo_db=None, **kwargs):
<add> def insert_many(self,
<add> mongo_collection: str,
<add> docs: dict,
<add> mongo_db: Optional[str] = None,
<add> **kwargs) -> pymongo.results.InsertManyResult:
<ide> """
<ide> Inserts many docs into a mongo collection.
<ide> https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_many
<ide> def insert_many(self, mongo_collection, docs, mongo_db=None, **kwargs):
<ide>
<ide> return collection.insert_many(docs, **kwargs)
<ide>
<del> def update_one(self, mongo_collection, filter_doc, update_doc,
<del> mongo_db=None, **kwargs):
<add> def update_one(self,
<add> mongo_collection: str,
<add> filter_doc: dict,
<add> update_doc: dict,
<add> mongo_db: Optional[str] = None,
<add> **kwargs) -> pymongo.results.UpdateResult:
<ide> """
<ide> Updates a single document in a mongo collection.
<ide> https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_one
<ide> def update_one(self, mongo_collection, filter_doc, update_doc,
<ide>
<ide> return collection.update_one(filter_doc, update_doc, **kwargs)
<ide>
<del> def update_many(self, mongo_collection, filter_doc, update_doc,
<del> mongo_db=None, **kwargs):
<add> def update_many(self,
<add> mongo_collection: str,
<add> filter_doc: dict,
<add> update_doc: dict,
<add> mongo_db: Optional[str] = None,
<add> **kwargs) -> pymongo.results.UpdateResult:
<ide> """
<ide> Updates one or more documents in a mongo collection.
<ide> https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_many
<ide> def update_many(self, mongo_collection, filter_doc, update_doc,
<ide>
<ide> return collection.update_many(filter_doc, update_doc, **kwargs)
<ide>
<del> def replace_one(self, mongo_collection, doc, filter_doc=None,
<del> mongo_db=None, **kwargs):
<add> def replace_one(self,
<add> mongo_collection: str,
<add> doc: dict,
<add> filter_doc: Optional[dict] = None,
<add> mongo_db: Optional[str] = None,
<add> **kwargs) -> pymongo.results.UpdateResult:
<ide> """
<ide> Replaces a single document in a mongo collection.
<ide> https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.replace_one
<ide> def replace_one(self, mongo_collection, doc, filter_doc=None,
<ide>
<ide> return collection.replace_one(filter_doc, doc, **kwargs)
<ide>
<del> def replace_many(self, mongo_collection, docs,
<del> filter_docs=None, mongo_db=None, upsert=False, collation=None,
<del> **kwargs):
<add> def replace_many(self,
<add> mongo_collection: str,
<add> docs: List[dict],
<add> filter_docs: Optional[List[dict]] = None,
<add> mongo_db: Optional[str] = None,
<add> upsert: bool = False,
<add> collation: Optional[pymongo.collation.Collation] = None,
<add> **kwargs) -> pymongo.results.BulkWriteResult:
<ide> """
<ide> Replaces many documents in a mongo collection.
<ide>
<ide> def replace_many(self, mongo_collection, docs,
<ide>
<ide> return collection.bulk_write(requests, **kwargs)
<ide>
<del> def delete_one(self, mongo_collection, filter_doc, mongo_db=None, **kwargs):
<add> def delete_one(self,
<add> mongo_collection: str,
<add> filter_doc: dict,
<add> mongo_db: Optional[str] = None,
<add> **kwargs) -> pymongo.results.DeleteResult:
<ide> """
<ide> Deletes a single document in a mongo collection.
<ide> https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.delete_one
<ide> def delete_one(self, mongo_collection, filter_doc, mongo_db=None, **kwargs):
<ide>
<ide> return collection.delete_one(filter_doc, **kwargs)
<ide>
<del> def delete_many(self, mongo_collection, filter_doc, mongo_db=None, **kwargs):
<add> def delete_many(self,
<add> mongo_collection: str,
<add> filter_doc: dict,
<add> mongo_db: Optional[str] = None,
<add> **kwargs) -> pymongo.results.DeleteResult:
<ide> """
<ide> Deletes one or more documents in a mongo collection.
<ide> https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.delete_many
<ide><path>airflow/providers/mongo/sensors/mongo.py
<ide> class MongoSensor(BaseSensorOperator):
<ide> template_fields = ('collection', 'query')
<ide>
<ide> @apply_defaults
<del> def __init__(self, collection, query, mongo_conn_id="mongo_default", *args, **kwargs):
<add> def __init__(self,
<add> collection: str,
<add> query: dict,
<add> mongo_conn_id: str = "mongo_default",
<add> *args,
<add> **kwargs) -> None:
<ide> super().__init__(*args, **kwargs)
<ide> self.mongo_conn_id = mongo_conn_id
<ide> self.collection = collection
<ide> self.query = query
<ide>
<del> def poke(self, context):
<add> def poke(self, context: dict) -> bool:
<ide> self.log.info("Sensor check existence of the document "
<ide> "that matches the following query: %s", self.query)
<ide> hook = MongoHook(self.mongo_conn_id) | 2 |
Javascript | Javascript | avoid race enabling debugger in worker | 4dd22b946ebfec81a7c4a61aa9c6ed528e317802 | <ide><path>lib/cluster.js
<ide> function masterInit() {
<ide> var key;
<ide> for (key in cluster.workers) {
<ide> var worker = cluster.workers[key];
<del> if (worker.state === 'online') {
<add> if (worker.state === 'online' || worker.state === 'listening') {
<ide> process._debugProcess(worker.process.pid);
<ide> } else {
<ide> worker.once('online', function() { | 1 |
Ruby | Ruby | fix preventing_writes for granular swapping | b92dc5b01cfbbb44d6625e933e3a2167f61d077e | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
<ide> class NullPool # :nodoc:
<ide> include ConnectionAdapters::AbstractPool
<ide>
<ide> attr_accessor :schema_cache
<add>
<add> def owner_name
<add> nil
<add> end
<ide> end
<ide>
<ide> # Connection pool base class for managing Active Record database
<ide> def run
<ide> include ConnectionAdapters::AbstractPool
<ide>
<ide> attr_accessor :automatic_reconnect, :checkout_timeout
<del> attr_reader :db_config, :size, :reaper, :pool_config
<add> attr_reader :db_config, :size, :reaper, :pool_config, :owner_name
<ide>
<ide> delegate :schema_cache, :schema_cache=, to: :pool_config
<ide>
<ide> def initialize(pool_config)
<ide>
<ide> @pool_config = pool_config
<ide> @db_config = pool_config.db_config
<add> @owner_name = pool_config.connection_specification_name
<ide>
<ide> @checkout_timeout = db_config.checkout_timeout
<ide> @idle_timeout = db_config.idle_timeout
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
<ide> def use_metadata_table?
<ide>
<ide> # Determines whether writes are currently being prevents.
<ide> #
<del> # Returns true if the connection is a replica, or if +prevent_writes+
<del> # is set to true.
<add> # Returns true if the connection is a replica.
<add> #
<add> # If the application is using legacy handling, returns
<add> # true if `connection_handler.prevent_writes` is set.
<add> #
<add> # If the application is using the new connection handling
<add> # will return true based on `current_preventing_writes`.
<ide> def preventing_writes?
<del> if ActiveRecord::Base.legacy_connection_handling
<del> replica? || ActiveRecord::Base.connection_handler.prevent_writes
<del> else
<del> replica? || ActiveRecord::Base.current_preventing_writes
<del> end
<add> return true if replica?
<add> return ActiveRecord::Base.connection_handler.prevent_writes if ActiveRecord::Base.legacy_connection_handling
<add> return false if owner_name.nil?
<add>
<add> klass = self.owner_name.safe_constantize
<add> klass&.current_preventing_writes
<ide> end
<ide>
<ide> def migrations_paths # :nodoc:
<ide> def lease
<ide> @owner = Thread.current
<ide> end
<ide>
<add> def owner_name # :nodoc:
<add> @pool.owner_name
<add> end
<add>
<ide> def schema_cache
<ide> @pool.get_schema_cache(self)
<ide> end
<ide><path>activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_prevent_writes_test.rb
<ide> class SQLite3AdapterPreventWritesTest < ActiveRecord::SQLite3TestCase
<ide> self.use_transactional_tests = false
<ide>
<ide> def setup
<del> @conn = Base.sqlite3_connection database: ":memory:",
<del> adapter: "sqlite3",
<del> timeout: 100
<add> @conn = ActiveRecord::Base.connection
<ide> end
<ide>
<ide> def test_errors_when_an_insert_query_is_called_while_preventing_writes
<ide> def setup
<ide> @old_value = ActiveRecord::Base.legacy_connection_handling
<ide> ActiveRecord::Base.legacy_connection_handling = true
<ide>
<del> @conn = Base.sqlite3_connection database: ":memory:",
<del> adapter: "sqlite3",
<del> timeout: 100
<add> @conn = ActiveRecord::Base.connection
<ide>
<ide> @connection_handler = ActiveRecord::Base.connection_handler
<ide> end
<ide><path>activerecord/test/cases/connection_adapters/connection_swapping_nested_test.rb
<ide> def test_connected_to_many
<ide> ActiveRecord::Base.establish_connection(:arunit)
<ide> ENV["RAILS_ENV"] = previous_env
<ide> end
<add>
<add> def test_prevent_writes_can_be_changed_granularly
<add> previous_env, ENV["RAILS_ENV"] = ENV["RAILS_ENV"], "default_env"
<add>
<add> # replica: true is purposefully left out so we can test the pools behavior
<add> config = {
<add> "default_env" => {
<add> "primary" => { "adapter" => "sqlite3", "database" => "test/db/primary.sqlite3" },
<add> "primary_replica" => { "adapter" => "sqlite3", "database" => "test/db/primary.sqlite3" },
<add> "secondary" => { "adapter" => "sqlite3", "database" => "test/db/secondary.sqlite3" },
<add> "secondary_replica" => { "adapter" => "sqlite3", "database" => "test/db/secondary_replica.sqlite3" }
<add> }
<add> }
<add>
<add> @prev_configs, ActiveRecord::Base.configurations = ActiveRecord::Base.configurations, config
<add>
<add> PrimaryBase.connects_to database: { writing: :primary, reading: :primary_replica }
<add> SecondaryBase.connects_to database: { writing: :secondary, reading: :secondary_replica }
<add>
<add> # Switch everything to writing
<add> ActiveRecord::Base.connected_to(role: :writing) do
<add> assert_not_predicate ActiveRecord::Base.connection, :preventing_writes?
<add> assert_not_predicate PrimaryBase.connection, :preventing_writes?
<add> assert_not_predicate SecondaryBase.connection, :preventing_writes?
<add>
<add> # Switch only primary to reading
<add> PrimaryBase.connected_to(role: :reading) do
<add> assert_predicate PrimaryBase.connection, :preventing_writes?
<add> assert_not_predicate SecondaryBase.connection, :preventing_writes?
<add>
<add> # Switch global to reading
<add> ActiveRecord::Base.connected_to(role: :reading) do
<add> assert_predicate PrimaryBase.connection, :preventing_writes?
<add> assert_predicate SecondaryBase.connection, :preventing_writes?
<add>
<add> # Switch only secondary to writing
<add> SecondaryBase.connected_to(role: :writing) do
<add> assert_predicate PrimaryBase.connection, :preventing_writes?
<add> assert_not_predicate SecondaryBase.connection, :preventing_writes?
<add> end
<add>
<add> # Ensure restored to global reading
<add> assert_predicate PrimaryBase.connection, :preventing_writes?
<add> assert_predicate SecondaryBase.connection, :preventing_writes?
<add> end
<add>
<add> # Switch everything to writing
<add> ActiveRecord::Base.connected_to(role: :writing) do
<add> assert_not_predicate PrimaryBase.connection, :preventing_writes?
<add> assert_not_predicate SecondaryBase.connection, :preventing_writes?
<add> end
<add>
<add> assert_predicate PrimaryBase.connection, :preventing_writes?
<add> assert_not_predicate SecondaryBase.connection, :preventing_writes?
<add> end
<add>
<add> # Ensure restored to global writing
<add> assert_not_predicate PrimaryBase.connection, :preventing_writes?
<add> assert_not_predicate SecondaryBase.connection, :preventing_writes?
<add> end
<add> ensure
<add> ActiveRecord::Base.configurations = @prev_configs
<add> ActiveRecord::Base.establish_connection(:arunit)
<add> ENV["RAILS_ENV"] = previous_env
<add> end
<ide> end
<ide> end
<ide> end | 4 |
Text | Text | update releases.md with new changelog structure | 118162ee67b8111231aeb523f1843ddda5d3828d | <ide><path>doc/releases.md
<ide> The general rule is to bump this version when there are _breaking ABI_ changes a
<ide>
<ide> **Note** that it is current TSC policy to bump major version when ABI changes. If you see a need to bump `NODE_MODULE_VERSION` then you should consult the TSC. Commits may need to be reverted or a major version bump may need to happen.
<ide>
<del>### 3. Update `CHANGELOG.md`
<add>### 3. Update the Changelog
<add>
<add>#### Step 1: Collecting the formatted list of changes:
<ide>
<ide> Collect a formatted list of commits since the last release. Use [`changelog-maker`](https://github.com/rvagg/changelog-maker) to do this.
<ide>
<ide> Note that changelog-maker counts commits since the last tag and if the last tag
<ide> $ changelog-maker --group --start-ref v2.3.1
<ide> ```
<ide>
<del>The `CHANGELOG.md` entry should take the following form:
<add>#### Step 2: Update the appropriate doc/changelogs/CHANGELOG_*.md file
<add>
<add>There is a separate `CHANGELOG_*.md` file for each major Node.js release line.
<add>These are located in the `doc/changelogs/` directory. Once the formatted list
<add>of changes is collected, it must be added to the top of the relevant changelog
<add>file in the release branch (e.g. a release for Node.js v4 would be added to the
<add>`/doc/changelogs/CHANGELOG_V4.md`).
<add>
<add>**Please do *not* add the changelog entries to the root `CHANGELOG.md` file.**
<add>
<add>The new entry should take the following form:
<ide>
<ide> ```
<add><a id="x.y.x></a>"
<ide> ## YYYY-MM-DD, Version x.y.z (Release Type), @releaser
<ide>
<ide> ### Notable changes
<ide> The `CHANGELOG.md` entry should take the following form:
<ide> * Also be sure to look at any changes introduced by dependencies such as npm
<ide> * ... and include any notable items from there
<ide>
<del>### Known issues
<del>
<del>See https://github.com/nodejs/node/labels/confirmed-bug for complete and current list of known issues.
<del>
<del>* Include this section if there are any known problems with this release
<del>* Scan GitHub for unresolved problems that users may need to be aware of
<del>
<ide> ### Commits
<ide>
<ide> * Include the full list of commits since the last release here. Do not include "Working on X.Y.Z+1" commits.
<ide> ```
<ide>
<ide> The release type should be either Current, LTS, or Maintenance, depending on the type of release being produced.
<ide>
<add>At the top of each `CHANGELOG_*.md` file, and in the root `CHANGELOG.md` file,
<add>there is a table indexing all releases in each major release line. A link to
<add>the new release needs to be added to each. Follow the existing examples and be
<add>sure to add the release to the *top* of the list.
<add>
<add>In the root `CHANGELOG.md` file, the most recent release for each release line
<add>is shown in **bold** in the index. When updating the index, please make sure
<add>to update the display accordingly by removing the bold styling from the previous
<add>release.
<add>
<ide> ### 4. Create Release Commit
<ide>
<del>The `CHANGELOG.md` and `src/node_version.h` changes should be the final commit that will be tagged for the release. When committing these to git, use the following message format:
<add>The `CHANGELOG.md`, `doc/changelogs/CHANGELOG_*.md`, and `src/node_version.h`
<add>changes should be the final commit that will be tagged for the release. When
<add>committing these to git, use the following message format:
<ide>
<ide> ```
<ide> YYYY-MM-DD, Version x.y.z (Release Type) | 1 |
Javascript | Javascript | add broken test passing a buffer through http | 0a0e90dcca1642849ffa8b8cee4ad9b8f15c0fc1 | <ide><path>test/simple/test-http-buffer-sanity.js
<add>var common = require('../common');
<add>var assert = require('assert');
<add>var http = require('http');
<add>var sys = require('sys');
<add>
<add>var bufferSize = 5 * 1024 * 1024;
<add>var measuredSize = 0;
<add>
<add>var buffer = Buffer(bufferSize);
<add>for (var i = 0; i < buffer.length; i++) {
<add> buffer[i] = i % 256;
<add>}
<add>
<add>
<add>var web = http.Server(function (req, res) {
<add> web.close();
<add>
<add> console.log(req.headers);
<add>
<add> var i = 0;
<add>
<add> req.on('data', function (d) {
<add> process.stdout.write(",");
<add> measuredSize += d.length;
<add> for (var j = 0; j < d.length; j++) {
<add> assert.equal(buffer[i], d[j]);
<add> i++;
<add> }
<add> });
<add>
<add>
<add> req.on('end', function () {
<add> res.writeHead(200);
<add> res.write("thanks");
<add> res.end();
<add> console.log("response with 'thanks'");
<add> });
<add>
<add> req.connection.on('error', function (e) {
<add> console.log("http server-side error: " + e.message);
<add> process.exit(1);
<add> });
<add>});
<add>
<add>web.listen(common.PORT, function () {
<add> console.log("Making request");
<add>
<add> var client = http.createClient(common.PORT);
<add> var req = client.request('GET', '/', { 'content-length': buffer.length });
<add> req.end(buffer);
<add>
<add> req.on('response', function (res) {
<add> console.log('Got response');
<add> res.setEncoding('utf8');
<add> res.on('data', function (string) {
<add> assert.equal("thanks", string);
<add> gotThanks = true;
<add> });
<add> });
<add>});
<add>
<add>
<add>process.on('exit', function () {
<add> assert.equal(bufferSize, measuredSize);
<add>}); | 1 |
Text | Text | provide link to s3 documentation | 9fc62ea21aa1c6dd979d10677b92e8ad5d93c4dc | <ide><path>client/src/pages/guide/english/miscellaneous/guide-to-store-media-files-of-django-app-to-aws-s3/index.md
<ide> title: Django-file-storage
<ide> ---
<ide> ## Django Media Files and Static files Storage
<ide>
<del>#### Steps to create AWS S3 Bucket
<add>#### Steps to create AWS S3 Bucket (More information on S3 [Visit Here!](https://docs.aws.amazon.com/AmazonS3/latest/gsg/GetStartedWithS3.html))
<ide>
<ide> * Open aws console and create IAM user for S3 bucket
<ide> * In services select S3
<del>* Create new S3 buket in S3 console
<add>* Create new S3 bucket in S3 console
<ide>
<ide> #### Steps to do in django app
<ide>
<ide> STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
<ide>
<ide> DEFAULT_FILE_STORAGE = 'mysite.storage_backends.MediaStorage'
<ide>
<del>```
<ide>\ No newline at end of file
<add>``` | 1 |
Ruby | Ruby | reduce allocations in transition_table | 6e636e2336b497e2a1c864ddf6a5fa9aa4ffe0f4 | <ide><path>actionpack/lib/action_dispatch/journey/gtg/builder.rb
<ide> class Builder # :nodoc:
<ide> def initialize(root)
<ide> @root = root
<ide> @ast = Nodes::Cat.new root, DUMMY
<del> @followpos = nil
<add> @followpos = build_followpos
<ide> end
<ide>
<ide> def transition_table
<ide> dtrans = TransitionTable.new
<ide> marked = {}
<ide> state_id = Hash.new { |h, k| h[k] = h.length }
<add> dstates = [firstpos(root)]
<ide>
<del> start = firstpos(root)
<del> dstates = [start]
<ide> until dstates.empty?
<ide> s = dstates.shift
<ide> next if marked[s]
<ide> marked[s] = true # mark s
<ide>
<ide> s.group_by { |state| symbol(state) }.each do |sym, ps|
<del> u = ps.flat_map { |l| followpos(l) }
<add> u = ps.flat_map { |l| @followpos[l] }
<ide> next if u.empty?
<ide>
<del> if u.uniq == [DUMMY]
<del> from = state_id[s]
<add> from = state_id[s]
<add>
<add> if u.all? { |pos| pos == DUMMY }
<ide> to = state_id[Object.new]
<ide> dtrans[from, to] = sym
<del>
<ide> dtrans.add_accepting(to)
<add>
<ide> ps.each { |state| dtrans.add_memo(to, state.memo) }
<ide> else
<del> dtrans[state_id[s], state_id[u]] = sym
<add> to = state_id[u]
<add> dtrans[from, to] = sym
<ide>
<ide> if u.include?(DUMMY)
<del> to = state_id[u]
<del>
<del> accepting = ps.find_all { |l| followpos(l).include?(DUMMY) }
<del>
<del> accepting.each { |accepting_state|
<del> dtrans.add_memo(to, accepting_state.memo)
<del> }
<add> ps.each do |state|
<add> if @followpos[state].include?(DUMMY)
<add> dtrans.add_memo(to, state.memo)
<add> end
<add> end
<ide>
<del> dtrans.add_accepting(state_id[u])
<add> dtrans.add_accepting(to)
<ide> end
<ide> end
<ide>
<ide> def firstpos(node)
<ide> firstpos(node.left)
<ide> end
<ide> when Nodes::Or
<del> node.children.flat_map { |c| firstpos(c) }.uniq
<add> node.children.flat_map { |c| firstpos(c) }.tap(&:uniq!)
<ide> when Nodes::Unary
<ide> firstpos(node.left)
<ide> when Nodes::Terminal
<ide> def lastpos(node)
<ide> when Nodes::Star
<ide> firstpos(node.left)
<ide> when Nodes::Or
<del> node.children.flat_map { |c| lastpos(c) }.uniq
<add> node.children.flat_map { |c| lastpos(c) }.tap(&:uniq!)
<ide> when Nodes::Cat
<ide> if nullable?(node.right)
<ide> lastpos(node.left) | lastpos(node.right)
<ide> def lastpos(node)
<ide> end
<ide> end
<ide>
<del> def followpos(node)
<del> followpos_table[node]
<del> end
<del>
<ide> private
<del> def followpos_table
<del> @followpos ||= build_followpos
<del> end
<del>
<ide> def build_followpos
<ide> table = Hash.new { |h, k| h[k] = [] }
<ide> @ast.each do |n|
<ide> def build_followpos
<ide> end
<ide>
<ide> def symbol(edge)
<del> case edge
<del> when Journey::Nodes::Symbol
<del> edge.regexp
<del> else
<del> edge.left
<del> end
<add> edge.symbol? ? edge.regexp : edge.left
<ide> end
<ide> end
<ide> end | 1 |
Text | Text | fix typo - not providing initial state to reducer | aa84f989c68474bdcf82a27f9fb3f5296c0eb978 | <ide><path>docs/basics/Reducers.md
<ide> export default todoApp;
<ide> Note that this is completely equivalent to:
<ide>
<ide> ```js
<del>export default function todoApp(state, action) {
<add>export default function todoApp(state = {}, action) {
<ide> return {
<ide> visibilityFilter: visibilityFilter(state.visibilityFilter, action),
<ide> todos: todos(state.todos, action) | 1 |
Ruby | Ruby | remove unused code | bbbe1a58e60da079d5d353777561d1c998549571 | <ide><path>actionpack/lib/action_dispatch/routing/route_set.rb
<ide> def add_route(app, conditions = {}, requirements = {}, defaults = {}, name = nil
<ide> ast = conditions.delete :parsed_path_info
<ide> required_defaults = conditions.delete :required_defaults
<ide> path = build_path(path, ast, requirements, anchor)
<del> conditions = build_conditions(conditions, path.names.map(&:to_sym))
<add> conditions = build_conditions(conditions)
<ide>
<ide> route = @set.add_route(app, path, conditions, required_defaults, defaults, name)
<ide> named_routes[name] = route if name
<ide> def build_path(path, ast, requirements, anchor)
<ide> end
<ide> private :build_path
<ide>
<del> def build_conditions(current_conditions, path_values)
<add> def build_conditions(current_conditions)
<ide> conditions = current_conditions.dup
<ide>
<ide> # Rack-Mount requires that :request_method be a regular expression. | 1 |
Javascript | Javascript | prevent collisions with object.prototype | 9d76c0b163675505d1a901e5fe5249a2c55609bc | <ide><path>src/data/Data.js
<ide> Data.prototype = {
<ide>
<ide> // If not, create one
<ide> if ( !value ) {
<del> value = {};
<add> value = Object.create( null );
<ide>
<ide> // We can accept data for non-element nodes in modern browsers,
<ide> // but we should not, see #8335.
<ide><path>src/event.js
<ide> jQuery.event = {
<ide>
<ide> // Init the element's event structure and main handler, if this is the first
<ide> if ( !( events = elemData.events ) ) {
<del> events = elemData.events = {};
<add> events = elemData.events = Object.create( null );
<ide> }
<ide> if ( !( eventHandle = elemData.handle ) ) {
<ide> eventHandle = elemData.handle = function( e ) {
<ide> jQuery.event = {
<ide> // Make a writable jQuery.Event from the native event object
<ide> event = jQuery.event.fix( nativeEvent ),
<ide>
<del> handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [],
<add> handlers = (
<add> dataPriv.get( this, "events" ) || Object.create( null )
<add> )[ event.type ] || [],
<ide> special = jQuery.event.special[ event.type ] || {};
<ide>
<ide> // Use the fix-ed jQuery.Event rather than the (read-only) native event
<ide><path>src/event/trigger.js
<ide> jQuery.extend( jQuery.event, {
<ide> special.bindType || type;
<ide>
<ide> // jQuery handler
<del> handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] &&
<add> handle = (
<add> dataPriv.get( cur, "events" ) || Object.create( null )
<add> )[ event.type ] &&
<ide> dataPriv.get( cur, "handle" );
<ide> if ( handle ) {
<ide> handle.apply( cur, data );
<ide><path>src/manipulation.js
<ide> function restoreScript( elem ) {
<ide> }
<ide>
<ide> function cloneCopyEvent( src, dest ) {
<del> var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
<add> var i, l, type, pdataOld, udataOld, udataCur, events;
<ide>
<ide> if ( dest.nodeType !== 1 ) {
<ide> return;
<ide> }
<ide>
<ide> // 1. Copy private data: events, handlers, etc.
<ide> if ( dataPriv.hasData( src ) ) {
<del> pdataOld = dataPriv.access( src );
<del> pdataCur = dataPriv.set( dest, pdataOld );
<add> pdataOld = dataPriv.get( src );
<ide> events = pdataOld.events;
<ide>
<ide> if ( events ) {
<del> delete pdataCur.handle;
<del> pdataCur.events = {};
<add> dataPriv.remove( dest, "handle events" );
<ide>
<ide> for ( type in events ) {
<ide> for ( i = 0, l = events[ type ].length; i < l; i++ ) {
<ide><path>test/unit/data.js
<ide> QUnit.test( ".data(prop) does not create expando", function( assert ) {
<ide> }
<ide> }
<ide> } );
<add>
<add>QUnit.test( "keys matching Object.prototype properties (gh-3256)", function( assert ) {
<add> assert.expect( 2 );
<add>
<add> var div = jQuery( "<div/>" );
<add>
<add> assert.strictEqual( div.data( "hasOwnProperty" ), undefined,
<add> "hasOwnProperty not matched (before forced data creation)" );
<add>
<add> // Force the creation of a data object for this element.
<add> div.data( { foo: "bar" } );
<add>
<add> assert.strictEqual( div.data( "hasOwnProperty" ), undefined,
<add> "hasOwnProperty not matched (after forced data creation)" );
<add>} );
<ide><path>test/unit/event.js
<ide> QUnit.test( "jQuery.off using dispatched jQuery.Event", function( assert ) {
<ide> .remove();
<ide> } );
<ide>
<add>QUnit.test( "events with type matching an Object.prototype property (gh-3256)", function( assert ) {
<add> assert.expect( 1 );
<add>
<add> var elem = jQuery( "<div/>" ),
<add> eventFired = false;
<add>
<add> elem.appendTo( "#qunit-fixture" );
<add>
<add> try {
<add> elem
<add> .one( "hasOwnProperty", function() {
<add> eventFired = true;
<add> } )
<add> .trigger( "hasOwnProperty" );
<add> } finally {
<add> assert.strictEqual( eventFired, true, "trigger fired without crashing" );
<add> }
<add>} );
<add>
<add>QUnit.test( "events with type matching an Object.prototype property, cloned element (gh-3256)",
<add> function( assert ) {
<add> assert.expect( 1 );
<add>
<add> var elem = jQuery( "<div/>" ),
<add> eventFired = false;
<add>
<add> elem.appendTo( "#qunit-fixture" );
<add>
<add> try {
<add> // Make sure the original element has some event data.
<add> elem.on( "click", function() {} );
<add>
<add> elem
<add> .clone( true )
<add> .one( "hasOwnProperty", function() {
<add> eventFired = true;
<add> } )
<add> .trigger( "hasOwnProperty" );
<add> } finally {
<add> assert.strictEqual( eventFired, true, "trigger fired without crashing" );
<add> }
<add>} );
<add>
<ide> // selector-native does not support scope-fixing in delegation
<ide> QUnit[ QUnit.jQuerySelectors ? "test" : "skip" ]( "delegated event with delegateTarget-relative selector", function( assert ) {
<ide> assert.expect( 3 ); | 6 |
Javascript | Javascript | fix lint warnings | de408dac70a56e9dd007557b5d89894ff5d1d6d0 | <ide><path>examples/helloworld/hello.js
<ide>
<ide> 'use strict';
<ide>
<del>getPdf('helloworld.pdf', function(data){
<add>getPdf('helloworld.pdf', function getPdfHelloWorld(data) {
<ide> //
<ide> // Instantiate PDFDoc with PDF data
<ide> //
<ide><path>pdf.js
<ide> function getPdf(arg, callback) {
<ide> xhr.mozResponseType = xhr.responseType = 'arraybuffer';
<ide> xhr.expected = (document.URL.indexOf('file:') === 0) ? 0 : 200;
<ide> xhr.onprogress = params.progress || undefined;
<del>
<del> xhr.onreadystatechange = function() {
<add>
<add> xhr.onreadystatechange = function getPdfOnreadystatechange() {
<ide> var data;
<ide> if (xhr.readyState === 4 && xhr.status === xhr.expected) {
<ide> data = (xhr.mozResponseArrayBuffer || xhr.mozResponse ||
<del> xhr.responseArrayBuffer || xhr.response);
<add> xhr.responseArrayBuffer || xhr.response);
<ide> callback(data);
<ide> }
<ide> };
<del> xhr.send(null);
<add> xhr.send(null);
<ide> }
<ide>
<ide> var Stream = (function streamStream() {
<ide> var CanvasGraphics = (function canvasGraphics() {
<ide> if (IsDict(extGState) && extGState.has(dictName.name)) {
<ide> var gsState = this.xref.fetchIfRef(extGState.get(dictName.name));
<ide> var self = this;
<del> gsState.forEach(function(key, value) {
<add> gsState.forEach(function canvasGraphicsSetGStateForEach(key, value) {
<ide> switch (key) {
<ide> case 'Type':
<ide> break;
<ide><path>test/driver.js
<ide> function nextTask() {
<ide>
<ide> log('Loading file "' + task.file + '"\n');
<ide>
<del> getPdf(task.file, function(data){
<add> getPdf(task.file, function nextTaskGetPdf(data) {
<ide> var failure;
<ide> try {
<ide> task.pdfDoc = new PDFDoc(data);
<ide><path>web/viewer.js
<ide> var PDFView = {
<ide>
<ide> document.title = url;
<ide>
<del> getPdf({url:url, progress:PDFView.progressLevel}, function(data) {
<add> getPdf({url: url, progress: PDFView.progressLevel}, function(data) {
<ide> document.getElementById('loading').style.display = 'none';
<ide> PDFView.load(data, scale);
<ide> }); | 4 |
Javascript | Javascript | fix bug with pie/doughnut chart legends | 051f5b015bc9d1fb07cd23ec3bfc78e6e3914360 | <ide><path>src/controllers/controller.doughnut.js
<ide> module.exports = function(Chart) {
<ide>
<ide> for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
<ide> meta = chart.getDatasetMeta(i);
<del> meta.data[index].hidden = !meta.data[index].hidden;
<add> // toggle visibility of index if exists
<add> if (meta.data[index]) {
<add> meta.data[index].hidden = !meta.data[index].hidden;
<add> }
<ide> }
<ide>
<ide> chart.update(); | 1 |
Text | Text | fix typos [ci-skip] | a713f7f22fd076bfa57ee5500e5a6fa206b2867b | <ide><path>guides/source/active_record_querying.md
<ide> you get the instance method `find_by_first_name` for free from Active Record.
<ide> If you also have a `locked` field on the `Customer` model, you also get `find_by_locked` method.
<ide>
<ide> You can specify an exclamation point (`!`) on the end of the dynamic finders
<del>to get them to raise an `ActiveRecord::RecordNotFound` error if they do not return any records, like `Customer.find_by_name!("Ryan")`
<add>to get them to raise an `ActiveRecord::RecordNotFound` error if they do not return any records, like `Customer.find_by_first_name!("Ryan")`
<ide>
<ide> If you want to find both by `first_name` and `orders_count`, you can chain these finders together by simply typing "`and`" between the fields.
<ide> For example, `Customer.find_by_first_name_and_orders_count("Ryan", 5)`.
<ide><path>guides/source/api_documentation_guidelines.md
<ide> If you need to use `return` statements in your callbacks, it is recommended that
<ide> use this style:
<ide>
<ide> ```markdown
<del>If `return` is needed it is recommended to explicitly define a method.
<add>If `return` is needed, it is recommended to explicitly define a method.
<ide> ```
<ide>
<ide> That said, when using pronouns in reference to a hypothetical person, such as "a
<ide><path>guides/source/autoloading_and_reloading_constants.md
<ide> $ bin/rails runner 'p UsersHelper'
<ide> UsersHelper
<ide> ```
<ide>
<del>Rails adds custom directories under `app` to the autoload paths automatically. For example, if your application has `app/presenters`, you don't need to configure anything in order to autoload presenters, it works out of the box.
<add>Rails adds custom directories under `app` to the autoload paths automatically. For example, if your application has `app/presenters`, you don't need to configure anything in order to autoload presenters; it works out of the box.
<ide>
<ide> The array of default autoload paths can be extended by pushing to `config.autoload_paths`, in `config/application.rb` or `config/environments/*.rb`. For example:
<ide>
<ide><path>guides/source/caching_with_rails.md
<ide> store is not appropriate for large application deployments. However, it can
<ide> work well for small, low traffic sites with only a couple of server processes,
<ide> as well as development and test environments.
<ide>
<del>New Rails projects are configured to use this implementation in development environment by default.
<add>New Rails projects are configured to use this implementation in the development environment by default.
<ide>
<ide> NOTE: Since processes will not share cache data when using `:memory_store`,
<ide> it will not be possible to manually read, write, or expire the cache via the Rails console.
<ide><path>guides/source/configuring.md
<ide> Allows you to configure the application's middleware. This is covered in depth i
<ide>
<ide> #### `config.public_file_server.enabled`
<ide>
<del>Configures Rails to serve static files from the public directory. 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 using WEBrick (it is not recommended to use WEBrick in production) set the option to `true`. Otherwise, you won't be able to use page caching and request for files that exist under the public directory.
<add>Configures Rails to serve static files from the public directory. 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 using WEBrick (it is not recommended to use WEBrick in production), set the option to `true`. Otherwise, you won't be able to use page caching and request for files that exist under the public directory.
<ide>
<ide> #### `config.railties_order`
<ide>
<ide><path>guides/source/contributing_to_ruby_on_rails.md
<ide> NOTE: Bugs in the most recent released version of Ruby on Rails will likely get
<ide>
<ide> If you've found a problem in Ruby on Rails that is not a security risk, search the [Issues](https://github.com/rails/rails/issues) on GitHub, in case it has already been reported. If you cannot find any open GitHub issues addressing the problem you found, your next step will be to [open a new issue](https://github.com/rails/rails/issues/new). (See the next section for reporting security issues.)
<ide>
<del>We've provided an issue template for you so that when creating an issue you include all the information needed to determine whether there is a bug in the framework. Each issue needs to include a title and clear description of the problem. Make sure to include as much relevant information as possible including a code sample or failing test that demonstrates the expected behavior, as well as your system configuration. Your goal should be to make it easy for yourself - and others - to reproduce the bug and figure out a fix.
<add>We've provided an issue template for you so that when creating an issue you include all the information needed to determine whether there is a bug in the framework. Each issue needs to include a title and clear description of the problem. Make sure to include as much relevant information as possible, including a code sample or failing test that demonstrates the expected behavior, as well as your system configuration. Your goal should be to make it easy for yourself - and others - to reproduce the bug and figure out a fix.
<ide>
<del>Once you open an issue it may or may not see activity right away unless it is a "Code Red, Mission Critical, the World is Coming to an End" kind of bug. That doesn't mean we don't care about your bug, just that there are a lot of issues and pull requests to get through. Other people with the same problem can find your issue and confirm the bug and may collaborate with you on fixing it. If you know how to fix the bug, go ahead and open a pull request.
<add>Once you open an issue, it may or may not see activity right away unless it is a "Code Red, Mission Critical, the World is Coming to an End" kind of bug. That doesn't mean we don't care about your bug, just that there are a lot of issues and pull requests to get through. Other people with the same problem can find your issue, and confirm the bug, and may collaborate with you on fixing it. If you know how to fix the bug, go ahead and open a pull request.
<ide>
<ide> ### Create an Executable Test Case
<ide>
<ide> discussions new features require.
<ide> Helping to Resolve Existing Issues
<ide> ----------------------------------
<ide>
<del>Beyond reporting issues, you can help the core team resolve existing ones by providing feedback about them. If you are new to Rails core development providing feedback will help you get familiar with the codebase and the processes.
<add>Beyond reporting issues, you can help the core team resolve existing ones by providing feedback about them. If you are new to Rails core development, providing feedback will help you get familiar with the codebase and the processes.
<ide>
<ide> If you check the [issues list](https://github.com/rails/rails/issues) in GitHub Issues, you'll find lots of issues already requiring attention. What can you do about these? Quite a bit, actually:
<ide>
<ide> $ yarn link "@rails/activestorage"
<ide>
<ide> ### Write Your Code
<ide>
<del>Now it's time to write some code! When making changes for Rails here are some things to keep in mind:
<add>Now it's time to write some code! When making changes for Rails, here are some things to keep in mind:
<ide>
<ide> * Follow Rails style and conventions.
<ide> * Use Rails idioms and helpers.
<ide> pull requests and give someone else some! They'll appreciate it in
<ide> the same way that you appreciate feedback on your patches.
<ide>
<ide> Note that only the Core and Committers teams are permitted to merge code changes.
<del>If someone gives feedback and "approves" your changes they may not have the ability
<add>If someone gives feedback and "approves" your changes, they may not have the ability
<ide> or final say to merge your change.
<ide>
<ide> ### Iterate as Necessary
<ide><path>guides/source/development_dependencies_install.md
<ide> After reading this guide, you will know:
<ide> Other Ways to Set Up Your Environment
<ide> -------------------------------------
<ide>
<del>If you don't want to set up Rails for development on your local machine you can use Codespaces, the VS Code Remote Plugin, or rails-dev-box. Learn more about these options [here](https://guides.rubyonrails.org/contributing_to_ruby_on_rails.html#setting-up-a-development-environment).
<add>If you don't want to set up Rails for development on your local machine, you can use Codespaces, the VS Code Remote Plugin, or rails-dev-box. Learn more about these options [here](https://guides.rubyonrails.org/contributing_to_ruby_on_rails.html#setting-up-a-development-environment).
<ide>
<ide> Local Development
<ide> -----------------
<ide>
<del>If you want to develop Ruby on Rails locally on your machine see the steps below.
<add>If you want to develop Ruby on Rails locally on your machine, see the steps below.
<ide>
<ide> ### Install Git
<ide>
<ide> In order to compile the `mysql2` gem on macOS you will need the following:
<ide> 2) Ruby compiled with `[email protected]`
<ide> 3) Set compiler flags in the bundle config for `mysql2`.
<ide>
<del>If both `[email protected]` and `openssl@3` are installed you will need to tell Ruby to use `[email protected]` in order for Rails to bundle `mysql2`.
<add>If both `[email protected]` and `openssl@3` are installed, you will need to tell Ruby to use `[email protected]` in order for Rails to bundle `mysql2`.
<ide>
<ide> In your `.bash_profile` set the `PATH` and `RUBY_CONFIGURE_OPTS` to point to `[email protected]`:
<ide>
<ide> In your `~/.bundle/config` set the following for `mysql2`. Be sure to delete any
<ide> BUNDLE_BUILD__MYSQL2: "--with-ldflags=-L/usr/local/opt/[email protected]/lib --with-cppflags=-L/usr/local/opt/[email protected]/include"
<ide> ```
<ide>
<del>By setting these flags before installing Ruby and bundling Rails you should be able to get your local macOS development environment working.
<add>By setting these flags before installing Ruby and bundling Rails, you should be able to get your local macOS development environment working.
<ide>
<ide> #### Ubuntu
<ide>
<ide> To install the Gemfile for Rails run:
<ide> $ bundle install
<ide> ```
<ide>
<del>If you don't need to run Active Record tests you can run:
<add>If you don't need to run Active Record tests, you can run:
<ide>
<ide> ```bash
<ide> $ bundle install --without db
<ide><path>guides/source/form_helpers.md
<ide> This will generate the following HTML:
<ide> </form>
<ide> ```
<ide>
<del>TIP: Passing `url: my_specified_path` to `form_with` tells the form where to make the request. However, as explained below, you can also pass ActiveRecord objects to the form.
<add>TIP: Passing `url: my_specified_path` to `form_with` tells the form where to make the request. However, as explained below, you can also pass Active Record objects to the form.
<ide>
<ide> TIP: For every form input, an ID attribute is generated from its name (`"query"` in above example). These IDs can be very useful for CSS styling or manipulation of form controls with JavaScript.
<ide>
<ide><path>guides/source/getting_started.md
<ide> $ ruby --version
<ide> ruby 2.7.0
<ide> ```
<ide>
<del>Rails requires Ruby version 2.7.0 or later. It is preferred to use latest Ruby version.
<add>Rails requires Ruby version 2.7.0 or later. It is preferred to use the latest Ruby version.
<ide> If the version number returned is less than that number (such as 2.3.7, or 1.8.7),
<ide> you'll need to install a fresh copy of Ruby.
<ide>
<ide><path>guides/source/security.md
<ide> HTTP Security Headers
<ide> ---------------------
<ide>
<ide> To improve the security of your application, Rails can be configured to return
<del>HTTP security headers. Some headers are configured by default, others need to
<add>HTTP security headers. Some headers are configured by default; others need to
<ide> be explicitly configured.
<ide>
<ide> ### Default Security Headers
<ide> PDF clients from embedding your page on other domains.
<ide> #### Referrer-Policy
<ide>
<ide> This header is set to `strict-origin-when-cross-origin` in Rails by default.
<del>For cross-origin request this only sends the origin in the Referer header. This
<add>For cross-origin requests, this only sends the origin in the Referer header. This
<ide> prevents leaks of private data that may be accessible from other parts of the
<del>full URL such as the path and query string.
<add>full URL, such as the path and query string.
<ide>
<ide> #### Configuring the Default Headers
<ide>
<ide> loaded inline `<script>` elements.
<ide> NOTE: The Feature-Policy header has been renamed to Permissions-Policy.
<ide> The Permissions-Policy requires a different implementation and isn't
<ide> yet supported by all browsers. To avoid having to rename this
<del>middleware in the future we use the new name for the middleware but
<add>middleware in the future, we use the new name for the middleware but
<ide> keep the old header name and implementation for now.
<ide>
<del>To allow or block the use of browser features you can define a
<add>To allow or block the use of browser features, you can define a
<ide> [Feature-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Feature-Policy)
<ide> response header for your application. Rails provides a DSL that allows you to
<ide> configure the header.
<ide><path>guides/source/upgrading_ruby_on_rails.md
<ide> video.preview(resize_to_limit: [100, 100])
<ide> video.preview(resize_to_fill: [100, 100])
<ide> ```
<ide>
<del>### New `ActiveModel:Errors` class
<add>### New `ActiveModel::Error` class
<ide>
<ide> Errors are now instances of a new `ActiveModel::Error` class, with changes to
<ide> the API. Some of these changes may throw errors depending on how you manipulate | 11 |
Go | Go | remove the error message on mac delete failure. | d51ed8a97be8e984c502ab1c1018e9891d4b3fed | <ide><path>libnetwork/osl/neigh_linux.go
<ide> func (n *networkNamespace) DeleteNeighbor(dstIP net.IP, dstMac net.HardwareAddr,
<ide> if nh.linkDst != "" {
<ide> nlnh.LinkIndex = iface.Attrs().Index
<ide> }
<del> if err := nlh.NeighDel(nlnh); err != nil {
<del> logrus.Warnf("Deleting bridge mac mac %s failed, %v", dstMac, err)
<del> }
<add> nlh.NeighDel(nlnh)
<ide> }
<ide> }
<ide> | 1 |
Java | Java | adjust logging following sockjs client disconnect | 49b872e387cf698de653dffa1b268c0950c0c23f | <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/session/AbstractSockJsSession.java
<ide> public abstract class AbstractSockJsSession implements SockJsSession {
<ide> private static final Set<String> disconnectedClientExceptions;
<ide>
<ide> static {
<del>
<ide> Set<String> set = new HashSet<String>(2);
<ide> set.add("ClientAbortException"); // Tomcat
<add> set.add("EOFException"); // Tomcat
<ide> set.add("EofException"); // Jetty
<ide> // java.io.IOException "Broken pipe" on WildFly, Glassfish (already covered)
<ide> disconnectedClientExceptions = Collections.unmodifiableSet(set);
<ide> protected void writeFrame(SockJsFrame frame) throws SockJsTransportFailureExcept
<ide> disconnect(CloseStatus.SERVER_ERROR);
<ide> }
<ide> catch (Throwable disconnectFailure) {
<del> logger.error("Failure while closing " + this, disconnectFailure);
<add> // Ignore
<ide> }
<ide> try {
<ide> close(CloseStatus.SERVER_ERROR); | 1 |
Ruby | Ruby | fix where.not with in clause | 89ab303d8b78a73cb7d306a026f185986f44aa2a | <ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> def initialize(scope)
<ide> # User.where.not(name: nil)
<ide> # # SELECT * FROM users WHERE name IS NOT NULL
<ide> #
<del> # User.where.not(name: %(Ko1 Nobu))
<add> # User.where.not(name: %w(Ko1 Nobu))
<ide> # # SELECT * FROM users WHERE name NOT IN ('Ko1', 'Nobu')
<ide> def not(opts, *rest)
<ide> where_value = @scope.send(:build_where, opts, rest).map do |rel|
<ide> case rel
<del> when Arel::Nodes::Equality
<del> Arel::Nodes::NotEqual.new(rel.left, rel.right)
<ide> when Arel::Nodes::In
<ide> Arel::Nodes::NotIn.new(rel.left, rel.right)
<add> when Arel::Nodes::Equality
<add> Arel::Nodes::NotEqual.new(rel.left, rel.right)
<ide> when String
<ide> Arel::Nodes::Not.new(Arel::Nodes::SqlLiteral.new(rel))
<ide> else
<ide><path>activerecord/test/cases/relation/where_chain_test.rb
<ide> def test_not_null
<ide> end
<ide>
<ide> def test_not_in
<del> expected = Arel::Nodes::NotEqual.new(Post.arel_table[:title], %w[hello goodbye])
<add> expected = Arel::Nodes::NotIn.new(Post.arel_table[:title], %w[hello goodbye])
<ide> relation = Post.where.not(title: %w[hello goodbye])
<ide> assert_equal([expected], relation.where_values)
<ide> end | 2 |
PHP | PHP | add argument support for detectors | e248f6f54e50480d5c6e84b0305ea28c9ce8e0b9 | <ide><path>src/Network/Request.php
<ide> public function __isset($name)
<ide> */
<ide> public function is($type)
<ide> {
<add> $args = func_get_args();
<add> array_shift($args);
<add>
<ide> if (is_array($type)) {
<ide> $result = array_map([$this, 'is'], $type);
<ide> return count(array_filter($result)) > 0;
<ide> public function is($type)
<ide> }
<ide>
<ide> if (!isset($this->_detectorCache[$type])) {
<del> $this->_detectorCache[$type] = $this->_is($type);
<add> $this->_detectorCache[$type] = $this->_is($type, $args);
<ide> }
<ide>
<ide> return $this->_detectorCache[$type];
<ide> public function clearDetectorCache()
<ide> * this method will return true if the request matches any type.
<ide> * @return bool Whether or not the request is the type you are checking.
<ide> */
<del> protected function _is($type)
<add> protected function _is($type, $args)
<ide> {
<ide> $detect = static::$_detectors[$type];
<ide> if (is_callable($detect)) {
<del> return call_user_func($detect, $this);
<add> array_unshift($args, $this);
<add> return call_user_func_array($detect, $args);
<ide> }
<ide> if (isset($detect['env']) && $this->_environmentDetector($detect)) {
<ide> return true;
<ide><path>tests/TestCase/Network/RequestTest.php
<ide> public function tearDown()
<ide> }
<ide> }
<ide>
<add> /**
<add> * Test custom detector with extra arguments.
<add> *
<add> * @return void
<add> */
<add> public function testCustomArgsDetector()
<add> {
<add> $request = new Request();
<add> $request->addDetector('controller', function ($request, $name) {
<add> return $request->param('controller') === $name;
<add> });
<add>
<add> $request->params = ['controller' => 'cake'];
<add> $this->assertTrue($request->is('controller', 'cake'));
<add> $this->assertTrue($request->isController('cake'));
<add> }
<add>
<ide> /**
<ide> * Test the header detector.
<ide> * | 2 |
Javascript | Javascript | add locale sinhalese (si) (redo ) | 0a41577648573112adf436fda1b4609fbbec7008 | <ide><path>src/locale/si.js
<add>//! moment.js locale configuration
<add>//! locale : Sinhalese (si)
<add>//! author : Sampath Sitinamaluwa : https://github.com/sampathsris
<add>
<add>import moment from '../moment';
<add>
<add>/*jshint -W100*/
<add>export default moment.defineLocale('si', {
<add> months : 'ජනවාරි_පෙබරවාරි_මාර්තු_අප්රේල්_මැයි_ජූනි_ජූලි_අගෝස්තු_සැප්තැම්බර්_ඔක්තෝබර්_නොවැම්බර්_දෙසැම්බර්'.split('_'),
<add> monthsShort : 'ජන_පෙබ_මාර්_අප්_මැයි_ජූනි_ජූලි_අගෝ_සැප්_ඔක්_නොවැ_දෙසැ'.split('_'),
<add> weekdays : 'ඉරිදා_සඳුදා_අඟහරුවාදා_බදාදා_බ්රහස්පතින්දා_සිකුරාදා_සෙනසුරාදා'.split('_'),
<add> weekdaysShort : 'ඉරි_සඳු_අඟ_බදා_බ්රහ_සිකු_සෙන'.split('_'),
<add> weekdaysMin : 'ඉ_ස_අ_බ_බ්ර_සි_සෙ'.split('_'),
<add> longDateFormat : {
<add> LT : 'a h:mm',
<add> LTS : 'a h:mm:ss',
<add> L : 'YYYY/MM/DD',
<add> LL : 'YYYY MMMM D',
<add> LLL : 'YYYY MMMM D, LT',
<add> LLLL : 'YYYY MMMM D [වැනි] dddd, LTS'
<add> },
<add> calendar : {
<add> sameDay : '[අද] LT[ට]',
<add> nextDay : '[හෙට] LT[ට]',
<add> nextWeek : 'dddd LT[ට]',
<add> lastDay : '[ඊයේ] LT[ට]',
<add> lastWeek : '[පසුගිය] dddd LT[ට]',
<add> sameElse : 'L'
<add> },
<add> relativeTime : {
<add> future : '%sකින්',
<add> past : '%sකට පෙර',
<add> s : 'තත්පර කිහිපය',
<add> m : 'මිනිත්තුව',
<add> mm : 'මිනිත්තු %d',
<add> h : 'පැය',
<add> hh : 'පැය %d',
<add> d : 'දිනය',
<add> dd : 'දින %d',
<add> M : 'මාසය',
<add> MM : 'මාස %d',
<add> y : 'වසර',
<add> yy : 'වසර %d'
<add> },
<add> ordinalParse: /\d{1,2} වැනි/,
<add> ordinal : function (number) {
<add> return number + ' වැනි';
<add> },
<add> meridiem : function (hours, minutes, isLower) {
<add> if (hours > 11) {
<add> return isLower ? 'ප.ව.' : 'පස් වරු';
<add> } else {
<add> return isLower ? 'පෙ.ව.' : 'පෙර වරු';
<add> }
<add> }
<add>});
<ide><path>src/test/locale/si.js
<add>import {localeModule, test} from '../qunit';
<add>import {moment} from '../../moment';
<add>localeModule('si');
<add>
<add>/*jshint -W100*/
<add>test('parse', function (assert) {
<add> var tests = 'ජනවාරි ජන_පෙබරවාරි පෙබ_මාර්තු මාර්_අප්රේල් අප්_මැයි මැයි_ජූනි ජූනි_ජූලි ජූලි_අගෝස්තු අගෝ_සැප්තැම්බර් සැප්_ඔක්තෝබර් ඔක්_නොවැම්බර් නොවැ_දෙසැම්බර් දෙසැ'.split('_'), i;
<add> function equalTest(input, mmm, i) {
<add> assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1));
<add> }
<add> for (i = 0; i < 12; i++) {
<add> tests[i] = tests[i].split(' ');
<add> equalTest(tests[i][0], 'MMM', i);
<add> equalTest(tests[i][1], 'MMM', i);
<add> equalTest(tests[i][0], 'MMMM', i);
<add> equalTest(tests[i][1], 'MMMM', i);
<add> equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i);
<add> equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i);
<add> equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i);
<add> equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i);
<add> }
<add>});
<add>
<add>test('format', function (assert) {
<add> var a = [
<add> ['YYYY MMMM Do dddd, a h:mm:ss', '2010 පෙබරවාරි 14 වැනි ඉරිදා, ප.ව. 3:25:50'],
<add> ['YYYY MMMM Do dddd, a h:mm:ss', '2010 පෙබරවාරි 14 වැනි ඉරිදා, ප.ව. 3:25:50'],
<add> ['ddd, A h', 'ඉරි, පස් වරු 3'],
<add> ['M Mo MM MMMM MMM', '2 2 වැනි 02 පෙබරවාරි පෙබ'],
<add> ['YYYY YY', '2010 10'],
<add> ['D Do DD', '14 14 වැනි 14'],
<add> ['d do dddd ddd dd', '0 0 වැනි ඉරිදා ඉරි ඉ'],
<add> ['DDD DDDo DDDD', '45 45 වැනි 045'],
<add> ['h hh', '3 03'],
<add> ['H HH', '15 15'],
<add> ['m mm', '25 25'],
<add> ['s ss', '50 50'],
<add> ['a A', 'ප.ව. පස් වරු'],
<add> ['[වසරේ] DDDo [දිනය]', 'වසරේ 45 වැනි දිනය'],
<add> ['LTS', 'ප.ව. 3:25:50'],
<add> ['LT', 'ප.ව. 3:25'],
<add> ['L', '2010/02/14'],
<add> ['LL', '2010 පෙබරවාරි 14'],
<add> ['LLL', '2010 පෙබරවාරි 14, ප.ව. 3:25'],
<add> ['LLLL', '2010 පෙබරවාරි 14 වැනි ඉරිදා, ප.ව. 3:25:50'],
<add> ['l', '2010/2/14'],
<add> ['ll', '2010 පෙබ 14'],
<add> ['lll', '2010 පෙබ 14, ප.ව. 3:25'],
<add> ['llll', '2010 පෙබ 14 වැනි ඉරි, ප.ව. 3:25:50']
<add> ],
<add> b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)),
<add> i;
<add> for (i = 0; i < a.length; i++) {
<add> assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]);
<add> }
<add>});
<add>
<add>test('format ordinal', function (assert) {
<add> assert.equal(moment([2011, 0, 1]).format('DDDo'), '1 වැනි', '1 වැනි');
<add> assert.equal(moment([2011, 0, 2]).format('DDDo'), '2 වැනි', '2 වැනි');
<add> assert.equal(moment([2011, 0, 3]).format('DDDo'), '3 වැනි', '3 වැනි');
<add> assert.equal(moment([2011, 0, 4]).format('DDDo'), '4 වැනි', '4 වැනි');
<add> assert.equal(moment([2011, 0, 5]).format('DDDo'), '5 වැනි', '5 වැනි');
<add> assert.equal(moment([2011, 0, 6]).format('DDDo'), '6 වැනි', '6 වැනි');
<add> assert.equal(moment([2011, 0, 7]).format('DDDo'), '7 වැනි', '7 වැනි');
<add> assert.equal(moment([2011, 0, 8]).format('DDDo'), '8 වැනි', '8 වැනි');
<add> assert.equal(moment([2011, 0, 9]).format('DDDo'), '9 වැනි', '9 වැනි');
<add> assert.equal(moment([2011, 0, 10]).format('DDDo'), '10 වැනි', '10 වැනි');
<add>
<add> assert.equal(moment([2011, 0, 11]).format('DDDo'), '11 වැනි', '11 වැනි');
<add> assert.equal(moment([2011, 0, 12]).format('DDDo'), '12 වැනි', '12 වැනි');
<add> assert.equal(moment([2011, 0, 13]).format('DDDo'), '13 වැනි', '13 වැනි');
<add> assert.equal(moment([2011, 0, 14]).format('DDDo'), '14 වැනි', '14 වැනි');
<add> assert.equal(moment([2011, 0, 15]).format('DDDo'), '15 වැනි', '15 වැනි');
<add> assert.equal(moment([2011, 0, 16]).format('DDDo'), '16 වැනි', '16 වැනි');
<add> assert.equal(moment([2011, 0, 17]).format('DDDo'), '17 වැනි', '17 වැනි');
<add> assert.equal(moment([2011, 0, 18]).format('DDDo'), '18 වැනි', '18 වැනි');
<add> assert.equal(moment([2011, 0, 19]).format('DDDo'), '19 වැනි', '19 වැනි');
<add> assert.equal(moment([2011, 0, 20]).format('DDDo'), '20 වැනි', '20 වැනි');
<add>
<add> assert.equal(moment([2011, 0, 21]).format('DDDo'), '21 වැනි', '21 වැනි');
<add> assert.equal(moment([2011, 0, 22]).format('DDDo'), '22 වැනි', '22 වැනි');
<add> assert.equal(moment([2011, 0, 23]).format('DDDo'), '23 වැනි', '23 වැනි');
<add> assert.equal(moment([2011, 0, 24]).format('DDDo'), '24 වැනි', '24 වැනි');
<add> assert.equal(moment([2011, 0, 25]).format('DDDo'), '25 වැනි', '25 වැනි');
<add> assert.equal(moment([2011, 0, 26]).format('DDDo'), '26 වැනි', '26 වැනි');
<add> assert.equal(moment([2011, 0, 27]).format('DDDo'), '27 වැනි', '27 වැනි');
<add> assert.equal(moment([2011, 0, 28]).format('DDDo'), '28 වැනි', '28 වැනි');
<add> assert.equal(moment([2011, 0, 29]).format('DDDo'), '29 වැනි', '29 වැනි');
<add> assert.equal(moment([2011, 0, 30]).format('DDDo'), '30 වැනි', '30 වැනි');
<add>
<add> assert.equal(moment([2011, 0, 31]).format('DDDo'), '31 වැනි', '31 වැනි');
<add>});
<add>
<add>test('format month', function (assert) {
<add> var expected = 'ජනවාරි ජන_පෙබරවාරි පෙබ_මාර්තු මාර්_අප්රේල් අප්_මැයි මැයි_ජූනි ජූනි_ජූලි ජූලි_අගෝස්තු අගෝ_සැප්තැම්බර් සැප්_ඔක්තෝබර් ඔක්_නොවැම්බර් නොවැ_දෙසැම්බර් දෙසැ'.split('_'), i;
<add> for (i = 0; i < expected.length; i++) {
<add> assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]);
<add> }
<add>});
<add>
<add>test('format week', function (assert) {
<add> var expected = 'ඉරිදා ඉරි ඉ_සඳුදා සඳු ස_අඟහරුවාදා අඟ අ_බදාදා බදා බ_බ්රහස්පතින්දා බ්රහ බ්ර_සිකුරාදා සිකු සි_සෙනසුරාදා සෙන සෙ'.split('_'), i;
<add> for (i = 0; i < expected.length; i++) {
<add> assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]);
<add> }
<add>});
<add>
<add>test('from', function (assert) {
<add> var start = moment([2007, 1, 28]);
<add> assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'තත්පර කිහිපය', '44 seconds = a few seconds');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'මිනිත්තුව', '45 seconds = a minute');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'මිනිත්තුව', '89 seconds = a minute');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), 'මිනිත්තු 2', '90 seconds = 2 minutes');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), 'මිනිත්තු 44', '44 minutes = 44 minutes');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'පැය', '45 minutes = an hour');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'පැය', '89 minutes = an hour');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), 'පැය 2', '90 minutes = 2 hours');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), 'පැය 5', '5 hours = 5 hours');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), 'පැය 21', '21 hours = 21 hours');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'දිනය', '22 hours = a day');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'දිනය', '35 hours = a day');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), 'දින 2', '36 hours = 2 days');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'දිනය', '1 day = a day');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), 'දින 5', '5 days = 5 days');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), 'දින 25', '25 days = 25 days');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'මාසය', '26 days = a month');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'මාසය', '30 days = a month');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'මාසය', '43 days = a month');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), 'මාස 2', '46 days = 2 months');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), 'මාස 2', '75 days = 2 months');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), 'මාස 3', '76 days = 3 months');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'මාසය', '1 month = a month');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), 'මාස 5', '5 months = 5 months');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'වසර', '345 days = a year');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), 'වසර 2', '548 days = 2 years');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'වසර', '1 year = a year');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), 'වසර 5', '5 years = 5 years');
<add>});
<add>
<add>test('suffix', function (assert) {
<add> assert.equal(moment(30000).from(0), 'තත්පර කිහිපයකින්', 'prefix');
<add> assert.equal(moment(0).from(30000), 'තත්පර කිහිපයකට පෙර', 'suffix');
<add>});
<add>
<add>test('now from now', function (assert) {
<add> assert.equal(moment().fromNow(), 'තත්පර කිහිපයකට පෙර', 'now from now should display as in the past');
<add>});
<add>
<add>test('fromNow', function (assert) {
<add> assert.equal(moment().add({s: 30}).fromNow(), 'තත්පර කිහිපයකින්', 'in a few seconds');
<add> assert.equal(moment().add({d: 5}).fromNow(), 'දින 5කින්', 'in 5 days');
<add>});
<add>
<add>test('calendar day', function (assert) {
<add> var a = moment().hours(2).minutes(0).seconds(0);
<add>
<add> assert.equal(moment(a).calendar(), 'අද පෙ.ව. 2:00ට', 'today at the same time');
<add> assert.equal(moment(a).add({m: 25}).calendar(), 'අද පෙ.ව. 2:25ට', 'Now plus 25 min');
<add> assert.equal(moment(a).add({h: 1}).calendar(), 'අද පෙ.ව. 3:00ට', 'Now plus 1 hour');
<add> assert.equal(moment(a).add({d: 1}).calendar(), 'හෙට පෙ.ව. 2:00ට', 'tomorrow at the same time');
<add> assert.equal(moment(a).subtract({h: 1}).calendar(), 'අද පෙ.ව. 1:00ට', 'Now minus 1 hour');
<add> assert.equal(moment(a).subtract({d: 1}).calendar(), 'ඊයේ පෙ.ව. 2:00ට', 'yesterday at the same time');
<add>});
<add>
<add>test('calendar next week', function (assert) {
<add> var i, m;
<add> for (i = 2; i < 7; i++) {
<add> m = moment().add({d: i});
<add> assert.equal(m.calendar(), m.format('dddd LT[ට]'), 'Today + ' + i + ' days current time');
<add> m.hours(0).minutes(0).seconds(0).milliseconds(0);
<add> assert.equal(m.calendar(), m.format('dddd LT[ට]'), 'Today + ' + i + ' days beginning of day');
<add> m.hours(23).minutes(59).seconds(59).milliseconds(999);
<add> assert.equal(m.calendar(), m.format('dddd LT[ට]'), 'Today + ' + i + ' days end of day');
<add> }
<add>});
<add>
<add>test('calendar last week', function (assert) {
<add> var i, m;
<add>
<add> for (i = 2; i < 7; i++) {
<add> m = moment().subtract({d: i});
<add> assert.equal(m.calendar(), m.format('[පසුගිය] dddd LT[ට]'), 'Today - ' + i + ' days current time');
<add> m.hours(0).minutes(0).seconds(0).milliseconds(0);
<add> assert.equal(m.calendar(), m.format('[පසුගිය] dddd LT[ට]'), 'Today - ' + i + ' days beginning of day');
<add> m.hours(23).minutes(59).seconds(59).milliseconds(999);
<add> assert.equal(m.calendar(), m.format('[පසුගිය] dddd LT[ට]'), 'Today - ' + i + ' days end of day');
<add> }
<add>});
<add>
<add>test('calendar all else', function (assert) {
<add> var weeksAgo = moment().subtract({w: 1}),
<add> weeksFromNow = moment().add({w: 1});
<add>
<add> assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago');
<add> assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week');
<add>
<add> weeksAgo = moment().subtract({w: 2});
<add> weeksFromNow = moment().add({w: 2});
<add>
<add> assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago');
<add> assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks');
<add>});
<add>
<add>test('lenient ordinal parsing', function (assert) {
<add> var i, ordinalStr, testMoment;
<add> for (i = 1; i <= 31; ++i) {
<add> ordinalStr = moment([2014, 0, i]).format('YYYY MM Do');
<add> testMoment = moment(ordinalStr, 'YYYY MM Do');
<add> assert.equal(testMoment.year(), 2014,
<add> 'lenient ordinal parsing ' + i + ' year check');
<add> assert.equal(testMoment.month(), 0,
<add> 'lenient ordinal parsing ' + i + ' month check');
<add> assert.equal(testMoment.date(), i,
<add> 'lenient ordinal parsing ' + i + ' date check');
<add> }
<add>});
<add>
<add>test('lenient ordinal parsing of number', function (assert) {
<add> var i, testMoment;
<add> for (i = 1; i <= 31; ++i) {
<add> testMoment = moment('2014 01 ' + i, 'YYYY MM Do');
<add> assert.equal(testMoment.year(), 2014,
<add> 'lenient ordinal parsing of number ' + i + ' year check');
<add> assert.equal(testMoment.month(), 0,
<add> 'lenient ordinal parsing of number ' + i + ' month check');
<add> assert.equal(testMoment.date(), i,
<add> 'lenient ordinal parsing of number ' + i + ' date check');
<add> }
<add>});
<add>
<add>test('strict ordinal parsing', function (assert) {
<add> var i, ordinalStr, testMoment;
<add> for (i = 1; i <= 31; ++i) {
<add> ordinalStr = moment([2014, 0, i]).format('YYYY MM Do');
<add> testMoment = moment(ordinalStr, 'YYYY MM Do', true);
<add> assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i);
<add> }
<add>}); | 2 |
PHP | PHP | fix failing test from 2.5 | 2247d521a29103e7c778b8d1b388cb4005991b51 | <ide><path>Cake/Test/TestCase/View/ViewTest.php
<ide> public function testExtendWithElementBeforeExtend() {
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<del>/**
<del> * Test that setting arbitrary properties still works.
<del> *
<del> * @return void
<del> */
<del> public function testPropertySettingMagicGet() {
<del> $this->assertFalse(isset($this->View->action));
<del> $this->View->request->params['action'] = 'login';
<del> $this->assertEquals('login', $this->View->action);
<del> $this->assertTrue(isset($this->View->action));
<del> $this->assertTrue(!empty($this->View->action));
<del> }
<del>
<ide> /**
<ide> * Test memory leaks that existed in _paths at one point.
<ide> * | 1 |
Python | Python | replace assertions with runtimeerror exceptions | 4469010c1be3a94f74d6448497051468f617baf2 | <ide><path>src/transformers/integrations.py
<ide> class TensorBoardCallback(TrainerCallback):
<ide>
<ide> def __init__(self, tb_writer=None):
<ide> has_tensorboard = is_tensorboard_available()
<del> assert (
<del> has_tensorboard
<del> ), "TensorBoardCallback requires tensorboard to be installed. Either update your PyTorch version or install tensorboardX."
<add> if not has_tensorboard:
<add> raise RuntimeError(
<add> "TensorBoardCallback requires tensorboard to be installed. Either update your PyTorch version or install tensorboardX."
<add> )
<ide> if has_tensorboard:
<ide> try:
<ide> from torch.utils.tensorboard import SummaryWriter # noqa: F401
<ide> class WandbCallback(TrainerCallback):
<ide>
<ide> def __init__(self):
<ide> has_wandb = is_wandb_available()
<del> assert has_wandb, "WandbCallback requires wandb to be installed. Run `pip install wandb`."
<add> if not has_wandb:
<add> raise RuntimeError("WandbCallback requires wandb to be installed. Run `pip install wandb`.")
<ide> if has_wandb:
<ide> import wandb
<ide>
<ide> class CometCallback(TrainerCallback):
<ide> """
<ide>
<ide> def __init__(self):
<del> assert _has_comet, "CometCallback requires comet-ml to be installed. Run `pip install comet-ml`."
<add> if not _has_comet:
<add> raise RuntimeError("CometCallback requires comet-ml to be installed. Run `pip install comet-ml`.")
<ide> self._initialized = False
<ide>
<ide> def setup(self, args, state, model):
<ide> class AzureMLCallback(TrainerCallback):
<ide> """
<ide>
<ide> def __init__(self, azureml_run=None):
<del> assert (
<del> is_azureml_available()
<del> ), "AzureMLCallback requires azureml to be installed. Run `pip install azureml-sdk`."
<add> if not is_azureml_available():
<add> raise RuntimeError("AzureMLCallback requires azureml to be installed. Run `pip install azureml-sdk`.")
<ide> self.azureml_run = azureml_run
<ide>
<ide> def on_init_end(self, args, state, control, **kwargs):
<ide> class MLflowCallback(TrainerCallback):
<ide> """
<ide>
<ide> def __init__(self):
<del> assert is_mlflow_available(), "MLflowCallback requires mlflow to be installed. Run `pip install mlflow`."
<add> if not is_mlflow_available():
<add> raise RuntimeError("MLflowCallback requires mlflow to be installed. Run `pip install mlflow`.")
<ide> import mlflow
<ide>
<ide> self._MAX_PARAM_VAL_LENGTH = mlflow.utils.validation.MAX_PARAM_VAL_LENGTH
<ide> class NeptuneCallback(TrainerCallback):
<ide> """
<ide>
<ide> def __init__(self):
<del> assert (
<del> is_neptune_available()
<del> ), "NeptuneCallback requires neptune-client to be installed. Run `pip install neptune-client`."
<add> if not is_neptune_available():
<add> raise ValueError(
<add> "NeptuneCallback requires neptune-client to be installed. Run `pip install neptune-client`."
<add> )
<ide> import neptune.new as neptune
<ide>
<ide> self._neptune = neptune
<ide> class CodeCarbonCallback(TrainerCallback):
<ide> """
<ide>
<ide> def __init__(self):
<del> assert (
<del> is_codecarbon_available()
<del> ), "CodeCarbonCallback requires `codecarbon` to be installed. Run `pip install codecarbon`."
<add> if not is_codecarbon_available():
<add> raise RuntimeError(
<add> "CodeCarbonCallback requires `codecarbon` to be installed. Run `pip install codecarbon`."
<add> )
<ide> import codecarbon
<ide>
<ide> self._codecarbon = codecarbon | 1 |
Python | Python | remove the state argument from language | 66ea9aebe748ce99a104480bb41ade6725e37c9a | <ide><path>spacy/language.py
<ide> def __init__(self, vocab=True, make_doc=True, pipeline=None, meta={}):
<ide> else:
<ide> self.pipeline = []
<ide>
<del> def __call__(self, text, state=None, **disabled):
<add> def __call__(self, text, **disabled):
<ide> """
<ide> Apply the pipeline to some text. The text can span multiple sentences,
<ide> and can contain arbtrary whitespace. Alignment into the original string
<ide> is preserved.
<ide>
<ide> Args:
<ide> text (unicode): The text to be processed.
<del> state: Arbitrary
<ide>
<ide> Returns:
<ide> doc (Doc): A container for accessing the annotations.
<ide> def __call__(self, text, state=None, **disabled):
<ide> name = getattr(proc, 'name', None)
<ide> if name in disabled and not disabled[name]:
<ide> continue
<del> state = proc(doc, state=state)
<add> proc(doc)
<ide> return doc
<ide>
<del> def update(self, docs, golds, state=None, drop=0., sgd=None):
<add> def update(self, docs, golds, drop=0., sgd=None):
<ide> grads = {}
<ide> def get_grads(W, dW, key=None):
<ide> grads[key] = (W, dW)
<del> state = {} if state is None else state
<del> for process in self.pipeline:
<del> if hasattr(process, 'update'):
<del> state = process.update(docs, golds,
<del> state=state,
<del> drop=drop,
<del> sgd=get_grads)
<del> else:
<del> process(docs, state=state)
<del> if sgd is not None:
<del> for key, (W, dW) in grads.items():
<del> # TODO: Unhack this when thinc improves
<del> if isinstance(W, numpy.ndarray):
<del> sgd.ops = NumpyOps()
<del> else:
<del> sgd.ops = CupyOps()
<del> sgd(W, dW, key=key)
<del> return state
<add> tok2vec = self.pipeline[0]
<add> feats = tok2vec.doc2feats(docs)
<add> for proc in self.pipeline[1:]:
<add> tokvecs, bp_tokvecs = tok2vec.model.begin_update(feats, drop=drop)
<add> grads = {}
<add> d_tokvecs = proc.update((docs, tokvecs), golds, sgd=get_grads, drop=drop)
<add> bp_tokvecs(d_tokvecs, sgd=get_grads)
<add> if sgd is not None:
<add> for key, (W, dW) in grads.items():
<add> # TODO: Unhack this when thinc improves
<add> if isinstance(W, numpy.ndarray):
<add> sgd.ops = NumpyOps()
<add> else:
<add> sgd.ops = CupyOps()
<add> sgd(W, dW, key=key)
<ide>
<ide> @contextmanager
<ide> def begin_training(self, gold_tuples, **cfg):
<ide> def pipe(self, texts, n_threads=2, batch_size=1000, **disabled):
<ide> parse (bool)
<ide> entity (bool)
<ide> """
<del> #stream = ((self.make_doc(text), None) for text in texts)
<del> stream = ((doc, {}) for doc in texts)
<add> #docs = (self.make_doc(text) for text in texts)
<add> docs = texts
<ide> for proc in self.pipeline:
<ide> name = getattr(proc, 'name', None)
<ide> if name in disabled and not disabled[name]:
<ide> continue
<ide>
<ide> if hasattr(proc, 'pipe'):
<del> stream = proc.pipe(stream, n_threads=n_threads, batch_size=batch_size)
<add> docs = proc.pipe(docs, n_threads=n_threads, batch_size=batch_size)
<ide> else:
<del> stream = (proc(doc, state) for doc, state in stream)
<del> for doc, state in stream:
<add> docs = (proc(doc) for doc in docs)
<add> for doc in docs:
<ide> yield doc
<ide>
<ide> def to_disk(self, path, **exclude): | 1 |
Javascript | Javascript | remove some unwanted code | f6f175db73ad60d413a05613f7536a9fa7a16e10 | <ide><path>server/render.js
<ide> import { renderToString, renderToStaticMarkup } from 'react-dom/server'
<ide> import send from 'send'
<ide> import requireModule from './require'
<ide> import resolvePath from './resolve'
<del>import readPage from './read-page'
<ide> import { Router } from '../lib/router'
<ide> import { loadGetInitialProps } from '../lib/utils'
<ide> import Head, { defaultHead } from '../lib/head'
<ide> async function doRender (req, res, pathname, query, {
<ide> Component = Component.default || Component
<ide> Document = Document.default || Document
<ide> const ctx = { err, req, res, pathname, query }
<del>
<del> const [
<del> props,
<del> component,
<del> errorComponent
<del> ] = await Promise.all([
<del> loadGetInitialProps(Component, ctx),
<del> readPage(join(dir, '.next', 'bundles', 'pages', page)),
<del> readPage(join(dir, '.next', 'bundles', 'pages', '_error'))
<del> ])
<add> const props = await loadGetInitialProps(Component, ctx)
<ide>
<ide> // the response might be finshed on the getinitialprops call
<ide> if (res.finished) return
<ide> async function doRender (req, res, pathname, query, {
<ide> err: (err && dev) ? errorToJSON(err) : null
<ide> },
<ide> dev,
<del> component,
<del> errorComponent,
<ide> staticMarkup,
<ide> ...docProps
<ide> }) | 1 |
Go | Go | remove sys.go mocking framework | 39d244a593aad63be58d8b2e452715e25135f255 | <ide><path>daemon/graphdriver/devmapper/attach_loopback.go
<ide> package devmapper
<ide>
<ide> import (
<ide> "fmt"
<add> "os"
<add> "syscall"
<add>
<ide> "github.com/dotcloud/docker/utils"
<ide> )
<ide>
<ide> func stringToLoopName(src string) [LoNameSize]uint8 {
<ide> }
<ide>
<ide> func getNextFreeLoopbackIndex() (int, error) {
<del> f, err := osOpenFile("/dev/loop-control", osORdOnly, 0644)
<add> f, err := os.OpenFile("/dev/loop-control", os.O_RDONLY, 0644)
<ide> if err != nil {
<ide> return 0, err
<ide> }
<ide> func getNextFreeLoopbackIndex() (int, error) {
<ide> return index, err
<ide> }
<ide>
<del>func openNextAvailableLoopback(index int, sparseFile *osFile) (loopFile *osFile, err error) {
<add>func openNextAvailableLoopback(index int, sparseFile *os.File) (loopFile *os.File, err error) {
<ide> // Start looking for a free /dev/loop
<ide> for {
<ide> target := fmt.Sprintf("/dev/loop%d", index)
<ide> index++
<ide>
<del> fi, err := osStat(target)
<add> fi, err := os.Stat(target)
<ide> if err != nil {
<del> if osIsNotExist(err) {
<add> if os.IsNotExist(err) {
<ide> utils.Errorf("There are no more loopback device available.")
<ide> }
<ide> return nil, ErrAttachLoopbackDevice
<ide> }
<ide>
<del> if fi.Mode()&osModeDevice != osModeDevice {
<add> if fi.Mode()&os.ModeDevice != os.ModeDevice {
<ide> utils.Errorf("Loopback device %s is not a block device.", target)
<ide> continue
<ide> }
<ide>
<ide> // OpenFile adds O_CLOEXEC
<del> loopFile, err = osOpenFile(target, osORdWr, 0644)
<add> loopFile, err = os.OpenFile(target, os.O_RDWR, 0644)
<ide> if err != nil {
<ide> utils.Errorf("Error openning loopback device: %s", err)
<ide> return nil, ErrAttachLoopbackDevice
<ide> func openNextAvailableLoopback(index int, sparseFile *osFile) (loopFile *osFile,
<ide> loopFile.Close()
<ide>
<ide> // If the error is EBUSY, then try the next loopback
<del> if err != sysEBusy {
<add> if err != syscall.EBUSY {
<ide> utils.Errorf("Cannot set up loopback device %s: %s", target, err)
<ide> return nil, ErrAttachLoopbackDevice
<ide> }
<ide> func openNextAvailableLoopback(index int, sparseFile *osFile) (loopFile *osFile,
<ide> }
<ide>
<ide> // attachLoopDevice attaches the given sparse file to the next
<del>// available loopback device. It returns an opened *osFile.
<del>func attachLoopDevice(sparseName string) (loop *osFile, err error) {
<add>// available loopback device. It returns an opened *os.File.
<add>func attachLoopDevice(sparseName string) (loop *os.File, err error) {
<ide>
<ide> // Try to retrieve the next available loopback device via syscall.
<ide> // If it fails, we discard error and start loopking for a
<ide> func attachLoopDevice(sparseName string) (loop *osFile, err error) {
<ide> }
<ide>
<ide> // OpenFile adds O_CLOEXEC
<del> sparseFile, err := osOpenFile(sparseName, osORdWr, 0644)
<add> sparseFile, err := os.OpenFile(sparseName, os.O_RDWR, 0644)
<ide> if err != nil {
<ide> utils.Errorf("Error openning sparse file %s: %s", sparseName, err)
<ide> return nil, ErrAttachLoopbackDevice
<ide><path>daemon/graphdriver/devmapper/deviceset.go
<ide> import (
<ide> "fmt"
<ide> "io"
<ide> "io/ioutil"
<add> "os"
<add> "os/exec"
<ide> "path"
<ide> "path/filepath"
<ide> "strconv"
<ide> func (devices *DeviceSet) hasImage(name string) bool {
<ide> dirname := devices.loopbackDir()
<ide> filename := path.Join(dirname, name)
<ide>
<del> _, err := osStat(filename)
<add> _, err := os.Stat(filename)
<ide> return err == nil
<ide> }
<ide>
<ide> func (devices *DeviceSet) ensureImage(name string, size int64) (string, error) {
<ide> dirname := devices.loopbackDir()
<ide> filename := path.Join(dirname, name)
<ide>
<del> if err := osMkdirAll(dirname, 0700); err != nil && !osIsExist(err) {
<add> if err := os.MkdirAll(dirname, 0700); err != nil && !os.IsExist(err) {
<ide> return "", err
<ide> }
<ide>
<del> if _, err := osStat(filename); err != nil {
<del> if !osIsNotExist(err) {
<add> if _, err := os.Stat(filename); err != nil {
<add> if !os.IsNotExist(err) {
<ide> return "", err
<ide> }
<ide> utils.Debugf("Creating loopback file %s for device-manage use", filename)
<del> file, err := osOpenFile(filename, osORdWr|osOCreate, 0600)
<add> file, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0600)
<ide> if err != nil {
<ide> return "", err
<ide> }
<ide> func (devices *DeviceSet) allocateTransactionId() uint64 {
<ide> }
<ide>
<ide> func (devices *DeviceSet) removeMetadata(info *DevInfo) error {
<del> if err := osRemoveAll(devices.metadataFile(info)); err != nil {
<add> if err := os.RemoveAll(devices.metadataFile(info)); err != nil {
<ide> return fmt.Errorf("Error removing metadata file %s: %s", devices.metadataFile(info), err)
<ide> }
<ide> return nil
<ide> func (devices *DeviceSet) saveMetadata(info *DevInfo) error {
<ide> if err := tmpFile.Close(); err != nil {
<ide> return fmt.Errorf("Error closing metadata file %s: %s", tmpFile.Name(), err)
<ide> }
<del> if err := osRename(tmpFile.Name(), devices.metadataFile(info)); err != nil {
<add> if err := os.Rename(tmpFile.Name(), devices.metadataFile(info)); err != nil {
<ide> return fmt.Errorf("Error committing metadata file %s: %s", tmpFile.Name(), err)
<ide> }
<ide>
<ide> func (devices *DeviceSet) activateDeviceIfNeeded(info *DevInfo) error {
<ide> func (devices *DeviceSet) createFilesystem(info *DevInfo) error {
<ide> devname := info.DevName()
<ide>
<del> err := execRun("mkfs.ext4", "-E", "discard,lazy_itable_init=0,lazy_journal_init=0", devname)
<add> err := exec.Command("mkfs.ext4", "-E", "discard,lazy_itable_init=0,lazy_journal_init=0", devname).Run()
<ide> if err != nil {
<del> err = execRun("mkfs.ext4", "-E", "discard,lazy_itable_init=0", devname)
<add> err = exec.Command("mkfs.ext4", "-E", "discard,lazy_itable_init=0", devname).Run()
<ide> }
<ide> if err != nil {
<ide> utils.Debugf("\n--->Err: %s\n", err)
<ide> func (devices *DeviceSet) initMetaData() error {
<ide> // Migrate old metadatafile
<ide>
<ide> jsonData, err := ioutil.ReadFile(devices.oldMetadataFile())
<del> if err != nil && !osIsNotExist(err) {
<add> if err != nil && !os.IsNotExist(err) {
<ide> utils.Debugf("\n--->Err: %s\n", err)
<ide> return err
<ide> }
<ide> func (devices *DeviceSet) initMetaData() error {
<ide> devices.saveMetadata(info)
<ide> }
<ide> }
<del> if err := osRename(devices.oldMetadataFile(), devices.oldMetadataFile()+".migrated"); err != nil {
<add> if err := os.Rename(devices.oldMetadataFile(), devices.oldMetadataFile()+".migrated"); err != nil {
<ide> return err
<ide> }
<ide>
<ide> func (devices *DeviceSet) setupBaseImage() error {
<ide> func setCloseOnExec(name string) {
<ide> if fileInfos, _ := ioutil.ReadDir("/proc/self/fd"); fileInfos != nil {
<ide> for _, i := range fileInfos {
<del> link, _ := osReadlink(filepath.Join("/proc/self/fd", i.Name()))
<add> link, _ := os.Readlink(filepath.Join("/proc/self/fd", i.Name()))
<ide> if link == name {
<ide> fd, err := strconv.Atoi(i.Name())
<ide> if err == nil {
<del> sysCloseOnExec(fd)
<add> syscall.CloseOnExec(fd)
<ide> }
<ide> }
<ide> }
<ide> func (devices *DeviceSet) ResizePool(size int64) error {
<ide> datafilename := path.Join(dirname, "data")
<ide> metadatafilename := path.Join(dirname, "metadata")
<ide>
<del> datafile, err := osOpenFile(datafilename, osORdWr, 0)
<add> datafile, err := os.OpenFile(datafilename, os.O_RDWR, 0)
<ide> if datafile == nil {
<ide> return err
<ide> }
<ide> func (devices *DeviceSet) ResizePool(size int64) error {
<ide> }
<ide> defer dataloopback.Close()
<ide>
<del> metadatafile, err := osOpenFile(metadatafilename, osORdWr, 0)
<add> metadatafile, err := os.OpenFile(metadatafilename, os.O_RDWR, 0)
<ide> if metadatafile == nil {
<ide> return err
<ide> }
<ide> func (devices *DeviceSet) ResizePool(size int64) error {
<ide> func (devices *DeviceSet) initDevmapper(doInit bool) error {
<ide> logInit(devices)
<ide>
<del> if err := osMkdirAll(devices.metadataDir(), 0700); err != nil && !osIsExist(err) {
<add> if err := os.MkdirAll(devices.metadataDir(), 0700); err != nil && !os.IsExist(err) {
<ide> return err
<ide> }
<ide>
<ide> // Set the device prefix from the device id and inode of the docker root dir
<ide>
<del> st, err := osStat(devices.root)
<add> st, err := os.Stat(devices.root)
<ide> if err != nil {
<ide> return fmt.Errorf("Error looking up dir %s: %s", devices.root, err)
<ide> }
<del> sysSt := toSysStatT(st.Sys())
<add> sysSt := st.Sys().(*syscall.Stat_t)
<ide> // "reg-" stands for "regular file".
<ide> // In the future we might use "dev-" for "device file", etc.
<ide> // docker-maj,min[-inode] stands for:
<ide> func (devices *DeviceSet) Shutdown() error {
<ide> // We use MNT_DETACH here in case it is still busy in some running
<ide> // container. This means it'll go away from the global scope directly,
<ide> // and the device will be released when that container dies.
<del> if err := sysUnmount(info.mountPath, syscall.MNT_DETACH); err != nil {
<add> if err := syscall.Unmount(info.mountPath, syscall.MNT_DETACH); err != nil {
<ide> utils.Debugf("Shutdown unmounting %s, error: %s\n", info.mountPath, err)
<ide> }
<ide>
<ide> func (devices *DeviceSet) MountDevice(hash, path, mountLabel string) error {
<ide> return fmt.Errorf("Error activating devmapper device for '%s': %s", hash, err)
<ide> }
<ide>
<del> var flags uintptr = sysMsMgcVal
<add> var flags uintptr = syscall.MS_MGC_VAL
<ide>
<ide> mountOptions := label.FormatMountLabel("discard", mountLabel)
<del> err = sysMount(info.DevName(), path, "ext4", flags, mountOptions)
<del> if err != nil && err == sysEInval {
<add> err = syscall.Mount(info.DevName(), path, "ext4", flags, mountOptions)
<add> if err != nil && err == syscall.EINVAL {
<ide> mountOptions = label.FormatMountLabel("", mountLabel)
<del> err = sysMount(info.DevName(), path, "ext4", flags, mountOptions)
<add> err = syscall.Mount(info.DevName(), path, "ext4", flags, mountOptions)
<ide> }
<ide> if err != nil {
<ide> return fmt.Errorf("Error mounting '%s' on '%s': %s", info.DevName(), path, err)
<ide> func (devices *DeviceSet) UnmountDevice(hash string) error {
<ide> }
<ide>
<ide> utils.Debugf("[devmapper] Unmount(%s)", info.mountPath)
<del> if err := sysUnmount(info.mountPath, 0); err != nil {
<add> if err := syscall.Unmount(info.mountPath, 0); err != nil {
<ide> utils.Debugf("\n--->Err: %s\n", err)
<ide> return err
<ide> }
<ide><path>daemon/graphdriver/devmapper/devmapper.go
<ide> package devmapper
<ide> import (
<ide> "errors"
<ide> "fmt"
<del> "github.com/dotcloud/docker/utils"
<add> "os"
<ide> "runtime"
<ide> "syscall"
<add>
<add> "github.com/dotcloud/docker/utils"
<ide> )
<ide>
<ide> type DevmapperLogger interface {
<ide> func (t *Task) GetNextTarget(next uintptr) (nextPtr uintptr, start uint64,
<ide> start, length, targetType, params
<ide> }
<ide>
<del>func getLoopbackBackingFile(file *osFile) (uint64, uint64, error) {
<add>func getLoopbackBackingFile(file *os.File) (uint64, uint64, error) {
<ide> loopInfo, err := ioctlLoopGetStatus64(file.Fd())
<ide> if err != nil {
<ide> utils.Errorf("Error get loopback backing file: %s\n", err)
<ide> func getLoopbackBackingFile(file *osFile) (uint64, uint64, error) {
<ide> return loopInfo.loDevice, loopInfo.loInode, nil
<ide> }
<ide>
<del>func LoopbackSetCapacity(file *osFile) error {
<add>func LoopbackSetCapacity(file *os.File) error {
<ide> if err := ioctlLoopSetCapacity(file.Fd(), 0); err != nil {
<ide> utils.Errorf("Error loopbackSetCapacity: %s", err)
<ide> return ErrLoopbackSetCapacity
<ide> }
<ide> return nil
<ide> }
<ide>
<del>func FindLoopDeviceFor(file *osFile) *osFile {
<add>func FindLoopDeviceFor(file *os.File) *os.File {
<ide> stat, err := file.Stat()
<ide> if err != nil {
<ide> return nil
<ide> }
<del> targetInode := stat.Sys().(*sysStatT).Ino
<del> targetDevice := stat.Sys().(*sysStatT).Dev
<add> targetInode := stat.Sys().(*syscall.Stat_t).Ino
<add> targetDevice := stat.Sys().(*syscall.Stat_t).Dev
<ide>
<ide> for i := 0; true; i++ {
<ide> path := fmt.Sprintf("/dev/loop%d", i)
<ide>
<del> file, err := osOpenFile(path, osORdWr, 0)
<add> file, err := os.OpenFile(path, os.O_RDWR, 0)
<ide> if err != nil {
<del> if osIsNotExist(err) {
<add> if os.IsNotExist(err) {
<ide> return nil
<ide> }
<ide>
<ide> func RemoveDevice(name string) error {
<ide> return nil
<ide> }
<ide>
<del>func GetBlockDeviceSize(file *osFile) (uint64, error) {
<add>func GetBlockDeviceSize(file *os.File) (uint64, error) {
<ide> size, err := ioctlBlkGetSize64(file.Fd())
<ide> if err != nil {
<ide> utils.Errorf("Error getblockdevicesize: %s", err)
<ide> func GetBlockDeviceSize(file *osFile) (uint64, error) {
<ide> }
<ide>
<ide> func BlockDeviceDiscard(path string) error {
<del> file, err := osOpenFile(path, osORdWr, 0)
<add> file, err := os.OpenFile(path, os.O_RDWR, 0)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func BlockDeviceDiscard(path string) error {
<ide> }
<ide>
<ide> // This is the programmatic example of "dmsetup create"
<del>func createPool(poolName string, dataFile, metadataFile *osFile) error {
<add>func createPool(poolName string, dataFile, metadataFile *os.File) error {
<ide> task, err := createTask(DeviceCreate, poolName)
<ide> if task == nil {
<ide> return err
<ide> func createPool(poolName string, dataFile, metadataFile *osFile) error {
<ide> return nil
<ide> }
<ide>
<del>func reloadPool(poolName string, dataFile, metadataFile *osFile) error {
<add>func reloadPool(poolName string, dataFile, metadataFile *os.File) error {
<ide> task, err := createTask(DeviceReload, poolName)
<ide> if task == nil {
<ide> return err
<ide><path>daemon/graphdriver/devmapper/driver.go
<ide> type Driver struct {
<ide> home string
<ide> }
<ide>
<del>var Init = func(home string) (graphdriver.Driver, error) {
<add>func Init(home string) (graphdriver.Driver, error) {
<ide> deviceSet, err := NewDeviceSet(home, true)
<ide> if err != nil {
<ide> return nil, err
<ide> func (d *Driver) Get(id, mountLabel string) (string, error) {
<ide> mp := path.Join(d.home, "mnt", id)
<ide>
<ide> // Create the target directories if they don't exist
<del> if err := osMkdirAll(mp, 0755); err != nil && !osIsExist(err) {
<add> if err := os.MkdirAll(mp, 0755); err != nil && !os.IsExist(err) {
<ide> return "", err
<ide> }
<ide>
<ide> func (d *Driver) Get(id, mountLabel string) (string, error) {
<ide> }
<ide>
<ide> rootFs := path.Join(mp, "rootfs")
<del> if err := osMkdirAll(rootFs, 0755); err != nil && !osIsExist(err) {
<add> if err := os.MkdirAll(rootFs, 0755); err != nil && !os.IsExist(err) {
<ide> d.DeviceSet.UnmountDevice(id)
<ide> return "", err
<ide> }
<ide>
<ide> idFile := path.Join(mp, "id")
<del> if _, err := osStat(idFile); err != nil && osIsNotExist(err) {
<add> if _, err := os.Stat(idFile); err != nil && os.IsNotExist(err) {
<ide> // Create an "id" file with the container/image id in it to help reconscruct this in case
<ide> // of later problems
<ide> if err := ioutil.WriteFile(idFile, []byte(id), 0600); err != nil {
<ide><path>daemon/graphdriver/devmapper/ioctl.go
<ide> package devmapper
<ide>
<ide> import (
<add> "syscall"
<ide> "unsafe"
<ide> )
<ide>
<ide> func ioctlLoopCtlGetFree(fd uintptr) (int, error) {
<del> index, _, err := sysSyscall(sysSysIoctl, fd, LoopCtlGetFree, 0)
<add> index, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, LoopCtlGetFree, 0)
<ide> if err != 0 {
<ide> return 0, err
<ide> }
<ide> return int(index), nil
<ide> }
<ide>
<ide> func ioctlLoopSetFd(loopFd, sparseFd uintptr) error {
<del> if _, _, err := sysSyscall(sysSysIoctl, loopFd, LoopSetFd, sparseFd); err != 0 {
<add> if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, loopFd, LoopSetFd, sparseFd); err != 0 {
<ide> return err
<ide> }
<ide> return nil
<ide> }
<ide>
<ide> func ioctlLoopSetStatus64(loopFd uintptr, loopInfo *LoopInfo64) error {
<del> if _, _, err := sysSyscall(sysSysIoctl, loopFd, LoopSetStatus64, uintptr(unsafe.Pointer(loopInfo))); err != 0 {
<add> if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, loopFd, LoopSetStatus64, uintptr(unsafe.Pointer(loopInfo))); err != 0 {
<ide> return err
<ide> }
<ide> return nil
<ide> }
<ide>
<ide> func ioctlLoopClrFd(loopFd uintptr) error {
<del> if _, _, err := sysSyscall(sysSysIoctl, loopFd, LoopClrFd, 0); err != 0 {
<add> if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, loopFd, LoopClrFd, 0); err != 0 {
<ide> return err
<ide> }
<ide> return nil
<ide> func ioctlLoopClrFd(loopFd uintptr) error {
<ide> func ioctlLoopGetStatus64(loopFd uintptr) (*LoopInfo64, error) {
<ide> loopInfo := &LoopInfo64{}
<ide>
<del> if _, _, err := sysSyscall(sysSysIoctl, loopFd, LoopGetStatus64, uintptr(unsafe.Pointer(loopInfo))); err != 0 {
<add> if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, loopFd, LoopGetStatus64, uintptr(unsafe.Pointer(loopInfo))); err != 0 {
<ide> return nil, err
<ide> }
<ide> return loopInfo, nil
<ide> }
<ide>
<ide> func ioctlLoopSetCapacity(loopFd uintptr, value int) error {
<del> if _, _, err := sysSyscall(sysSysIoctl, loopFd, LoopSetCapacity, uintptr(value)); err != 0 {
<add> if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, loopFd, LoopSetCapacity, uintptr(value)); err != 0 {
<ide> return err
<ide> }
<ide> return nil
<ide> }
<ide>
<ide> func ioctlBlkGetSize64(fd uintptr) (int64, error) {
<ide> var size int64
<del> if _, _, err := sysSyscall(sysSysIoctl, fd, BlkGetSize64, uintptr(unsafe.Pointer(&size))); err != 0 {
<add> if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, BlkGetSize64, uintptr(unsafe.Pointer(&size))); err != 0 {
<ide> return 0, err
<ide> }
<ide> return size, nil
<ide> func ioctlBlkDiscard(fd uintptr, offset, length uint64) error {
<ide> r[0] = offset
<ide> r[1] = length
<ide>
<del> if _, _, err := sysSyscall(sysSysIoctl, fd, BlkDiscard, uintptr(unsafe.Pointer(&r[0]))); err != 0 {
<add> if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, BlkDiscard, uintptr(unsafe.Pointer(&r[0]))); err != 0 {
<ide> return err
<ide> }
<ide> return nil
<ide><path>daemon/graphdriver/devmapper/mount.go
<ide> package devmapper
<ide>
<ide> import (
<add> "os"
<ide> "path/filepath"
<add> "syscall"
<ide> )
<ide>
<ide> // FIXME: this is copy-pasted from the aufs driver.
<ide> // It should be moved into the core.
<ide>
<del>var Mounted = func(mountpoint string) (bool, error) {
<del> mntpoint, err := osStat(mountpoint)
<add>func Mounted(mountpoint string) (bool, error) {
<add> mntpoint, err := os.Stat(mountpoint)
<ide> if err != nil {
<del> if osIsNotExist(err) {
<add> if os.IsNotExist(err) {
<ide> return false, nil
<ide> }
<ide> return false, err
<ide> }
<del> parent, err := osStat(filepath.Join(mountpoint, ".."))
<add> parent, err := os.Stat(filepath.Join(mountpoint, ".."))
<ide> if err != nil {
<ide> return false, err
<ide> }
<del> mntpointSt := toSysStatT(mntpoint.Sys())
<del> parentSt := toSysStatT(parent.Sys())
<add> mntpointSt := mntpoint.Sys().(*syscall.Stat_t)
<add> parentSt := parent.Sys().(*syscall.Stat_t)
<ide> return mntpointSt.Dev != parentSt.Dev, nil
<ide> }
<ide><path>daemon/graphdriver/devmapper/sys.go
<del>// +build linux,amd64
<del>
<del>package devmapper
<del>
<del>import (
<del> "os"
<del> "os/exec"
<del> "syscall"
<del>)
<del>
<del>type (
<del> sysStatT syscall.Stat_t
<del> sysErrno syscall.Errno
<del>
<del> osFile struct{ *os.File }
<del>)
<del>
<del>var (
<del> sysMount = syscall.Mount
<del> sysUnmount = syscall.Unmount
<del> sysCloseOnExec = syscall.CloseOnExec
<del> sysSyscall = syscall.Syscall
<del>
<del> osOpenFile = func(name string, flag int, perm os.FileMode) (*osFile, error) {
<del> f, err := os.OpenFile(name, flag, perm)
<del> return &osFile{File: f}, err
<del> }
<del> osOpen = func(name string) (*osFile, error) { f, err := os.Open(name); return &osFile{File: f}, err }
<del> osNewFile = os.NewFile
<del> osCreate = os.Create
<del> osStat = os.Stat
<del> osIsNotExist = os.IsNotExist
<del> osIsExist = os.IsExist
<del> osMkdirAll = os.MkdirAll
<del> osRemoveAll = os.RemoveAll
<del> osRename = os.Rename
<del> osReadlink = os.Readlink
<del>
<del> execRun = func(name string, args ...string) error { return exec.Command(name, args...).Run() }
<del>)
<del>
<del>const (
<del> sysMsMgcVal = syscall.MS_MGC_VAL
<del> sysMsRdOnly = syscall.MS_RDONLY
<del> sysEInval = syscall.EINVAL
<del> sysSysIoctl = syscall.SYS_IOCTL
<del> sysEBusy = syscall.EBUSY
<del>
<del> osORdOnly = os.O_RDONLY
<del> osORdWr = os.O_RDWR
<del> osOCreate = os.O_CREATE
<del> osModeDevice = os.ModeDevice
<del>)
<del>
<del>func toSysStatT(i interface{}) *sysStatT {
<del> return (*sysStatT)(i.(*syscall.Stat_t))
<del>} | 7 |
Ruby | Ruby | add stubs for `sorbet-runtime` | ec5eb56a72864dbf4322b9996bcf6b90304d0d62 | <ide><path>Library/Homebrew/utils.rb
<ide> require "utils/livecheck_formula"
<ide> require "utils/popen"
<ide> require "utils/repology"
<add>require "utils/sorbet"
<ide> require "utils/svn"
<ide> require "utils/tty"
<ide> require "tap_constants"
<ide><path>Library/Homebrew/utils/sorbet.rb
<add># typed: strict
<add># frozen_string_literal: true
<add>
<add>if ENV["HOMEBREW_TESTS_COVERAGE"]
<add> require "sorbet-runtime"
<add>else
<add> require "utils/sorbet/stubs"
<add>end
<ide><path>Library/Homebrew/utils/sorbet/stubs.rb
<add># typed: false
<add># frozen_string_literal: true
<add>
<add># Stubs for `sorbet-runtime`, all taken from `sorbet/t` except for `T::Sig.sig`.
<add>#
<add># @private
<add>module T
<add> # rubocop:disable Style/Documentation
<add> module Sig
<add> module WithoutRuntime
<add> def self.sig(arg = nil, &blk); end
<add> end
<add>
<add> module_function
<add>
<add> def sig(arg = nil, &blk); end
<add> end
<add>
<add> def self.any(type_a, type_b, *types); end
<add>
<add> def self.nilable(type); end
<add>
<add> def self.untyped; end
<add>
<add> def self.noreturn; end
<add>
<add> def self.all(type_a, type_b, *types); end
<add>
<add> def self.enum(values); end
<add>
<add> def self.proc; end
<add>
<add> def self.self_type; end
<add>
<add> def self.class_of(klass); end
<add>
<add> def self.type_alias(type = nil, &blk); end
<add>
<add> def self.type_parameter(name); end
<add>
<add> def self.cast(value, _type, checked: true)
<add> value
<add> end
<add>
<add> def self.let(value, _type, checked: true)
<add> value
<add> end
<add>
<add> def self.assert_type!(value, _type, checked: true)
<add> value
<add> end
<add>
<add> def self.unsafe(value)
<add> value
<add> end
<add>
<add> def self.must(arg, _msg = nil)
<add> arg
<add> end
<add>
<add> def self.reveal_type(value)
<add> value
<add> end
<add>
<add> module Array
<add> def self.[](type); end
<add> end
<add>
<add> module Hash
<add> def self.[](keys, values); end
<add> end
<add>
<add> module Enumerable
<add> def self.[](type); end
<add> end
<add>
<add> module Range
<add> def self.[](type); end
<add> end
<add>
<add> module Set
<add> def self.[](type); end
<add> end
<add> # rubocop:enable Style/Documentation
<add>end | 3 |
Text | Text | update documentation [ci skip] | bc32fa66ee0ebf1be57adb6adae183e61291eed5 | <ide><path>guides/source/action_mailer_basics.md
<ide> Introduction
<ide> ------------
<ide>
<ide> Action Mailer allows you to send emails from your application using mailer classes
<del>and views. Mailers work very similarly to controllers. They inherit from
<del>`ActionMailer::Base` and live in `app/mailers`, and they have associated views
<del>that appear in `app/views`.
<add>and views.
<add>
<add>#### Mailers are similar to controllers
<add>They inherit from `ActionMailer::Base` and live in `app/mailers`. Mailers also work very similarly to controllers. Some examples of similarities are enumerated below. Mailers have:
<add>
<add>* actions, and also, associated views that appear in `app/views`.
<add>
<add>* instance variables that are accessible in views.
<add>
<add>* the ability to utilise layouts and partials.
<add>
<add>* the ability to access a params hash.
<ide>
<ide> Sending Emails
<ide> --------------
<ide> end
<ide> ```
<ide>
<ide> As you can see, you can generate mailers just like you use other generators with
<del>Rails. Mailers are conceptually similar to controllers, and so we get a mailer,
<del>a directory for views, and a test.
<add>Rails.
<ide>
<ide> If you didn't want to use a generator, you could create your own file inside of
<ide> `app/mailers`, just make sure that it inherits from `ActionMailer::Base`:
<ide> end
<ide>
<ide> #### Edit the Mailer
<ide>
<del>Mailers are very similar to Rails controllers. They also have methods called
<del>"actions" and use views to structure the content. Where a controller generates
<del>content like HTML to send back to the client, a Mailer creates a message to be
<del>delivered via email.
<add>Mailers have methods called "actions" and they use views to structure their content. Where a controller generates
<add>content like HTML to send back to the client, a Mailer creates a message to be delivered via email.
<ide>
<ide> `app/mailers/user_mailer.rb` contains an empty mailer:
<ide>
<ide> messages in this class. This can be overridden on a per-email basis.
<ide> * `mail` - The actual email message, we are passing the `:to` and `:subject`
<ide> headers in.
<ide>
<del>Just like controllers, any instance variables we define in the method become
<del>available for use in the views.
<del>
<ide> #### Create a Mailer View
<ide>
<ide> Create a file called `welcome_email.html.erb` in `app/views/user_mailer/`. This | 1 |
Go | Go | remove unused lookupimage() | 2527e6dd096517b2979c699933e73d5a1bedf74c | <ide><path>daemon/containerd/service.go
<ide> func (cs *ImageService) LoadImage(inTar io.ReadCloser, outStream io.Writer, quie
<ide> panic("not implemented")
<ide> }
<ide>
<del>// LookupImage is not implemented.
<del>func (cs *ImageService) LookupImage(ctx context.Context, name string) (*types.ImageInspect, error) {
<del> panic("not implemented")
<del>}
<del>
<ide> // PushImage initiates a push operation on the repository named localName.
<ide> func (cs *ImageService) PushImage(ctx context.Context, image, tag string, metaHeaders map[string][]string, authConfig *types.AuthConfig, outStream io.Writer) error {
<ide> panic("not implemented") | 1 |
Javascript | Javascript | fix orderedmap equality | 406b11935c4caed2c98446962e0a4d9180f6fa51 | <ide><path>dist/Immutable.dev.js
<ide> var $OrderedMap = OrderedMap;
<ide> return this._vector ? this._vector.fromEntries().__iterate(fn, reverse) : 0;
<ide> },
<ide> __deepEqual: function(other) {
<del> var iterator = this._vector.__iterator__();
<add> var iterator = this._vector.iterator();
<ide> return other.every((function(v, k) {
<del> var entry = iterator.next();
<add> var entry = iterator.next().value;
<ide> entry && (entry = entry[1]);
<ide> return entry && is(k, entry[0]) && is(v, entry[1]);
<ide> }));
<ide><path>dist/Immutable.js
<ide> return ze.from(t)},ze=Ue;te.createClass(Ue,{toString:function(){return this.__to
<ide> },merge:function(){return N(this,null,arguments)},mergeWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return N(this,t,e)},mergeDeep:function(){return N(this,q(null),arguments)},mergeDeepWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return N(this,q(t),e)},setLength:function(t){return K(this,0,t)},slice:function(t,e,r){var n=te.superCall(this,ze.prototype,"slice",[t,e,r]);if(!r&&n!==this){var i=this,u=i.length;n.toVector=function(){return K(i,0>t?Math.max(0,u+t):u?Math.min(u,t):t,null==e?u:0>e?Math.max(0,u+e):u?Math.min(u,e):e)}}return n},iterator:function(){return new Be(this,this._origin,this._size,this._level,this._root,this._tail)},__iterate:function(t,e,r){var n=this,i=0,u=n.length-1;r^=e;var s,a=function(e,s){return t(e,r?u-s:s,n)===!1?!1:(i=s,!0)},h=G(this._size);return s=e?this._tail.iterate(0,h-this._origin,this._size-this._origin,a,e)&&this._root.iterate(this._level,-this._origin,h-this._origin,a,e):this._root.iterate(this._level,-this._origin,h-this._origin,a,e)&&this._tail.iterate(0,h-this._origin,this._size-this._origin,a,e),(s?u:e?u-i:i)+1},__deepEquals:function(t){var e=this.iterator();return t.every(function(t,r){var n=e.next().value;return n&&r===n[0]&&w(t,n[1])})},__ensureOwner:function(t){return t===this.__ownerID?this:t?L(this._origin,this._size,this._level,this._root,this._tail,t):(this.__ownerID=t,this)}},{empty:function(){return Le||(Le=L(0,0,fe,Ve,Ve))},from:function(t){if(t&&t.constructor===ze)return t;if(!t||0===t.length)return ze.empty();var e=Array.isArray(t);return t.length>0&&le>t.length?L(0,t.length,fe,Ve,new We(e?t.slice():ee(t).toArray())):(e||(t=ee(t),t instanceof ie||(t=t.values())),ze.empty().merge(t))}},ie);var Re=Ue.prototype;Re["@@iterator"]=Re.__iterator__,Re.update=me.update,Re.updateIn=me.updateIn,Re.cursor=me.cursor,Re.withMutations=me.withMutations,Re.asMutable=me.asMutable,Re.asImmutable=me.asImmutable;var We=function(t,e){this.array=t,this.ownerID=e},Je=We;te.createClass(We,{ensureOwner:function(t){return t&&t===this.ownerID?this:new Je(this.array.slice(),t)
<ide> },removeBefore:function(t,e,r){if(r===e?1<<e:0||0===this.array.length)return this;var n=r>>>e&_e;if(n>=this.array.length)return new Je([],t);var i,u=0===n;if(e>0){var s=this.array[n];if(i=s&&s.removeBefore(t,e-fe,r),i===s&&u)return this}if(u&&!i)return this;var a=this.ensureOwner();if(!u)for(var h=0;n>h;h++)delete a.array[h];return i&&(a.array[n]=i),a},removeAfter:function(t,e,r){if(r===e?1<<e:0||0===this.array.length)return this;var n=r-1>>>e&_e;if(n>=this.array.length)return this;var i,u=n===this.array.length-1;if(e>0){var s=this.array[n];if(i=s&&s.removeAfter(t,e-fe,r),i===s&&u)return this}if(u&&!i)return this;var a=this.ensureOwner();return u||(a.array.length=n+1),i&&(a.array[n]=i),a},iterate:function(t,e,r,n,i){if(0===t){if(i){for(var u=this.array.length-1;u>=0;u--)if(this.array.hasOwnProperty(u)){var s=u+e;if(s>=0&&r>s&&n(this.array[u],s)===!1)return!1}return!0}return this.array.every(function(t,i){var u=i+e;return 0>u||u>=r||n(t,u)!==!1})}var a=1<<t,h=t-fe;if(i){for(var o=this.array.length-1;o>=0;o--){var c=e+o*a;if(r>c&&c+a>0&&this.array.hasOwnProperty(o)&&!this.array[o].iterate(h,c,r,n,i))return!1}return!0}return this.array.every(function(t,u){var s=e+u*a;return s>=r||0>=s+a||t.iterate(h,s,r,n,i)})}},{});var Be=function(t,e,r,n,i,u){var s=G(r);this._stack={node:i.array,level:n,offset:-e,max:s-e,__prev:{node:u.array,level:0,offset:s-e,max:r-e}}};te.createClass(Be,{next:function(){var t=this._stack;t:for(;t;){if(0===t.level)for(t.rawIndex||(t.rawIndex=0);t.node.length>t.rawIndex;){var e=t.rawIndex+t.offset;if(e>=0&&t.max>e&&t.node.hasOwnProperty(t.rawIndex)){var r=t.node[t.rawIndex];return t.rawIndex++,{value:[e,r],done:!0}}t.rawIndex++}else{var n=1<<t.level;for(t.levelIndex||(t.levelIndex=0);t.node.length>t.levelIndex;){var i=t.offset+t.levelIndex*n;if(i+n>0&&t.max>i&&t.node.hasOwnProperty(t.levelIndex)){var u=t.node[t.levelIndex].array;t.levelIndex++,t=this._stack={node:u,level:t.level-fe,offset:i,max:t.max,__prev:t};continue t}t.levelIndex++}}t=this._stack=this._stack.__prev}return{done:!0}}},{});var Le,Ve=new We([]),Ke=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];
<ide> return Ne.from(t)},Ne=Ke;te.createClass(Ke,{toString:function(){return this.__toString("Set {","}")},has:function(t){return this._map?this._map.has(t):!1},get:function(t,e){return this.has(t)?t:e},add:function(t){if(null==t)return this;var e=this._map;return e||(e=ge.empty().__ensureOwner(this.__ownerID)),e=e.set(t,null),this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:H(e)},"delete":function(t){if(null==t||null==this._map)return this;var e=this._map.delete(t);return 0===e.length?this.clear():this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:H(e)},clear:function(){return this.__ownerID?(this.length=0,this._map=null,this):Ne.empty()},union:function(){var t=arguments;return 0===t.length?this:this.withMutations(function(e){for(var r=0;t.length>r;r++){var n=t[r];n=n.forEach?n:ee(n),n.forEach(function(t){return e.add(t)})}})},intersect:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return ee(t)});var r=this;return this.withMutations(function(e){r.forEach(function(r){t.every(function(t){return t.contains(r)})||e.delete(r)})})},subtract:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return ee(t)});var r=this;return this.withMutations(function(e){r.forEach(function(r){t.some(function(t){return t.contains(r)})&&e.delete(r)})})},isSubset:function(t){return t=ee(t),this.every(function(e){return t.contains(e)})},isSuperset:function(t){var e=this;return t=ee(t),t.every(function(t){return e.contains(t)})},__iterate:function(t,e){var r=this;return this._map?this._map.__iterate(function(e,n){return t(n,n,r)},e):0},__deepEquals:function(t){return!(this._map||t._map)||this._map.equals(t._map)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t);return t?H(e,t):(this.__ownerID=t,this._map=e,this)}},{empty:function(){return Ge||(Ge=H())},from:function(t){return t&&t.constructor===Ne?t:t&&0!==t.length?Ne.empty().union(t):Ne.empty()
<del>},fromKeys:function(t){return Ne.from(ee(t).flip())}},ee);var Fe=Ke.prototype;Fe.contains=Fe.has,Fe.withMutations=ge.prototype.withMutations,Fe.asMutable=ge.prototype.asMutable,Fe.asImmutable=ge.prototype.asImmutable,Fe.__toJS=ie.prototype.__toJS,Fe.__toStringMapper=ie.prototype.__toStringMapper;var Ge,He=function(t){return t&&t.constructor===Qe?t:t&&0!==t.length?Qe.empty().merge(t):Qe.empty()},Qe=He;te.createClass(He,{toString:function(){return this.__toString("OrderedMap {","}")},get:function(t,e){if(null!=t&&this._map){var r=this._map.get(t);if(null!=r)return this._vector.get(r)[1]}return e},clear:function(){return this.__ownerID?(this.length=0,this._map=this._vector=null,this):Qe.empty()},set:function(t,e){if(null==t)return this;var r=this._map,n=this._vector;if(r){var i=r.get(t);null==i?(r=r.set(t,n.length),n=n.push([t,e])):n.get(i)[1]!==e&&(n=n.set(i,[t,e]))}else n=Ue.empty().__ensureOwner(this.__ownerID).set(0,[t,e]),r=ge.empty().__ensureOwner(this.__ownerID).set(t,0);return this.__ownerID?(this.length=r.length,this._map=r,this._vector=n,this):n===this._vector?this:Q(r,n)},"delete":function(t){if(null==t||null==this._map)return this;var e=this._map.get(t);if(null==e)return this;var r=this._map.delete(t),n=this._vector.delete(e);return 0===r.length?this.clear():this.__ownerID?(this.length=r.length,this._map=r,this._vector=n,this):r===this._map?this:Q(r,n)},__iterate:function(t,e){return this._vector?this._vector.fromEntries().__iterate(t,e):0},__deepEqual:function(t){var e=this._vector.__iterator__();return t.every(function(t,r){var n=e.next();return n&&(n=n[1]),n&&w(r,n[0])&&w(t,n[1])})},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t),r=this._vector&&this._vector.__ensureOwner(t);return t?Q(e,r,t):(this.__ownerID=t,this._map=e,this._vector=r,this)}},{empty:function(){return Te||(Te=Q())}},ge),He.from=He;var Te,Xe=function(t,e){var r=function(t){this._map=ge(t)};t=ee(t);var n=r.prototype=Object.create(Ze);n.constructor=r,n._name=e,n._defaultValues=t;var i=Object.keys(t);
<add>},fromKeys:function(t){return Ne.from(ee(t).flip())}},ee);var Fe=Ke.prototype;Fe.contains=Fe.has,Fe.withMutations=ge.prototype.withMutations,Fe.asMutable=ge.prototype.asMutable,Fe.asImmutable=ge.prototype.asImmutable,Fe.__toJS=ie.prototype.__toJS,Fe.__toStringMapper=ie.prototype.__toStringMapper;var Ge,He=function(t){return t&&t.constructor===Qe?t:t&&0!==t.length?Qe.empty().merge(t):Qe.empty()},Qe=He;te.createClass(He,{toString:function(){return this.__toString("OrderedMap {","}")},get:function(t,e){if(null!=t&&this._map){var r=this._map.get(t);if(null!=r)return this._vector.get(r)[1]}return e},clear:function(){return this.__ownerID?(this.length=0,this._map=this._vector=null,this):Qe.empty()},set:function(t,e){if(null==t)return this;var r=this._map,n=this._vector;if(r){var i=r.get(t);null==i?(r=r.set(t,n.length),n=n.push([t,e])):n.get(i)[1]!==e&&(n=n.set(i,[t,e]))}else n=Ue.empty().__ensureOwner(this.__ownerID).set(0,[t,e]),r=ge.empty().__ensureOwner(this.__ownerID).set(t,0);return this.__ownerID?(this.length=r.length,this._map=r,this._vector=n,this):n===this._vector?this:Q(r,n)},"delete":function(t){if(null==t||null==this._map)return this;var e=this._map.get(t);if(null==e)return this;var r=this._map.delete(t),n=this._vector.delete(e);return 0===r.length?this.clear():this.__ownerID?(this.length=r.length,this._map=r,this._vector=n,this):r===this._map?this:Q(r,n)},__iterate:function(t,e){return this._vector?this._vector.fromEntries().__iterate(t,e):0},__deepEqual:function(t){var e=this._vector.iterator();return t.every(function(t,r){var n=e.next().value;return n&&(n=n[1]),n&&w(r,n[0])&&w(t,n[1])})},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t),r=this._vector&&this._vector.__ensureOwner(t);return t?Q(e,r,t):(this.__ownerID=t,this._map=e,this._vector=r,this)}},{empty:function(){return Te||(Te=Q())}},ge),He.from=He;var Te,Xe=function(t,e){var r=function(t){this._map=ge(t)};t=ee(t);var n=r.prototype=Object.create(Ze);n.constructor=r,n._name=e,n._defaultValues=t;var i=Object.keys(t);
<ide> return r.prototype.length=i.length,Object.defineProperty&&t.forEach(function(t,e){Object.defineProperty(r.prototype,e,{get:function(){return this.get(e)},set:function(t){I(this.__ownerID,"Cannot set on an immutable record."),this.set(e,t)}})}),r},Ye=Xe;te.createClass(Xe,{toString:function(){return this.__toString((this._name||"Record")+" {","}")},has:function(t){return this._defaultValues.has(t)},get:function(t,e){return void 0===e||this.has(t)?this._map.get(t,this._defaultValues.get(t)):e},clear:function(){if(this.__ownerID)return this._map.clear(),this;Object.getPrototypeOf(this).constructor;return Ye._empty||(Ye._empty=T(this,ge.empty()))},set:function(t,e){if(null==t||!this.has(t))return this;var r=this._map.set(t,e);return this.__ownerID||r===this._map?this:T(this,r)},"delete":function(t){if(null==t||!this.has(t))return this;var e=this._map.delete(t);return this.__ownerID||e===this._map?this:T(this,e)},__iterate:function(t,e){var r=this;return this._defaultValues.map(function(t,e){return r.get(e)}).__iterate(t,e)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t);return t?T(this,e,t):(this.__ownerID=t,this._map=e,this)}},{},ee);var Ze=Xe.prototype;Ze.__deepEqual=me.__deepEqual,Ze.merge=me.merge,Ze.mergeWith=me.mergeWith,Ze.mergeDeep=me.mergeDeep,Ze.mergeDeepWith=me.mergeDeepWith,Ze.update=me.update,Ze.updateIn=me.updateIn,Ze.cursor=me.cursor,Ze.withMutations=me.withMutations,Ze.asMutable=me.asMutable,Ze.asImmutable=me.asImmutable;var $e=function(t,e,r){return this instanceof tr?(I(0!==r,"Cannot step a Range by 0"),t=t||0,null==e&&(e=1/0),t===e&&rr?rr:(r=null==r?1:Math.abs(r),t>e&&(r=-r),this._start=t,this._end=e,this._step=r,void(this.length=Math.max(0,Math.ceil((e-t)/r-1)+1)))):new tr(t,e,r)},tr=$e;te.createClass($e,{toString:function(){return 0===this.length?"Range []":"Range [ "+this._start+"..."+this._end+(this._step>1?" by "+this._step:"")+" ]"},has:function(t){return I(t>=0,"Index out of bounds"),this.length>t},get:function(t,e){return I(t>=0,"Index out of bounds"),1/0===this.length||this.length>t?this._start+t*this._step:e
<ide> },contains:function(t){var e=(t-this._start)/this._step;return e>=0&&this.length>e&&e===Math.floor(e)},slice:function(t,e,r){return s(t,e,this.length)?this:r?te.superCall(this,tr.prototype,"slice",[t,e,r]):(t=a(t,this.length),e=h(e,this.length),t>=e?rr:new tr(this.get(t,this._end),this.get(e,this._end),this._step))},indexOf:function(t){var e=t-this._start;if(e%this._step===0){var r=e/this._step;if(r>=0&&this.length>r)return r}return-1},lastIndexOf:function(t){return this.indexOf(t)},take:function(t){return this.slice(0,t)},skip:function(t,e){return e?te.superCall(this,tr.prototype,"skip",[t]):this.slice(t)},__iterate:function(t,e,r){for(var n=e^r,i=this.length-1,u=this._step,s=e?this._start+i*u:this._start,a=0;i>=a&&t(s,n?i-a:a,this)!==!1;a++)s+=e?-u:u;return n?this.length:a},__deepEquals:function(t){return this._start===t._start&&this._end===t._end&&this._step===t._step}},{},ie);var er=$e.prototype;er.__toJS=er.toArray,er.first=Re.first,er.last=Re.last;var rr=$e(0,0),nr=function(t,e){return 0===e&&sr?sr:this instanceof ir?(this._value=t,void(this.length=null==e?1/0:Math.max(0,e))):new ir(t,e)},ir=nr;te.createClass(nr,{toString:function(){return 0===this.length?"Repeat []":"Repeat [ "+this._value+" "+this.length+" times ]"},get:function(t,e){return I(t>=0,"Index out of bounds"),1/0===this.length||this.length>t?this._value:e},first:function(){return this._value},contains:function(t){return w(this._value,t)},slice:function(t,e,r){if(r)return te.superCall(this,ir.prototype,"slice",[t,e,r]);var n=this.length;return t=0>t?Math.max(0,n+t):Math.min(n,t),e=null==e?n:e>0?Math.min(n,e):Math.max(0,n+e),e>t?new ir(this._value,e-t):sr},reverse:function(t){return t?te.superCall(this,ir.prototype,"reverse",[t]):this},indexOf:function(t){return w(this._value,t)?0:-1},lastIndexOf:function(t){return w(this._value,t)?this.length:-1},__iterate:function(t,e,r){var n=e^r;I(!n||1/0>this.length,"Cannot access end of infinite range.");for(var i=this.length-1,u=0;i>=u&&t(this._value,n?i-u:u,this)!==!1;u++);return n?this.length:u},__deepEquals:function(t){return w(this._value,t._value)
<ide> }},{},ie);var ur=nr.prototype;ur.last=ur.first,ur.has=er.has,ur.take=er.take,ur.skip=er.skip,ur.__toJS=er.__toJS;var sr=new nr(void 0,0),ar={Sequence:ee,Map:ge,Vector:Ue,Set:Ke,OrderedMap:He,Record:Xe,Range:$e,Repeat:nr,is:w,fromJS:X};return ar}"object"==typeof exports?module.exports=t():"function"==typeof define&&define.amd?define(t):Immutable=t();
<ide>\ No newline at end of file
<ide><path>src/OrderedMap.js
<ide> class OrderedMap extends Map {
<ide> }
<ide>
<ide> __deepEqual(other) {
<del> var iterator = this._vector.__iterator__();
<add> var iterator = this._vector.iterator();
<ide> return other.every((v, k) => {
<ide> var entry = iterator.next().value;
<ide> entry && (entry = entry[1]); | 3 |
PHP | PHP | fix reversed arguments in error message | cb45821c4333591d987e57dc5cb36688e065c533 | <ide><path>lib/Cake/Network/CakeResponse.php
<ide> protected function _setContentLength() {
<ide> protected function _sendHeader($name, $value = null) {
<ide> if (headers_sent($filename, $linenum)) {
<ide> throw new CakeException(
<del> __d('cake_dev', 'Headers already sent in %d on line %s', $linenum, $filename)
<add> __d('cake_dev', 'Headers already sent in %s on line %s', $filename, $linenum)
<ide> );
<ide> }
<ide> if ($value === null) { | 1 |
Ruby | Ruby | make an internal command | 3a432bcc2a20ff2c61ae074ff70ca9faaee4b19b | <ide><path>Library/Contributions/cmd/brew-pull.rb
<del># Gets a patch from a GitHub commit or pull request and applies it to Homebrew.
<del># Optionally, installs it too.
<del>
<del>require 'utils'
<del>require 'formula'
<del>
<del>def tap arg
<del> match = arg.match(%r[homebrew-(\w+)/])
<del> match[1].downcase if match
<del>end
<del>
<del>if ARGV.empty?
<del> onoe 'This command requires at least one argument containing a URL or pull request number'
<del>end
<del>
<del>if ARGV[0] == '--rebase'
<del> onoe 'You meant `git pull --rebase`.'
<del>end
<del>
<del>ARGV.named.each do |arg|
<del> if arg.to_i > 0
<del> url = 'https://github.com/Homebrew/homebrew/pull/' + arg
<del> issue = arg
<del> else
<del> url_match = arg.match HOMEBREW_PULL_OR_COMMIT_URL_REGEX
<del> unless url_match
<del> ohai 'Ignoring URL:', "Not a GitHub pull request or commit: #{arg}"
<del> next
<del> end
<del>
<del> url = url_match[0]
<del> issue = url_match[3]
<del> end
<del>
<del> if tap_name = tap(url)
<del> user = url_match[1].downcase
<del> tap_dir = HOMEBREW_REPOSITORY/"Library/Taps/#{user}/homebrew-#{tap_name}"
<del> safe_system "brew", "tap", "#{user}/#{tap_name}" unless tap_dir.exist?
<del> Dir.chdir tap_dir
<del> else
<del> Dir.chdir HOMEBREW_REPOSITORY
<del> end
<del>
<del> if ARGV.include? '--bottle'
<del> if issue
<del> url = "https://github.com/BrewTestBot/homebrew/compare/homebrew:master...pr-#{issue}"
<del> else
<del> raise "No pull request detected!"
<del> end
<del> end
<del>
<del> # GitHub provides commits'/pull-requests' raw patches using this URL.
<del> url += '.patch'
<del>
<del> # The cache directory seems like a good place to put patches.
<del> HOMEBREW_CACHE.mkpath
<del> patchpath = HOMEBREW_CACHE + File.basename(url)
<del> curl url, '-o', patchpath
<del>
<del> # Store current revision
<del> revision = `git rev-parse --short HEAD`.strip
<del>
<del> ohai 'Applying patch'
<del> patch_args = []
<del> # Normally we don't want whitespace errors, but squashing them can break
<del> # patches so an option is provided to skip this step.
<del> if ARGV.include? '--ignore-whitespace' or ARGV.include? '--clean'
<del> patch_args << '--whitespace=nowarn'
<del> else
<del> patch_args << '--whitespace=fix'
<del> end
<del>
<del> # Fall back to three-way merge if patch does not apply cleanly
<del> patch_args << "-3"
<del> patch_args << patchpath
<del>
<del> begin
<del> safe_system 'git', 'am', *patch_args
<del> rescue ErrorDuringExecution
<del> system 'git', 'am', '--abort'
<del> odie 'Patch failed to apply: aborted.'
<del> ensure
<del> patchpath.unlink
<del> end
<del>
<del> changed_formulae = []
<del>
<del> if tap_dir
<del> formula_dir = %w[Formula HomebrewFormula].find { |d| tap_dir.join(d).directory? } || ""
<del> else
<del> formula_dir = "Library/Formula"
<del> end
<del>
<del> Utils.popen_read(
<del> "git", "diff-tree", "-r", "--name-only",
<del> "--diff-filter=AM", revision, "HEAD", "--", formula_dir
<del> ).each_line do |line|
<del> name = File.basename(line.chomp, ".rb")
<del>
<del> begin
<del> changed_formulae << Formula[name]
<del> # Make sure we catch syntax errors.
<del> rescue Exception => e
<del> next
<del> end
<del> end
<del>
<del> unless ARGV.include?('--bottle')
<del> changed_formulae.each do |f|
<del> next unless f.bottle
<del> opoo "#{f} has a bottle: do you need to update it with --bottle?"
<del> end
<del> end
<del>
<del> if issue && !ARGV.include?('--clean')
<del> ohai "Patch closes issue ##{issue}"
<del> message = `git log HEAD^.. --format=%B`
<del>
<del> if ARGV.include? '--bump'
<del> onoe 'Can only bump one changed formula' unless changed_formulae.length == 1
<del> f = changed_formulae.first
<del> subject = "#{f.name} #{f.version}"
<del> ohai "New bump commit subject: #{subject}"
<del> message = "#{subject}\n\n#{message}"
<del> end
<del>
<del> # If this is a pull request, append a close message.
<del> unless message.include? 'Closes #'
<del> message += "\nCloses ##{issue}."
<del> safe_system 'git', 'commit', '--amend', '--signoff', '-q', '-m', message
<del> end
<del> end
<del>
<del> ohai 'Patch changed:'
<del> safe_system "git", "diff-tree", "-r", "--stat", revision, "HEAD"
<del>
<del> if ARGV.include? '--install'
<del> changed_formulae.each do |f|
<del> ohai "Installing #{f.name}"
<del> install = f.installed? ? 'upgrade' : 'install'
<del> safe_system 'brew', install, '--debug', f.name
<del> end
<del> end
<del>end
<ide><path>Library/Homebrew/cmd/pull.rb
<add># Gets a patch from a GitHub commit or pull request and applies it to Homebrew.
<add># Optionally, installs it too.
<add>
<add>require 'utils'
<add>require 'formula'
<add>
<add>module Homebrew
<add> def tap arg
<add> match = arg.match(%r[homebrew-(\w+)/])
<add> match[1].downcase if match
<add> end
<add>
<add> def pull
<add> if ARGV.empty?
<add> onoe 'This command requires at least one argument containing a URL or pull request number'
<add> end
<add>
<add> if ARGV[0] == '--rebase'
<add> onoe 'You meant `git pull --rebase`.'
<add> end
<add>
<add> ARGV.named.each do |arg|
<add> if arg.to_i > 0
<add> url = 'https://github.com/Homebrew/homebrew/pull/' + arg
<add> issue = arg
<add> else
<add> url_match = arg.match HOMEBREW_PULL_OR_COMMIT_URL_REGEX
<add> unless url_match
<add> ohai 'Ignoring URL:', "Not a GitHub pull request or commit: #{arg}"
<add> next
<add> end
<add>
<add> url = url_match[0]
<add> issue = url_match[3]
<add> end
<add>
<add> if tap_name = tap(url)
<add> user = url_match[1].downcase
<add> tap_dir = HOMEBREW_REPOSITORY/"Library/Taps/#{user}/homebrew-#{tap_name}"
<add> safe_system "brew", "tap", "#{user}/#{tap_name}" unless tap_dir.exist?
<add> Dir.chdir tap_dir
<add> else
<add> Dir.chdir HOMEBREW_REPOSITORY
<add> end
<add>
<add> if ARGV.include? '--bottle'
<add> if issue
<add> url = "https://github.com/BrewTestBot/homebrew/compare/homebrew:master...pr-#{issue}"
<add> else
<add> raise "No pull request detected!"
<add> end
<add> end
<add>
<add> # GitHub provides commits'/pull-requests' raw patches using this URL.
<add> url += '.patch'
<add>
<add> # The cache directory seems like a good place to put patches.
<add> HOMEBREW_CACHE.mkpath
<add> patchpath = HOMEBREW_CACHE + File.basename(url)
<add> curl url, '-o', patchpath
<add>
<add> # Store current revision
<add> revision = `git rev-parse --short HEAD`.strip
<add>
<add> ohai 'Applying patch'
<add> patch_args = []
<add> # Normally we don't want whitespace errors, but squashing them can break
<add> # patches so an option is provided to skip this step.
<add> if ARGV.include? '--ignore-whitespace' or ARGV.include? '--clean'
<add> patch_args << '--whitespace=nowarn'
<add> else
<add> patch_args << '--whitespace=fix'
<add> end
<add>
<add> # Fall back to three-way merge if patch does not apply cleanly
<add> patch_args << "-3"
<add> patch_args << patchpath
<add>
<add> begin
<add> safe_system 'git', 'am', *patch_args
<add> rescue ErrorDuringExecution
<add> system 'git', 'am', '--abort'
<add> odie 'Patch failed to apply: aborted.'
<add> ensure
<add> patchpath.unlink
<add> end
<add>
<add> changed_formulae = []
<add>
<add> if tap_dir
<add> formula_dir = %w[Formula HomebrewFormula].find { |d| tap_dir.join(d).directory? } || ""
<add> else
<add> formula_dir = "Library/Formula"
<add> end
<add>
<add> Utils.popen_read(
<add> "git", "diff-tree", "-r", "--name-only",
<add> "--diff-filter=AM", revision, "HEAD", "--", formula_dir
<add> ).each_line do |line|
<add> name = File.basename(line.chomp, ".rb")
<add>
<add> begin
<add> changed_formulae << Formula[name]
<add> # Make sure we catch syntax errors.
<add> rescue Exception => e
<add> next
<add> end
<add> end
<add>
<add> unless ARGV.include?('--bottle')
<add> changed_formulae.each do |f|
<add> next unless f.bottle
<add> opoo "#{f} has a bottle: do you need to update it with --bottle?"
<add> end
<add> end
<add>
<add> if issue && !ARGV.include?('--clean')
<add> ohai "Patch closes issue ##{issue}"
<add> message = `git log HEAD^.. --format=%B`
<add>
<add> if ARGV.include? '--bump'
<add> onoe 'Can only bump one changed formula' unless changed_formulae.length == 1
<add> f = changed_formulae.first
<add> subject = "#{f.name} #{f.version}"
<add> ohai "New bump commit subject: #{subject}"
<add> message = "#{subject}\n\n#{message}"
<add> end
<add>
<add> # If this is a pull request, append a close message.
<add> unless message.include? 'Closes #'
<add> message += "\nCloses ##{issue}."
<add> safe_system 'git', 'commit', '--amend', '--signoff', '-q', '-m', message
<add> end
<add> end
<add>
<add> ohai 'Patch changed:'
<add> safe_system "git", "diff-tree", "-r", "--stat", revision, "HEAD"
<add>
<add> if ARGV.include? '--install'
<add> changed_formulae.each do |f|
<add> ohai "Installing #{f.name}"
<add> install = f.installed? ? 'upgrade' : 'install'
<add> safe_system 'brew', install, '--debug', f.name
<add> end
<add> end
<add> end
<add> end
<add>end | 2 |
Ruby | Ruby | remove empty test file | 79953637711de5ba74a9228d6d415c76c1353588 | <ide><path>Library/Homebrew/test/test_python.rb
<del>#TODO!
<ide>\ No newline at end of file | 1 |
Javascript | Javascript | sync latest immutable changes | 0cec4af8d7bf1eb70f34f9f253a7897449bf1573 | <ide><path>src/utils/ImmutableObject.js
<ide> * limitations under the License.
<ide> *
<ide> * @providesModule ImmutableObject
<del> * @typechecks
<ide> */
<ide>
<ide> "use strict";
<ide>
<add>var Immutable = require('Immutable');
<add>
<ide> var invariant = require('invariant');
<del>var isNode = require('isNode');
<del>var merge = require('merge');
<del>var mergeInto = require('mergeInto');
<add>var keyOf = require('keyOf');
<ide> var mergeHelpers = require('mergeHelpers');
<ide>
<ide> var checkMergeObjectArgs = mergeHelpers.checkMergeObjectArgs;
<ide> var isTerminal = mergeHelpers.isTerminal;
<ide>
<add>var SECRET_KEY = keyOf({_DONT_EVER_TYPE_THIS_SECRET_KEY: null});
<add>
<ide> /**
<del> * Wrapper around JavaScript objects that provide a guarantee of immutability at
<del> * developer time when strict mode is used. The extra computations required to
<del> * enforce immutability is stripped out in production for performance reasons.
<add> * Static methods creating and operating on instances of `Immutable`.
<ide> */
<del>var ImmutableObject;
<del>
<del>function assertImmutableObject(immutableObject) {
<add>function assertImmutable(immutable) {
<ide> invariant(
<del> immutableObject instanceof ImmutableObject,
<add> immutable instanceof Immutable,
<ide> 'ImmutableObject: Attempted to set fields on an object that is not an ' +
<del> 'instance of ImmutableObject.'
<add> 'instance of Immutable.'
<ide> );
<ide> }
<ide>
<del>if (__DEV__) {
<del> /**
<del> * Constructs an instance of `ImmutableObject`.
<del> *
<del> * @param {?object} initialProperties The initial set of properties.
<del> * @constructor
<del> */
<del> ImmutableObject = function ImmutableObject(initialProperties) {
<del> mergeInto(this, initialProperties);
<del> deepFreeze(this);
<del> };
<del>
<add>/**
<add> * Static methods for reasoning about instances of `ImmutableObject`. Execute
<add> * the freeze commands in `__DEV__` mode to alert the programmer that something
<add> * is attempting to mutate. Since freezing is very expensive, we avoid doing it
<add> * at all in production.
<add> */
<add>class ImmutableObject extends Immutable {
<ide> /**
<del> * Checks if an object should be deep frozen. Instances of `ImmutableObject`
<del> * are assumed to have already been deep frozen.
<del> *
<del> * @param {*} object The object to check.
<del> * @return {boolean} Whether or not deep freeze is needed.
<add> * @arguments {array<object>} The arguments is an array of objects that, when
<add> * merged together, will form the immutable objects.
<ide> */
<del> var shouldRecurseFreeze = function(object) {
<del> return (
<del> typeof object === 'object' &&
<del> !(object instanceof ImmutableObject) &&
<del> object !== null
<del> );
<del> };
<add> constructor() {
<add> super(Immutable[SECRET_KEY]);
<add> Immutable.mergeAllPropertiesInto(this, arguments);
<add> if (__DEV__) {
<add> Immutable.deepFreezeRootNode(this);
<add> }
<add> }
<ide>
<ide> /**
<del> * Freezes the supplied object deeply.
<add> * DEPRECATED - prefer to instantiate with new ImmutableObject().
<ide> *
<del> * @param {*} object The object to freeze.
<add> * @arguments {array<object>} The arguments is an array of objects that, when
<add> * merged together, will form the immutable objects.
<ide> */
<del> var deepFreeze = function(object) {
<del> if (isNode(object)) {
<del> return; // Don't try to freeze DOM nodes.
<del> }
<del> Object.freeze(object); // First freeze the object.
<del> for (var prop in object) {
<del> var field = object[prop];
<del> if (object.hasOwnProperty(prop) && shouldRecurseFreeze(field)) {
<del> deepFreeze(field);
<del> }
<del> }
<del> };
<add> static create() {
<add> var obj = Object.create(ImmutableObject.prototype);
<add> ImmutableObject.apply(obj, arguments);
<add> return obj;
<add> }
<ide>
<ide> /**
<del> * Returns a new ImmutableObject that is identical to the supplied object but
<del> * with the supplied changes, `put`.
<add> * Returns a new `Immutable` that is identical to the supplied `Immutable`
<add> * but with the specified changes, `put`. Any keys that are in the
<add> * intersection of `immutable` and `put` retain the ordering of `immutable.
<add> * New keys are placed after keys that exist in `immutable`.
<ide> *
<del> * @param {ImmutableObject} immutableObject Starting object.
<add> * @param {Immutable} immutable Starting object.
<ide> * @param {?object} put Fields to merge into the object.
<del> * @return {ImmutableObject} The result of merging in `put` fields.
<add> * @return {Immutable} The result of merging in `put` fields.
<ide> */
<del> ImmutableObject.set = function(immutableObject, put) {
<del> assertImmutableObject(immutableObject);
<del> var totalNewFields = merge(immutableObject, put);
<del> return new ImmutableObject(totalNewFields);
<del> };
<add> static set(immutable, put) {
<add> assertImmutable(immutable);
<add> invariant(
<add> typeof put === 'object' && put !== undefined && !Array.isArray(put),
<add> 'Invalid ImmutableMap.set argument `put`'
<add> );
<add> return new ImmutableObject(immutable, put);
<add> }
<ide>
<del>} else {
<ide> /**
<del> * Constructs an instance of `ImmutableObject`.
<add> * Sugar for `ImmutableObject.set(ImmutableObject, {fieldName: putField})`.
<add> * Look out for key crushing: Use `keyOf()` to guard against it.
<ide> *
<del> * @param {?object} initialProperties The initial set of properties.
<del> * @constructor
<add> * @param {Immutable} immutable Object on which to set properties.
<add> * @param {string} fieldName Name of the field to set.
<add> * @param {*} putField Value of the field to set.
<add> * @return {Immutable} new Immutable as described in `set`.
<ide> */
<del> ImmutableObject = function ImmutableObject(initialProperties) {
<del> mergeInto(this, initialProperties);
<del> };
<add> static setProperty(immutableObject, fieldName, putField) {
<add> var put = {};
<add> put[fieldName] = putField;
<add> return ImmutableObject.set(immutableObject, put);
<add> }
<ide>
<ide> /**
<del> * Returns a new ImmutableObject that is identical to the supplied object but
<del> * with the supplied changes, `put`.
<add> * Returns a new `Immutable` that is identical to the supplied object but
<add> * with the supplied changes recursively applied.
<ide> *
<del> * @param {ImmutableObject} immutableObject Starting object.
<del> * @param {?object} put Fields to merge into the object.
<del> * @return {ImmutableObject} The result of merging in `put` fields.
<add> * Experimental. Likely does not handle `Arrays` correctly.
<add> *
<add> * @param {Immutable} immutable Object on which to set fields.
<add> * @param {object} put Fields to merge into the object.
<add> * @return {Immutable} The result of merging in `put` fields.
<ide> */
<del> ImmutableObject.set = function(immutableObject, put) {
<del> assertImmutableObject(immutableObject);
<del> var newMap = new ImmutableObject(immutableObject);
<del> mergeInto(newMap, put);
<del> return newMap;
<del> };
<add> static setDeep(immutable, put) {
<add> assertImmutable(immutable);
<add> return _setDeep(immutable, put);
<add> }
<ide> }
<ide>
<del>/**
<del> * Sugar for `ImmutableObject.set(ImmutableObject, {fieldName: putField})`.
<del> *
<del> * @param {ImmutableObject} immutableObject Object on which to set field.
<del> * @param {string} fieldName Name of the field to set.
<del> * @param {*} putField Value of the field to set.
<del> * @return {ImmutableObject} [description]
<del> */
<del>ImmutableObject.setField = function(immutableObject, fieldName, putField) {
<del> var put = {};
<del> put[fieldName] = putField;
<del> return ImmutableObject.set(immutableObject, put);
<del>};
<del>
<del>/**
<del> * Returns a new ImmutableObject that is identical to the supplied object but
<del> * with the supplied changes recursively applied.
<del> *
<del> * @param {ImmutableObject} immutableObject Object on which to set fields.
<del> * @param {object} put Fields to merge into the object.
<del> * @return {ImmutableObject} The result of merging in `put` fields.
<del> */
<del>ImmutableObject.setDeep = function(immutableObject, put) {
<del> assertImmutableObject(immutableObject);
<del> return _setDeep(immutableObject, put);
<del>};
<del>
<del>function _setDeep(object, put) {
<del> checkMergeObjectArgs(object, put);
<add>function _setDeep(obj, put) {
<add> checkMergeObjectArgs(obj, put);
<ide> var totalNewFields = {};
<ide>
<ide> // To maintain the order of the keys, copy the base object's entries first.
<del> var keys = Object.keys(object);
<add> var keys = Object.keys(obj);
<ide> for (var ii = 0; ii < keys.length; ii++) {
<ide> var key = keys[ii];
<ide> if (!put.hasOwnProperty(key)) {
<del> totalNewFields[key] = object[key];
<del> } else if (isTerminal(object[key]) || isTerminal(put[key])) {
<add> totalNewFields[key] = obj[key];
<add> } else if (isTerminal(obj[key]) || isTerminal(put[key])) {
<ide> totalNewFields[key] = put[key];
<ide> } else {
<del> totalNewFields[key] = _setDeep(object[key], put[key]);
<add> totalNewFields[key] = _setDeep(obj[key], put[key]);
<ide> }
<ide> }
<ide>
<del> // Apply any new keys that the base object didn't have.
<add> // Apply any new keys that the base obj didn't have.
<ide> var newKeys = Object.keys(put);
<ide> for (ii = 0; ii < newKeys.length; ii++) {
<ide> var newKey = newKeys[ii];
<del> if (object.hasOwnProperty(newKey)) {
<add> if (obj.hasOwnProperty(newKey)) {
<ide> continue;
<ide> }
<ide> totalNewFields[newKey] = put[newKey];
<ide> }
<ide>
<del> return (object instanceof ImmutableObject || put instanceof ImmutableObject) ?
<del> new ImmutableObject(totalNewFields) :
<del> totalNewFields;
<add> return (
<add> obj instanceof Immutable ? new ImmutableObject(totalNewFields) :
<add> put instanceof Immutable ? new ImmutableObject(totalNewFields) :
<add> totalNewFields
<add> );
<ide> }
<ide>
<ide> module.exports = ImmutableObject;
<ide><path>src/utils/__tests__/ImmutableObject-test.js
<ide>
<ide> "use strict";
<ide>
<del>require('mock-modules')
<del> .dontMock('ImmutableObject');
<del>
<ide> var ImmutableObject;
<add>var Immutable;
<ide>
<ide> /**
<ide> * To perform performance testing of using `ImmutableObject` vs. not using
<ide> var ImmutableObject;
<ide> describe('ImmutableObject', function() {
<ide> var message;
<ide> beforeEach(function() {
<del> require('mock-modules').dumpCache();
<ide> ImmutableObject = require('ImmutableObject');
<del> this.addMatchers({
<del> /**
<del> * Equivalent with respect to serialization. Must stringify because
<del> * constructors are different and other comparison methods will not
<del> * consider them structurally equal. Probably not useful for use outside
<del> * of this test module.
<del> */
<del> toBeSeriallyEqualTo: function(expected) {
<del> var actual = this.actual;
<del> var notText = this.isNot ? " not" : "";
<del> this.message = function () {
<del> return "Expected " + JSON.stringify(actual) + notText +
<del> " to be serially equal to " + JSON.stringify(expected);
<del> };
<del>
<del> return JSON.stringify(actual) === JSON.stringify(expected);
<del> }
<del> });
<add> Immutable = require('Immutable');
<ide> });
<ide>
<del> /**
<del> * We are in __DEV__ by default.
<del> */
<ide> var testDev = function(message, testFunc) {
<del> it(message, testFunc);
<add> it(message, function() {
<add> var old = window.__DEV__;
<add> window.__DEV__ = true;
<add> testFunc();
<add> window.__DEV__ = old;
<add> });
<ide> };
<ide>
<ide> var testProd = function(message, testFunc) {
<del> // Temporarily enter production mode
<del> window.__DEV__ = false;
<del> it(message, testFunc);
<del> window.__DEV__ = true;
<add> it(message, function() {
<add> // Temporarily enter production mode
<add> var old = window.__DEV__;
<add> window.__DEV__ = false;
<add> testFunc();
<add> window.__DEV__ = old;
<add> });
<ide> };
<ide>
<ide> var testDevAndProd = function(message, testFunc) {
<ide> describe('ImmutableObject', function() {
<ide> }).not.toThrow();
<ide> });
<ide>
<add> testDevAndProd('should extend Immutable', function() {
<add> var object = new ImmutableObject({foo: 'bar'});
<add> expect (object instanceof Immutable).toBe(true);
<add> expect (object instanceof ImmutableObject).toBe(true);
<add> });
<add>
<ide> testDev('should not exceed maximum call stack size with nodes', function() {
<ide> var node = document.createElement('div');
<ide> var object = new ImmutableObject({node: node});
<ide> describe('ImmutableObject', function() {
<ide> var beforeIO =
<ide> new ImmutableObject({shallowField: {deepField: {oldField: null}}});
<ide> var afterIO = ImmutableObject.set(beforeIO, {});
<del> expect(afterIO).toBeSeriallyEqualTo(beforeIO);
<add> expect(afterIO).toSeriallyEqual(beforeIO);
<ide> expect(afterIO).not.toBe(beforeIO);
<ide> }
<ide> );
<ide> describe('ImmutableObject', function() {
<ide>
<ide> var beforeIO = new ImmutableObject(beforeStructure);
<ide> var afterIO = ImmutableObject.set(beforeIO, delta);
<del> expect(afterIO).toBeSeriallyEqualTo(expectedAfterStructure);
<add> expect(afterIO).toSeriallyEqual(expectedAfterStructure);
<ide> expect(afterIO).not.toBe(beforeIO);
<ide> }
<ide> );
<ide> describe('ImmutableObject', function() {
<ide>
<ide> var beforeIO = new ImmutableObject(beforeStructure);
<ide> var afterIO = ImmutableObject.set(beforeIO, delta);
<del> expect(afterIO).toBeSeriallyEqualTo(expectedAfterStructure);
<add> expect(afterIO).toSeriallyEqual(expectedAfterStructure);
<ide> expect(afterIO).not.toBe(beforeIO);
<ide> }
<ide> );
<ide> describe('ImmutableObject', function() {
<ide>
<ide> var beforeIO = new ImmutableObject(beforeStructure);
<ide> var afterIO = ImmutableObject.set(beforeIO, delta);
<del> expect(afterIO).toBeSeriallyEqualTo(expectedAfterStructure);
<add> expect(afterIO).toSeriallyEqual(expectedAfterStructure);
<ide> expect(afterIO).not.toBe(beforeIO);
<ide> });
<ide>
<ide> message =
<ide> 'should tolerate arrays at deeper levels and prevent mutation on them';
<del> testDevAndProd(message, function() {
<add> testDev(message, function() {
<ide> if (window.callPhantom) {
<ide> // PhantomJS has a bug with Object.freeze and Arrays.
<ide> // https://github.com/ariya/phantomjs/issues/10817
<ide> describe('ImmutableObject', function() {
<ide> expect(io.shallowField[1]).toEqual('second field');
<ide> });
<ide>
<del> message = 'should provide a setField interface as sugar for set()';
<add> message = 'should provide a setProperty interface as sugar for set()';
<ide> testDevAndProd(message, function() {
<ide> var beforeIO = new ImmutableObject({initialField: null});
<ide> var afterIO =
<del> ImmutableObject.setField(beforeIO, 'anotherField', 'anotherValue');
<del> expect(afterIO).toBeSeriallyEqualTo({
<add> ImmutableObject.setProperty(beforeIO, 'anotherField', 'anotherValue');
<add> expect(afterIO).toSeriallyEqual({
<ide> initialField: null,
<ide> anotherField: 'anotherValue'
<ide> });
<ide> describe('ImmutableObject', function() {
<ide> var afterIO = ImmutableObject.setDeep(beforeIO, {
<ide> a: {b: {}, c: 'C', e: {f: 'F', g: 'G'}, h: 'H'}
<ide> });
<del> expect(afterIO).toBeSeriallyEqualTo({
<add> expect(afterIO).toSeriallyEqual({
<ide> a: {b: {}, c: 'C', d: 'd', e: {f: 'F', g: 'G'}, h: 'H'}
<ide> });
<ide> expect(afterIO).not.toBe(beforeIO);
<ide> describe('ImmutableObject', function() {
<ide> var afterIO = ImmutableObject.setDeep(beforeIO, {
<ide> a: {b: {d: 'D'}, e: new ImmutableObject({g: 'G'})}
<ide> });
<del> expect(afterIO).toBeSeriallyEqualTo({
<add> expect(afterIO).toSeriallyEqual({
<ide> a: {b: {c: 'c', d: 'D'}, e: {f: 'f', g: 'G'}}
<ide> });
<del> expect(afterIO instanceof ImmutableObject).toBe(true);
<del> expect(afterIO.a.b instanceof ImmutableObject).toBe(true);
<del> expect(afterIO.a.e instanceof ImmutableObject).toBe(true);
<add> expect(afterIO instanceof Immutable).toBe(true);
<add> expect(afterIO.a.b instanceof Immutable).toBe(true);
<add> expect(afterIO.a.e instanceof Immutable).toBe(true);
<ide> });
<ide> });
<add>
<ide><path>src/utils/immutable/Immutable.js
<ide> /**
<del> * Copyright 2014 Facebook, Inc.
<add> * Copyright 2013-2014 Facebook, Inc.
<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> class Immutable {
<ide> /**
<ide> * Helper method for classes that make use of `Immutable`.
<ide> * @param {Immutable} immutable Object to merge properties into.
<del> * @param {Array<object>} propertyObjects List of objects to merge into
<add> * @param {array<object>} propertyObjects List of objects to merge into
<ide> * `destination`.
<ide> */
<ide> static mergeAllPropertiesInto(destination, propertyObjects) { | 3 |
Python | Python | add missing assertin, assertnotin methods on 2.6 | 8f73c552a96cc54e6abefcfc0c4e9d4cdd7dc040 | <ide><path>flask/testsuite/__init__.py
<ide> def assert_in(self, x, y):
<ide> def assert_not_in(self, x, y):
<ide> self.assertNotIn(x, y)
<ide>
<add> if sys.version_info[:2] == (2, 6):
<add> def assertIn(self, x, y):
<add> assert x in y, "%r unexpectedly not in %r" % (x, y)
<add>
<add> def assertNotIn(self, x, y):
<add> assert x not in y, "%r unexpectedly in %r" % (x, y)
<add>
<ide>
<ide> class _ExceptionCatcher(object):
<ide> | 1 |
Text | Text | add discussion forums to troubleshooting | 412be8e024b9cb3a27fb7074d60ecbcd2e98dffc | <ide><path>docs/Troubleshooting.md
<ide> This document will help you check for common issues and make sure your issue has
<ide>
<ide> * Search the [Homebrew/homebrew-core issue tracker](https://github.com/Homebrew/homebrew-core/issues) or [Homebrew/linuxbrew-core issue tracker](https://github.com/Homebrew/linuxbrew-core/issues) to see if someone else has already reported the same issue.
<ide> * If a formula that has failed to build is part of a non-core tap or a cask is part of [homebrew/cask](https://github.com/Homebrew/homebrew-cask/issues) check those issue trackers instead.
<add>* Search the [Homebrew discussion forum](https://github.com/homebrew/discussions/discussions) or [Discourse](https://discourse.brew.sh/) to see if any discussions have started about the issue.
<ide>
<ide> ## Create an issue
<ide> | 1 |
Text | Text | update changelog for 2.11.0 | f640515dba61512ff573a7fd45c768bd140af74a | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<del>### 2.11.0-beta.4 (December 14, 2016)
<add>### 2.11.0 (January 23, 2017)
<ide>
<add>- [#14762](https://github.com/emberjs/ember.js/pull/14762) [BUGFIX] Ensure subexpressions can be used for `{{input}}`'s `type`.
<add>- [#14723](https://github.com/emberjs/ember.js/pull/14723) [BUGFIX] Improved backtracking re-render assertion message.
<add>- [#14750](https://github.com/emberjs/ember.js/pull/14750) [BUGFIX] Add assertion when a component's `tagName` is a computed property.
<ide> - [#14685](https://github.com/emberjs/ember.js/pull/14685) [BUGFIX] Fix `this.$()` returning `undefined` in `willDestroyElement`.
<ide> - [#14717](https://github.com/emberjs/ember.js/pull/14717) [BUGFIX] Fix an issue with block params named `attrs`.
<del>
<del>### 2.11.0-beta.3 (December 7, 2016)
<del>
<ide> - [#14671](https://github.com/emberjs/ember.js/pull/14671) [BUGFIX] Fix an issue with the `list` attribute in `<input>` elements.
<ide> - [#14681](https://github.com/emberjs/ember.js/pull/14681) [BUGFIX] Fix an issue with computed properties when using aliases as dependent keys.
<ide> - [#14682](https://github.com/emberjs/ember.js/pull/14682) [BUGFIX] Ensure closure actions do not trigger unnecessary re-renders.
<del>
<del>### 2.11.0-beta.2 (November 29, 2016)
<del>
<ide> - [#14658](https://github.com/emberjs/ember.js/pull/14658) [BUGFIX] Make the ember-source build work.
<del>
<del>### 2.11.0-beta.1 (November 28, 2016)
<del>
<ide> - [#14389](https://github.com/emberjs/ember.js/pull/14389) [BUGFIX] Move `classNames` and `classNameBindings` properties into the component's prototype.
<ide> - [#14389](https://github.com/emberjs/ember.js/pull/14389) [BUGFIX] Disallow mutation of shared concatenatedProperties, such as `classNames` and `classNameBindings`.
<ide> - [#14441](https://github.com/emberjs/ember.js/pull/14441) [DEPRECATION] Deprecate remaining usage of the `{{render}}` helper. | 1 |
Python | Python | restore tensorboard update_freq behavior | 9a3d0c96fcb23d50c95ea78d118faaf4bb0064b4 | <ide><path>keras/callbacks.py
<ide> def on_train_batch_end(self, batch, logs=None):
<ide> 1.0 / batch_run_time,
<ide> step=self._train_step,
<ide> )
<add>
<add> # `logs` is a `RemoteValue` when using asynchronous strategies, for now
<add> # we just disable `update_freq` entirely in those cases.
<add> if isinstance(logs, dict):
<add> for name, value in logs.items():
<add> tf.summary.scalar("batch_" + name, value, step=self._train_step)
<add>
<ide> if not self._should_trace:
<ide> return
<ide>
<ide><path>keras/callbacks_test.py
<ide> def test_TensorBoard_batch_metrics(self):
<ide> self.assertEqual(
<ide> summary_file.scalars,
<ide> {
<add> _ObservedSummary(logdir=self.train_dir, tag="batch_loss"),
<ide> _ObservedSummary(logdir=self.train_dir, tag="epoch_loss"),
<ide> _ObservedSummary(logdir=self.validation_dir, tag="epoch_loss"),
<ide> _ObservedSummary(
<ide> def test_TensorBoard_global_step(self):
<ide> self.assertEqual(
<ide> summary_file.scalars,
<ide> {
<add> _ObservedSummary(logdir=self.train_dir, tag="batch_loss"),
<ide> _ObservedSummary(logdir=self.train_dir, tag="epoch_loss"),
<ide> _ObservedSummary(
<ide> logdir=self.train_dir, tag="epoch_learning_rate"
<ide> def call(self, x):
<ide> self.assertEqual(
<ide> summary_file.scalars,
<ide> {
<add> _ObservedSummary(logdir=self.train_dir, tag="batch_loss"),
<ide> _ObservedSummary(logdir=self.train_dir, tag="epoch_loss"),
<ide> _ObservedSummary(logdir=self.validation_dir, tag="epoch_loss"),
<ide> _ObservedSummary(
<ide><path>keras/integration_test/distributed_training_test.py
<ide> def dataset_fn(input_context):
<ide>
<ide> x = tf.keras.utils.experimental.DatasetCreator(dataset_fn)
<ide>
<del> model.fit(x, epochs=2, steps_per_epoch=10)
<add> model.fit(
<add> x,
<add> epochs=2,
<add> steps_per_epoch=10,
<add> callbacks=[
<add> tf.keras.callbacks.TensorBoard(
<add> update_freq=5,
<add> write_steps_per_second=True,
<add> )
<add> ],
<add> )
<ide>
<ide>
<ide> if __name__ == "__main__": | 3 |
Python | Python | use url_scheme from path if provided | 241673fd153bad011c3fbbb41580450f39874cad | <ide><path>flask/testing.py
<ide> def make_test_environ_builder(
<ide> if subdomain:
<ide> http_host = '{0}.{1}'.format(subdomain, http_host)
<ide>
<add> url = url_parse(path)
<ide> if url_scheme is None:
<del> url_scheme = app.config['PREFERRED_URL_SCHEME']
<add> url_scheme = url.scheme or app.config['PREFERRED_URL_SCHEME']
<ide>
<del> url = url_parse(path)
<ide> base_url = '{0}://{1}/{2}'.format(
<ide> url_scheme, url.netloc or http_host, app_root.lstrip('/')
<ide> ) | 1 |
PHP | PHP | add test for mix() return value | 6a69a09f256690c04c3e1b6eb0043ff5501169f7 | <ide><path>tests/Foundation/FoundationHelpersTest.php
<ide> public function testUnversionedElixir()
<ide>
<ide> unlink(public_path($file));
<ide> }
<add>
<add> public function testMixDoesNotIncludeHost()
<add> {
<add> $file = 'unversioned.css';
<add>
<add> app()->singleton('path.public', function () {
<add> return __DIR__;
<add> });
<add>
<add> touch(public_path('mix-manifest.json'));
<add>
<add> file_put_contents(public_path('mix-manifest.json'), json_encode([
<add> '/unversioned.css' => '/versioned.css',
<add> ]));
<add>
<add> $result = mix($file);
<add>
<add> $this->assertEquals('/versioned.css', $result);
<add>
<add> unlink(public_path('mix-manifest.json'));
<add> }
<ide> } | 1 |
Ruby | Ruby | fix test_arch_for_command on 10.7 | 31e2ec485b1776cb00dac5043d2cae1c8d0aa123 | <ide><path>Library/Homebrew/test/test_utils.rb
<ide> def test_put_columns_empty
<ide>
<ide> def test_arch_for_command
<ide> arches=archs_for_command '/usr/bin/svn'
<del> if `sw_vers -productVersion` =~ /10\.(\d+)/ and $1.to_i >= 6
<add> if `sw_vers -productVersion` =~ /10\.(\d+)/ and $1.to_i >= 7
<add> assert_equal 2, arches.length
<add> assert arches.include?(:x86_64)
<add> elsif `sw_vers -productVersion` =~ /10\.(\d+)/ and $1.to_i = 6
<ide> assert_equal 3, arches.length
<ide> assert arches.include?(:x86_64)
<add> assert arches.include?(:ppc7400)
<ide> else
<ide> assert_equal 2, arches.length
<add> assert arches.include?(:ppc7400)
<ide> end
<ide> assert arches.include?(:i386)
<del> assert arches.include?(:ppc7400)
<ide> end
<ide>
<ide> end | 1 |
Python | Python | update model_training_utils for bert | d0ef3913ccb119a2a4bf7acb9fd4477d0a86d245 | <ide><path>official/nlp/bert/model_training_utils.py
<ide> def run_customized_training_loop(
<ide> init_checkpoint: Optional checkpoint to load to `sub_model` returned by
<ide> `model_fn`.
<ide> custom_callbacks: A list of Keras Callbacks objects to run during
<del> training. More specifically, `on_batch_begin()`, `on_batch_end()`,
<del> `on_epoch_begin()`, `on_epoch_end()` methods are invoked during
<del> training. Note that some metrics may be missing from `logs`.
<add> training. More specifically, `on_train_begin(), on_train_end(),
<add> on_batch_begin()`, `on_batch_end()`, `on_epoch_begin()`,
<add> `on_epoch_end()` methods are invoked during training.
<add> Note that some metrics may be missing from `logs`.
<ide> run_eagerly: Whether to run model training in pure eager execution. This
<ide> should be disable for TPUStrategy.
<ide> sub_model_export_name: If not None, will export `sub_model` returned by
<ide> def run_customized_training_loop(
<ide> raise ValueError(
<ide> 'if `metric_fn` is specified, metric_fn must be a callable.')
<ide>
<del> callback_list = tf.keras.callbacks.CallbackList(custom_callbacks)
<del>
<ide> total_training_steps = steps_per_epoch * epochs
<ide> train_iterator = _get_input_iterator(train_input_fn, strategy)
<ide> eval_loss_metric = tf.keras.metrics.Mean('training_loss', dtype=tf.float32)
<ide> def run_customized_training_loop(
<ide> raise ValueError('sub_model_export_name is specified as %s, but '
<ide> 'sub_model is None.' % sub_model_export_name)
<ide>
<add> callback_list = tf.keras.callbacks.CallbackList(
<add> callbacks=custom_callbacks, model=model)
<add>
<ide> optimizer = model.optimizer
<ide>
<ide> if init_checkpoint:
<ide> def _run_evaluation(current_training_step, test_iterator):
<ide> checkpoint_name = 'ctl_step_{step}.ckpt'
<ide>
<ide> logs = {}
<del> while current_step < total_training_steps:
<add> callback_list.on_train_begin()
<add> while current_step < total_training_steps and not model.stop_training:
<ide> if current_step % steps_per_epoch == 0:
<ide> callback_list.on_epoch_begin(
<ide> int(current_step / steps_per_epoch) + 1)
<ide> def _run_evaluation(current_training_step, test_iterator):
<ide> if not _should_export_summary(strategy):
<ide> tf.io.gfile.rmtree(summary_dir)
<ide>
<add> callback_list.on_train_end()
<add>
<ide> return model | 1 |
Javascript | Javascript | add action decorator | 53b84e24220861bb45987b0dfd2461b70c909fe8 | <ide><path>packages/@ember/object/index.js
<add>import { EMBER_NATIVE_DECORATOR_SUPPORT } from '@ember/canary-features';
<add>import { assert } from '@ember/debug';
<add>import { assign } from '@ember/polyfills';
<add>
<add>/**
<add> Decorator that turns the target function into an Action
<add> Adds an `actions` object to the target object and creates a passthrough
<add> function that calls the original. This means the function still exists
<add> on the original object, and can be used directly.
<add>
<add> ```js
<add> export default class ActionDemoComponent extends Component {
<add> @action
<add> foo() {
<add> // do something
<add> }
<add> }
<add> ```
<add> ```hbs
<add> <!-- template.hbs -->
<add> <button onclick={{action "foo"}}>Execute foo action</button>
<add> ```
<add>
<add> It also binds the function directly to the instance, so it can be used in any
<add> context:
<add>
<add> ```hbs
<add> <!-- template.hbs -->
<add> <button onclick={{this.foo}}>Execute foo action</button>
<add> ```
<add> @method computed
<add> @for @ember/object
<add> @static
<add> @param {ElementDescriptor} elementDesc the descriptor of the element to decorate
<add> @return {ElementDescriptor} the decorated descriptor
<add> @private
<add>*/
<add>export let action;
<add>
<add>if (EMBER_NATIVE_DECORATOR_SUPPORT) {
<add> let BINDINGS_MAP = new WeakMap();
<add>
<add> action = function action(elementDesc) {
<add> assert(
<add> 'The @action decorator must be applied to methods',
<add> elementDesc &&
<add> elementDesc.kind === 'method' &&
<add> elementDesc.descriptor &&
<add> typeof elementDesc.descriptor.value === 'function'
<add> );
<add>
<add> let actionFn = elementDesc.descriptor.value;
<add>
<add> elementDesc.descriptor = {
<add> get() {
<add> let bindings = BINDINGS_MAP.get(this);
<add>
<add> if (bindings === undefined) {
<add> bindings = new Map();
<add> BINDINGS_MAP.set(this, bindings);
<add> }
<add>
<add> let fn = bindings.get(actionFn);
<add>
<add> if (fn === undefined) {
<add> fn = actionFn.bind(this);
<add> bindings.set(actionFn, fn);
<add> }
<add>
<add> return fn;
<add> },
<add> };
<add>
<add> elementDesc.finisher = target => {
<add> let { key } = elementDesc;
<add> let { prototype } = target;
<add>
<add> if (typeof target.proto === 'function') {
<add> target.proto();
<add> }
<add>
<add> if (!prototype.hasOwnProperty('actions')) {
<add> let parentActions = prototype.actions;
<add> // we need to assign because of the way mixins copy actions down when inheriting
<add> prototype.actions = parentActions ? assign({}, parentActions) : {};
<add> }
<add>
<add> prototype.actions[key] = actionFn;
<add>
<add> return target;
<add> };
<add>
<add> return elementDesc;
<add> };
<add>}
<ide><path>packages/@ember/object/tests/action_test.js
<add>import { EMBER_NATIVE_DECORATOR_SUPPORT } from '@ember/canary-features';
<add>import { Component } from '@ember/-internals/glimmer';
<add>import { Object as EmberObject } from '@ember/-internals/runtime';
<add>import { moduleFor, RenderingTestCase, strip } from 'internal-test-helpers';
<add>
<add>import { action } from '../index';
<add>
<add>if (EMBER_NATIVE_DECORATOR_SUPPORT) {
<add> moduleFor(
<add> '@action decorator',
<add> class extends RenderingTestCase {
<add> '@test action decorator works with ES6 class'(assert) {
<add> class FooComponent extends Component {
<add> @action
<add> foo() {
<add> assert.ok(true, 'called!');
<add> }
<add> }
<add>
<add> this.registerComponent('foo-bar', {
<add> ComponentClass: FooComponent,
<add> template: "<button {{action 'foo'}}>Click Me!</button>",
<add> });
<add>
<add> this.render('{{foo-bar}}');
<add>
<add> this.$('button').click();
<add> }
<add>
<add> '@test action decorator does not add actions to superclass'(assert) {
<add> class Foo extends EmberObject {
<add> @action
<add> foo() {
<add> // Do nothing
<add> }
<add> }
<add>
<add> class Bar extends Foo {
<add> @action
<add> bar() {
<add> assert.ok(false, 'called');
<add> }
<add> }
<add>
<add> let foo = Foo.create();
<add> let bar = Bar.create();
<add>
<add> assert.equal(typeof foo.actions.foo, 'function', 'foo has foo action');
<add> assert.equal(typeof foo.actions.bar, 'undefined', 'foo does not have bar action');
<add>
<add> assert.equal(typeof bar.actions.foo, 'function', 'bar has foo action');
<add> assert.equal(typeof bar.actions.bar, 'function', 'bar has bar action');
<add> }
<add>
<add> '@test actions are properly merged through traditional and ES6 prototype hierarchy'(assert) {
<add> assert.expect(4);
<add>
<add> let FooComponent = Component.extend({
<add> actions: {
<add> foo() {
<add> assert.ok(true, 'foo called!');
<add> },
<add> },
<add> });
<add>
<add> class BarComponent extends FooComponent {
<add> @action
<add> bar() {
<add> assert.ok(true, 'bar called!');
<add> }
<add> }
<add>
<add> let BazComponent = BarComponent.extend({
<add> actions: {
<add> baz() {
<add> assert.ok(true, 'baz called!');
<add> },
<add> },
<add> });
<add>
<add> class QuxComponent extends BazComponent {
<add> @action
<add> qux() {
<add> assert.ok(true, 'qux called!');
<add> }
<add> }
<add>
<add> this.registerComponent('qux-component', {
<add> ComponentClass: QuxComponent,
<add> template: strip`
<add> <button {{action 'foo'}}>Click Foo!</button>
<add> <button {{action 'bar'}}>Click Bar!</button>
<add> <button {{action 'baz'}}>Click Baz!</button>
<add> <button {{action 'qux'}}>Click Qux!</button>
<add> `,
<add> });
<add>
<add> this.render('{{qux-component}}');
<add>
<add> this.$('button').click();
<add> }
<add>
<add> '@test action decorator super works with native class methods'(assert) {
<add> class FooComponent extends Component {
<add> foo() {
<add> assert.ok(true, 'called!');
<add> }
<add> }
<add>
<add> class BarComponent extends FooComponent {
<add> @action
<add> foo() {
<add> super.foo();
<add> }
<add> }
<add>
<add> this.registerComponent('bar-bar', {
<add> ComponentClass: BarComponent,
<add> template: "<button {{action 'foo'}}>Click Me!</button>",
<add> });
<add>
<add> this.render('{{bar-bar}}');
<add>
<add> this.$('button').click();
<add> }
<add>
<add> '@test action decorator super works with traditional class methods'(assert) {
<add> let FooComponent = Component.extend({
<add> foo() {
<add> assert.ok(true, 'called!');
<add> },
<add> });
<add>
<add> class BarComponent extends FooComponent {
<add> @action
<add> foo() {
<add> super.foo();
<add> }
<add> }
<add>
<add> this.registerComponent('bar-bar', {
<add> ComponentClass: BarComponent,
<add> template: "<button {{action 'foo'}}>Click Me!</button>",
<add> });
<add>
<add> this.render('{{bar-bar}}');
<add>
<add> this.$('button').click();
<add> }
<add>
<add> '@test action decorator works with parent native class actions'(assert) {
<add> class FooComponent extends Component {
<add> @action
<add> foo() {
<add> assert.ok(true, 'called!');
<add> }
<add> }
<add>
<add> class BarComponent extends FooComponent {
<add> @action
<add> foo() {
<add> super.foo();
<add> }
<add> }
<add>
<add> this.registerComponent('bar-bar', {
<add> ComponentClass: BarComponent,
<add> template: "<button {{action 'foo'}}>Click Me!</button>",
<add> });
<add>
<add> this.render('{{bar-bar}}');
<add>
<add> this.$('button').click();
<add> }
<add>
<add> '@test action decorator binds functions'(assert) {
<add> class FooComponent extends Component {
<add> bar = 'some value';
<add>
<add> @action
<add> foo() {
<add> assert.equal(this.bar, 'some value', 'context bound correctly');
<add> }
<add> }
<add>
<add> this.registerComponent('foo-bar', {
<add> ComponentClass: FooComponent,
<add> template: '<button onclick={{this.foo}}>Click Me!</button>',
<add> });
<add>
<add> this.render('{{foo-bar}}');
<add>
<add> this.$('button').click();
<add> }
<add>
<add> '@test action decorator super works correctly when bound'(assert) {
<add> class FooComponent extends Component {
<add> bar = 'some value';
<add>
<add> @action
<add> foo() {
<add> assert.equal(this.bar, 'some value', 'context bound correctly');
<add> }
<add> }
<add>
<add> class BarComponent extends FooComponent {
<add> @action
<add> foo() {
<add> super.foo();
<add> }
<add> }
<add>
<add> this.registerComponent('bar-bar', {
<add> ComponentClass: BarComponent,
<add> template: '<button onclick={{this.foo}}>Click Me!</button>',
<add> });
<add>
<add> this.render('{{bar-bar}}');
<add>
<add> this.$('button').click();
<add> }
<add>
<add> '@test action decorator throws an error if applied to non-methods'() {
<add> expectAssertion(() => {
<add> class TestObject extends EmberObject {
<add> @action foo = 'bar';
<add> }
<add>
<add> new TestObject();
<add> }, /The @action decorator must be applied to methods/);
<add> }
<add> }
<add> );
<add>}
<ide><path>packages/ember/index.js
<ide> import {
<ide> } from '@ember/string';
<ide> import Service, { inject as injectService } from '@ember/service';
<ide>
<add>import { action } from '@ember/object';
<add>
<ide> import {
<ide> and,
<ide> bool,
<ide> Ember._ProxyMixin = _ProxyMixin;
<ide> Ember.RSVP = RSVP;
<ide> Ember.Namespace = Namespace;
<ide>
<add>Ember._action = action;
<add>
<ide> computed.empty = empty;
<ide> computed.notEmpty = notEmpty;
<ide> computed.none = none;
<ide><path>packages/ember/tests/reexports_test.js
<ide> import Ember from '../index';
<del>import { FEATURES } from '@ember/canary-features';
<add>import { FEATURES, EMBER_NATIVE_DECORATOR_SUPPORT } from '@ember/canary-features';
<ide> import { confirmExport } from 'internal-test-helpers';
<ide> import { moduleFor, AbstractTestCase } from 'internal-test-helpers';
<ide> import { jQueryDisabled, jQuery } from '@ember/-internals/views';
<ide> let allExports = [
<ide> '@ember/-internals/metal',
<ide> { get: 'isNamespaceSearchDisabled', set: 'setNamespaceSearchDisabled' },
<ide> ],
<add> EMBER_NATIVE_DECORATOR_SUPPORT ? ['_action', '@ember/object', 'action'] : null,
<ide> ['computed.empty', '@ember/object/computed', 'empty'],
<ide> ['computed.notEmpty', '@ember/object/computed', 'notEmpty'],
<ide> ['computed.none', '@ember/object/computed', 'none'], | 4 |
Text | Text | add runonclick=1 param to csb embeds | 04073b4ec1672fca35d5efeeaf12935329b66239 | <ide><path>docs/introduction/Examples.md
<ide> open index.html
<ide>
<ide> Or check out the [sandbox](https://codesandbox.io/s/github/reduxjs/redux/tree/master/examples/counter-vanilla):
<ide>
<del><iframe class="codesandbox"src="https://codesandbox.io/embed/github/reduxjs/redux/tree/master/examples/counter-vanilla"sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>
<add><iframe class="codesandbox"src="https://codesandbox.io/embed/github/reduxjs/redux/tree/master/examples/counter-vanilla/?runonclick=1"sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>
<ide>
<ide> It does not require a build system or a view framework and exists to show the raw Redux API used with ES5.
<ide>
<ide> npm start
<ide>
<ide> Or check out the [sandbox](https://codesandbox.io/s/github/reduxjs/redux/tree/master/examples/counter):
<ide>
<del><iframe class="codesandbox"src="https://codesandbox.io/embed/github/reduxjs/redux/tree/master/examples/counter"sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>
<add><iframe class="codesandbox"src="https://codesandbox.io/embed/github/reduxjs/redux/tree/master/examples/counter/?runonclick=1"sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>
<ide>
<ide> This is the most basic example of using Redux together with React. For simplicity, it re-renders the React component manually when the store changes. In real projects, you will likely want to use the highly performant [React Redux](https://github.com/reduxjs/react-redux) bindings instead.
<ide>
<ide> npm start
<ide>
<ide> Or check out the [sandbox](https://codesandbox.io/s/github/reduxjs/redux/tree/master/examples/todos):
<ide>
<del><iframe class="codesandbox"src="https://codesandbox.io/embed/github/reduxjs/redux/tree/master/examples/todos"sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>
<add><iframe class="codesandbox"src="https://codesandbox.io/embed/github/reduxjs/redux/tree/master/examples/todos/?runonclick=1"sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>
<ide>
<ide> This is the best example to get a deeper understanding of how the state updates work together with components in Redux. It shows how reducers can delegate handling actions to other reducers, and how you can use [React Redux](https://github.com/reduxjs/react-redux) to generate container components from your presentational components.
<ide>
<ide> npm start
<ide>
<ide> Or check out the [sandbox](https://codesandbox.io/s/github/reduxjs/redux/tree/master/examples/todos-with-undo):
<ide>
<del><iframe class="codesandbox"src="https://codesandbox.io/embed/github/reduxjs/redux/tree/master/examples/todos-with-undo"sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>
<add><iframe class="codesandbox"src="https://codesandbox.io/embed/github/reduxjs/redux/tree/master/examples/todos-with-undo/?runonclick=1"sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>
<ide>
<ide> This is a variation on the previous example. It is almost identical, but additionally shows how wrapping your reducer with [Redux Undo](https://github.com/omnidan/redux-undo) lets you add a Undo/Redo functionality to your app with a few lines of code.
<ide>
<ide> npm start
<ide>
<ide> Or check out the [sandbox](https://codesandbox.io/s/github/reduxjs/redux/tree/master/examples/todos-flow):
<ide>
<del><iframe class="codesandbox"src="https://codesandbox.io/embed/github/reduxjs/redux/tree/master/examples/todos-flow"sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>
<add><iframe class="codesandbox"src="https://codesandbox.io/embed/github/reduxjs/redux/tree/master/examples/todos-flow/?runonclick=1"sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>
<ide>
<ide> This is like the previous Todos examples, but shows how to use Redux in conjunction with [Flow](https://flow.org/).
<ide>
<ide> npm start
<ide>
<ide> Or check out the [sandbox](https://codesandbox.io/s/github/reduxjs/redux/tree/master/examples/todomvc):
<ide>
<del><iframe class="codesandbox"src="https://codesandbox.io/embed/github/reduxjs/redux/tree/master/examples/todomvc"sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>
<add><iframe class="codesandbox"src="https://codesandbox.io/embed/github/reduxjs/redux/tree/master/examples/todomvc/?runonclick=1"sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>
<ide>
<ide> This is the classical [TodoMVC](http://todomvc.com/) example. It's here for the sake of comparison, but it covers the same points as the Todos example.
<ide>
<ide> npm start
<ide>
<ide> Or check out the [sandbox](https://codesandbox.io/s/github/reduxjs/redux/tree/master/examples/shopping-cart):
<ide>
<del><iframe class="codesandbox"src="https://codesandbox.io/embed/github/reduxjs/redux/tree/master/examples/shopping-cart"sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>
<add><iframe class="codesandbox"src="https://codesandbox.io/embed/github/reduxjs/redux/tree/master/examples/shopping-cart/?runonclick=1"sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>
<ide>
<ide> This example shows important idiomatic Redux patterns that become important as your app grows. In particular, it shows how to store entities in a normalized way by their IDs, how to compose reducers on several levels, and how to define selectors alongside the reducers so the knowledge about the state shape is encapsulated. It also demonstrates logging with [Redux Logger](https://github.com/fcomb/redux-logger) and conditional dispatching of actions with [Redux Thunk](https://github.com/gaearon/redux-thunk) middleware.
<ide>
<ide> npm start
<ide>
<ide> Or check out the [sandbox](https://codesandbox.io/s/github/reduxjs/redux/tree/master/examples/tree-view):
<ide>
<del><iframe class="codesandbox"src="https://codesandbox.io/embed/github/reduxjs/redux/tree/master/examples/tree-view"sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>
<add><iframe class="codesandbox"src="https://codesandbox.io/embed/github/reduxjs/redux/tree/master/examples/tree-view/?runonclick=1"sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>
<ide>
<ide> This example demonstrates rendering a deeply nested tree view and representing its state in a normalized form so it is easy to update from reducers. Good rendering performance is achieved by the container components granularly subscribing only to the tree nodes that they render.
<ide>
<ide> npm start
<ide>
<ide> Or check out the [sandbox](https://codesandbox.io/s/github/reduxjs/redux/tree/master/examples/async):
<ide>
<del><iframe class="codesandbox"src="https://codesandbox.io/embed/github/reduxjs/redux/tree/master/examples/async"sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>
<add><iframe class="codesandbox"src="https://codesandbox.io/embed/github/reduxjs/redux/tree/master/examples/async/?runonclick=1"sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>
<ide>
<ide> This example includes reading from an asynchronous API, fetching data in response to user input, showing loading indicators, caching the response, and invalidating the cache. It uses [Redux Thunk](https://github.com/gaearon/redux-thunk) middleware to encapsulate asynchronous side effects.
<ide>
<ide> npm start
<ide>
<ide> Or check out the [sandbox](https://codesandbox.io/s/github/reduxjs/redux/tree/master/examples/real-world):
<ide>
<del><iframe class="codesandbox" src="https://codesandbox.io/embed/github/reduxjs/redux/tree/master/examples/real-world" sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>
<add><iframe class="codesandbox" src="https://codesandbox.io/embed/github/reduxjs/redux/tree/master/examples/real-world/?runonclick=1" sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>
<ide>
<ide> This is the most advanced example. It is dense by design. It covers keeping fetched entities in a normalized cache, implementing a custom middleware for API calls, rendering partially loaded data, pagination, caching responses, displaying error messages, and routing. Additionally, it includes Redux DevTools.
<ide>
<ide><path>docs/tutorials/essentials/part-2-app-structure.md
<ide> Here's the live version of the project. You can play around with it by clicking
<ide>
<ide> <iframe
<ide> class="codesandbox"
<del> src="https://codesandbox.io/embed/github/reduxjs/redux-essentials-counter-example/tree/master/?fontsize=14&hidenavigation=1&module=%2Fsrc%2Ffeatures%2Fcounter%2FcounterSlice.js&theme=dark"
<add> src="https://codesandbox.io/embed/github/reduxjs/redux-essentials-counter-example/tree/master/?fontsize=14&hidenavigation=1&module=%2Fsrc%2Ffeatures%2Fcounter%2FcounterSlice.js&theme=dark&runonclick=1"
<ide> title="redux-essentials-example"
<ide> allow="geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb"
<ide> sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
<ide> Earlier, we saw that we can write "selector" functions, which take `state` as an
<ide>
<ide> Our `counterSlice.js` has this selector function at the bottom:
<ide>
<del>```js title="features/counter/counterSlice.js"
<add>```js title="features/counter/counterSlice.js"
<ide> // The function below is called a selector and allows us to select a value from
<ide> // the state. Selectors can also be defined inline where they're used instead of
<ide> // in the slice file. For example: `useSelector((state) => state.counter.value)`
<ide> const dispatch = useDispatch()
<ide>
<ide> From there, we can dispatch actions when the user does something like clicking on a button:
<ide>
<del>```jsx title="features/counter/Counter.js"
<add>```jsx title="features/counter/Counter.js"
<ide> <button
<ide> className={styles.button}
<ide> aria-label="Increment value"
<ide> We've seen that our components can use the `useSelector` and `useDispatch` hooks
<ide>
<ide> Now that we've seen all the different pieces of this application, it's time to circle back to the starting point of this application and see how the last pieces of the puzzle fit together.
<ide>
<del>```jsx title="index.js"
<add>```jsx title="index.js"
<ide> import React from 'react'
<ide> import ReactDOM from 'react-dom'
<ide> import './index.css'
<ide><path>docs/tutorials/essentials/part-3-data-flow.md
<ide> To get started, you can open and fork this CodeSandbox:
<ide>
<ide> <iframe
<ide> class="codesandbox"
<del> src="https://codesandbox.io/embed/github/reduxjs/redux-essentials-example-app/tree/master/?fontsize=14&hidenavigation=1&theme=dark"
<add> src="https://codesandbox.io/embed/github/reduxjs/redux-essentials-example-app/tree/master/?fontsize=14&hidenavigation=1&theme=dark&runonclick=1"
<ide> title="redux-quick-start-example-app"
<ide> allow="geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb"
<ide> sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
<ide> Here's what the app looks like so far:
<ide>
<ide> <iframe
<ide> class="codesandbox"
<del> src="https://codesandbox.io/embed/github/reduxjs/redux-essentials-example-app/tree/checkpoint-1-postAdded/?fontsize=14&hidenavigation=1&theme=dark"
<add> src="https://codesandbox.io/embed/github/reduxjs/redux-essentials-example-app/tree/checkpoint-1-postAdded/?fontsize=14&hidenavigation=1&theme=dark&runonclick=1"
<ide> title="redux-quick-start-example-app"
<ide> allow="geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb"
<ide> sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
<ide><path>docs/tutorials/essentials/part-4-using-data.md
<ide> Here's what our app looks like after all these changes:
<ide>
<ide> <iframe
<ide> class="codesandbox"
<del> src="https://codesandbox.io/embed/github/reduxjs/redux-essentials-example-app/tree/checkpoint-2-reactionButtons/?fontsize=14&hidenavigation=1&theme=dark"
<add> src="https://codesandbox.io/embed/github/reduxjs/redux-essentials-example-app/tree/checkpoint-2-reactionButtons/?fontsize=14&hidenavigation=1&theme=dark&runonclick=1"
<ide> title="redux-essentials-example-app"
<ide> allow="geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb"
<ide> sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
<ide><path>docs/tutorials/essentials/part-5-async-logic.md
<ide> Here's what our app looks like now that we're fetching data from that fake API:
<ide>
<ide> <iframe
<ide> class="codesandbox"
<del> src="https://codesandbox.io/embed/github/reduxjs/redux-essentials-example-app/tree/checkpoint-3-postRequests/?fontsize=14&hidenavigation=1&theme=dark"
<add> src="https://codesandbox.io/embed/github/reduxjs/redux-essentials-example-app/tree/checkpoint-3-postRequests/?fontsize=14&hidenavigation=1&theme=dark&runonclick=1"
<ide> title="redux-essentials-example-app"
<ide> allow="geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb"
<ide> sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
<ide><path>docs/tutorials/essentials/part-6-performance-normalization.md
<ide> Congratulations, you've completed the Redux Essentials tutorial! Let's see what
<ide>
<ide> <iframe
<ide> class="codesandbox"
<del> src="https://codesandbox.io/embed/github/reduxjs/redux-essentials-example-app/tree/checkpoint-4-entitySlices/?fontsize=14&hidenavigation=1&theme=dark"
<add> src="https://codesandbox.io/embed/github/reduxjs/redux-essentials-example-app/tree/checkpoint-4-entitySlices/?fontsize=14&hidenavigation=1&theme=dark&runonclick=1"
<ide> title="redux-essentials-example-app"
<ide> allow="geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb"
<ide> sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
<ide><path>docs/tutorials/fundamentals/part-1-overview.md
<ide> Let's look at a minimal working example of a Redux app - a small counter applica
<ide>
<ide> <iframe
<ide> class="codesandbox"
<del> src="https://codesandbox.io/embed/dank-architecture-lr7k1?fontsize=14&hidenavigation=1&theme=dark"
<add> src="https://codesandbox.io/embed/dank-architecture-lr7k1?fontsize=14&hidenavigation=1&theme=dark&runonclick=1"
<ide> title="redux-fundamentals-core-example"
<ide> allow="geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb"
<ide> sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
<ide><path>docs/tutorials/fundamentals/part-3-state-actions-reducers.md
<ide> To get started, you can open and fork this CodeSandbox:
<ide>
<ide> <iframe
<ide> class="codesandbox"
<del> src="https://codesandbox.io/embed/github/reduxjs/redux-fundamentals-example-app/tree/master/?fontsize=14&hidenavigation=1&theme=dark"
<add> src="https://codesandbox.io/embed/github/reduxjs/redux-fundamentals-example-app/tree/master/?fontsize=14&hidenavigation=1&theme=dark&runonclick=1"
<ide> title="redux-fundamentals-example-app"
<ide> allow="geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb"
<ide> sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
<ide> Here's the contents of our app so far:
<ide>
<ide> <iframe
<ide> class="codesandbox"
<del> src="https://codesandbox.io/embed/github/reduxjs/redux-fundamentals-example-app/tree/checkpoint-1-combinedReducers/?fontsize=14&hidenavigation=1&module=%2Fsrc%2Freducer.js&theme=dark"
<add> src="https://codesandbox.io/embed/github/reduxjs/redux-fundamentals-example-app/tree/checkpoint-1-combinedReducers/?fontsize=14&hidenavigation=1&module=%2Fsrc%2Freducer.js&theme=dark&runonclick=1"
<ide> title="redux-fundamentals-example-app"
<ide> allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
<ide> sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
<ide><path>docs/tutorials/fundamentals/part-4-store.md
<ide> Let's see how our example app looks now:
<ide>
<ide> <iframe
<ide> class="codesandbox"
<del> src="https://codesandbox.io/embed/github/reduxjs/redux-fundamentals-example-app/tree/checkpoint-2-storeSetup/?fontsize=14&hidenavigation=1&theme=dark&module=%2Fsrc%2Fstore.js"
<add> src="https://codesandbox.io/embed/github/reduxjs/redux-fundamentals-example-app/tree/checkpoint-2-storeSetup/?fontsize=14&hidenavigation=1&theme=dark&module=%2Fsrc%2Fstore.js&runonclick=1"
<ide> title="redux-fundamentals-example-app"
<ide> allow="geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb"
<ide> sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
<ide><path>docs/tutorials/fundamentals/part-5-ui-and-react.md
<ide> Here's the initial React UI of this app looks like before we start adding any Re
<ide>
<ide> <iframe
<ide> class="codesandbox"
<del> src="https://codesandbox.io/embed/github/reduxjs/redux-fundamentals-example-app/tree/checkpoint-3-initialUI/?fontsize=14&hidenavigation=1&theme=dark&view=preview"
<add> src="https://codesandbox.io/embed/github/reduxjs/redux-fundamentals-example-app/tree/checkpoint-3-initialUI/?fontsize=14&hidenavigation=1&theme=dark&view=preview&runonclick=1"
<ide> title="redux-fundamentals-example-app"
<ide> allow="geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb"
<ide> sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
<ide> We should now be able to actually interact with the app! Here's the working UI s
<ide>
<ide> <iframe
<ide> class="codesandbox"
<del> src="https://codesandbox.io/embed/github/reduxjs/redux-fundamentals-example-app/tree/checkpoint-4-initialHooks/?fontsize=14&hidenavigation=1&theme=dark"
<add> src="https://codesandbox.io/embed/github/reduxjs/redux-fundamentals-example-app/tree/checkpoint-4-initialHooks/?fontsize=14&hidenavigation=1&theme=dark&runonclick=1"
<ide> title="redux-fundamentals-example-app"
<ide> allow="geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb"
<ide> sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
<ide> Let's see how the app looks now, including the components and sections we skippe
<ide>
<ide> <iframe
<ide> class="codesandbox"
<del> src="https://codesandbox.io/embed/github/reduxjs/redux-fundamentals-example-app/tree/checkpoint-5-uiAllActions/?fontsize=14&hidenavigation=1&theme=dark"
<add> src="https://codesandbox.io/embed/github/reduxjs/redux-fundamentals-example-app/tree/checkpoint-5-uiAllActions/?fontsize=14&hidenavigation=1&theme=dark&runonclick=1"
<ide> title="redux-fundamentals-example-app"
<ide> allow="geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb"
<ide> sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
<ide><path>docs/tutorials/fundamentals/part-6-async-logic.md
<ide> Here's what the current app looks like:
<ide>
<ide> <iframe
<ide> class="codesandbox"
<del> src="https://codesandbox.io/embed/github/reduxjs/redux-fundamentals-example-app/tree/checkpoint-6-asyncThunks/?fontsize=14&hidenavigation=1&theme=dark"
<add> src="https://codesandbox.io/embed/github/reduxjs/redux-fundamentals-example-app/tree/checkpoint-6-asyncThunks/?fontsize=14&hidenavigation=1&theme=dark&runonclick=1"
<ide> title="redux-fundamentals-example-app"
<ide> allow="geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb"
<ide> sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
<ide><path>docs/tutorials/fundamentals/part-7-standard-patterns.md
<ide> Here's what the app looks like with that loading status enabled (to see the spin
<ide>
<ide> <iframe
<ide> class="codesandbox"
<del> src="https://codesandbox.io/embed/github/reduxjs/redux-fundamentals-example-app/tree/checkpoint-7-asyncLoading/?fontsize=14&hidenavigation=1&theme=dark"
<add> src="https://codesandbox.io/embed/github/reduxjs/redux-fundamentals-example-app/tree/checkpoint-7-asyncLoading/?fontsize=14&hidenavigation=1&theme=dark&runonclick=1"
<ide> title="redux-fundamentals-example-app"
<ide> allow="geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb"
<ide> sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
<ide> Here's how our app looks after it's been fully converted to use these patterns:
<ide>
<ide> <iframe
<ide> class="codesandbox"
<del> src="https://codesandbox.io/embed/github/reduxjs/redux-fundamentals-example-app/tree/checkpoint-8-normalizedState/?fontsize=14&hidenavigation=1&theme=dark"
<add> src="https://codesandbox.io/embed/github/reduxjs/redux-fundamentals-example-app/tree/checkpoint-8-normalizedState/?fontsize=14&hidenavigation=1&theme=dark&runonclick=1"
<ide> title="redux-fundamentals-example-app"
<ide> allow="geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb"
<ide> sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
<ide><path>docs/tutorials/fundamentals/part-8-modern-redux.md
<ide> Here's how our code looks with all the slices converted:
<ide>
<ide> <iframe
<ide> class="codesandbox"
<del> src="https://codesandbox.io/embed/github/reduxjs/redux-fundamentals-example-app/tree/checkpoint-9-createSlice/?fontsize=14&hidenavigation=1&theme=dark&module=%2Fsrc%2Ffeatures%2Ftodos%2FtodosSlice.js"
<add> src="https://codesandbox.io/embed/github/reduxjs/redux-fundamentals-example-app/tree/checkpoint-9-createSlice/?fontsize=14&hidenavigation=1&theme=dark&module=%2Fsrc%2Ffeatures%2Ftodos%2FtodosSlice.js&runonclick=1"
<ide> title="redux-fundamentals-example-app"
<ide> allow="geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb"
<ide> sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
<ide> Let's take one final look at the completed todo application, including all the c
<ide>
<ide> <iframe
<ide> class="codesandbox"
<del> src="https://codesandbox.io/embed/github/reduxjs/redux-fundamentals-example-app/tree/checkpoint-10-finalCode/?fontsize=14&hidenavigation=1&theme=dark&module=%2Fsrc%2Ffeatures%2Ftodos%2FtodosSlice.js"
<add> src="https://codesandbox.io/embed/github/reduxjs/redux-fundamentals-example-app/tree/checkpoint-10-finalCode/?fontsize=14&hidenavigation=1&theme=dark&module=%2Fsrc%2Ffeatures%2Ftodos%2FtodosSlice.js&runonclick=1"
<ide> title="redux-fundamentals-example-app"
<ide> allow="geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb"
<ide> sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin" | 13 |
Python | Python | add missing import | 8904814c0e9b9edff165db6fcc8b400432c14f17 | <ide><path>spacy/_ml.py
<ide> from thinc.neural._classes.static_vectors import StaticVectors
<ide> from thinc.neural._classes.batchnorm import BatchNorm
<ide> from thinc.neural._classes.resnet import Residual
<add>from thinc.neural import ReLu
<ide> from thinc import describe
<ide> from thinc.describe import Dimension, Synapses, Biases, Gradient
<ide> from thinc.neural._classes.affine import _set_dimensions_if_needed | 1 |
PHP | PHP | use illuminate response | 3789a96ec84fdc94685c90eb12e378dedb97411d | <ide><path>src/Illuminate/Auth/SessionGuard.php
<ide>
<ide> use RuntimeException;
<ide> use Illuminate\Support\Str;
<add>use Illuminate\Http\Response;
<ide> use Illuminate\Contracts\Events\Dispatcher;
<ide> use Illuminate\Contracts\Auth\UserProvider;
<ide> use Illuminate\Contracts\Auth\StatefulGuard;
<ide> use Symfony\Component\HttpFoundation\Request;
<del>use Symfony\Component\HttpFoundation\Response;
<ide> use Illuminate\Contracts\Auth\SupportsBasicAuth;
<ide> use Illuminate\Contracts\Cookie\QueueingFactory as CookieJar;
<ide> use Symfony\Component\HttpFoundation\Session\SessionInterface; | 1 |
Text | Text | remove duplicate link | 31d2184972097741cadcbee534b018fac1cf9de0 | <ide><path>docs/testing.md
<ide> You can learn more about Playwright and Continuous Integration from these resour
<ide> - [Getting started with Playwright](https://playwright.dev/docs/intro)
<ide> - [Use a development server](https://playwright.dev/docs/test-advanced#launching-a-development-web-server-during-the-tests)
<ide> - [Playwright on your CI provider](https://playwright.dev/docs/ci)
<del>- [Use a development server](https://playwright.dev/docs/test-advanced#launching-a-development-web-server-during-the-tests)
<ide>
<ide> ## Jest and React Testing Library
<ide> | 1 |
Go | Go | fix race in runcommandwithoutputforduration | 2704fd9156bfb0fb8dc16c42902bb18ea5aa94a9 | <ide><path>pkg/integration/utils.go
<ide> func RunCommandWithOutputForDuration(cmd *exec.Cmd, duration time.Duration) (out
<ide> }
<ide> cmd.Stderr = &outputBuffer
<ide>
<del> done := make(chan error)
<del>
<ide> // Start the command in the main thread..
<ide> err = cmd.Start()
<ide> if err != nil {
<ide> err = fmt.Errorf("Fail to start command %v : %v", cmd, err)
<ide> }
<ide>
<add> type exitInfo struct {
<add> exitErr error
<add> exitCode int
<add> }
<add>
<add> done := make(chan exitInfo, 1)
<add>
<ide> go func() {
<ide> // And wait for it to exit in the goroutine :)
<del> exitErr := cmd.Wait()
<del> exitCode = ProcessExitCode(exitErr)
<del> done <- exitErr
<add> info := exitInfo{}
<add> info.exitErr = cmd.Wait()
<add> info.exitCode = ProcessExitCode(info.exitErr)
<add> done <- info
<ide> }()
<ide>
<ide> select {
<ide> func RunCommandWithOutputForDuration(cmd *exec.Cmd, duration time.Duration) (out
<ide> fmt.Printf("failed to kill (pid=%d): %v\n", cmd.Process.Pid, killErr)
<ide> }
<ide> timedOut = true
<del> break
<del> case err = <-done:
<del> break
<add> case info := <-done:
<add> err = info.exitErr
<add> exitCode = info.exitCode
<ide> }
<ide> output = outputBuffer.String()
<ide> return | 1 |
Javascript | Javascript | remove custom attrs properly when setting to null | c3cfcf073dab2e6fff1ebf32ef2bbacc37a57992 | <ide><path>src/browser/ui/dom/DOMPropertyOperations.js
<ide> var DOMPropertyOperations = {
<ide> }
<ide> } else if (DOMProperty.isCustomAttribute(name)) {
<ide> if (value == null) {
<del> node.removeAttribute(DOMProperty.getAttributeName[name]);
<add> node.removeAttribute(name);
<ide> } else {
<ide> node.setAttribute(name, '' + value);
<ide> }
<ide><path>src/browser/ui/dom/__tests__/DOMPropertyOperations-test.js
<ide> describe('DOMPropertyOperations', function() {
<ide> expect(stubNode.hasAttribute('allowFullScreen')).toBe(false);
<ide> });
<ide>
<add> it('should remove when setting custom attr to null', function() {
<add> DOMPropertyOperations.setValueForProperty(
<add> stubNode,
<add> 'data-foo',
<add> 'bar'
<add> );
<add> expect(stubNode.hasAttribute('data-foo')).toBe(true);
<add> DOMPropertyOperations.setValueForProperty(
<add> stubNode,
<add> 'data-foo',
<add> null
<add> );
<add> expect(stubNode.hasAttribute('data-foo')).toBe(false);
<add> });
<add>
<ide> it('should use mutation method where applicable', function() {
<ide> var foobarSetter = mocks.getMockFunction();
<ide> // inject foobar DOM property | 2 |
Ruby | Ruby | remove stray unicode | 7242365ff39b2184a81a7aaad40735daca0e1fbd | <ide><path>Library/Contributions/example-formula.rb
<ide> def install
<ide> args << "--universal-binary" if build.universal?
<ide>
<ide> # The `build.with?` and `build.without?` are smart enough to do the
<del> # right thing™ with respect to defaults defined via `:optional` and
<add> # right thing with respect to defaults defined via `:optional` and
<ide> # `:recommended` dependencies.
<ide>
<ide> # If you need to give the path to lib/include of another brewed formula | 1 |
Python | Python | update maintainer on equinix metal | a35173c70675bbfd373fc72aa802265c6f9dc4cb | <ide><path>libcloud/test/compute/test_equinixmetal.py
<ide> # See the License for the specific language governing permissions and
<ide> # limitations under the License.
<ide> #
<del># Maintainer: Aaron Welch <[email protected]>
<del># Based on code written by Jed Smith <[email protected]> who based it on
<add># Maintainer:
<add># Based on code written by Jed Smith <[email protected]> who based it on
<ide> # code written by Alex Polvi <[email protected]>
<ide> #
<ide> | 1 |
Javascript | Javascript | add test for unique challenge titles | be693638de0953390f3389d0f8248491a4c1dc2a | <ide><path>seed/challengeTitles.js
<add>import _ from 'lodash';
<add>
<add>class ChallengeTitles {
<add> constructor() {
<add> this.knownTitles = [];
<add> }
<add> check(title) {
<add> if (typeof title !== 'string') {
<add> throw new Error(`Expected a valid string for ${title}, got ${typeof title}`);
<add> } else if (title.length === 0) {
<add> throw new Error(`Expected a title length greater than 0`);
<add> }
<add> const titleToCheck = title.toLowerCase().replace(/\s+/g, '');
<add> const titleIndex = _.findIndex(this.knownTitles, existing => titleToCheck === existing);
<add> if (titleIndex !== -1) {
<add> throw new Error(`
<add> All challenges must have a unique title.
<add>
<add> The title ${title} is already assigned
<add> `);
<add> }
<add> this.knownTitles = [ ...this.knownTitles, titleToCheck ];
<add> }
<add>}
<add>
<add>export default ChallengeTitles;
<ide><path>seed/test-challenges.js
<ide> import tape from 'tape';
<ide> import getChallenges from './getChallenges';
<ide> import { modern } from '../common/app/utils/challengeTypes';
<ide> import MongoIds from './mongoIds';
<add>import ChallengeTitles from './challengeTitles';
<ide> import addAssertsToTapTest from './addAssertsToTapTest';
<ide>
<ide> let mongoIds = new MongoIds();
<add>let challengeTitles = new ChallengeTitles();
<ide>
<ide> function evaluateTest(solution, assert,
<ide> react, redux, reactRedux,
<ide> function createTest({
<ide> reactRedux = false
<ide> }) {
<ide> mongoIds.check(id, title);
<add> challengeTitles.check(title);
<ide>
<ide> solutions = solutions.filter(solution => !!solution);
<ide> tests = tests.filter(test => !!test); | 2 |
Text | Text | add v4.0.0-beta.9 to changelog | 41438a8a5e26261239565bbcd1459d1b6a71f1b8 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v4.0.0-beta.9 (November 20, 2021)
<add>
<add>- [#19749](https://github.com/emberjs/ember.js/pull/19749) [CLEANUP] Remove `deprecate-router-events` support code
<add>- [#19762](https://github.com/emberjs/ember.js/pull/19762) [CLEANUP] Update GlimmerVM to 0.81
<add> - removes deprecation of mutations during helper compute
<add> - removes deprecation of mutations during unknownProperty
<add> - `@glimmer/integration-tests`, `@glimmer/manager`, `@glimmer/validator`
<add> * [#1330](https://github.com/glimmerjs/glimmer-vm/pull/1330) Remove deprecated support for mutation after consumption during certain manager hooks ([@snewcomer](https://github.com/snewcomer))
<add> - `@glimmer/manager`
<add> * [#1328](https://github.com/glimmerjs/glimmer-vm/pull/1328) Remove deprecated Component Manager version 3.4 ([@nlfurniss](https://github.com/nlfurniss))
<add> - `@glimmer/integration-tests`, `@glimmer/manager`
<add> * [#1329](https://github.com/glimmerjs/glimmer-vm/pull/1329) Remove deprecated Modifier Manager version 3.13 ([@nlfurniss](https://github.com/nlfurniss))
<add>- [#19806](https://github.com/emberjs/ember.js/pull/19806) [CLEANUP] Drop export of built-ins, remove legacy components
<add>
<ide> ### v4.0.0-beta.8 (November 5, 2021)
<ide>
<ide> - [#19823](https://github.com/emberjs/ember.js/pull/19823) / [#19828](https://github.com/emberjs/ember.js/pull/19828) [BUGFIX] Fix deprecation `until` and link for Component.reopenClass and Component.reopen | 1 |
Ruby | Ruby | fix isolated tests | 8c679fe0ca77e8cc6de6ae408a556995f3801ee8 | <ide><path>activesupport/lib/active_support/core_ext/big_decimal/yaml_conversions.rb
<ide>
<ide> require 'bigdecimal'
<ide> require 'yaml'
<add>require 'active_support/core_ext/big_decimal/conversions'
<ide>
<ide> class BigDecimal
<ide> YAML_MAPPING = { 'Infinity' => '.Inf', '-Infinity' => '-.Inf', 'NaN' => '.NaN' } | 1 |
Javascript | Javascript | fix bug report with-portals example | f177be9e0540822763ae9baa2a425cd4c9187a28 | <ide><path>examples/with-portals/components/Portal.js
<ide> import ReactDOM from 'react-dom'
<ide> export class Portal extends React.Component {
<ide> componentDidMount () {
<ide> this.element = document.querySelector(this.props.selector)
<add> this.forceUpdate()
<ide> }
<ide>
<ide> render () { | 1 |
Javascript | Javascript | fix bug in objectloader | a15ffe8dd987fba876da6c14e37ee0506f01b771 | <ide><path>src/loaders/ObjectLoader.js
<ide> THREE.ObjectLoader.prototype = {
<ide>
<ide> for ( var child in data.children ) {
<ide>
<del> object.add( this.parseObject( data.children[ child ], geometries, materials ) );
<add> object.add( this.parseObject( data.children[ child ], geometries, materials, tracks ) );
<ide>
<ide> }
<ide>
<ide> THREE.ObjectLoader.prototype = {
<ide>
<ide> if( dataTracks.position ) {
<ide>
<del> tracks.add( THREE.VectorKeyframeTrack.parse( object.uuid + '.position', dataTracks.position ) );
<add> tracks.push( THREE.VectorKeyframeTrack.parse( object.uuid + '.position', dataTracks.position ) );
<ide>
<ide> }
<ide>
<ide> if( dataTracks.quaternion ) {
<ide>
<del> tracks.add( THREE.QuaternionKeyframeTrack.parse( object.uuid + '.quaternion', dataTracks.quaternion ) );
<add> tracks.push( THREE.QuaternionKeyframeTrack.parse( object.uuid + '.quaternion', dataTracks.quaternion ) );
<ide>
<ide> }
<ide>
<ide> if( dataTracks.scale ) {
<ide>
<del> tracks.add( THREE.VectorKeyframeTrack.parse( object.uuid + '.scale', dataTracks.scale ) );
<add> tracks.push( THREE.VectorKeyframeTrack.parse( object.uuid + '.scale', dataTracks.scale ) );
<ide>
<ide> }
<ide> } | 1 |
Javascript | Javascript | remove unused doc_widget.js file | 4235ee9ad6edb56e49a852204a721715fa429e94 | <ide><path>docs/src/templates/js/doc_widgets.js
<del>angular.module('ngdocs.directives', [], function($compileProvider) {
<del>
<del> var angularJsUrl;
<del> var scripts = document.getElementsByTagName("script");
<del> var angularJsRegex = /^(|.*\/)angular(-\d.*?)?(\.min)?.js(\?[^#]*)?(#(.*))?$/;
<del> for(var j = 0; j < scripts.length; j++) {
<del> var src = scripts[j].src;
<del> if (src && src.match(angularJsRegex)) {
<del> angularJsUrl = src.replace(/docs(-next)?\.angularjs\.org/, 'code.angularjs.org');
<del> continue;
<del> }
<del> }
<del>
<del>
<del> var HTML_TEMPLATE =
<del> '<!doctype html>\n' +
<del> '<html ng-app_MODULE_>\n' +
<del> ' <script src="' + angularJsUrl + '"></script>\n' +
<del> '_SCRIPT_SOURCE_' +
<del> ' <body>\n' +
<del> '_HTML_SOURCE_\n' +
<del> ' </body>\n' +
<del> '</html>';
<del>
<del> $compileProvider.directive('docExample', ['$injector', '$log', '$browser', '$location',
<del> function($injector, $log, $browser, $location) {
<del> return {
<del> restrict: 'E',
<del> terminal: true,
<del> compile: function(element, attrs) {
<del> var module = attrs.module;
<del>
<del> //jQuery find() methods in this widget contain primitive selectors on purpose so that we can use
<del> //jqlite instead. jqlite's find() method currently supports onlt getElementsByTagName!
<del> var example = element.find('pre').eq(0), //doc-source
<del> scriptSrc = '',
<del> htmlSrc = example.text().replace(/<script(\s+type="text\/javascript")?>([\s\S]+)<\/script>/im, function(_, type, script) {
<del> scriptSrc = script;
<del> return '';
<del> }),
<del> showSource = example.attr('source') !== 'false',
<del> jsfiddle = example.attr('jsfiddle') || true,
<del> scenario = element.find('pre').eq(1); //doc-scenario
<del>
<del> var tabs = angular.element('<ul class="doc-example">');
<del>
<del> // show source tab, if not disabled
<del> if (showSource) {
<del> tabs.append(
<del> '<li class="doc-example-heading"><h3>Source</h3></li>' +
<del> '<li class="doc-example-source" ng:non-bindable>' +
<del> jsFiddleButton(jsfiddle) + // may or may not have value
<del> '<pre class="brush: js; html-script: true; toolbar: false;"></pre></li>');
<del> }
<del> // show live preview tab
<del> var livePreviewTab;
<del> tabs.append('<li class="doc-example-heading"><h3>Live Preview</h3></li>');
<del> tabs.append(livePreviewTab = angular.element('<li class="doc-example-live">' + htmlSrc +'</li>'));
<del> // show scenario tab, if present
<del> if (scenario.text()) {
<del> tabs.append(
<del> '<li class="doc-example-heading"><h3>Scenario Test</h3></li>' +
<del> '<li class="doc-example-scenario"><pre class="brush: js">' + scenario.text() + '</pre></li>');
<del> }
<del>
<del> tabs.find('li').eq(1).find('pre').text(
<del> HTML_TEMPLATE.
<del> replace('_SCRIPT_SOURCE_', scriptSrc ? ' <script>\n' + indent(scriptSrc, ' ') + '\n </script>\n' : '').
<del> replace('_HTML_SOURCE_', indent(htmlSrc, ' ')).
<del> replace('_MODULE_', module ? '="' + module + '"' : ''));
<del>
<del> element.html('');
<del> element.append(tabs);
<del>
<del> try {
<del> if (window.execScript) { // IE
<del> window.execScript(scriptSrc || '"stupid IE!"'); // IE complains when evaling empty string
<del> } else {
<del> window.eval(scriptSrc);
<del> }
<del> } catch (e) {
<del> alert(e);
<del> }
<del>
<del> return function(docsAppScope) {
<del> var modules = [
<del> function($provide) {
<del> $provide.value('$browser', $browser);
<del> $provide.provider('$location', function() {
<del> this.$get = function() {
<del> return $location;
<del> };
<del> this.hashPrefix = this.html5Mode = angular.noop;
<del> });
<del> $provide.decorator('$defer', function($rootScope, $delegate) {
<del> return angular.extend(function(fn, delay) {
<del> if (delay && delay > 500) {
<del> return setTimeout(function() {
<del> $rootScope.$apply(fn);
<del> }, delay);
<del> } else {
<del> return $delegate.apply(this, arguments);
<del> }
<del> }, $delegate);
<del> });
<del> }
<del> ];
<del> module && modules.push(module);
<del>
<del> angular.bootstrap(livePreviewTab, modules).
<del> invoke(['$rootScope', function(example$rootScope) {
<del> element.bind('$destroy', docsAppScope.$root.$watch(function() {
<del> // this propagates the $watch from the docs app to the example app
<del> example$rootScope.$digest();
<del> }));
<del> }]);
<del> };
<del>
<del> function jsFiddleButton(jsfiddle) {
<del> var fixJsFiddleIssue132 = true;
<del> if (jsfiddle !== 'false') {
<del> if(jsfiddle === true) {
<del> //dynamically generate a fiddle
<del> var fiddleUrl = 'http://jsfiddle.net/api/post/library/pure/';
<del>
<del> function jsFiddleEscape(text, prefix) {
<del> return indent(text.replace(/<\/textarea>/gi,'</textarea>'), prefix);
<del> }
<del>
<del> return '<form class="jsfiddle" method="post" action="' + fiddleUrl + '" target="_blank">' +
<del> (fixJsFiddleIssue132 ? '' : '<textarea name="resources">' + angularJsUrl + '</textarea>') +
<del> '<textarea name="css">\n' +
<del> (fixJsFiddleIssue132 ? '</style>\n<script src="' + angularJsUrl + '"></script>\n<style>\n' : '') +
<del> '.ng-invalid { border: 1px solid red; } \n' +
<del> 'body { font-family: Arial,Helvetica,sans-serif; }\n' +
<del> 'body, td, th { font-size: 14px; margin: 0; }\n' +
<del> 'table { border-collapse: separate; border-spacing: 2px; display: table; margin-bottom: 0; margin-top: 0; -moz-box-sizing: border-box; text-indent: 0; }\n' +
<del> 'a:link, a:visited, a:hover { color: #5D6DB6; text-decoration: none; }\n' +
<del> '.error { color: red; }\n' +
<del> '</textarea>' +
<del> '<input type="text" name="title" value="AngularJS Live Example">' +
<del> '<textarea name="html">' +
<del> '<div ng:app' + (module ? '="' + module + '"' : '') + '>\n' + jsFiddleEscape(htmlSrc, ' ') + '\n</div>' +
<del> '</textarea>' +
<del> '<textarea name="js">' + jsFiddleEscape(scriptSrc) + '</textarea>' +
<del> '<button>edit at jsFiddle</button>' +
<del> '</form>';
<del> } else {
<del> //use existing fiddle
<del> fiddleUrl = "http://jsfiddle.net" + jsfiddle;
<del> return '<form class="jsfiddle" method="get" action="' + fiddleUrl + '" target="_blank">' +
<del> '<button>edit at jsFiddle</button>' +
<del> '</form>';
<del> }
<del> } else {
<del> return '';
<del> }
<del> };
<del> }
<del> }
<del> }]);
<del>
<del> function indent(text, prefix) {
<del> prefix = prefix || '';
<del> if (!text) return text;
<del> var lines = text.split(/\r?\n/);
<del> var i;
<del>
<del> // remove any leading blank lines
<del> while (lines[0].match(/^\s*$/)) lines.shift();
<del> // remove any trailing blank lines
<del> while (lines[lines.length - 1].match(/^\s*$/)) lines.pop();
<del> var minIndent = 999;
<del> for (i = 0; i < lines.length; i++) {
<del> var line = lines[0];
<del> var indent = line.match(/^\s*/)[0];
<del> if (indent !== line && indent.length < minIndent) {
<del> minIndent = indent.length;
<del> }
<del> }
<del>
<del> for (i = 0; i < lines.length; i++) {
<del> lines[i] = prefix + lines[i].substring(minIndent);
<del> }
<del> return lines.join('\n');
<del> }
<del>
<del> $compileProvider.directive('docTutorialInstructions', function() {
<del> var HTML_NAV = '<li ng:class="currentCls(\'{id}\')"><a ng:click="select(\'{id}\')" href>{title}</a></li>';
<del> var HTML_CONTENT = '<div ng:show="selected==\'{id}\'">{content}</div>';
<del>
<del> var HTML_TPL =
<del> '<p><a ng:init="showInstructions = {show}" ng:show="!showInstructions" ng:click="showInstructions = true" href>Workspace Reset Instructions ➤</a></p>' +
<del> '<div ng:controller="TutorialInstructionsCtrl" ng:show="showInstructions">' +
<del> '<div class="tabs-nav">' +
<del> '<ul>' +
<del> '</ul>' +
<del> '</div>' +
<del> '<div class="tabs-content"><div class="tabs-content-inner">' +
<del>
<del> '</div></div>' +
<del> '</div>';
<del>
<del> var DEFAULT_NAV =
<del> '<li ng:class="currentCls(\'git-mac\')"><a ng:click="select(\'git-mac\')" href>Git on Mac/Linux</a></li>' +
<del> '<li ng:class="currentCls(\'git-win\')"><a ng:click="select(\'git-win\')" href>Git on Windows</a></li>' +
<del> '<li ng:class="currentCls(\'ss-mac\')"><a ng:click="select(\'ss-mac\')" href>Snapshots on Mac/Linux</a></li>' +
<del> '<li ng:class="currentCls(\'ss-win\')"><a ng:click="select(\'ss-win\')" href>Snapshots on Windows</a></li>';
<del>
<del> var DEFAULT_CONTENT =
<del> '<div ng:show="selected==\'git-mac\'">' +
<del> '<ol>' +
<del> '<li><p>Reset the workspace to step {step}.</p>' +
<del> '<pre><code> git checkout -f step-{step}</code></pre></li>' +
<del> '<li><p>Refresh your browser or check the app out on <a href="http://angular.github.com/angular-phonecat/step-{step}/app">angular\'s server</a>.</p></li>' +
<del> '</ol>' +
<del> '</div>' +
<del>
<del> '<div ng:show="selected==\'git-win\'">' +
<del> '<ol>' +
<del> '<li><p>Reset the workspace to step {step}.</p>' +
<del> '<pre><code> git checkout -f step-{step}</code></pre></li>' +
<del> '<li><p>Refresh your browser or check the app out on <a href="http://angular.github.com/angular-phonecat/step-{step}/app">angular\'s server</a>.</p></li>' +
<del> '</ol>' +
<del> '</div>' +
<del>
<del> '<div ng:show="selected==\'ss-mac\'">' +
<del> '<ol>' +
<del> '<li><p>Reset the workspace to step {step}.</p>' +
<del> '<pre><code> ./goto_step.sh {step}</code></pre></li>' +
<del> '<li><p>Refresh your browser or check the app out on <a href="http://angular.github.com/angular-phonecat/step-{step}/app">angular\'s server</a>.</p></li>' +
<del> '</ol>' +
<del> '</div>' +
<del>
<del> '<div ng:show="selected==\'ss-win\'">' +
<del> '<ol>' +
<del> '<li><p>Reset the workspace to step {step}.</p>' +
<del> '<pre><code> ./goto_step.bat {step}</code></pre></li>' +
<del> '<li><p>Refresh your browser or check the app out on <a href="http://angular.github.com/angular-phonecat/step-{step}/app">angular\'s server</a>.</p></li>' +
<del> '</ol>' +
<del> '</div>';
<del>
<del> return {
<del> restrict: 'EA',
<del> compile: function(element, attrs) {
<del> var tabs = angular.element(HTML_TPL.replace('{show}', attrs.show || 'false')),
<del> nav = tabs.find('ul'),
<del> // use simple selectors because jqLite find() supports getElementsByTagName only
<del> content = tabs.find('div').find('div'),
<del> children = element.children();
<del>
<del> if (children.length) {
<del> // load custom content
<del> angular.forEach(element.children(), function(elm) {
<del> elm = angular.element(elm);
<del> var id = elm.attr('id');
<del>
<del> nav.append(HTML_NAV.replace('{title}', elm.attr('title')).replace(/\{id\}/g, id));
<del> content.append(HTML_CONTENT.replace('{id}', id).replace('{content}', elm.html()));
<del> });
<del> } else {
<del> // default
<del> nav.append(DEFAULT_NAV);
<del> content.append(DEFAULT_CONTENT.replace(/\{step\}/g, element.attr('step')));
<del> }
<del>
<del> element.html('');
<del> element.append(tabs);
<del> }
<del> }
<del> });
<del>
<del>
<del> $compileProvider.directive('docTutorialNav', function() {
<del> return {
<del> restrict: 'EA',
<del> link:function(scope, element, attrs) {
<del> var prevStep, codeDiff, nextStep,
<del> content, step = attrs.docTutorialNav;
<del>
<del> step = parseInt(step, 10);
<del>
<del> if (step === 0) {
<del> prevStep = '';
<del> nextStep = 'step_01';
<del> codeDiff = 'step-0~7...step-0';
<del> } else if (step === 11){
<del> prevStep = 'step_10';
<del> nextStep = 'the_end';
<del> codeDiff = 'step-10...step-11';
<del> } else {
<del> prevStep = 'step_' + pad(step - 1);
<del> nextStep = 'step_' + pad(step + 1);
<del> codeDiff = 'step-' + (step-1) + '...step-' + step;
<del> }
<del>
<del> content = angular.element(
<del> '<li><a href="tutorial/' + prevStep + '">Previous</a></li>' +
<del> '<li><a href="http://angular.github.com/angular-phonecat/step-' + step + '/app">Live Demo</a></li>' +
<del> '<li><a href="https://github.com/angular/angular-phonecat/compare/' + codeDiff + '">Code Diff</a></li>' +
<del> '<li><a href="tutorial/' + nextStep + '">Next</a></li>'
<del> );
<del>
<del> element.attr('id', 'tutorial-nav');
<del> element.append(content);
<del> }
<del> };
<del>
<del> function pad(step) {
<del> return (step < 10) ? ('0' + step) : step;
<del> }
<del> });
<del>}); | 1 |
Javascript | Javascript | fix typo in example | dfbe69c45a391b52d7c539243d92fdbb128c17fd | <ide><path>src/ng/interval.js
<ide> function $IntervalProvider() {
<ide> * };
<ide> *
<ide> * $scope.$on('$destroy', function() {
<del> * // Make sure that the interval nis destroyed too
<add> * // Make sure that the interval is destroyed too
<ide> * $scope.stopFight();
<ide> * });
<ide> * }]) | 1 |
Text | Text | fix typo in doc/api/http2/md | 15b3641bb4236741555c9faa1265af8429664d33 | <ide><path>doc/api/http2.md
<ide> changes:
<ide> - v14.5.0
<ide> - v12.19.0
<ide> pr-url: https://github.com/nodejs/node/pull/33160
<del> description: Allow explicity setting date headers.
<add> description: Allow explicitly setting date headers.
<ide> -->
<ide>
<ide> * `headers` {HTTP/2 Headers Object}
<ide> changes:
<ide> - v14.5.0
<ide> - v12.19.0
<ide> pr-url: https://github.com/nodejs/node/pull/33160
<del> description: Allow explicity setting date headers.
<add> description: Allow explicitly setting date headers.
<ide> - version: v12.12.0
<ide> pr-url: https://github.com/nodejs/node/pull/29876
<ide> description: The `fd` option may now be a `FileHandle`.
<ide> changes:
<ide> - v14.5.0
<ide> - v12.19.0
<ide> pr-url: https://github.com/nodejs/node/pull/33160
<del> description: Allow explicity setting date headers.
<add> description: Allow explicitly setting date headers.
<ide> - version: v10.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/18936
<ide> description: Any readable file, not necessarily a | 1 |
PHP | PHP | use imported classes | d79f1385aa9a67a2fb48d678f5224530a4e8c650 | <ide><path>src/Illuminate/Foundation/Exceptions/Handler.php
<ide> class Handler implements ExceptionHandlerContract
<ide> * @var array
<ide> */
<ide> protected $internalDontReport = [
<del> \Illuminate\Auth\AuthenticationException::class,
<del> \Illuminate\Auth\Access\AuthorizationException::class,
<del> \Symfony\Component\HttpKernel\Exception\HttpException::class,
<add> AuthenticationException::class,
<add> AuthorizationException::class,
<add> HttpException::class,
<ide> HttpResponseException::class,
<del> \Illuminate\Database\Eloquent\ModelNotFoundException::class,
<del> \Illuminate\Session\TokenMismatchException::class,
<del> \Illuminate\Validation\ValidationException::class,
<add> ModelNotFoundException::class,
<add> TokenMismatchException::class,
<add> ValidationException::class,
<ide> ];
<ide>
<ide> /** | 1 |
Python | Python | fix assignment of unassigned triggers | b26d4d8a290ce0104992ba28850113490c1ca445 | <ide><path>airflow/models/trigger.py
<ide> import datetime
<ide> from typing import Any, Dict, Iterable, Optional
<ide>
<del>from sqlalchemy import Column, Integer, String, func
<add>from sqlalchemy import Column, Integer, String, func, or_
<ide>
<ide> from airflow.models.base import Base
<ide> from airflow.models.taskinstance import TaskInstance
<ide> def assign_unassigned(cls, triggerer_id, capacity, session=None):
<ide> alive_triggerer_ids = [
<ide> row[0]
<ide> for row in session.query(BaseJob.id).filter(
<del> BaseJob.end_date is None,
<add> BaseJob.end_date.is_(None),
<ide> BaseJob.latest_heartbeat > timezone.utcnow() - datetime.timedelta(seconds=30),
<ide> BaseJob.job_type == "TriggererJob",
<ide> )
<ide> def assign_unassigned(cls, triggerer_id, capacity, session=None):
<ide> # Find triggers who do NOT have an alive triggerer_id, and then assign
<ide> # up to `capacity` of those to us.
<ide> trigger_ids_query = (
<del> session.query(cls.id).filter(cls.triggerer_id.notin_(alive_triggerer_ids)).limit(capacity).all()
<add> session.query(cls.id)
<add> # notin_ doesn't find NULL rows
<add> .filter(or_(cls.triggerer_id.is_(None), cls.triggerer_id.notin_(alive_triggerer_ids)))
<add> .limit(capacity)
<add> .all()
<ide> )
<ide> session.query(cls).filter(cls.id.in_([i.id for i in trigger_ids_query])).update(
<ide> {cls.triggerer_id: triggerer_id},
<ide><path>tests/models/test_trigger.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide>
<add>import datetime
<add>
<ide> import pytest
<ide>
<add>from airflow.jobs.triggerer_job import TriggererJob
<ide> from airflow.models import TaskInstance, Trigger
<ide> from airflow.operators.dummy import DummyOperator
<ide> from airflow.triggers.base import TriggerEvent
<ide> def session():
<ide> def clear_db(session):
<ide> session.query(TaskInstance).delete()
<ide> session.query(Trigger).delete()
<add> session.query(TriggererJob).delete()
<ide> yield session
<ide> session.query(TaskInstance).delete()
<ide> session.query(Trigger).delete()
<add> session.query(TriggererJob).delete()
<ide> session.commit()
<ide>
<ide>
<ide> def test_submit_failure(session, create_task_instance):
<ide> updated_task_instance = session.query(TaskInstance).one()
<ide> assert updated_task_instance.state == State.SCHEDULED
<ide> assert updated_task_instance.next_method == "__fail__"
<add>
<add>
<add>def test_assign_unassigned(session, create_task_instance):
<add> """
<add> Tests that unassigned triggers of all appropriate states are assigned.
<add> """
<add> finished_triggerer = TriggererJob(None, heartrate=10, state=State.SUCCESS)
<add> finished_triggerer.end_date = timezone.utcnow() - datetime.timedelta(hours=1)
<add> session.add(finished_triggerer)
<add> assert not finished_triggerer.is_alive()
<add> healthy_triggerer = TriggererJob(None, heartrate=10, state=State.RUNNING)
<add> session.add(healthy_triggerer)
<add> assert healthy_triggerer.is_alive()
<add> new_triggerer = TriggererJob(None, heartrate=10, state=State.RUNNING)
<add> session.add(new_triggerer)
<add> assert new_triggerer.is_alive()
<add> session.commit()
<add> trigger_on_healthy_triggerer = Trigger(classpath="airflow.triggers.testing.SuccessTrigger", kwargs={})
<add> trigger_on_healthy_triggerer.id = 1
<add> trigger_on_healthy_triggerer.triggerer_id = healthy_triggerer.id
<add> trigger_on_killed_triggerer = Trigger(classpath="airflow.triggers.testing.SuccessTrigger", kwargs={})
<add> trigger_on_killed_triggerer.id = 2
<add> trigger_on_killed_triggerer.triggerer_id = finished_triggerer.id
<add> trigger_unassigned_to_triggerer = Trigger(classpath="airflow.triggers.testing.SuccessTrigger", kwargs={})
<add> trigger_unassigned_to_triggerer.id = 3
<add> assert trigger_unassigned_to_triggerer.triggerer_id is None
<add> session.add(trigger_on_healthy_triggerer)
<add> session.add(trigger_on_killed_triggerer)
<add> session.add(trigger_unassigned_to_triggerer)
<add> session.commit()
<add> assert session.query(Trigger).count() == 3
<add> Trigger.assign_unassigned(new_triggerer.id, 100, session=session)
<add> session.expire_all()
<add> # Check that trigger on killed triggerer and unassigned trigger are assigned to new triggerer
<add> assert (
<add> session.query(Trigger).filter(Trigger.id == trigger_on_killed_triggerer.id).one().triggerer_id
<add> == new_triggerer.id
<add> )
<add> assert (
<add> session.query(Trigger).filter(Trigger.id == trigger_unassigned_to_triggerer.id).one().triggerer_id
<add> == new_triggerer.id
<add> )
<add> # Check that trigger on healthy triggerer still assigned to existing triggerer
<add> assert (
<add> session.query(Trigger).filter(Trigger.id == trigger_on_healthy_triggerer.id).one().triggerer_id
<add> == healthy_triggerer.id
<add> ) | 2 |
Javascript | Javascript | fix inconsistent slice usage | 60a01c11c0b879dacee73c26402469e1d97e2e3e | <ide><path>packages/ember-metal/lib/computed.js
<ide> Ember.computed = function(func) {
<ide> var args;
<ide>
<ide> if (arguments.length > 1) {
<del> args = [].slice.call(arguments, 0, -1);
<del> func = [].slice.call(arguments, -1)[0];
<add> args = a_slice.call(arguments, 0, -1);
<add> func = a_slice.call(arguments, -1)[0];
<ide> }
<ide>
<ide> var cp = new ComputedProperty(func); | 1 |
Javascript | Javascript | remove input source on xr session end | 95172e542c07d40ff89d2e716e01358eff59fad0 | <ide><path>src/renderers/webxr/WebXRManager.js
<ide> class WebXRManager extends EventDispatcher {
<ide>
<ide> if ( inputSource === null ) continue;
<ide>
<add> controllerInputSources[ i ] = null;
<add>
<ide> controllers[ i ].disconnect( inputSource );
<ide>
<ide> } | 1 |
Javascript | Javascript | apply review tasks | b9507cca99bee87e2c8ec9d34d3c4bfefc25c53d | <ide><path>lib/NormalModule.js
<ide>
<ide> const path = require("path");
<ide> const NativeModule = require("module");
<del>const Module = require("./Module");
<add>const crypto = require("crypto");
<add>
<ide> const SourceMapSource = require("webpack-sources").SourceMapSource;
<ide> const OriginalSource = require("webpack-sources").OriginalSource;
<ide> const RawSource = require("webpack-sources").RawSource;
<ide> const ReplaceSource = require("webpack-sources").ReplaceSource;
<ide> const CachedSource = require("webpack-sources").CachedSource;
<ide> const LineToLineMappedSource = require("webpack-sources").LineToLineMappedSource;
<del>const ModuleParseError = require("./ModuleParseError");
<ide>
<add>const Module = require("./Module");
<add>const ModuleParseError = require("./ModuleParseError");
<ide> const ModuleBuildError = require("./ModuleBuildError");
<ide> const ModuleError = require("./ModuleError");
<ide> const ModuleWarning = require("./ModuleWarning");
<ide> class NormalModule extends Module {
<ide> module._compile(code, filename);
<ide> return module.exports;
<ide> },
<del> resolve: function(context, request, callback) {
<add> resolve(context, request, callback) {
<ide> resolver.resolve({}, context, request, callback);
<ide> },
<del> resolveSync: function(context, request) {
<add> resolveSync(context, request) {
<ide> return resolver.resolveSync({}, context, request);
<ide> },
<ide> emitFile: (name, content, sourceMap) => {
<ide> class NormalModule extends Module {
<ide> }
<ide>
<ide> source(dependencyTemplates, outputOptions, requestShortener) {
<del> let hash = require("crypto").createHash("md5");
<add> let hash = crypto.createHash("md5");
<ide> this.updateHash(hash);
<ide> hash = hash.digest("hex");
<ide> if(this._cachedSource && this._cachedSource.hash === hash) {
<ide> class NormalModule extends Module {
<ide> needRebuild(fileTimestamps, contextTimestamps) {
<ide> const highestFileDepTimestamp = this.getHighestTimestamp(
<ide> this.fileDependencies, fileTimestamps);
<del> // if the hightest is Infinity, we need a needRebuild
<add> // if the hightest is Infinity, we need a rebuild
<ide> // exit early here.
<ide> if(highestFileDepTimestamp === Infinity) {
<ide> return true;
<ide> class NormalModule extends Module {
<ide> const highestContextDepTimestamp = this.getHighestTimestamp(
<ide> this.contextDependencies, contextTimestamps);
<ide>
<del> // Again if the hightest is Infinity, we need a needRebuild
<add> // Again if the hightest is Infinity, we need a rebuild
<ide> // exit early here.
<ide> if(highestContextDepTimestamp === Infinity) {
<ide> return true; | 1 |
Ruby | Ruby | remove dead constants | 293cdecee309744d4e75e1b9f5bdd8d523d27c2e | <ide><path>activesupport/lib/active_support/multibyte/unicode.rb
<ide> module Unicode
<ide> HANGUL_NCOUNT = HANGUL_VCOUNT * HANGUL_TCOUNT
<ide> HANGUL_SCOUNT = 11172
<ide> HANGUL_SLAST = HANGUL_SBASE + HANGUL_SCOUNT
<del> HANGUL_JAMO_FIRST = 0x1100
<del> HANGUL_JAMO_LAST = 0x11FF
<del>
<del> # All the unicode whitespace
<del> WHITESPACE = [
<del> (0x0009..0x000D).to_a, # White_Space # Cc [5] <control-0009>..<control-000D>
<del> 0x0020, # White_Space # Zs SPACE
<del> 0x0085, # White_Space # Cc <control-0085>
<del> 0x00A0, # White_Space # Zs NO-BREAK SPACE
<del> 0x1680, # White_Space # Zs OGHAM SPACE MARK
<del> (0x2000..0x200A).to_a, # White_Space # Zs [11] EN QUAD..HAIR SPACE
<del> 0x2028, # White_Space # Zl LINE SEPARATOR
<del> 0x2029, # White_Space # Zp PARAGRAPH SEPARATOR
<del> 0x202F, # White_Space # Zs NARROW NO-BREAK SPACE
<del> 0x205F, # White_Space # Zs MEDIUM MATHEMATICAL SPACE
<del> 0x3000, # White_Space # Zs IDEOGRAPHIC SPACE
<del> ].flatten.freeze
<del>
<del> # BOM (byte order mark) can also be seen as whitespace, it's a
<del> # non-rendering character used to distinguish between little and big
<del> # endian. This is not an issue in utf-8, so it must be ignored.
<del> LEADERS_AND_TRAILERS = WHITESPACE + [65279] # ZERO-WIDTH NO-BREAK SPACE aka BOM
<del>
<del> # Returns a regular expression pattern that matches the passed Unicode
<del> # codepoints.
<del> def self.codepoints_to_pattern(array_of_codepoints) #:nodoc:
<del> array_of_codepoints.collect { |e| [e].pack "U*".freeze }.join("|".freeze)
<del> end
<del> TRAILERS_PAT = /(#{codepoints_to_pattern(LEADERS_AND_TRAILERS)})+\Z/u
<del> LEADERS_PAT = /\A(#{codepoints_to_pattern(LEADERS_AND_TRAILERS)})+/u
<ide>
<ide> # Detect whether the codepoint is in a certain character class. Returns
<ide> # +true+ when it's in the specified character class and +false+ otherwise. | 1 |
Javascript | Javascript | fix setstate in componentwillmount | 9c21e2f3c447776bb38a71b12b60a1c3218edf97 | <ide><path>src/test/ReactTestUtils.js
<ide> ReactShallowRenderer.prototype.render = function(element, context) {
<ide> if (!context) {
<ide> context = emptyObject;
<ide> }
<del> var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(true);
<del> this._render(element, transaction, context);
<del> ReactUpdates.ReactReconcileTransaction.release(transaction);
<add> ReactUpdates.batchedUpdates(_batchedRender, this, element, context);
<ide>
<ide> return this.getRenderOutput();
<ide> };
<ide>
<add>function _batchedRender(renderer, element, context) {
<add> var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(true);
<add> renderer._render(element, transaction, context);
<add> ReactUpdates.ReactReconcileTransaction.release(transaction);
<add>}
<add>
<ide> ReactShallowRenderer.prototype.getRenderOutput = function() {
<ide> return (
<ide> (this._instance && this._instance._renderedComponent &&
<ide><path>src/test/__tests__/ReactTestUtils-test.js
<ide> describe('ReactTestUtils', function() {
<ide> expect(result.props.className).toEqual('clicked');
<ide> });
<ide>
<add> it('can setState in componentWillMount when shallow rendering', function() {
<add> var SimpleComponent = React.createClass({
<add> componentWillMount() {
<add> this.setState({groovy: 'doovy'});
<add> },
<add> render() {
<add> return <div>{this.state.groovy}</div>;
<add> },
<add> });
<add>
<add> var shallowRenderer = ReactTestUtils.createRenderer();
<add> var result = shallowRenderer.render(<SimpleComponent />);
<add> expect(result).toEqual(<div>doovy</div>);
<add> });
<add>
<ide> it('can pass context when shallowly rendering', function() {
<ide> var SimpleComponent = React.createClass({
<ide> contextTypes: { | 2 |
PHP | PHP | break constructor line | 4e9c9fd98b4dff71f449764e87c52577e2634587 | <ide><path>src/Illuminate/Validation/Validator.php
<ide> class Validator implements ValidatorContract
<ide> * @param array $customAttributes
<ide> * @return void
<ide> */
<del> public function __construct(TranslatorInterface $translator, array $data, array $rules, array $messages = [], array $customAttributes = [])
<add> public function __construct(TranslatorInterface $translator, array $data, array $rules,
<add> array $messages = [], array $customAttributes = [])
<ide> {
<ide> $this->initialRules = $rules;
<ide> $this->translator = $translator; | 1 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.