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 execin with environment and enabled support | aa9705f832d847d6e6ce76e19f3c952c194c167e | <ide><path>pkg/libcontainer/nsinit/execin.go
<ide> import (
<ide>
<ide> // ExecIn uses an existing pid and joins the pid's namespaces with the new command.
<ide> func ExecIn(container *libcontainer.Container, nspid int, args []string) (int, error) {
<add> // clear the current processes env and replace it with the environment
<add> // defined on the container
<add> if err := LoadContainerEnvironment(container); err != nil {
<add> return -1, err
<add> }
<add>
<ide> for _, nsv := range container.Namespaces {
<ide> // skip the PID namespace on unshare because it it not supported
<del> if nsv.Key != "NEWPID" {
<add> if nsv.Enabled && nsv.Key != "NEWPID" {
<ide> if err := system.Unshare(nsv.Value); err != nil {
<ide> return -1, err
<ide> } | 1 |
Text | Text | remove elements from a linked list" | f6fcb26a9d5801396743d5ba0dd44d48e1c5ac21 | <ide><path>curriculum/challenges/english/10-coding-interview-prep/data-structures/remove-elements-from-a-linked-list.md
<ide> tests:
<ide> - text: Your <code>remove</code> method should reassign <code>head</code> to the second node when the first node is removed.
<ide> testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog'); test.remove('cat'); return test.head().element === 'dog'}()));
<ide> - text: Your <code>remove</code> method should decrease the <code>length</code> of the linked list by one for every node removed.
<del> testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog'); test.remove('cat'); return test.size() === 1})());
<add> testString: assert((function(){var test = new LinkedList(); test.add("cat"); test.add("dog"); test.add("hamster"); test.remove("cat"); test.remove("fish"); return test.size() === 2})());
<ide> - text: Your <code>remove</code> method should reassign the reference of the previous node of the removed node to the removed node's <code>next</code> reference.
<ide> testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog');test.add('kitten'); test.remove('dog'); return test.head().next.element === 'kitten'})());
<ide> - text: Your <code>remove</code> method should not change the linked list if the element does not exist in the linked list. | 1 |
Go | Go | remove word "fail" from tests | aadb6289ccd84b9997a43c8b74b2948236f30e76 | <ide><path>integration-cli/docker_cli_build_test.go
<ide> func TestBuildWithInaccessibleFilesInContext(t *testing.T) {
<ide> }
<ide>
<ide> }
<del> logDone("build - ADD from context with inaccessible files must fail")
<add> logDone("build - ADD from context with inaccessible files must not pass")
<ide> logDone("build - ADD from context with accessible links must work")
<ide> logDone("build - ADD from context with ignored inaccessible files must work")
<ide> }
<ide> func TestBuildContextCleanupFailedBuild(t *testing.T) {
<ide> t.Fatalf("context should have been deleted, but wasn't")
<ide> }
<ide>
<del> logDone("build - verify context cleanup works properly after a failed build")
<add> logDone("build - verify context cleanup works properly after an unsuccessful build")
<ide> }
<ide>
<ide> func TestBuildCmd(t *testing.T) {
<ide> func TestBuildFails(t *testing.T) {
<ide> } else {
<ide> t.Fatal("Error must not be nil")
<ide> }
<del> logDone("build - fails")
<add> logDone("build - unsuccessful")
<ide> }
<ide>
<ide> func TestBuildFailsDockerfileEmpty(t *testing.T) {
<ide> func TestBuildFailsDockerfileEmpty(t *testing.T) {
<ide> } else {
<ide> t.Fatal("Error must not be nil")
<ide> }
<del> logDone("build - fails with empty dockerfile")
<add> logDone("build - unsuccessful with empty dockerfile")
<ide> }
<ide>
<ide> func TestBuildOnBuild(t *testing.T) {
<ide> func TestBuildVerifySingleQuoteFails(t *testing.T) {
<ide> t.Fatal("The image was not supposed to be able to run")
<ide> }
<ide>
<del> logDone("build - verify single quotes fail")
<add> logDone("build - verify single quotes break the build")
<ide> }
<ide>
<ide> func TestBuildVerboseOut(t *testing.T) {
<ide><path>integration-cli/docker_cli_events_test.go
<ide> func TestEventsContainerFailStartDie(t *testing.T) {
<ide> t.Fatalf("event should be die, not %#v", dieEvent)
<ide> }
<ide>
<del> logDone("events - container failed to start logs die")
<add> logDone("events - container unwilling to start logs die")
<ide> }
<ide>
<ide> func TestEventsLimit(t *testing.T) {
<ide><path>integration-cli/docker_cli_history_test.go
<ide> func TestHistoryExistentImage(t *testing.T) {
<ide> if err != nil || exitCode != 0 {
<ide> t.Fatal("failed to get image history")
<ide> }
<del> logDone("history - history on existent image must not fail")
<add> logDone("history - history on existent image must pass")
<ide> }
<ide>
<ide> func TestHistoryNonExistentImage(t *testing.T) {
<ide> func TestHistoryNonExistentImage(t *testing.T) {
<ide> if err == nil || exitCode == 0 {
<ide> t.Fatal("history on a non-existent image didn't result in a non-zero exit status")
<ide> }
<del> logDone("history - history on non-existent image must fail")
<add> logDone("history - history on non-existent image must pass")
<ide> }
<ide><path>integration-cli/docker_cli_links_test.go
<ide> func TestLinksNotStartedParentNotFail(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(out, err)
<ide> }
<del> logDone("link - container start not failing on updating stopped parent links")
<add> logDone("link - container start successfully updating stopped parent links")
<ide> }
<ide>
<ide> func TestLinksHostsFilesInject(t *testing.T) {
<ide><path>integration-cli/docker_cli_push_test.go
<ide> func TestPushUnprefixedRepo(t *testing.T) {
<ide> if out, _, err := runCommandWithOutput(pushCmd); err == nil {
<ide> t.Fatalf("pushing an unprefixed repo didn't result in a non-zero exit status: %s", out)
<ide> }
<del> logDone("push - unprefixed busybox repo must fail")
<add> logDone("push - unprefixed busybox repo must not pass")
<ide> }
<ide>
<ide> func TestPushUntagged(t *testing.T) {
<ide><path>integration-cli/docker_cli_run_test.go
<ide> func TestRunDisallowBindMountingRootToRoot(t *testing.T) {
<ide>
<ide> deleteAllContainers()
<ide>
<del> logDone("run - bind mount /:/ as volume should fail")
<add> logDone("run - bind mount /:/ as volume should not work")
<ide> }
<ide>
<ide> // Verify that a container gets default DNS when only localhost resolvers exist
<ide> func TestRunCidFileCleanupIfEmpty(t *testing.T) {
<ide> t.Fatalf("empty CIDFile %q should've been deleted", tmpCidFile)
<ide> }
<ide> deleteAllContainers()
<del> logDone("run - cleanup empty cidfile on fail")
<add> logDone("run - cleanup empty cidfile on error")
<ide> }
<ide>
<ide> // #2098 - Docker cidFiles only contain short version of the containerId
<ide> func TestRunPortInUse(t *testing.T) {
<ide> }
<ide>
<ide> deleteAllContainers()
<del> logDone("run - fail if port already in use")
<add> logDone("run - error out if port already in use")
<ide> }
<ide>
<ide> // https://github.com/docker/docker/issues/8428
<ide><path>integration-cli/docker_cli_start_test.go
<ide> func TestStartRecordError(t *testing.T) {
<ide> t.Fatalf("Expected to not have state error but got state.Error(%q)", stateErr)
<ide> }
<ide>
<del> logDone("start - set state error when start fails")
<add> logDone("start - set state error when start is unsuccessful")
<ide> }
<ide>
<ide> // gh#8726: a failed Start() breaks --volumes-from on subsequent Start()'s
<ide><path>integration-cli/docker_cli_tag_test.go
<ide> func TestTagInvalidUnprefixedRepo(t *testing.T) {
<ide> t.Fatalf("tag busybox %v should have failed", repo)
<ide> }
<ide> }
<del> logDone("tag - busybox invalid repo names --> must fail")
<add> logDone("tag - busybox invalid repo names --> must not work")
<ide> }
<ide>
<ide> // ensure we don't allow the use of invalid tags; these tag operations should fail
<ide> func TestTagInvalidPrefixedRepo(t *testing.T) {
<ide> t.Fatalf("tag busybox %v should have failed", repotag)
<ide> }
<ide> }
<del> logDone("tag - busybox with invalid repo:tagnames --> must fail")
<add> logDone("tag - busybox with invalid repo:tagnames --> must not work")
<ide> }
<ide>
<ide> // ensure we allow the use of valid tags
<ide> func TestTagExistedNameWithoutForce(t *testing.T) {
<ide> }
<ide> deleteImages("busybox:test")
<ide>
<del> logDone("tag - busybox with an existed tag name without -f option --> must fail")
<add> logDone("tag - busybox with an existed tag name without -f option --> must not work")
<ide> }
<ide>
<ide> // tag an image with an existed tag name with -f option should work | 8 |
Javascript | Javascript | remove unnecessary properties | 533c00efa078ca67ef0276275d41e9ad4640a153 | <ide><path>lib/BannerPlugin.js
<ide> class BannerPlugin {
<ide> continue;
<ide> }
<ide>
<del> const hash = compilation.hash;
<ide> let filename = file;
<ide>
<ide> const data = {
<del> hash,
<ide> chunk,
<ide> filename
<ide> };
<ide>
<del> const comment = compilation.getPath(banner(data), data);
<add> const comment = compilation.getPath(banner, data);
<ide>
<ide> compilation.assets[file] = new ConcatSource(
<ide> comment,
<ide><path>lib/LibManifestPlugin.js
<ide> class LibManifestPlugin {
<ide> }
<ide> const chunkGraph = compilation.chunkGraph;
<ide> const targetPath = compilation.getPath(this.options.path, {
<del> hash: compilation.hash,
<ide> chunk
<ide> });
<ide> const name =
<ide> this.options.name &&
<ide> compilation.getPath(this.options.name, {
<del> hash: compilation.hash,
<ide> chunk
<ide> });
<ide> const manifest = { | 2 |
Javascript | Javascript | revert temporary change | f1f9a36010e2ff24234e08ec7865a443f162f711 | <ide><path>lib/stats/DefaultStatsPresetPlugin.js
<ide> class DefaultStatsPresetPlugin {
<ide> apply(compiler) {
<ide> compiler.hooks.compilation.tap("DefaultStatsPresetPlugin", compilation => {
<ide> compilation.hooks.statsPreset
<del> .for("false")
<add> .for(false)
<ide> .tap("DefaultStatsPresetPlugin", (options, context) => {
<ide> applyDefaults(options, NAMED_PRESETS.none);
<ide> }); | 1 |
Ruby | Ruby | improve language and examples in railtie docs | 8af066b1666b63caab31126273fc757abe724906 | <ide><path>railties/lib/rails/railtie.rb
<ide> require 'active_support/inflector'
<ide>
<ide> module Rails
<del> # Railtie is the core of the Rails Framework and provides several hooks to extend
<add> # Railtie is the core of the Rails framework and provides several hooks to extend
<ide> # Rails and/or modify the initialization process.
<ide> #
<ide> # Every major component of Rails (Action Mailer, Action Controller,
<del> # Action View, Active Record and Active Resource) are all Railties, so each of
<del> # them is responsible to set their own initialization. This makes, for example,
<del> # Rails absent of any Active Record hook, allowing any other ORM framework to hook in.
<add> # Action View, Active Record and Active Resource) is a Railtie. Each of
<add> # them is responsible for their own initialization. This makes Rails itself
<add> # absent of any component hooks, allowing other components to be used in
<add> # place of any of the Rails defaults.
<ide> #
<ide> # Developing a Rails extension does _not_ require any implementation of
<ide> # Railtie, but if you need to interact with the Rails framework during
<del> # or after boot, then Railtie is what you need to do that interaction.
<add> # or after boot, then Railtie is needed.
<ide> #
<del> # For example, the following would need you to implement Railtie in your
<del> # plugin:
<add> # For example, an extension doing any of the following would require Railtie:
<ide> #
<ide> # * creating initializers
<del> # * configuring a Rails framework or the Application, like setting a generator
<del> # * adding Rails config.* keys to the environment
<del> # * setting up a subscriber to the Rails +ActiveSupport::Notifications+
<del> # * adding rake tasks into rails
<add> # * configuring a Rails framework for the application, like setting a generator
<add> # * adding config.* keys to the environment
<add> # * setting up a subscriber with ActiveSupport::Notifications
<add> # * adding rake tasks
<ide> #
<ide> # == Creating your Railtie
<ide> #
<del> # Implementing Railtie in your Rails extension is done by creating a class
<del> # Railtie that has your extension name and making sure that this gets loaded
<del> # during boot time of the Rails stack.
<add> # To extend Rails using Railtie, create a Railtie class which inherits
<add> # from Rails::Railtie within your extension's namespace. This class must be
<add> # loaded during the Rails boot process.
<ide> #
<del> # You can do this however you wish, but here is an example if you want to provide
<del> # it for a gem that can be used with or without Rails:
<add> # The following example demonstrates an extension which can be used with or without Rails.
<ide> #
<del> # * Create a file (say, lib/my_gem/railtie.rb) which contains class Railtie inheriting from
<del> # Rails::Railtie and is namespaced to your gem:
<del> #
<del> # # lib/my_gem/railtie.rb
<del> # module MyGem
<del> # class Railtie < Rails::Railtie
<del> # end
<add> # # lib/my_gem/railtie.rb
<add> # module MyGem
<add> # class Railtie < Rails::Railtie
<ide> # end
<add> # end
<ide> #
<del> # * Require your own gem as well as rails in this file:
<del> #
<del> # # lib/my_gem/railtie.rb
<del> # require 'my_gem'
<del> # require 'rails'
<del> #
<del> # module MyGem
<del> # class Railtie < Rails::Railtie
<del> # end
<del> # end
<add> # # lib/my_gem.rb
<add> # require 'my_gem/railtie' if defined?(Rails)
<ide> #
<ide> # == Initializers
<ide> # | 1 |
Text | Text | update the docs on texteditorview | e62485195a7b01eff54252d7358403abecc0c1fc | <ide><path>docs/upgrading/upgrading-your-package.md
<ide> class MyView extends View
<ide>
<ide> ### Upgrading to the new TextEditorView
<ide>
<del>You should not need to change anything to use the new `TextEditorView`! See the [docs][TextEditorView] for more info.
<add>All of the atom-specific methods available on the `TextEditorView` have been moved to the `TextEditor`, available via `TextEditorView::getModel`. See the [`TextEditorView` docs][TextEditorView] and [`TextEditor` docs][TextEditor] for more info.
<ide>
<ide> ### Upgrading classes extending ScrollView
<ide>
<ide> See [Upgrading Your Package Selectors guide][upgrading-selectors] for more infor
<ide> [selectlistview]:https://github.com/atom/atom-space-pen-views#selectlistview
<ide> [selectlistview-example]:https://github.com/atom/command-palette/pull/19/files
<ide> [emitter]:https://atom.io/docs/api/latest/Emitter
<add>[texteditor]:https://atom.io/docs/api/latest/TextEditor
<ide> [disposable]:https://atom.io/docs/api/latest/Disposable
<ide> [commands-add]:https://atom.io/docs/api/latest/CommandRegistry#instance-add
<ide> [upgrading-selectors]:upgrading-your-ui-theme | 1 |
Python | Python | use list for mutable retval rather than tuple | bd9272628f028f4f7c987156406be4c187bae02f | <ide><path>configure.py
<ide> def pkg_config(pkg):
<ide> otherwise (None, None, None, None)"""
<ide> pkg_config = os.environ.get('PKG_CONFIG', 'pkg-config')
<ide> args = [] # Print pkg-config warnings on first round.
<del> retval = ()
<add> retval = []
<ide> for flag in ['--libs-only-l', '--cflags-only-I',
<ide> '--libs-only-L', '--modversion']:
<ide> args += [flag]
<ide> def pkg_config(pkg):
<ide> except OSError as e:
<ide> if e.errno != errno.ENOENT: raise e # Unexpected error.
<ide> return (None, None, None, None) # No pkg-config/pkgconf installed.
<del> retval += (val,)
<add> retval.append(val)
<ide> args = ['--silence-errors']
<del> return retval
<add> return tuple(retval)
<ide>
<ide>
<ide> def try_check_compiler(cc, lang): | 1 |
Javascript | Javascript | improve error message for invalid data url | 46062a0d2c105aa8344e1f6f11ccb447a223b78d | <ide><path>lib/internal/modules/esm/loader.js
<ide> require('internal/modules/cjs/loader');
<ide> const {
<ide> FunctionPrototypeBind,
<ide> ObjectSetPrototypeOf,
<add> RegExpPrototypeExec,
<ide> SafeWeakMap,
<ide> StringPrototypeStartsWith,
<ide> } = primordials;
<ide>
<ide> const {
<ide> ERR_INVALID_ARG_VALUE,
<add> ERR_INVALID_MODULE_SPECIFIER,
<ide> ERR_INVALID_RETURN_PROPERTY,
<ide> ERR_INVALID_RETURN_PROPERTY_VALUE,
<ide> ERR_INVALID_RETURN_VALUE,
<ide> class Loader {
<ide> }
<ide>
<ide> const { format } = getFormatResponse;
<add> if (format === null) {
<add> const dataUrl = RegExpPrototypeExec(
<add> /^data:([^/]+\/[^;,]+)(?:[^,]*?)(;base64)?,/,
<add> url,
<add> );
<add> throw new ERR_INVALID_MODULE_SPECIFIER(
<add> url,
<add> dataUrl ? `has an unsupported MIME type "${dataUrl[1]}"` : '');
<add> }
<ide> if (typeof format !== 'string') {
<ide> throw new ERR_INVALID_RETURN_PROPERTY_VALUE(
<ide> 'string', 'loader getFormat', 'format', format);
<ide><path>test/es-module/test-esm-data-urls.js
<ide> function createBase64URL(mime, body) {
<ide> await import(plainESMURL);
<ide> common.mustNotCall()();
<ide> } catch (e) {
<del> assert.strictEqual(e.code, 'ERR_INVALID_RETURN_PROPERTY_VALUE');
<add> assert.strictEqual(e.code, 'ERR_INVALID_MODULE_SPECIFIER');
<ide> }
<ide> }
<ide> {
<ide><path>test/es-module/test-esm-invalid-data-urls.js
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>
<add>(async () => {
<add> await assert.rejects(import('data:text/plain,export default0'), {
<add> code: 'ERR_INVALID_MODULE_SPECIFIER',
<add> message:
<add> 'Invalid module "data:text/plain,export default0" has an unsupported ' +
<add> 'MIME type "text/plain"',
<add> });
<add> await assert.rejects(import('data:text/plain;base64,'), {
<add> code: 'ERR_INVALID_MODULE_SPECIFIER',
<add> message:
<add> 'Invalid module "data:text/plain;base64," has an unsupported ' +
<add> 'MIME type "text/plain"',
<add> });
<add> await assert.rejects(import('data:application/json,[]'), {
<add> code: 'ERR_INVALID_MODULE_SPECIFIER',
<add> message:
<add> 'Invalid module "data:application/json,[]" has an unsupported ' +
<add> 'MIME type "application/json"',
<add> });
<add>})().then(common.mustCall()); | 3 |
Javascript | Javascript | allow use of {{this}} inside {{#each}} | 770452df78031bd6a42f28879259bec160abe523 | <ide><path>packages/sproutcore-handlebars/lib/helpers/binding.js
<ide> var get = SC.get, getPath = SC.getPath, set = SC.set, fmt = SC.String.fmt;
<ide> });
<ide>
<ide> // Observes the given property on the context and
<del> // tells the SC._BindableSpan to re-render.
<del> SC.addObserver(ctx, property, observer);
<add> // tells the SC._BindableSpan to re-render. If property
<add> // is an empty string, we are printing the current context
<add> // object ({{this}}) so updating it is not our responsibility.
<add> if (property !== '') {
<add> SC.addObserver(ctx, property, observer);
<add> }
<ide> } else {
<ide> // The object is not observable, so just render it out and
<ide> // be done with it.
<ide><path>packages/sproutcore-handlebars/lib/views/bindable_span.js
<ide> SC._BindableSpanView = SC.View.extend(SC.Metamorph,
<ide> var inverseTemplate = get(this, 'inverseTemplate'),
<ide> displayTemplate = get(this, 'displayTemplate');
<ide>
<del> var result = getPath(context, property);
<add> var result;
<add>
<add>
<add> // Use the current context as the result if no
<add> // property is provided.
<add> if (property === '') {
<add> result = context;
<add> } else {
<add> result = getPath(context, property);
<add> }
<ide>
<ide> // First, test the conditional to see if we should
<ide> // render the template or not.
<ide><path>packages/sproutcore-handlebars/tests/each_test.js
<ide> test("it updates the view if an item is added", function() {
<ide> people.pushObject({ name: "Tom Dale" });
<ide> });
<ide>
<del> assertHTML(view, "Steve HoltAnnabelleTom Dale")
<add> assertHTML(view, "Steve HoltAnnabelleTom Dale");
<add>});
<add>
<add>test("it allows you to access the current context using {{this}}", function() {
<add> view = SC.View.create({
<add> template: templateFor("{{#each people}}{{this}}{{/each}}"),
<add> people: ['Black Francis', 'Joey Santiago', 'Kim Deal', 'David Lovering']
<add> });
<add>
<add> append(view);
<add>
<add> assertHTML(view, "Black FrancisJoey SantiagoKim DealDavid Lovering");
<ide> }); | 3 |
PHP | PHP | clear command | e0ae2f6825f5f87440ed8132479f488533334f15 | <ide><path>src/Illuminate/Foundation/Console/ViewClearCommand.php
<add><?php namespace Illuminate\Foundation\Console;
<add>
<add>use Illuminate\Console\Command;
<add>use Illuminate\Filesystem\Filesystem;
<add>
<add>class ViewClearCommand extends Command {
<add>
<add> /**
<add> * The console command name.
<add> *
<add> * @var string
<add> */
<add> protected $name = 'view:clear';
<add>
<add> /**
<add> * The console command description.
<add> *
<add> * @var string
<add> */
<add> protected $description = 'Clear all compiled view files';
<add>
<add> /**
<add> * The filesystem instance.
<add> *
<add> * @var \Illuminate\Filesystem\Filesystem
<add> */
<add> protected $files;
<add>
<add> /**
<add> * Create a new config clear command instance.
<add> *
<add> * @param \Illuminate\Filesystem\Filesystem $files
<add> * @return void
<add> */
<add> public function __construct(Filesystem $files)
<add> {
<add> parent::__construct();
<add>
<add> $this->files = $files;
<add> }
<add>
<add> /**
<add> * Execute the console command.
<add> *
<add> * @return void
<add> */
<add> public function fire()
<add> {
<add> // Because glob ignores hidden files, .gitignore will be preserved.
<add> $views = $this->files->glob($this->laravel['config']['view.compiled'].'/*');
<add>
<add> foreach ($views as $view)
<add> {
<add> $this->files->delete($view);
<add> }
<add>
<add> $this->info('Compiled views cleared!');
<add> }
<add>
<add>}
<ide><path>src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php
<ide> use Illuminate\Foundation\Console\RouteListCommand;
<ide> use Illuminate\Foundation\Console\EventMakeCommand;
<ide> use Illuminate\Foundation\Console\ModelMakeCommand;
<add>use Illuminate\Foundation\Console\ViewClearCommand;
<ide> use Illuminate\Foundation\Console\RouteCacheCommand;
<ide> use Illuminate\Foundation\Console\RouteClearCommand;
<ide> use Illuminate\Foundation\Console\CommandMakeCommand;
<ide> class ArtisanServiceProvider extends ServiceProvider {
<ide> 'Tinker' => 'command.tinker',
<ide> 'Up' => 'command.up',
<ide> 'VendorPublish' => 'command.vendor.publish',
<add> 'ViewClear' => 'command.view.clear',
<ide> ];
<ide>
<ide> /**
<ide> protected function registerVendorPublishCommand()
<ide> });
<ide> }
<ide>
<add> /**
<add> * Register the command.
<add> *
<add> * @return void
<add> */
<add> protected function registerViewClearCommand()
<add> {
<add> $this->app->singleton('command.view.clear', function($app)
<add> {
<add> return new ViewClearCommand($app['files']);
<add> });
<add> }
<add>
<ide> /**
<ide> * Get the services provided by the provider.
<ide> * | 2 |
Javascript | Javascript | move redundant regex test into assert | 71d1e61c44bbc84ee2a29d7ffc1173406e83cd88 | <ide><path>packages/ember-metal/lib/accessors.js
<ide> Ember.getPath = function(root, path) {
<ide> Ember.setPath = function(root, path, value, tolerant) {
<ide> var keyName;
<ide>
<del> if (typeof root === 'string' && IS_GLOBAL.test(root)) {
<add> if (typeof root === 'string') {
<add> Ember.assert("Path '" + root + "' must be global if no root is given.", IS_GLOBAL.test(root));
<ide> value = path;
<ide> path = root;
<ide> root = null; | 1 |
Mixed | Ruby | accept` header when rendering | 5745a3c0928ee5604ce80af19348efb42189f1d6 | <ide><path>actionpack/CHANGELOG.md
<add>* Add `Vary: Accept` header when using `Accept` header for response
<add>
<add> For some requests like `/users/1`, Rails uses requests' `Accept`
<add> header to determine what to return. And if we don't add `Vary`
<add> in the response header, browsers might accidentally cache different
<add> types of content, which would cause issues: e.g. javascript got displayed
<add> instead of html content. This PR fixes these issues by adding `Vary: Accept`
<add> in these types of requests. For more detailed problem description, please read:
<add>
<add> https://github.com/rails/rails/pull/36213
<add>
<add> Fixes #25842
<add>
<add> *Stan Lo*
<add>
<ide> * Fix IntegrationTest `follow_redirect!` to follow redirection using the same HTTP verb when following
<ide> a 307 redirection.
<ide>
<ide><path>actionpack/lib/abstract_controller/rendering.rb
<ide> def render(*args, &block)
<ide> else
<ide> _set_rendered_content_type rendered_format
<ide> end
<add> _set_vary_header
<ide> self.response_body = rendered_body
<ide> end
<ide>
<ide> def _process_variant(options)
<ide> def _set_html_content_type # :nodoc:
<ide> end
<ide>
<add> def _set_vary_header # :nodoc:
<add> end
<add>
<ide> def _set_rendered_content_type(format) # :nodoc:
<ide> end
<ide>
<ide><path>actionpack/lib/action_controller/metal/rendering.rb
<ide> def _set_rendered_content_type(format)
<ide> end
<ide> end
<ide>
<add> def _set_vary_header
<add> self.headers["Vary"] = "Accept" if request.should_apply_vary_header?
<add> end
<add>
<ide> # Normalize arguments by catching blocks and setting them on :update.
<ide> def _normalize_args(action = nil, options = {}, &blk)
<ide> options = super
<ide><path>actionpack/lib/action_dispatch/http/mime_negotiation.rb
<ide> def format(view_path = [])
<ide>
<ide> def formats
<ide> fetch_header("action_dispatch.request.formats") do |k|
<del> params_readable = begin
<del> parameters[:format]
<del> rescue *RESCUABLE_MIME_FORMAT_ERRORS
<del> false
<del> end
<del>
<del> v = if params_readable
<add> v = if params_readable?
<ide> Array(Mime[parameters[:format]])
<ide> elsif use_accept_header && valid_accept_header
<ide> accepts
<ide> def negotiate_mime(order)
<ide> order.include?(Mime::ALL) ? format : nil
<ide> end
<ide>
<add> def should_apply_vary_header?
<add> !params_readable? && use_accept_header && valid_accept_header
<add> end
<add>
<ide> private
<ide> BROWSER_LIKE_ACCEPTS = /,\s*\*\/\*|\*\/\*\s*,/
<ide>
<add> def params_readable? # :doc:
<add> parameters[:format]
<add> rescue *RESCUABLE_MIME_FORMAT_ERRORS
<add> false
<add> end
<add>
<ide> def valid_accept_header # :doc:
<ide> (xhr? && (accept.present? || content_mime_type)) ||
<ide> (accept.present? && accept !~ BROWSER_LIKE_ACCEPTS)
<ide><path>actionpack/test/controller/integration_test.rb
<ide> def test_accept_not_overridden_when_xhr_true
<ide> end
<ide> end
<ide>
<add> def test_setting_vary_header_when_request_is_xhr_with_accept_header
<add> with_test_route_set do
<add> get "/get", headers: { "Accept" => "application/json" }, xhr: true
<add> assert_equal "Accept", response.headers["Vary"]
<add> end
<add> end
<add>
<add> def test_not_setting_vary_header_when_format_is_provided
<add> with_test_route_set do
<add> get "/get", params: { format: "json" }
<add> assert_nil response.headers["Vary"]
<add> end
<add> end
<add>
<add> def test_not_setting_vary_header_when_ignore_accept_header_is_set
<add> original_ignore_accept_header = ActionDispatch::Request.ignore_accept_header
<add> ActionDispatch::Request.ignore_accept_header = true
<add>
<add> with_test_route_set do
<add> get "/get", headers: { "Accept" => "application/json" }, xhr: true
<add> assert_nil response.headers["Vary"]
<add> end
<add> ensure
<add> ActionDispatch::Request.ignore_accept_header = original_ignore_accept_header
<add> end
<add>
<ide> private
<ide> def with_default_headers(headers)
<ide> original = ActionDispatch::Response.default_headers | 5 |
Ruby | Ruby | remove a duplicate test of mysql_rake_test | 9862b3bf1e443703df4472a5c098aaeb205096d7 | <ide><path>activerecord/test/cases/tasks/mysql_rake_test.rb
<ide> def test_structure_dump
<ide> ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, filename)
<ide> end
<ide>
<del> def test_structure_dump
<del> filename = "awesome-file.sql"
<del> Kernel.expects(:system).with("mysqldump", "--result-file", filename, "--no-data", "--routines", "--skip-comments", "test-db").returns(true)
<del>
<del> ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, filename)
<del> end
<del>
<ide> def test_structure_dump_with_extra_flags
<ide> filename = "awesome-file.sql"
<ide> expected_command = ["mysqldump", "--result-file", filename, "--no-data", "--routines", "--skip-comments", "--noop", "test-db"] | 1 |
Python | Python | follow flake8 pep3101 and remove modulo formatting | f15cc2f01c2a4124ff6dc0843c728a546f9d9f79 | <ide><path>ciphers/elgamal_key_generator.py
<ide> def make_key_files(name: str, key_size: int) -> None:
<ide> if os.path.exists(f"{name}_pubkey.txt") or os.path.exists(f"{name}_privkey.txt"):
<ide> print("\nWARNING:")
<ide> print(
<del> '"%s_pubkey.txt" or "%s_privkey.txt" already exists. \n'
<add> f'"{name}_pubkey.txt" or "{name}_privkey.txt" already exists. \n'
<ide> "Use a different name or delete these files and re-run this program."
<del> % (name, name)
<ide> )
<ide> sys.exit()
<ide>
<ide> public_key, private_key = generate_key(key_size)
<ide> print(f"\nWriting public key to file {name}_pubkey.txt...")
<ide> with open(f"{name}_pubkey.txt", "w") as fo:
<del> fo.write(
<del> "%d,%d,%d,%d" % (public_key[0], public_key[1], public_key[2], public_key[3])
<del> )
<add> fo.write(f"{public_key[0]},{public_key[1]},{public_key[2]},{public_key[3]}")
<ide>
<ide> print(f"Writing private key to file {name}_privkey.txt...")
<ide> with open(f"{name}_privkey.txt", "w") as fo:
<del> fo.write("%d,%d" % (private_key[0], private_key[1]))
<add> fo.write(f"{private_key[0]},{private_key[1]}")
<ide>
<ide>
<ide> def main() -> None:
<ide><path>ciphers/rsa_key_generator.py
<ide> def make_key_files(name: str, key_size: int) -> None:
<ide> if os.path.exists(f"{name}_pubkey.txt") or os.path.exists(f"{name}_privkey.txt"):
<ide> print("\nWARNING:")
<ide> print(
<del> '"%s_pubkey.txt" or "%s_privkey.txt" already exists. \n'
<add> f'"{name}_pubkey.txt" or "{name}_privkey.txt" already exists. \n'
<ide> "Use a different name or delete these files and re-run this program."
<del> % (name, name)
<ide> )
<ide> sys.exit()
<ide>
<ide><path>dynamic_programming/edit_distance.py
<ide> def min_distance_bottom_up(word1: str, word2: str) -> int:
<ide> S2 = input("Enter the second string: ").strip()
<ide>
<ide> print()
<del> print("The minimum Edit Distance is: %d" % (solver.solve(S1, S2)))
<del> print("The minimum Edit Distance is: %d" % (min_distance_bottom_up(S1, S2)))
<add> print(f"The minimum Edit Distance is: {solver.solve(S1, S2)}")
<add> print(f"The minimum Edit Distance is: {min_distance_bottom_up(S1, S2)}")
<ide> print()
<ide> print("*************** End of Testing Edit Distance DP Algorithm ***************")
<ide><path>genetic_algorithm/basic_string.py
<ide> def mutate(child: str) -> str:
<ide> " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm"
<ide> "nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\"
<ide> )
<add> generation, population, target = basic(target_str, genes_list)
<ide> print(
<del> "\nGeneration: %s\nTotal Population: %s\nTarget: %s"
<del> % basic(target_str, genes_list)
<add> f"\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}"
<ide> )
<ide><path>graphs/minimum_spanning_tree_boruvka.py
<ide> def __str__(self):
<ide> for tail in self.adjacency:
<ide> for head in self.adjacency[tail]:
<ide> weight = self.adjacency[head][tail]
<del> string += "%d -> %d == %d\n" % (head, tail, weight)
<add> string += f"{head} -> {tail} == {weight}\n"
<ide> return string.rstrip("\n")
<ide>
<ide> def get_edges(self):
<ide><path>machine_learning/linear_regression.py
<ide> def run_linear_regression(data_x, data_y):
<ide> for i in range(0, iterations):
<ide> theta = run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta)
<ide> error = sum_of_square_error(data_x, data_y, len_data, theta)
<del> print("At Iteration %d - Error is %.5f " % (i + 1, error))
<add> print(f"At Iteration {i + 1} - Error is {error:.5f}")
<ide>
<ide> return theta
<ide>
<ide><path>matrix/sherman_morrison.py
<ide> def __str__(self) -> str:
<ide> """
<ide>
<ide> # Prefix
<del> s = "Matrix consist of %d rows and %d columns\n" % (self.row, self.column)
<add> s = f"Matrix consist of {self.row} rows and {self.column} columns\n"
<ide>
<ide> # Make string identifier
<ide> max_element_length = 0
<ide> for row_vector in self.array:
<ide> for obj in row_vector:
<ide> max_element_length = max(max_element_length, len(str(obj)))
<del> string_format_identifier = "%%%ds" % (max_element_length,)
<add> string_format_identifier = f"%{max_element_length}s"
<ide>
<ide> # Make string and return
<ide> def single_line(row_vector: list[float]) -> str:
<ide> def test1() -> None:
<ide> v[0, 0], v[1, 0], v[2, 0] = 4, -2, 5
<ide> print(f"u is {u}")
<ide> print(f"v is {v}")
<del> print("uv^T is %s" % (u * v.transpose()))
<add> print(f"uv^T is {u * v.transpose()}")
<ide> # Sherman Morrison
<ide> print(f"(a + uv^T)^(-1) is {ainv.sherman_morrison(u, v)}")
<ide>
<ide><path>neural_network/back_propagation_neural_network.py
<ide> def build(self):
<ide>
<ide> def summary(self):
<ide> for i, layer in enumerate(self.layers[:]):
<del> print("------- layer %d -------" % i)
<add> print(f"------- layer {i} -------")
<ide> print("weight.shape ", np.shape(layer.weight))
<ide> print("bias.shape ", np.shape(layer.bias))
<ide>
<ide><path>neural_network/convolution_neural_network.py
<ide> def train(
<ide> mse = 10000
<ide> while rp < n_repeat and mse >= error_accuracy:
<ide> error_count = 0
<del> print("-------------Learning Time %d--------------" % rp)
<add> print(f"-------------Learning Time {rp}--------------")
<ide> for p in range(len(datas_train)):
<ide> # print('------------Learning Image: %d--------------'%p)
<ide> data_train = np.asmatrix(datas_train[p]) | 9 |
Python | Python | fix poisson loss when target = 0 | 34999c865896642e25d46d6334200775008e1562 | <ide><path>keras/objectives.py
<ide> def binary_crossentropy(y_true, y_pred):
<ide>
<ide>
<ide> def poisson_loss(y_true, y_pred):
<del> return T.mean(y_pred - y_true * T.log(y_pred), axis=-1)
<add> return T.mean(y_pred - y_true * T.log(y_pred + epsilon), axis=-1)
<ide>
<ide> # aliases
<ide> mse = MSE = mean_squared_error | 1 |
Text | Text | fix typo in building a city skylines step 15 | aca7ca128ce702ec9f55c08e842915e7f424ccad | <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-css-variables-by-building-a-city-skyline/5d822fd413a79914d39e98d7.md
<ide> dashedName: step-15
<ide>
<ide> To use a variable, put the variable name in parentheses with `var` in front of them like this: `var(--variable-name)`. Whatever value you gave the variable will be applied to whatever property you use it on.
<ide>
<del>Add the variable `--building-color-1` you created in the previous step as the value of the `background-color` property of the `.bb1a` class.
<add>Add the variable `--building-color1` you created in the previous step as the value of the `background-color` property of the `.bb1a` class.
<ide>
<ide> # --hints--
<ide> | 1 |
Ruby | Ruby | remove assertion on date from humans.txt tests | f4c8f8c5aaaa778fcbae09674e2b3edb184f8dd3 | <ide><path>railties/test/generators/app_generator_test.rb
<ide> def test_pretend_option
<ide> def test_humans_txt_file
<ide> date = Date.today.strftime("%B %d, %Y")
<ide> run_generator [File.join(destination_root, 'things-43')]
<del> assert_file "things-43/public/humans.txt", /Name: Things43/, /Software: Ruby on Rails/, /Date Created: #{date}/
<add> assert_file "things-43/public/humans.txt", /Name: Things43/, /Software: Ruby on Rails/
<ide> end
<ide>
<ide> protected | 1 |
Text | Text | update changelog with 0.10.4 release notes | b4add97c17b9a84381bbb72cfc704a8dcf14e878 | <ide><path>CHANGELOG.md
<ide> - The Latest Stable Release: <a href="#0.9.19">0.9.19 canine-psychokinesis</a>
<del>- The Latest Unstable Release: <a href="#0.10.3">0.10.3 shattering-heartbeat</a>
<add>- The Latest Unstable Release: <a href="#0.10.4">0.10.4 human-torch</a>
<ide>
<ide> <a name="0.10.4"></a>
<del># 0.10.4 human-torch (in-progress) #
<add># 0.10.4 human-torch (2011-10-22) #
<add>
<add>## Features:
<add>
<add>- New validation options for
<add> [input widgets](http://docs-next.angularjs.org/api/angular.widget.input): `ng:minlength` and
<add> `ng:maxlength`
<add> ([commit](https://github.com/angular/angular.js/commit/78f394fd17be581c84ecd526bb786ed1681d35cb))
<add> (contributed by Konstantin Stepanov)
<add>- HTML sanitizer was updated to recognize all safe HTML5 elements
<add> (Issue [#89](https://github.com/angular/angular.js/issues/89))
<add>- [ng:options]' blank option is now compiled and data-bound as any other template
<add> (Issue [#562](https://github.com/angular/angular.js/issues/562))
<add> (contributed by tehek)
<add>- [$defer](http://docs-next.angularjs.org/api/angular.service.$defer) service now exposes `cancel`
<add> method for task cancellation
<add> ([commit](https://github.com/angular/angular.js/commit/ad90c3574f8365ee4a1a973d5e43c64fe9fcda2c))
<add>
<add>
<add>## Bug Fixes:
<add>
<add>- [ng:options] should select correct element when '?'-option (invalid value) was previously selected
<add> (Issue [#599](https://github.com/angular/angular.js/issues/599)) (contributed by Tehek)
<add>- Fix data-binding of radio button's value property
<add> (Issue [#316](https://github.com/angular/angular.js/issues/316))
<add>- Input with type `password` should no be turned into a readable text field
<add> ([commit](https://github.com/angular/angular.js/commit/e82e64d57b65d9f3c4f2e8831f30b615a069b7f6))
<add> (contributed by Konstantin Stepanov)
<add>- [ng:repeat] should ignore object properties starting with `$`
<add> ([commit](https://github.com/angular/angular.js/commit/833eb3c84445110dc1dad238120573f08ed8d102))
<add>- Correctly parse out inlined regexp from the input field's `ng:pattern` attribute.
<add> ([commit](https://github.com/angular/angular.js/commit/5d43439dbe764a4c7227f51b34a81b044f13901b))
<add>- $location service in html5 mode should correctly rewrite links that contain nested elements
<add> ([commit](https://github.com/angular/angular.js/commit/9b85757102fbd44e88d0a3909fdf8b90f191b593))
<add>
<add>
<add>## Breaking Changes:
<add>
<add>- the [date] filter now uses 'mediumDate' format if none is specified. This was done to deal with
<add> browser inconsistencies (each browser used to use different format)
<add> (Issue [#605](https://github.com/angular/angular.js/issues/605),
<add> [commit](https://github.com/angular/angular.js/commit/c6c3949b14f4003ecab291243edfca61262f2c3d),
<add> [commit](https://github.com/angular/angular.js/commit/e175db37c6f52bba4080efeec22a7120a896099e))
<add>- calling the linker function returned by [angular.compile][compile] doesn't automatically run
<add> `$digest` on the linked scope any more. This behavior was briefly introduced in 0.10.3 but was
<add> causing issues and inefficiencies in production apps so we reverted it. See:
<add> [commit](https://github.com/angular/angular.js/commit/f38010d3a2f457a53798212ef72418637dabe189)
<ide>
<ide>
<ide> | 1 |
Go | Go | add support to add bridge to the sandbox | 4ceec05f1bf11f7b3cd09461e2336a11a25a9101 | <ide><path>libnetwork/sandbox/interface_linux.go
<ide> type IfaceOption func(i *nwIface)
<ide> type nwIface struct {
<ide> srcName string
<ide> dstName string
<add> master string
<add> dstMaster string
<ide> address *net.IPNet
<ide> addressIPv6 *net.IPNet
<ide> routes []*net.IPNet
<add> bridge bool
<ide> ns *networkNamespace
<ide> sync.Mutex
<ide> }
<ide> func (n *networkNamespace) AddInterface(srcName, dstPrefix string, options ...If
<ide> i := &nwIface{srcName: srcName, dstName: dstPrefix, ns: n}
<ide> i.processInterfaceOptions(options...)
<ide>
<add> if i.master != "" {
<add> i.dstMaster = n.findDstMaster(i.master)
<add> if i.dstMaster == "" {
<add> return fmt.Errorf("could not find an appropriate master %q for %q",
<add> i.master, i.srcName)
<add> }
<add> }
<add>
<ide> n.Lock()
<ide> i.dstName = fmt.Sprintf("%s%d", i.dstName, n.nextIfIndex)
<ide> n.nextIfIndex++
<ide> path := n.path
<ide> n.Unlock()
<ide>
<ide> return nsInvoke(path, func(nsFD int) error {
<add> // If it is a bridge interface we have to create the bridge inside
<add> // the namespace so don't try to lookup the interface using srcName
<add> if i.bridge {
<add> return nil
<add> }
<add>
<ide> // Find the network interface identified by the SrcName attribute.
<ide> iface, err := netlink.LinkByName(i.srcName)
<ide> if err != nil {
<ide> func (n *networkNamespace) AddInterface(srcName, dstPrefix string, options ...If
<ide>
<ide> return nil
<ide> }, func(callerFD int) error {
<add> if i.bridge {
<add> link := &netlink.Bridge{
<add> LinkAttrs: netlink.LinkAttrs{
<add> Name: i.srcName,
<add> },
<add> }
<add>
<add> if err := netlink.LinkAdd(link); err != nil {
<add> return fmt.Errorf("failed to create bridge %q: %v", i.srcName, err)
<add> }
<add> }
<add>
<ide> // Find the network interface identified by the SrcName attribute.
<ide> iface, err := netlink.LinkByName(i.srcName)
<ide> if err != nil {
<ide><path>libnetwork/sandbox/options_linux.go
<ide> func (i *nwIface) processInterfaceOptions(options ...IfaceOption) {
<ide> }
<ide> }
<ide>
<add>func (n *networkNamespace) Bridge(isBridge bool) IfaceOption {
<add> return func(i *nwIface) {
<add> i.bridge = isBridge
<add> }
<add>}
<add>
<add>func (n *networkNamespace) Master(name string) IfaceOption {
<add> return func(i *nwIface) {
<add> i.master = name
<add> }
<add>}
<add>
<ide> func (n *networkNamespace) Address(addr *net.IPNet) IfaceOption {
<ide> return func(i *nwIface) {
<ide> i.address = addr
<ide><path>libnetwork/sandbox/sandbox.go
<ide> type Sandbox interface {
<ide>
<ide> // IfaceOptionSetter interface defines the option setter methods for interface options.
<ide> type IfaceOptionSetter interface {
<add> // Bridge returns an option setter to set if the interface is a bridge.
<add> Bridge(bool) IfaceOption
<add>
<ide> // Address returns an option setter to set IPv4 address.
<ide> Address(*net.IPNet) IfaceOption
<ide>
<ide> // Address returns an option setter to set IPv6 address.
<ide> AddressIPv6(*net.IPNet) IfaceOption
<ide>
<add> // Master returns an option setter to set the master interface if any for this
<add> // interface. The master interface name should refer to the srcname of a
<add> // previously added interface of type bridge.
<add> Master(string) IfaceOption
<add>
<ide> // Address returns an option setter to set interface routes.
<ide> Routes([]*net.IPNet) IfaceOption
<ide> }
<ide> type Interface interface {
<ide> // IP routes for the interface.
<ide> Routes() []*net.IPNet
<ide>
<add> // Bridge returns true if the interface is a bridge
<add> Bridge() bool
<add>
<add> // Master returns the srcname of the master interface for this interface.
<add> Master() string
<add>
<ide> // Remove an interface from the sandbox by renaming to original name
<ide> // and moving it out of the sandbox.
<ide> Remove() error
<ide><path>libnetwork/sandbox/sandbox_linux_test.go
<ide> func newInfo(t *testing.T) (Sandbox, error) {
<ide>
<ide> intf1.routes = []*net.IPNet{route}
<ide>
<add> intf2 := &nwIface{}
<add> intf2.srcName = "testbridge"
<add> intf2.dstName = sboxIfaceName
<add> intf2.bridge = true
<add>
<ide> veth = &netlink.Veth{
<ide> LinkAttrs: netlink.LinkAttrs{Name: vethName3, TxQLen: 0},
<ide> PeerName: vethName4}
<ide> func newInfo(t *testing.T) (Sandbox, error) {
<ide> return nil, err
<ide> }
<ide>
<del> intf2 := &nwIface{}
<del> intf2.srcName = vethName4
<del> intf2.dstName = sboxIfaceName
<del>
<del> ip4, addr, err = net.ParseCIDR("192.168.2.100/24")
<del> if err != nil {
<del> return nil, err
<del> }
<del> intf2.address = addr
<del> intf2.address.IP = ip4
<del>
<del> // ip6, addrv6, err := net.ParseCIDR("2001:DB8::ABCD/48")
<del> ip6, addrv6, err = net.ParseCIDR("fe80::3/64")
<del>
<del> if err != nil {
<del> return nil, err
<del> }
<del> intf2.addressIPv6 = addrv6
<del> intf2.addressIPv6.IP = ip6
<add> intf3 := &nwIface{}
<add> intf3.srcName = vethName4
<add> intf3.dstName = sboxIfaceName
<add> intf3.master = "testbridge"
<ide>
<del> info := &networkNamespace{iFaces: []*nwIface{intf1, intf2}}
<add> info := &networkNamespace{iFaces: []*nwIface{intf1, intf2, intf3}}
<ide>
<ide> info.gw = net.ParseIP("192.168.1.1")
<ide> // sinfo.GatewayIPv6 = net.ParseIP("2001:DB8::1")
<ide><path>libnetwork/sandbox/sandbox_test.go
<ide> func TestSandboxCreate(t *testing.T) {
<ide>
<ide> for _, i := range tbox.Info().Interfaces() {
<ide> err = s.AddInterface(i.SrcName(), i.DstName(),
<add> tbox.InterfaceOptions().Bridge(i.Bridge()),
<ide> tbox.InterfaceOptions().Address(i.Address()),
<ide> tbox.InterfaceOptions().AddressIPv6(i.AddressIPv6()))
<ide> if err != nil {
<ide> func TestSandboxCreate(t *testing.T) {
<ide> }
<ide> runtime.LockOSThread()
<ide>
<del> verifySandbox(t, s, []string{"0", "1"})
<add> verifySandbox(t, s, []string{"0", "1", "2"})
<ide> runtime.LockOSThread()
<ide>
<ide> s.Destroy()
<ide> func TestAddRemoveInterface(t *testing.T) {
<ide>
<ide> for _, i := range tbox.Info().Interfaces() {
<ide> err = s.AddInterface(i.SrcName(), i.DstName(),
<add> tbox.InterfaceOptions().Bridge(i.Bridge()),
<ide> tbox.InterfaceOptions().Address(i.Address()),
<ide> tbox.InterfaceOptions().AddressIPv6(i.AddressIPv6()))
<ide> if err != nil {
<ide> func TestAddRemoveInterface(t *testing.T) {
<ide> runtime.LockOSThread()
<ide> }
<ide>
<del> verifySandbox(t, s, []string{"0", "1"})
<add> verifySandbox(t, s, []string{"0", "1", "2"})
<ide> runtime.LockOSThread()
<ide>
<ide> interfaces := s.Info().Interfaces()
<ide> func TestAddRemoveInterface(t *testing.T) {
<ide> }
<ide> runtime.LockOSThread()
<ide>
<del> verifySandbox(t, s, []string{"1"})
<add> verifySandbox(t, s, []string{"1", "2"})
<ide> runtime.LockOSThread()
<ide>
<ide> i := tbox.Info().Interfaces()[0]
<ide> if err := s.AddInterface(i.SrcName(), i.DstName(),
<add> tbox.InterfaceOptions().Bridge(i.Bridge()),
<ide> tbox.InterfaceOptions().Address(i.Address()),
<ide> tbox.InterfaceOptions().AddressIPv6(i.AddressIPv6())); err != nil {
<ide> t.Fatalf("Failed to add interfaces to sandbox: %v", err)
<ide> }
<ide> runtime.LockOSThread()
<ide>
<del> verifySandbox(t, s, []string{"1", "2"})
<add> verifySandbox(t, s, []string{"1", "2", "3"})
<ide> runtime.LockOSThread()
<ide>
<ide> s.Destroy() | 5 |
Javascript | Javascript | remove a useless check in charstounicode | 71d0f0d55c4584e2731a9f0e573c183a87f39ea9 | <ide><path>fonts.js
<ide> var Font = (function Font() {
<ide> var constructor = function font_constructor(name, file, properties) {
<ide> this.name = name;
<ide> this.encoding = properties.encoding;
<del> this.glyphs = properties.glyphs;
<ide> this.sizes = [];
<ide>
<ide> var names = name.split("+");
<ide> var Font = (function Font() {
<ide> unicode = charcode;
<ide> }
<ide>
<del> // Check if the glyph has already been converted
<del> if (!IsNum(unicode))
<del> unicode = encoding[charcode].unicode = this.glyphs[unicode].unicode;
<del>
<ide> // Handle surrogate pairs
<ide> if (unicode > 0xFFFF) {
<ide> str += String.fromCharCode(unicode & 0xFFFF); | 1 |
Javascript | Javascript | fix route name in code comment | 94751275ee54c713fceae58a34af3dcce25ea154 | <ide><path>packages/ember-routing/lib/system/route.js
<ide> Ember.Route = Ember.Object.extend(Ember.ActionHandler, {
<ide> resolved.
<ide>
<ide> ```js
<del> App.PostRoute = Ember.Route.extend({
<add> App.PostsRoute = Ember.Route.extend({
<ide> afterModel: function(posts, transition) {
<ide> if (posts.length === 1) {
<ide> this.transitionTo('post.show', posts[0]); | 1 |
Javascript | Javascript | render charts only once in time scale tests | d480e11ea09681d3d95dd827688ff1a3819117ba | <ide><path>test/specs/scale.time.tests.js
<ide> // Time scale tests
<ide> describe('Time scale tests', function() {
<del> function createScale(data, options) {
<add> function createScale(data, options, dimensions) {
<ide> var scaleID = 'myScale';
<ide> var mockContext = window.createMockContext();
<ide> var Constructor = Chart.scaleService.getScaleConstructor('time');
<ide> describe('Time scale tests', function() {
<ide> id: scaleID
<ide> });
<ide>
<del> scale.update(400, 50);
<add> var width = (dimensions && dimensions.width) || 400;
<add> var height = (dimensions && dimensions.height) || 50;
<add> scale.update(width, height);
<ide> return scale;
<ide> }
<ide>
<ide> describe('Time scale tests', function() {
<ide> };
<ide>
<ide> var scaleOptions = Chart.scaleService.getScaleDefaults('time');
<del> var scale = createScale(mockData, scaleOptions);
<del> scale.update(1000, 200);
<add> var scale = createScale(mockData, scaleOptions, {width: 1000, height: 200});
<ide> var ticks = getTicksLabels(scale);
<ide>
<ide> // `bounds === 'data'`: first and last ticks removed since outside the data range
<ide> describe('Time scale tests', function() {
<ide> var mockData = {
<ide> labels: [newDateFromRef(0), newDateFromRef(1), newDateFromRef(2), newDateFromRef(4), newDateFromRef(6), newDateFromRef(7), newDateFromRef(9)], // days
<ide> };
<del> var scale = createScale(mockData, Chart.scaleService.getScaleDefaults('time'));
<del> scale.update(1000, 200);
<add> var scale = createScale(mockData, Chart.scaleService.getScaleDefaults('time'), {width: 1000, height: 200});
<ide> var ticks = getTicksLabels(scale);
<ide>
<ide> // `bounds === 'data'`: first and last ticks removed since outside the data range
<ide> describe('Time scale tests', function() {
<ide> }],
<ide> }
<ide> }
<del> });
<add> }, {canvas: {width: 800, height: 200}});
<ide>
<ide> var xScale = chart.scales.xScale0;
<del> xScale.update(800, 200);
<ide> var ticks = getTicksLabels(xScale);
<ide>
<ide> // `bounds === 'data'`: first and last ticks removed since outside the data range
<ide> describe('Time scale tests', function() {
<ide> }],
<ide> }
<ide> }
<del> });
<add> }, {canvas: {width: 800, height: 200}});
<ide>
<ide> var tScale = chart.scales.tScale0;
<del> tScale.update(800, 200);
<ide> var ticks = getTicksLabels(tScale);
<ide>
<ide> // `bounds === 'data'`: first and last ticks removed since outside the data range
<ide> describe('Time scale tests', function() {
<ide> var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('time'));
<ide> config.time.unit = 'hour';
<ide>
<del> var scale = createScale(mockData, config);
<del> scale.update(2500, 200);
<add> var scale = createScale(mockData, config, {width: 2500, height: 200});
<ide> var ticks = getTicksLabels(scale);
<ide>
<ide> expect(ticks).toEqual(['8PM', '9PM', '10PM', '11PM', '12AM', '1AM', '2AM', '3AM', '4AM', '5AM', '6AM', '7AM', '8AM', '9AM', '10AM', '11AM', '12PM', '1PM', '2PM', '3PM', '4PM', '5PM', '6PM', '7PM', '8PM', '9PM']);
<ide> describe('Time scale tests', function() {
<ide> }
<ide> }, Chart.scaleService.getScaleDefaults('time'));
<ide>
<del> var scale = createScale(mockData, config);
<del> scale.update(800, 200);
<add> var scale = createScale(mockData, config, {width: 800, height: 200});
<ide> var ticks = getTicksLabels(scale);
<ide>
<ide> // last date is feb 15 because we round to start of week
<ide> describe('Time scale tests', function() {
<ide> }
<ide> }, Chart.scaleService.getScaleDefaults('time'));
<ide>
<del> var scale = createScale(mockData, config);
<del> scale.update(2500, 200);
<add> var scale = createScale(mockData, config, {width: 2500, height: 200});
<ide> var ticks = getTicksLabels(scale);
<ide>
<ide> expect(ticks).toEqual(['8PM', '10PM']);
<ide> describe('Time scale tests', function() {
<ide> }],
<ide> }
<ide> }
<del> });
<add> }, {canvas: {width: 800, height: 200}});
<ide>
<ide> this.scale = this.chart.scales.xScale0;
<del> this.scale.update(800, 200);
<ide> });
<ide>
<ide> it('should be bounded by nearest step\'s year start and end', function() { | 1 |
PHP | PHP | fix lint errors | 733f8cbeb0dbdcb378fed67f4d7029436a18dbd6 | <ide><path>src/Console/Command.php
<ide> class Command
<ide> */
<ide> public function __construct()
<ide> {
<del> $locator = $this->getTableLocator();
<del> $this->modelFactory('Table', function($alias){
<add> $this->modelFactory('Table', function ($alias) {
<ide> return $this->getTableLocator()->get($alias);
<ide> });
<ide> } | 1 |
PHP | PHP | use the new class for doing requests | 135bc8f174bf09f09f5aada815f8dc58d4ef5d79 | <ide><path>lib/Cake/Utility/Xml.php
<ide>
<ide> use Cake\Core\Configure;
<ide> use Cake\Error;
<del>use Cake\Network\Http\HttpSocket;
<add>use Cake\Network\Http\Client;
<ide>
<ide> /**
<ide> * XML handling for Cake.
<ide> public static function build($input, $options = array()) {
<ide> } elseif (file_exists($input)) {
<ide> return static::_loadXml(file_get_contents($input), $options);
<ide> } elseif (strpos($input, 'http://') === 0 || strpos($input, 'https://') === 0) {
<del> $socket = new HttpSocket();
<add> $socket = new Client();
<ide> $response = $socket->get($input);
<ide> if (!$response->isOk()) {
<ide> throw new Error\XmlException(__d('cake_dev', 'XML cannot be read.')); | 1 |
Javascript | Javascript | add benchmark for buffer.concat | abd0d68bea82e6f22c1eaf28257cc6b33136cdbe | <ide><path>benchmark/buffers/buffer-concat.js
<add>'use strict';
<add>const common = require('../common.js');
<add>
<add>const bench = common.createBenchmark(main, {
<add> pieces: [1, 4, 16],
<add> pieceSize: [1, 16, 256],
<add> withTotalLength: [0, 1],
<add> n: [1024]
<add>});
<add>
<add>function main(conf) {
<add> const n = +conf.n;
<add> const size = +conf.pieceSize;
<add> const pieces = +conf.pieces;
<add>
<add> const list = new Array(pieces);
<add> list.fill(Buffer.allocUnsafe(size));
<add>
<add> const totalLength = conf.withTotalLength ? pieces * size : undefined;
<add>
<add> bench.start();
<add> for (var i = 0; i < n * 1024; i++) {
<add> Buffer.concat(list, totalLength);
<add> }
<add> bench.end(n);
<add>} | 1 |
Javascript | Javascript | fix types for dialogmanagerandroid | 7a62e7e333263d2594e63f3c5872bebea852d71c | <ide><path>Libraries/NativeModules/specs/NativeDialogManagerAndroid.js
<ide> export interface Spec extends TurboModule {
<ide> |};
<ide> +showAlert: (
<ide> config: DialogOptions,
<del> onError: (string) => void,
<add> onError: (error: string) => void,
<ide> onAction: (action: DialogAction, buttonKey?: DialogButtonKey) => void,
<ide> ) => void;
<ide> } | 1 |
Javascript | Javascript | make autoresize optional. fixes | ed00cd63fac6a13c55ccdd40c7c55d6931c118de | <ide><path>src/renderers/WebGLRenderer.js
<ide> THREE.WebGLRenderer = function ( parameters ) {
<ide>
<ide> };
<ide>
<del> this.setSize = function ( width, height ) {
<add> this.setSize = function ( width, height, autoResize ) {
<add>
<add> if ( autoResize === undefined ) {
<add> autoResize = true;
<add> }
<ide>
<ide> _canvas.width = width * this.devicePixelRatio;
<ide> _canvas.height = height * this.devicePixelRatio;
<del>
<del> _canvas.style.width = width + 'px';
<del> _canvas.style.height = height + 'px';
<add>
<add> if ( autoResize ){
<add>
<add> _canvas.style.width = width + 'px';
<add> _canvas.style.height = height + 'px';
<add>
<add> }
<ide>
<ide> this.setViewport( 0, 0, _canvas.width, _canvas.height );
<add>
<ide>
<ide> };
<ide> | 1 |
Ruby | Ruby | use arel in sql generation through associations | 8c3b8323f57d366fc308e773b286a1847552b0a3 | <ide><path>activerecord/lib/active_record/associations.rb
<ide> def select_all_rows(options, join_dependency)
<ide>
<ide> def construct_finder_sql_with_included_associations(options, join_dependency)
<ide> scope = scope(:find)
<del> sql = "SELECT #{column_aliases(join_dependency)} FROM #{(scope && scope[:from]) || options[:from] || quoted_table_name} "
<del> sql << join_dependency.join_associations.collect{|join| join.association_join }.join
<ide>
<del> add_joins!(sql, options[:joins], scope)
<del> add_conditions!(sql, options[:conditions], scope)
<del> add_limited_ids_condition!(sql, options, join_dependency) if !using_limitable_reflections?(join_dependency.reflections) && ((scope && scope[:limit]) || options[:limit])
<add> joins = join_dependency.join_associations.collect{|join| join.association_join }.join
<add> joins << construct_join(options[:joins], scope)
<ide>
<del> add_group!(sql, options[:group], options[:having], scope)
<del> add_order!(sql, options[:order], scope)
<del> add_limit!(sql, options, scope) if using_limitable_reflections?(join_dependency.reflections)
<del> add_lock!(sql, options, scope)
<add> conditions = construct_conditions(options[:conditions], scope) || ''
<add> conditions << construct_limited_ids_condition(conditions, options, join_dependency) if !using_limitable_reflections?(join_dependency.reflections) && ((scope && scope[:limit]) || options[:limit])
<ide>
<del> return sanitize_sql(sql)
<add> arel = arel_table((scope && scope[:from]) || options[:from] || table_name).
<add> join(joins).
<add> where(conditions).
<add> project(column_aliases(join_dependency)).
<add> group(construct_group(options[:group], options[:having], scope)).
<add> order(construct_order(options[:order], scope))
<add>
<add> arel = arel.take(construct_limit(options, scope)) if using_limitable_reflections?(join_dependency.reflections)
<add>
<add> return sanitize_sql(arel.to_sql)
<ide> end
<ide>
<ide> def add_limited_ids_condition!(sql, options, join_dependency)
<ide> def add_limited_ids_condition!(sql, options, join_dependency)
<ide>
<ide> def construct_limited_ids_condition(where, options, join_dependency)
<ide> unless (id_list = select_limited_ids_list(options, join_dependency)).empty?
<del> "#{where.blank? ? 'WHERE ' : ' AND '} #{connection.quote_table_name table_name}.#{primary_key} IN (#{id_list}) "
<add> "#{where.blank? ? '' : ' AND '} #{connection.quote_table_name table_name}.#{primary_key} IN (#{id_list}) "
<ide> else
<ide> throw :invalid_query
<ide> end
<ide><path>activerecord/lib/active_record/associations/has_many_through_association.rb
<ide> def size
<ide> return @target.size if loaded?
<ide> return count
<ide> end
<del>
<add>
<ide> protected
<ide> def target_reflection_has_associated_record?
<ide> if @reflection.through_reflection.macro == :belongs_to && @owner[@reflection.through_reflection.primary_key_name].blank?
<ide> def construct_find_options!(options)
<ide> options[:joins] = construct_joins(options[:joins])
<ide> options[:include] = @reflection.source_reflection.options[:include] if options[:include].nil?
<ide> end
<del>
<add>
<ide> def insert_record(record, force = true, validate = true)
<ide> if record.new_record?
<ide> if force
<ide> def construct_conditions
<ide> end
<ide>
<ide> def construct_from
<del> @reflection.quoted_table_name
<add> @reflection.table_name
<ide> end
<ide>
<ide> def construct_select(custom_select = nil)
<ide> def build_through_conditions
<ide> interpolate_sql(sanitize_sql(conditions))
<ide> end
<ide> end
<del>
<add>
<ide> def build_sti_condition
<ide> @reflection.through_reflection.klass.send(:type_condition)
<ide> end | 2 |
Go | Go | set network id as part of parsenetworkoptions | a893540b667c302ae3267d3968628b19f8aca4ec | <ide><path>libnetwork/drivers/ipvlan/ipvlan_network.go
<ide> func (d *driver) CreateNetwork(nid string, option map[string]interface{}, nInfo
<ide> if err != nil {
<ide> return err
<ide> }
<del> config.ID = nid
<ide> err = config.processIPAM(nid, ipV4Data, ipV6Data)
<ide> if err != nil {
<ide> return err
<ide> func parseNetworkOptions(id string, option options.Generic) (*configuration, err
<ide> config.Internal = true
<ide> }
<ide> }
<add> config.ID = id
<ide> return config, nil
<ide> }
<ide> | 1 |
Text | Text | add £15, cleanup | 4a2817d8260348f94ad6ae64c93e5d4ebda13c8c | <ide><path>SUPPORTERS.md
<ide> These awesome people supported our Kickstarter by giving us £50 or more:
<ide> * [Dmitri Akatov](http://akatov.com)
<ide> * [Joey Mink](http://joeymink.com)
<ide> * [MentalPower](http://mentalpower.us)
<del>* [@worldofchris](http://www.worldofchris.com)
<add>* [worldofchris](http://www.worldofchris.com)
<ide> * [Joël Kuijten](http://pm5544.eu)
<ide> * [William Griffiths](http://Cwmni.com)
<ide> * [Paul Howard](https://github.com/pauldhoward)
<ide> * [Mårten Gustafson](http://marten.gustafson.pp.se)
<ide> * [Markus Heurung](http://markusheurung.de)
<ide>
<add>These brilliant people supported our Kickstarter by giving us £15 or more:
<add>
<add>* [Brian Lalor](http://github.com/blalor)
<add>* [Aaron Ackerman](https://twitter.com/_aaronackerman_)
<add>* [Rodreegez](http://rodreegez.com)
<add>* [Stephan Diederich](https://github.com/diederich)
<add>* [Andrew Nesbitt](http://nesbitt.io)
<add>* [Blaine Cook](http://romeda.org/)
<add>* [Raquel Hernandez](http://raquelhernandez.net)
<add>* [JD Harrington](http://twitter.com/psi)
<add>* [P.J. Onori](www.somerandomdude.com)
<add>* [Egbert Veenstra](http://egbert.co)
<add>* [Bramus Van Damme](http://www.bram.us/)
<add>* [Matt Vagni](http://www.twitter.com/mattvagni)
<add>* [Matt Cannon](www.mattcannon.co.uk)
<add>* [Dannel Jurado](http://demarko.org)
<add>* [Benjamin Esham](http://www.bdesham.info)
<add>* [Nick Rogers](http://twitter.com/zikolas)
<add>* [Abe Estrada](http://abeestrada.com)
<add>* [Mattias Larsson](http://www.yahoo.com/)
<add>* [Dave Ross](http://davidmichaelross.com)
<add>* [Andrian Budantsov](http://andrian.io/)
<add>* [Jason Smith](https://twitter.com/waitingallday)
<add>* [Martin Coxall](twitter.com/grabcocque)
<add>* [Nick Jones](nick@dischord.org)
<add>* [Esmé Cowles](https://github.com/escowles)
<add>* [Garrett L. Ward](http://glward.net)
<add>* Carl Laird
<add>* [Mx A. Matienzo](http://matienzo.org/)
<add>* [Sean Dunn](http://www.dunns.me)
<add>* [Kara Van Malssen](avpreserve.com)
<add>* [phette23](http://phette.net)
<add>* [Jemal Cole](http://jemal.co/)
<add>* [Branden Wiegand](http://brandenwiegand.com)
<add>* [Adam Spooner](http://adamjspooner.com)
<add>* [Evan McNulty](http://www.evanm.net/)
<add>* [Abdullah AlDwyish](https://twitter.com/adwayish)
<add>* [Simon Jodet](http://jodet.com)
<add>* [Christian Maier](http://sieben.me)
<add>* [Justin Pecott](http://justin.pecott.net)
<add>* [Yuya Saito](https://github.com/studiomohawk)
<add>* [jan](https://alpha.app.net/derjan)
<add>* [beanieboi](abwesend.com)
<add>* [dirkr](niebegeg.net)
<add>* [ouvanous](ouvanous.com)
<add>* [dlinsin](http://dlinsin.github.io)
<add>* [Alex Morega](http://grep.ro/)
<add>* [Chris McGrath](https://twitter.com/chrismcg)
<add>* [Ben](http://blog.bueti-online.ch)
<add>* [Ishaan Gulrajani](http://ishaan.io)
<add>* [Horst Gutmann](http://zerokspot.com/)
<add>* [freecastle](http://freiburg79.de/)
<add>* [Hynek Schlawack](http://hynek.me)
<add>* [aiusepsi](http://aiusepsi.co.uk)
<add>* [Stefan Borsje](https://yourkarma.com)
<add>* [Mark Goody](http://markgoody.ie/)
<add>* [Terje Sten Bjerkseth](github.com/terjesb)
<add>* [Wade Winningham](http://www.updrift.com)
<add>* [Opendream](http://www.opendream.co.th)
<add>* [Todd Grooms](toddgrooms.com)
<add>* Christian Savard
<add>* [Michael Novak](http://michaelnovakjr.com)
<add>* [Jon Prettyman](https://www.sprighealth.com/)
<add>* [Ruby Daily](http://rubydaily.org)
<add>* derBernd
<add>* [toolbear](http://tool-man.org/)
<add>* [S Schreiber](www.stevenfschreiber.com)
<add>* [Paul Bowsher](http://github.com/boffbowsh/)
<add>* [Daniel Lindsley](http://toastdriven.com/)
<add>* [Felipe Coury](http://gistia.com)
<add>* [noahhendrix](http://twitter.com/noahhendrix)
<add>* [Kevin Davies](http://theausguild.org)
<add>* [Geknowm](http://geknowm.com)
<add>* [Tod Olson](http://www.lib.uchicago.edu/~tod/)
<add>* [Christian Busch](http://debilux.org)
<add>* [Victor Asteinza](http://victorasteinza.com)
<add>* [Hans N. Hjort](www.hansnilsson.net)
<add>* [Rachel Heaton](www.rmheaton.com)
<add>* [CodeCatalyst](http://codecatalyst.com/)
<add>* [Luke Karrys](lukekarrys.com)
<add>* [Brandon Weiss](http://brandonweiss.me)
<add>* [Gareth](http://gareth.com.au)
<add>* [Nate Robins](http://xmission.com/~nate)
<add>* [Jay Graves](http://doubleencore.com)
<add>* [John Wittkoski](https://github.com/jwittkoski)
<add>* [Micah Woods](http://www.hashrocket.com)
<add>* [Raphael Stolt](http://raphaelstolt.blogspot.de)
<add>* [Hatimeria](hatimeria.com)
<add>* [Barron Bichon](http://blueplaid.net/)
<add>* [Torvos](www.torvos.ca)
<add>* [Alexander Zautke](http://alexander-zautke.com)
<add>* [Sam Kelly](http://skel.ly)
<add>* [Tobias Ottenweller](https://github.com/tomco)
<add>* [Ragan Webber](Http://raganwebber.com)
<add>* [Wesley Moore](http://wezm.net/)
<add>* [pangratz](http://code418.com)
<add>* [jus](http://jus.li)
<add>* [Teng Siong Ong](http://siong1987.com)
<add>* [Bryan Liles](http://thunderboltlabs.com)
<add>* [Tony Pitale](http://tpitale.com)
<add>* [Ryan Ahearn](http://rcahearn.net)
<add>* [ITerativ GmbH](http://www.iterativ.ch/)
<add>* [Brian Nelson](www.clientresourcesinc.com)
<add>* [Jeff Beemn](http://jeffbeeman.com)
<add>* [loranger](https://github.com/loranger/)
<add>* Torbjørn Vatn
<add>* [Justin Hileman](http://justinhileman.info)
<add>* [Martin Tithonium](http://martian.at/)
<add>* [Ivan De Marino](http://ivandemarino.me)
<add>* [Jørgen Tjernø](http://jorgenpt.tumblr.com)
<add>* [Peter Souter](http://github.com/petems)
<add>* Marco
<add>* [Steve McKinney](http://stephenmckinney.me)
<add>* Felix Adusei
<add>* [Richard Lee](http://dlackty.org/)
<add>* [Shane O'Grady](http://ogrady.ie)
<add>* [Sebastian Staudt](http://koraktor.de)
<add>* [Eric Blair](http://room45.co/)
<add>* [Andreas Behr](http://www.codedreality.com)
<add>* [Terry Churchill](http://www.doc-linux.co.uk)
<add>* [Maximilian Haack](http://3141.eu)
<add>* [Pascal Jungblut](http://pascalj.de)
<add>* [Absolight](http://www.absolight.fr/)
<add>* [Ben Hagen](https://plus.google.com/102873090274552422645/)
<add>* [Wilbur Smith](twitter.com/thewilbur)
<add>* bup
<add>* [epiGenesys](http://www.epigenesys.co.uk/)
<add>* Greg Clarke
<add>* [CoEPP](www.coepp.org.au)
<add>* [Jérôme Foray](http://foray-jero.me/)
<add>* [bobuk](http://twitter.com/bobuk)
<add>* [Christoph Hochstrasser](http://christophh.net)
<add>* [João Bolila](Bolila.com)
<add>* [Yaroslav Markin](https://github.com/yaroslav)
<add>* [David White](http://wizardfrag.co.uk)
<add>* Jonatan Lindström
<add>* [AYSTech Consulting](aystech.net)
<add>* [Josh Dick](http://joshdick.net)
<add>* [Alexey Mirniy](http://www.linkedin.com/in/pharmazone)
<add>* [Simon Gate](Http://smgt.me)
<add>* [Josh Yaganeh](github.com/jyaganeh)
<add>* Dirk Kraft
<add>* [stefan crain](https://github.com/stefancrain)
<add>* [xorbyte](http://hackd.net)
<add>* Dom
<add>* [kmcphillips](http://kevinmcphillips.ca)
<add>* [Justin Kolberg](http://www.aelatis.com)
<add>* [Benjamin Medicke](http://benmedicke.com/)
<add>* [Hibri Marzook](www.hibri.net)
<add>* [Jeremy Pinnix](pixelgrazer.com)
<add>* [Arne de Bree](http://www.arnedebree.nl)
<add>* [Oleksandr Skrypnyk](http://sxua.github.com)
<add>* [Ilya Otyutskiy](https://twitter.com/thesharp)
<add>* Chris Hellmuth
<add>* Unknown Comic
<add>* Brian Miller
<add>* [Zhang Yi](http://tomodachi.name)
<add>* [Romain Lespinasse](dandelion.github.io)
<add>* [achiiive.com](http://achiiive.com)
<add>* [Michael Hawkins](hawkinsunlimited.com)
<add>* [Tim Sutton](https://github.com/timsutton)
<add>* [Arne Eilermann](https://kleinerdrei.net/)
<add>* [Jeroen Seegers](www.jeroenseegers.com)
<add>* [Dan Karney](https://twitter.com/KarneAsada)
<add>* [James Curbo](www.curbo.org)
<add>* [Mark Norman Francis](https://github.com/norm/)
<add>* [Lee Brandt](http://leebrandt.me)
<add>* [Dan Ivovich](http://danivovich.com/)
<add>* [Eli Juicy Jones](http://elijones.us/)
<add>* [Daniel Hertz](http://www.dhertz.com)
<add>* [Chuck Fouts](https://github.com/gnarl)
<add>* [Chip Warden](https://twitter.com/lgw4)
<add>* Ethan Schoonover
<add>* [Chi Trung Nguyen](http://www.napcaesmind.de)
<add>* [Danny Amey](http://www.dannyamey.com/)
<add>* Oscar
<add>* [Brian Pollack](http://www.protovate.com)
<add>* [Andrew Broman](http://cccultura.com)
<add>* [Chris Metcalf](http://chrismetcalf.net)
<add>* [smartwatermelon](projectinsomnia.com)
<add>* [Ursul_polar](twitter.com/ursul_polar)
<add>* David Hodo
<add>* [Jeff Field](https://twitter.com/jfield)
<add>* [dholm](http://github.com/dholm/)
<add>* [Chase Southard](southard.co)
<add>* Paul Jenkins
<add>* [Johnneylee Jack Rollins](http://Spaceghost.github.com)
<add>* [Jose Marcelino](http://metavurt.net)
<add>* [Adam](http://example.com)
<add>* [François Lamboley](http://www.frostland.fr/)
<add>* [Mike Anderson](mrmikea.com)
<add>* [Ian Johnson](http://ialsotakephotos.com/)
<add>* Dave Coyle
<add>* Brian Fuchs
<add>* Fernando
<add>* [Denny Lee](http://dennyglee.com)
<add>* [Ernie Hershey](www.ernie.org)
<add>* [Hao Gao](www.haogao.me)
<add>* [Tim Gilbert](http://timgilbert.wordpress.com/)
<add>* [Keith Thompson](keiththomps.com)
<add>
<ide> These wonderful people supported our Kickstarter by giving us £10 or more:
<ide>
<ide> * [Simon Rascovsky](http://teleradiologia.com)
<ide> These lovely people supported our Kickstarter by giving us £5 or more:
<ide> * Tony Fernandez
<ide> * Arizona Edwards
<ide> * Asaf Ary
<del> | 1 |
Javascript | Javascript | ignore properties in prototype chain | cb42766a14f8123aa288b6e20f879141970fb84d | <ide><path>src/Angular.js
<ide> function parseKeyValue(/**string*/keyValue) {
<ide> key = tryDecodeURIComponent(key_value[0]);
<ide> if ( isDefined(key) ) {
<ide> var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
<del> if (!obj[key]) {
<add> if (!hasOwnProperty.call(obj, key)) {
<ide> obj[key] = val;
<ide> } else if(isArray(obj[key])) {
<ide> obj[key].push(val);
<ide><path>test/AngularSpec.js
<ide> describe('angular', function() {
<ide> expect(parseKeyValue('flag1&flag1=value&flag1=value2&flag1')).
<ide> toEqual({flag1: [true,'value','value2',true]});
<ide> });
<add>
<add>
<add> it('should ignore properties higher in the prototype chain', function() {
<add> expect(parseKeyValue('toString=123')).toEqual({
<add> 'toString': '123'
<add> });
<add> });
<ide> });
<ide>
<ide> describe('toKeyValue', function() { | 2 |
Text | Text | add missing serial commas | ff9a6bc1f343c146c4d54034e351e1afb1da3238 | <ide><path>COLLABORATOR_GUIDE.md
<ide> - [How is an LTS release cut?](#how-is-an-lts-release-cut)
<ide>
<ide> This document contains information for Collaborators of the Node.js
<del>project regarding maintaining the code, documentation and issues.
<add>project regarding maintaining the code, documentation, and issues.
<ide>
<ide> Collaborators should be familiar with the guidelines for new
<ide> contributors in [CONTRIBUTING.md](./CONTRIBUTING.md) and also
<ide><path>CONTRIBUTING.md
<ide> for any individual to *act* in such a manner that is not in violation of the
<ide> strict letter of the Code of Conduct guidelines while still going completely
<ide> against the spirit of what that Code is intended to accomplish.
<ide>
<del>Open, diverse and inclusive communities live and die on the basis of trust.
<add>Open, diverse, and inclusive communities live and die on the basis of trust.
<ide> Contributors can disagree with one another so long as they trust that those
<ide> disagreements are in good faith and everyone is working towards a common goal.
<ide>
<ide> Node.js changed that broke the module.
<ide> Once an issue has been opened, it is not uncommon for there to be discussion
<ide> around it. Some contributors may have differing opinions about the issue,
<ide> including whether the behavior being seen is a bug or a feature. This discussion
<del>is part of the process and should be kept focused, helpful and professional.
<add>is part of the process and should be kept focused, helpful, and professional.
<ide>
<ide> Short, clipped responses—that provide neither additional context nor supporting
<ide> detail—are not helpful or professional. To many, such responses are simply
<ide><path>CPP_STYLE_GUIDE.md
<ide> * [4 spaces of indentation for statement continuations](#4-spaces-of-indentation-for-statement-continuations)
<ide> * [Align function arguments vertically](#align-function-arguments-vertically)
<ide> * [Initialization lists](#initialization-lists)
<del>* [CamelCase for methods, functions and classes](#camelcase-for-methods-functions-and-classes)
<add>* [CamelCase for methods, functions, and classes](#camelcase-for-methods-functions-and-classes)
<ide> * [snake\_case for local variables and parameters](#snake_case-for-local-variables-and-parameters)
<ide> * [snake\_case\_ for private class fields](#snake_case_-for-private-class-fields)
<ide> * [Space after `template`](#space-after-template)
<ide> HandleWrap::HandleWrap(Environment* env,
<ide> handle_(handle) {
<ide> ```
<ide>
<del>## CamelCase for methods, functions and classes
<add>## CamelCase for methods, functions, and classes
<ide>
<ide> Exceptions are simple getters/setters, which are named `property_name()` and
<ide> `set_property_name()`, respectively.
<ide><path>README.md
<ide> documentation of the latest stable version.
<ide>
<ide> ### Verifying Binaries
<ide>
<del>Current, LTS and Nightly download directories all contain a _SHASUMS256.txt_
<add>Current, LTS, and Nightly download directories all contain a _SHASUMS256.txt_
<ide> file that lists the SHA checksums for each file available for
<ide> download.
<ide>
<ide><path>doc/api/addons.md
<ide> involving knowledge of several components and APIs :
<ide> threads and all of the asynchronous behaviors of the platform. It also
<ide> serves as a cross-platform abstraction library, giving easy, POSIX-like
<ide> access across all major operating systems to many common system tasks, such
<del> as interacting with the filesystem, sockets, timers and system events. libuv
<add> as interacting with the filesystem, sockets, timers, and system events. libuv
<ide> also provides a pthreads-like threading abstraction that may be used to
<ide> power more sophisticated asynchronous Addons that need to move beyond the
<ide> standard event loop. Addon authors are encouraged to think about how to
<ide><path>doc/api/buffer.md
<ide> changes:
<ide> -->
<ide>
<ide> `Buffer` instances are commonly used to represent sequences of encoded characters
<del>such as UTF-8, UCS2, Base64 or even Hex-encoded data. It is possible to
<add>such as UTF-8, UCS2, Base64, or even Hex-encoded data. It is possible to
<ide> convert back and forth between `Buffer` instances and ordinary JavaScript strings
<ide> by using an explicit character encoding.
<ide>
<ide><path>doc/api/child_process.md
<ide> pipes between the parent and child. The value is one of the following:
<ide> 5. Positive integer - The integer value is interpreted as a file descriptor
<ide> that is is currently open in the parent process. It is shared with the child
<ide> process, similar to how {Stream} objects can be shared.
<del>6. `null`, `undefined` - Use default value. For stdio fds 0, 1 and 2 (in other
<add>6. `null`, `undefined` - Use default value. For stdio fds 0, 1, and 2 (in other
<ide> words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the
<ide> default is `'ignore'`.
<ide>
<ide><path>doc/api/crypto.md
<ide> > Stability: 2 - Stable
<ide>
<ide> The `crypto` module provides cryptographic functionality that includes a set of
<del>wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign and verify functions.
<add>wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.
<ide>
<ide> Use `require('crypto')` to access this module.
<ide>
<ide> In line with OpenSSL's recommendation to use pbkdf2 instead of
<ide> [`EVP_BytesToKey`][] it is recommended that developers derive a key and IV on
<ide> their own using [`crypto.pbkdf2()`][] and to use [`crypto.createCipheriv()`][]
<ide> to create the `Cipher` object. Users should not use ciphers with counter mode
<del>(e.g. CTR, GCM or CCM) in `crypto.createCipher()`. A warning is emitted when
<add>(e.g. CTR, GCM, or CCM) in `crypto.createCipher()`. A warning is emitted when
<ide> they are used in order to avoid the risk of IV reuse that causes
<ide> vulnerabilities. For the case when IV is reused in GCM, see [Nonce-Disrespecting
<ide> Adversaries][] for details.
<ide> Based on the recommendations of [NIST SP 800-131A][]:
<ide>
<ide> - MD5 and SHA-1 are no longer acceptable where collision resistance is
<ide> required such as digital signatures.
<del>- The key used with RSA, DSA and DH algorithms is recommended to have
<add>- The key used with RSA, DSA, and DH algorithms is recommended to have
<ide> at least 2048 bits and that of the curve of ECDSA and ECDH at least
<ide> 224 bits, to be safe to use for several years.
<ide> - The DH groups of `modp1`, `modp2` and `modp5` have a key size
<ide><path>doc/api/fs.md
<ide> Linux, and Windows, an error will be returned. On FreeBSD, a representation
<ide> of the directory's contents will be returned.
<ide>
<ide> ```js
<del>// macOS, Linux and Windows
<add>// macOS, Linux, and Windows
<ide> fs.readFile('<directory>', (err, data) => {
<ide> // => [Error: EISDIR: illegal operation on a directory, read <directory>]
<ide> });
<ide> string. Otherwise it returns a buffer.
<ide> behavior of `fs.readFileSync()` is platform-specific.
<ide>
<ide> ```js
<del>// macOS, Linux and Windows
<add>// macOS, Linux, and Windows
<ide> fs.readFileSync('<directory>');
<ide> // => [Error: EISDIR: illegal operation on a directory, read <directory>]
<ide>
<ide> The following constants are meant for use with the [`fs.Stats`][] object's
<ide> </tr>
<ide> <tr>
<ide> <td><code>S_IRWXU</code></td>
<del> <td>File mode indicating readable, writable and executable by owner.</td>
<add> <td>File mode indicating readable, writable, and executable by owner.</td>
<ide> </tr>
<ide> <tr>
<ide> <td><code>S_IRUSR</code></td>
<ide> The following constants are meant for use with the [`fs.Stats`][] object's
<ide> </tr>
<ide> <tr>
<ide> <td><code>S_IRWXG</code></td>
<del> <td>File mode indicating readable, writable and executable by group.</td>
<add> <td>File mode indicating readable, writable, and executable by group.</td>
<ide> </tr>
<ide> <tr>
<ide> <td><code>S_IRGRP</code></td>
<ide> The following constants are meant for use with the [`fs.Stats`][] object's
<ide> </tr>
<ide> <tr>
<ide> <td><code>S_IRWXO</code></td>
<del> <td>File mode indicating readable, writable and executable by others.</td>
<add> <td>File mode indicating readable, writable, and executable by others.</td>
<ide> </tr>
<ide> <tr>
<ide> <td><code>S_IROTH</code></td>
<ide><path>doc/api/http2.md
<ide> added: v8.4.0
<ide>
<ide> In `Http2Server`, there is no `'clientError'` event as there is in
<ide> HTTP1. However, there are `'socketError'`, `'sessionError'`, and
<del>`'streamError'`, for error happened on the socket, session or stream
<add>`'streamError'`, for error happened on the socket, session, or stream
<ide> respectively.
<ide>
<ide> #### Event: 'socketError'
<ide> performance.
<ide> There are several types of error conditions that may arise when using the
<ide> `http2` module:
<ide>
<del>Validation Errors occur when an incorrect argument, option or setting value is
<add>Validation Errors occur when an incorrect argument, option, or setting value is
<ide> passed in. These will always be reported by a synchronous `throw`.
<ide>
<ide> State Errors occur when an action is attempted at an incorrect time (for
<ide> added: v8.4.0
<ide> * {net.Socket|tls.TLSSocket}
<ide>
<ide> Returns a Proxy object that acts as a `net.Socket` (or `tls.TLSSocket`) but
<del>applies getters, setters and methods based on HTTP/2 logic.
<add>applies getters, setters, and methods based on HTTP/2 logic.
<ide>
<ide> `destroyed`, `readable`, and `writable` properties will be retrieved from and
<ide> set on `request.stream`.
<ide> added: v8.4.0
<ide> * {net.Socket|tls.TLSSocket}
<ide>
<ide> Returns a Proxy object that acts as a `net.Socket` (or `tls.TLSSocket`) but
<del>applies getters, setters and methods based on HTTP/2 logic.
<add>applies getters, setters, and methods based on HTTP/2 logic.
<ide>
<ide> `destroyed`, `readable`, and `writable` properties will be retrieved from and
<ide> set on `response.stream`.
<ide><path>doc/api/n-api.md
<ide> following forms:
<ide> - Named: a simple UTF8-encoded string
<ide> - Integer-Indexed: an index value represented by `uint32_t`
<ide> - JavaScript value: these are represented in N-API by `napi_value`. This can
<del>be a `napi_value` representing a String, Number or Symbol.
<add>be a `napi_value` representing a String, Number, or Symbol.
<ide>
<ide> N-API values are represented by the type `napi_value`.
<ide> Any N-API call that requires a JavaScript value takes in a `napi_value`.
<ide> napi_status napi_get_node_version(napi_env env,
<ide>
<ide> Returns `napi_ok` if the API succeeded.
<ide>
<del>This function fills the `version` struct with the major, minor and patch version
<del>of Node that is currently running, and the `release` field with the
<add>This function fills the `version` struct with the major, minor, and patch
<add>version of Node.js that is currently running, and the `release` field with the
<ide> value of [`process.release.name`][`process.release`].
<ide>
<ide> The returned buffer is statically allocated and does not need to be freed.
<ide><path>doc/api/os.md
<ide> The following signal constants are exported by `os.constants.signals`:
<ide> <tr>
<ide> <td><code>SIGILL</code></td>
<ide> <td>Sent to a process to notify that it has attempted to perform an illegal,
<del> malformed, unknown or privileged instruction.</td>
<add> malformed, unknown, or privileged instruction.</td>
<ide> </tr>
<ide> <tr>
<ide> <td><code>SIGTRAP</code></td>
<ide><path>doc/api/process.md
<ide> A process warning is similar to an error in that it describes exceptional
<ide> conditions that are being brought to the user's attention. However, warnings
<ide> are not part of the normal Node.js and JavaScript error handling flow.
<ide> Node.js can emit warnings whenever it detects bad coding practices that could
<del>lead to sub-optimal application performance, bugs or security vulnerabilities.
<add>lead to sub-optimal application performance, bugs, or security vulnerabilities.
<ide>
<ide> The listener function is called with a single `warning` argument whose value is
<ide> an `Error` object. There are three key properties that describe the warning:
<ide> objects managed by V8. `rss`, Resident Set Size, is the amount of space
<ide> occupied in the main memory device (that is a subset of the total allocated
<ide> memory) for the process, which includes the _heap_, _code segment_ and _stack_.
<ide>
<del>The _heap_ is where objects, strings and closures are stored. Variables are
<add>The _heap_ is where objects, strings, and closures are stored. Variables are
<ide> stored in the _stack_ and the actual JavaScript code resides in the
<ide> _code segment_.
<ide>
<ide><path>doc/api/tls.md
<ide> not required and a default ECDHE curve will be used. The `ecdhCurve` property
<ide> can be used when creating a TLS Server to specify the list of names of supported
<ide> curves to use, see [`tls.createServer()`] for more info.
<ide>
<del>### ALPN, NPN and SNI
<add>### ALPN, NPN, and SNI
<ide>
<ide> <!-- type=misc -->
<ide>
<ide><path>doc/releases.md
<ide> If you have an error on Windows and need to start again, be aware that you'll ge
<ide>
<ide> ARMv7 takes the longest to compile. Unfortunately ccache isn't as effective on release builds, I think it's because of the additional macro settings that go in to a release build that nullify previous builds. Also most of the release build machines are separate to the test build machines so they don't get any benefit from ongoing compiles between releases. You can expect 1.5 hours for the ARMv7 builder to complete and you should normally wait for this to finish. It is possible to rush a release out if you want and add additional builds later but we normally provide ARMv7 from initial promotion.
<ide>
<del>You do not have to wait for the ARMv6 / Raspberry PI builds if they take longer than the others. It is only necessary to have the main Linux (x64 and x86), macOS .pkg and .tar.gz, Windows (x64 and x86) .msi and .exe, source, headers and docs (both produced currently by an macOS worker). **If you promote builds _before_ ARM builds have finished, you must repeat the promotion step for the ARM builds when they are ready**.
<add>You do not have to wait for the ARMv6 / Raspberry PI builds if they take longer than the others. It is only necessary to have the main Linux (x64 and x86), macOS .pkg and .tar.gz, Windows (x64 and x86) .msi and .exe, source, headers, and docs (both produced currently by an macOS worker). **If you promote builds _before_ ARM builds have finished, you must repeat the promotion step for the ARM builds when they are ready**.
<ide>
<ide> ### 9. Test the Build
<ide> | 15 |
Python | Python | remove version warning in pretrained bart models | 3b20e910b45f392f247468e997b00ce12a4ca5c9 | <ide><path>src/transformers/models/bart/modeling_bart.py
<ide> def forward(self, hidden_states: torch.Tensor):
<ide> class BartPretrainedModel(PreTrainedModel):
<ide> config_class = BartConfig
<ide> base_model_prefix = "model"
<add> _keys_to_ignore_on_load_unexpected = [r"encoder\.version", r"decoder\.version"]
<ide>
<ide> def _init_weights(self, module):
<ide> std = self.config.init_std
<ide> def forward(
<ide> )
<ide> class BartForConditionalGeneration(BartPretrainedModel):
<ide> base_model_prefix = "model"
<del> _keys_to_ignore_on_load_missing = [
<del> r"final_logits_bias",
<del> r"encoder\.version",
<del> r"decoder\.version",
<del> r"lm_head\.weight",
<del> ]
<add> _keys_to_ignore_on_load_missing = [r"final_logits_bias", r"lm_head\.weight"]
<ide>
<ide> def __init__(self, config: BartConfig):
<ide> super().__init__(config) | 1 |
PHP | PHP | fix failing tests | c22d6d1507a65f959cdd71bc61697cef01c23e91 | <ide><path>lib/Cake/Network/Http/Adapter/Stream.php
<ide> protected function _buildHeaders(Request $request, $options) {
<ide> /**
<ide> * Builds the request content based on the request object.
<ide> *
<del> * If the $request->content() is a string, it will be used as is.
<add> * If the $request->body() is a string, it will be used as is.
<ide> * Array data will be processed with Cake\Network\Http\FormData
<ide> *
<ide> * @param Cake\Network\Http\Request $request The request being sent.
<ide> * @param array $options Array of options to use.
<ide> * @return void
<ide> */
<ide> protected function _buildContent(Request $request, $options) {
<del> $content = $request->content();
<add> $content = $request->body();
<ide> if (empty($content)) {
<ide> return;
<ide> }
<ide><path>lib/Cake/Network/Http/Message.php
<ide> class Message {
<ide> *
<ide> * @var array
<ide> */
<del> protected $_headers;
<add> protected $_headers = [];
<ide>
<ide> /**
<ide> * The array of cookies in the response.
<ide> *
<ide> * @var array
<ide> */
<del> protected $_cookies;
<add> protected $_cookies = [];
<ide>
<ide> /**
<ide> * HTTP Version being used.
<ide><path>lib/Cake/Test/TestCase/Network/Http/Adapter/StreamTest.php
<ide> public function testSendContextContentString() {
<ide> ->header([
<ide> 'Content-Type' => 'application/json'
<ide> ])
<del> ->content($content);
<add> ->body($content);
<ide>
<ide> $options = [
<ide> 'redirect' => 20
<ide> public function testSendContextContentArray() {
<ide> ->header([
<ide> 'Content-Type' => 'application/json'
<ide> ])
<del> ->content(['a' => 'my value']);
<add> ->body(['a' => 'my value']);
<ide>
<ide> $this->stream->send($request, []);
<ide> $result = $this->stream->contextOptions(); | 3 |
Ruby | Ruby | eliminate a nil check | eb528fd7cd01baac4fb0bcdf13ab2c0ab8f6c568 | <ide><path>Library/Homebrew/compilers.rb
<ide> module CompilerConstants
<ide> GNU_GCC_REGEXP = /^gcc-(4\.[3-9])$/
<ide> end
<ide>
<del>Compiler = Struct.new(:name, :version, :priority)
<add># TODO make this class private to CompilerSelector
<add>class Compiler
<add> attr_reader :name, :version, :priority
<add>
<add> def initialize(name, version=0, priority=0)
<add> @name = name
<add> @version = version
<add> @priority = priority
<add> end
<add>end
<ide>
<ide> class CompilerFailure
<ide> attr_reader :name
<ide> def initialize(name, version, &block)
<ide> end
<ide>
<ide> def ===(compiler)
<del> name == compiler.name && version >= (compiler.version || 0)
<add> name == compiler.name && version >= compiler.version
<ide> end
<ide>
<ide> MESSAGES = { | 1 |
Text | Text | add v4.8.3 to changelog | 1748d37781b40ee562f35e9b6a059810f9b759bc | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>## v4.8.3 (December 12, 2022)
<add>
<add>- [#20296](https://github.com/emberjs/ember.js/pull/20296) Controller `queryParams` should support `readonly` arrays
<add>- [#20318](https://github.com/emberjs/ember.js/pull/20318) Backport `Resolver` to preview types
<add>
<ide> ## v4.9.1 (November 30, 2022)
<ide>
<ide> - [#20284](https://github.com/emberjs/ember.js/pull/20284) [BUGFIX] remove incorrect types for deprecation functions | 1 |
PHP | PHP | fix disabled attribute calculation | e8090bce40364df26b1b5cd2a7c65a1c4eee7971 | <ide><path>src/View/Helper/FormHelper.php
<ide> protected function _initInputField($field, $options = [])
<ide> if ($context->hasError($field)) {
<ide> $options = $this->addClass($options, $this->_config['errorClass']);
<ide> }
<del> $isDisabled = false;
<del> if (isset($options['disabled'])) {
<del> $isDisabled = (
<del> $options['disabled'] === true ||
<del> $options['disabled'] === 'disabled' ||
<del> (is_array($options['disabled']) &&
<del> !empty($options['options']) &&
<del> array_diff($options['options'], $options['disabled']) === []
<del> )
<del> );
<del> }
<add> $isDisabled = $this->_isDisabled($options);
<ide> if ($isDisabled) {
<ide> $options['secure'] = self::SECURE_SKIP;
<ide> }
<ide> protected function _initInputField($field, $options = [])
<ide> return $options;
<ide> }
<ide>
<add> /**
<add> * Determine if a field is disabled.
<add> *
<add> * @param array $options The option set.
<add> * @return bool Whether or not the field is disabled.
<add> */
<add> protected function _isDisabled(array $options)
<add> {
<add> if (!isset($options['disabled'])) {
<add> return false;
<add> }
<add> if (is_scalar($options['disabled'])) {
<add> return ($options['disabled'] === true || $options['disabled'] === 'disabled');
<add> }
<add> if (!isset($options['options'])) {
<add> return false;
<add> }
<add> if (is_array($options['options'])) {
<add> // Simple list options
<add> $first = $options['options'][array_keys($options['options'])[0]];
<add> if (is_scalar($first)) {
<add> return array_diff($options['options'], $options['disabled']) === [];
<add> }
<add> // Complex option types
<add> if (is_array($first)) {
<add> $disabled = array_filter($options['options'], function ($i) use ($options) {
<add> return in_array($i['value'], $options['disabled']);
<add> });
<add>
<add> return count($disabled) > 0;
<add> }
<add> }
<add>
<add> return false;
<add> }
<add>
<ide> /**
<ide> * Get the field name for use with _secure().
<ide> *
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testRadio()
<ide> $this->assertHtml($expected, $result);
<ide> }
<ide>
<add> /**
<add> * Test radio with complex options and empty disabled data.
<add> *
<add> * @return void
<add> */
<add> public function testRadioComplexDisabled()
<add> {
<add> $options = [
<add> ['value' => 'r', 'text' => 'red'],
<add> ['value' => 'b', 'text' => 'blue'],
<add> ];
<add> $attrs = ['disabled' => []];
<add> $result = $this->Form->radio('Model.field', $options, $attrs);
<add> $expected = [
<add> 'input' => ['type' => 'hidden', 'name' => 'Model[field]', 'value' => ''],
<add> ['label' => ['for' => 'model-field-r']],
<add> ['input' => ['type' => 'radio', 'name' => 'Model[field]', 'value' => 'r', 'id' => 'model-field-r']],
<add> 'red',
<add> '/label',
<add> ['label' => ['for' => 'model-field-b']],
<add> ['input' => ['type' => 'radio', 'name' => 'Model[field]', 'value' => 'b', 'id' => 'model-field-b']],
<add> 'blue',
<add> '/label',
<add> ];
<add> $this->assertHtml($expected, $result);
<add>
<add> $attrs = ['disabled' => ['r']];
<add> $result = $this->Form->radio('Model.field', $options, $attrs);
<add> $this->assertContains('disabled="disabled"', $result);
<add> }
<add>
<ide> /**
<ide> * testRadioDefaultValue method
<ide> * | 2 |
PHP | PHP | use a temp variable instead of the array | a718ac7222e3c9fb11773b0505777d72b9468d72 | <ide><path>src/Collection/Iterator/SortIterator.php
<ide> public function __construct($items, $callback, $dir = SORT_DESC, $type = SORT_NU
<ide> $callback = $this->_propertyExtractor($callback);
<ide> $results = [];
<ide> foreach ($items as $key => $value) {
<del> $results[$key] = $callback($value);
<del> if ($results[$key] instanceof \DateTime && $type === SORT_NUMERIC) {
<del> $results[$key] = $results[$key]->format('U');
<add> $value = $callback($value);
<add> if ($value instanceof \DateTime && $type === SORT_NUMERIC) {
<add> $value = $value->format('U');
<ide> }
<add> $results[$key] = $value;
<ide> }
<ide>
<ide> $dir === SORT_DESC ? arsort($results, $type) : asort($results, $type);
<ide><path>tests/TestCase/Collection/Iterator/SortIteratorTest.php
<ide> public function testSortComplexDeepPath()
<ide> public function testSortDateTime()
<ide> {
<ide> $items = new ArrayObject([
<del> new Time('2014-07-21'),
<del> new Time('2015-06-30'),
<del> new Time('2013-08-12')
<add> new \DateTime('2014-07-21'),
<add> new \DateTime('2015-06-30'),
<add> new \DateTime('2013-08-12')
<ide> ]);
<add> $a = new \DateTime();
<add>
<ide> $callback = function ($a) {
<del> return $a->addYear();
<add> return $a->add(new \DateInterval('P1Y'));
<ide> };
<ide> $sorted = new SortIterator($items, $callback);
<ide> $expected = [
<del> new Time('2016-06-30'),
<del> new Time('2015-07-21'),
<del> new Time('2014-08-12')
<add> new \DateTime('2016-06-30'),
<add> new \DateTime('2015-07-21'),
<add> new \DateTime('2014-08-12')
<add>
<ide> ];
<ide> $this->assertEquals($expected, $sorted->toList());
<ide>
<ide> $items = new ArrayObject([
<del> new Time('2014-07-21'),
<del> new Time('2015-06-30'),
<del> new Time('2013-08-12')
<add> new \DateTime('2014-07-21'),
<add> new \DateTime('2015-06-30'),
<add> new \DateTime('2013-08-12')
<ide> ]);
<ide>
<ide> $sorted = new SortIterator($items, $callback, SORT_ASC);
<ide> $expected = [
<del> new Time('2014-08-12'),
<del> new Time('2015-07-21'),
<del> new Time('2016-06-30'),
<add> new \DateTime('2014-08-12'),
<add> new \DateTime('2015-07-21'),
<add> new \DateTime('2016-06-30'),
<ide> ];
<ide> $this->assertEquals($expected, $sorted->toList());
<ide> } | 2 |
Text | Text | update new ctc members | d958bf88b81aeae9262b2221b6233b7201116713 | <ide><path>README.md
<ide> more information about the governance of the Node.js project, see
<ide> **Fedor Indutny** <fedor.indutny@gmail.com>
<ide> * [jasnell](https://github.com/jasnell) -
<ide> **James M Snell** <jasnell@gmail.com> (he/him)
<add>* [joyeecheung](https://github.com/joyeecheung) -
<add>**Joyee Cheung** <joyeec9h3@gmail.com> (she/her)
<add>* [mcollina](https://github.com/mcollina) -
<add>**Matteo Collina** <matteo.collina@gmail.com> (he/him)
<ide> * [mhdawson](https://github.com/mhdawson) -
<ide> **Michael Dawson** <michael_dawson@ca.ibm.com> (he/him)
<ide> * [misterdjules](https://github.com/misterdjules) -
<ide> more information about the governance of the Node.js project, see
<ide> **João Reis** <reis@janeasystems.com>
<ide> * [joshgav](https://github.com/joshgav) -
<ide> **Josh Gavant** <josh.gavant@outlook.com>
<del>* [joyeecheung](https://github.com/joyeecheung) -
<del>**Joyee Cheung** <joyeec9h3@gmail.com> (she/her)
<ide> * [julianduque](https://github.com/julianduque) -
<ide> **Julian Duque** <julianduquej@gmail.com> (he/him)
<ide> * [JungMinu](https://github.com/JungMinu) -
<ide> more information about the governance of the Node.js project, see
<ide> **Aleksey Smolenchuk** <lxe@lxe.co>
<ide> * [matthewloring](https://github.com/matthewloring) -
<ide> **Matthew Loring** <mattloring@google.com>
<del>* [mcollina](https://github.com/mcollina) -
<del>**Matteo Collina** <matteo.collina@gmail.com> (he/him)
<ide> * [micnic](https://github.com/micnic) -
<ide> **Nicu Micleușanu** <micnic90@gmail.com> (he/him)
<ide> * [mikeal](https://github.com/mikeal) - | 1 |
Javascript | Javascript | add millisecond support for date filter | 841013a4c4d25acf6fc9ff40e449c3d0a4b82ec3 | <ide><path>src/filters.js
<ide> var DATE_FORMATS = {
<ide> }
<ide> };
<ide> var DATE_FORMATS_SPLIT = /([^yMdHhmsaZ]*)(y+|M+|d+|H+|h+|m+|s+|a|Z)(.*)/;
<add>var NUMBER_STRING = /^\d+$/;
<ide>
<ide> angularFilter.date = function(date, format) {
<del> if (!(date instanceof Date)) return date;
<add> if (isString(date) && NUMBER_STRING.test(date)) {
<add> date = parseInt(date, 10);
<add> }
<add>
<add> if (isNumber(date)) {
<add> date = new Date(date);
<add> } else if (!(date instanceof Date)) {
<add> return date;
<add> }
<add>
<ide> var text = date.toLocaleDateString(), fn;
<ide> if (format && isString(format)) {
<ide> text = '';
<ide><path>test/FiltersSpec.js
<ide> describe('filter', function(){
<ide> morning.getTimezoneOffset =
<ide> noon.getTimezoneOffset =
<ide> midnight.getTimezoneOffset =
<del> function() { return 7 * 60; };
<add> function() {return 7 * 60;};
<ide>
<ide> it('should ignore falsy inputs', function() {
<ide> expect(filter.date(null)).toEqual(null);
<ide> expect(filter.date('')).toEqual('');
<del> expect(filter.date(123)).toEqual(123);
<ide> });
<ide>
<ide> it('should do basic filter', function() {
<ide> expect(filter.date(noon)).toEqual(noon.toLocaleDateString());
<ide> expect(filter.date(noon, '')).toEqual(noon.toLocaleDateString());
<ide> });
<ide>
<add> it('should accept number or number string representing milliseconds as input', function() {
<add> expect(filter.date(noon.getTime())).toEqual(noon.toLocaleDateString());
<add> expect(filter.date(noon.getTime() + "")).toEqual(noon.toLocaleDateString());
<add> });
<add>
<ide> it('should accept format', function() {
<ide> expect(filter.date(midnight, "yyyy-M-d h=H:m:saZ")).
<ide> toEqual('2010-9-3 12=0:5:8am0700');
<ide> describe('filter', function(){
<ide> toEqual('2010-09-03 12=12:05:08pm0700');
<ide>
<ide> });
<del>
<del>
<ide> });
<ide> });
<ide> | 2 |
Go | Go | use common logging in engine | b3b40433451d8e76d02dc70d591027f680c9a3bf | <ide><path>engine/job.go
<ide> import (
<ide> "io"
<ide> "strings"
<ide> "time"
<add>
<add> log "github.com/Sirupsen/logrus"
<ide> )
<ide>
<ide> // A job is the fundamental unit of work in the docker engine.
<ide> func (job *Job) Run() error {
<ide> return fmt.Errorf("%s: job has already completed", job.Name)
<ide> }
<ide> // Log beginning and end of the job
<del> job.Eng.Logf("+job %s", job.CallString())
<del> defer func() {
<del> job.Eng.Logf("-job %s%s", job.CallString(), job.StatusString())
<del> }()
<add> if job.Eng.Logging {
<add> log.Infof("+job %s", job.CallString())
<add> defer func() {
<add> log.Infof("-job %s%s", job.CallString(), job.StatusString())
<add> }()
<add> }
<ide> var errorMessage = bytes.NewBuffer(nil)
<ide> job.Stderr.Add(errorMessage)
<ide> if job.handler == nil { | 1 |
Ruby | Ruby | use names for formula comparison | 0ae1785703cc816725c78bbff4b390b918d6fd29 | <ide><path>Library/Homebrew/formula.rb
<ide> def current_installed_alias_target
<ide> # Returns false if the formula wasn't installed with an alias.
<ide> def installed_alias_target_changed?
<ide> target = current_installed_alias_target
<del> target && target != self
<add> target && target.name != name
<ide> end
<ide>
<ide> # Is this formula the target of an alias used to install an old formula?
<ide> def old_installed_formulae
<ide> # it doesn't make sense to say that other formulae are older versions of it
<ide> # because we don't know which came first.
<ide> return [] if alias_path.nil? || installed_alias_target_changed?
<del> self.class.installed_with_alias_path(alias_path) - [self]
<add> self.class.installed_with_alias_path(alias_path).reject { |f| f.name == name }
<ide> end
<ide>
<ide> # @private | 1 |
Ruby | Ruby | drop array allocations when building paths | d993cb362969caa2cb3b3f2f86ddf653d34dfb1b | <ide><path>actionpack/lib/action_dispatch/journey/nodes/node.rb
<ide> def symbol?; false; end
<ide> def literal?; false; end
<ide> def terminal?; false; end
<ide> def star?; false; end
<add> def cat?; false; end
<ide> end
<ide>
<ide> class Terminal < Node # :nodoc:
<ide> def children; [left, right] end
<ide> end
<ide>
<ide> class Cat < Binary # :nodoc:
<add> def cat?; true; end
<ide> def type; :CAT; end
<ide> end
<ide>
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> def request_method
<ide> def build_path(ast, requirements, anchor)
<ide> pattern = Journey::Path::Pattern.new(ast, requirements, JOINED_SEPARATORS, anchor)
<ide>
<del> builder = Journey::GTG::Builder.new ast
<del>
<ide> # Get all the symbol nodes followed by literals that are not the
<ide> # dummy node.
<del> symbols = ast.grep(Journey::Nodes::Symbol).find_all { |n|
<del> builder.followpos(n).first.literal?
<del> }
<add> symbols = ast.find_all { |n|
<add> n.cat? && n.left.symbol? && n.right.cat? && n.right.left.literal?
<add> }.map(&:left)
<ide>
<ide> # Get all the symbol nodes preceded by literals.
<del> symbols.concat ast.find_all(&:literal?).map { |n|
<del> builder.followpos(n).first
<del> }.find_all(&:symbol?)
<add> symbols.concat ast.find_all { |n|
<add> n.cat? && n.left.literal? && n.right.cat? && n.right.left.symbol?
<add> }.map { |n| n.right.left }
<ide>
<ide> symbols.each { |x|
<ide> x.regexp = /(?:#{Regexp.union(x.regexp, '-')})+/ | 2 |
Python | Python | add code samples for tf speech models | 60d27b1f152c181705191765661967fef3016cef | <ide><path>src/transformers/utils/doc.py
<ide> def _prepare_output_docstrings(output_type, config_class, min_indent=None):
<ide> ```
<ide> """
<ide>
<add>TF_SPEECH_BASE_MODEL_SAMPLE = r"""
<add> Example:
<add>
<add> ```python
<add> >>> from transformers import {processor_class}, {model_class}
<add> >>> from datasets import load_dataset
<add>
<add> >>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation")
<add> >>> dataset = dataset.sort("id")
<add> >>> sampling_rate = dataset.features["audio"].sampling_rate
<add>
<add> >>> processor = {processor_class}.from_pretrained("{checkpoint}")
<add> >>> model = {model_class}.from_pretrained("{checkpoint}")
<add>
<add> >>> # audio file is decoded on the fly
<add> >>> inputs = processor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="tf")
<add> >>> outputs = model(**inputs)
<add>
<add> >>> last_hidden_states = outputs.last_hidden_state
<add> >>> list(last_hidden_states.shape)
<add> {expected_output}
<add> ```
<add>"""
<add>
<add>TF_SPEECH_CTC_SAMPLE = r"""
<add> Example:
<add>
<add> ```python
<add> >>> from transformers import {processor_class}, {model_class}
<add> >>> from datasets import load_dataset
<add> >>> import tensorflow as tf
<add>
<add> >>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation")
<add> >>> dataset = dataset.sort("id")
<add> >>> sampling_rate = dataset.features["audio"].sampling_rate
<add>
<add> >>> processor = {processor_class}.from_pretrained("{checkpoint}")
<add> >>> model = {model_class}.from_pretrained("{checkpoint}")
<add>
<add> >>> # audio file is decoded on the fly
<add> >>> inputs = processor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="tf")
<add> >>> logits = model(**inputs).logits
<add> >>> predicted_ids = tf.math.argmax(logits, axis=-1)
<add>
<add> >>> # transcribe speech
<add> >>> transcription = processor.batch_decode(predicted_ids)
<add> >>> transcription[0]
<add> {expected_output}
<add> ```
<add>
<add> ```python
<add> >>> with processor.as_target_processor():
<add> ... inputs["labels"] = processor(dataset[0]["text"], return_tensors="tf").input_ids
<add>
<add> >>> # compute loss
<add> >>> loss = model(**inputs).loss
<add> >>> round(float(loss), 2)
<add> {expected_loss}
<add> ```
<add>"""
<add>
<ide> TF_VISION_BASE_MODEL_SAMPLE = r"""
<ide> Example:
<ide>
<ide> def _prepare_output_docstrings(output_type, config_class, min_indent=None):
<ide> "MaskedLM": TF_MASKED_LM_SAMPLE,
<ide> "LMHead": TF_CAUSAL_LM_SAMPLE,
<ide> "BaseModel": TF_BASE_MODEL_SAMPLE,
<add> "SpeechBaseModel": TF_SPEECH_BASE_MODEL_SAMPLE,
<add> "CTC": TF_SPEECH_CTC_SAMPLE,
<ide> "VisionBaseModel": TF_VISION_BASE_MODEL_SAMPLE,
<ide> "ImageClassification": TF_VISION_SEQ_CLASS_SAMPLE,
<ide> } | 1 |
Python | Python | add profile function | 7be5f30f17bed017eb4ecdcbe2d451fc6fd86f4d | <ide><path>spacy/cli/__init__.py
<ide> from .info import info
<ide> from .link import link
<ide> from .package import package
<add>from .profile import profile
<ide> from .train import train
<ide> from .convert import convert
<ide> from .model import model
<ide><path>spacy/cli/profile.py
<add># coding: utf8
<add>from __future__ import unicode_literals, division, print_function
<add>
<add>import plac
<add>from pathlib import Path
<add>import ujson
<add>import cProfile
<add>import pstats
<add>
<add>import spacy
<add>import sys
<add>import tqdm
<add>import cytoolz
<add>
<add>
<add>def read_inputs(loc):
<add> if loc is None:
<add> file_ = sys.stdin
<add> file_ = (line.encode('utf8') for line in file_)
<add> else:
<add> file_ = Path(loc).open()
<add> for line in file_:
<add> data = ujson.loads(line)
<add> text = data['text']
<add> yield text
<add>
<add>
<add>@plac.annotations(
<add> lang=("model/language", "positional", None, str),
<add> inputs=("Location of input file", "positional", None, read_inputs)
<add>)
<add>def profile(cmd, lang, inputs=None):
<add> """
<add> Profile a spaCy pipeline, to find out which functions take the most time.
<add> """
<add> nlp = spacy.load(lang)
<add> texts = list(cytoolz.take(10000, inputs))
<add> cProfile.runctx("parse_texts(nlp, texts)", globals(), locals(), "Profile.prof")
<add> s = pstats.Stats("Profile.prof")
<add> s.strip_dirs().sort_stats("time").print_stats()
<add>
<add>
<add>def parse_texts(nlp, texts):
<add> for doc in nlp.pipe(tqdm.tqdm(texts), batch_size=128):
<add> pass | 2 |
Python | Python | fix typo in config | 4112bcec5d2e31ed377db26470b194a4a71f6d72 | <ide><path>airflow/configuration.py
<ide> def get(self, section, key, **kwargs):
<ide> d = self.defaults
<ide>
<ide> # environment variables get precedence
<del> # must have format AIRFLOW__{SESTION}__{KEY} (note double underscore)
<add> # must have format AIRFLOW__{SECTION}__{KEY} (note double underscore)
<ide> env_var = 'AIRFLOW__{S}__{K}'.format(S=section.upper(), K=key.upper())
<ide> if env_var in os.environ:
<ide> return expand_env_var(os.environ[env_var]) | 1 |
PHP | PHP | add blank lines between test methods | a8236fa1efaef9c23a763068d012e53a663bfe68 | <ide><path>tests/View/ViewBladeCompilerTest.php
<ide> public function testRetrieveDefaultEscapedContentTags()
<ide> $this->assertEquals(['{{{', '}}}'], $compiler->getEscapedContentTags());
<ide> }
<ide>
<add>
<ide> public function testSequentialCompileStringCalls()
<ide> {
<ide> $compiler = new BladeCompiler($this->getFiles(), __DIR__); | 1 |
Python | Python | fix use of python 2.6 deprecated escape sequences | d7d3e212ce1ff176c718485aed889c77a48ef88f | <ide><path>numpy/core/code_generators/genapi.py
<ide> def fullapi_hash(api_dicts):
<ide>
<ide> # To parse strings like 'hex = checksum' where hex is e.g. 0x1234567F and
<ide> # checksum a 128 bits md5 checksum (hex format as well)
<del>VERRE = re.compile('(^0x[\da-f]{8})\s*=\s*([\da-f]{32})')
<add>VERRE = re.compile(r'(^0x[\da-f]{8})\s*=\s*([\da-f]{32})')
<ide>
<ide> def get_versions_hash():
<ide> d = []
<ide><path>numpy/lib/function_base.py
<ide> def gradient(f, *varargs, **kwargs):
<ide> + \\left(h_{d}^{2} - h_{s}^{2}\\right)f\\left(x_{i}\\right)
<ide> - h_{d}^{2}f\\left(x_{i}-h_{s}\\right)}
<ide> { h_{s}h_{d}\\left(h_{d} + h_{s}\\right)}
<del> + \mathcal{O}\\left(\\frac{h_{d}h_{s}^{2}
<add> + \\mathcal{O}\\left(\\frac{h_{d}h_{s}^{2}
<ide> + h_{s}h_{d}^{2}}{h_{d}
<ide> + h_{s}}\\right)
<ide>
<ide> def gradient(f, *varargs, **kwargs):
<ide>
<ide> \\hat f_{i}^{(1)}=
<ide> \\frac{f\\left(x_{i+1}\\right) - f\\left(x_{i-1}\\right)}{2h}
<del> + \mathcal{O}\\left(h^{2}\\right)
<add> + \\mathcal{O}\\left(h^{2}\\right)
<ide>
<ide> With a similar procedure the forward/backward approximations used for
<ide> boundaries can be derived. | 2 |
Text | Text | move hostconfig.mounts to correct api version | cd73ceffd84d6d3af695a70485ca0d7899d0475a | <ide><path>docs/reference/api/docker_remote_api_v1.24.md
<ide> Create a container
<ide> "StorageOpt": {},
<ide> "CgroupParent": "",
<ide> "VolumeDriver": "",
<del> "ShmSize": 67108864,
<del> "Mounts": []
<add> "ShmSize": 67108864
<ide> },
<ide> "NetworkingConfig": {
<ide> "EndpointsConfig": {
<ide> Return low-level information on the container `id`
<ide> "VolumesFrom": null,
<ide> "Ulimits": [{}],
<ide> "VolumeDriver": "",
<del> "ShmSize": 67108864,
<del> "Mounts": []
<add> "ShmSize": 67108864
<ide> },
<ide> "HostnamePath": "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hostname",
<ide> "HostsPath": "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hosts",
<ide><path>docs/reference/api/docker_remote_api_v1.25.md
<ide> Create a container
<ide> "StorageOpt": {},
<ide> "CgroupParent": "",
<ide> "VolumeDriver": "",
<del> "ShmSize": 67108864
<add> "ShmSize": 67108864,
<add> "Mounts": []
<ide> },
<ide> "NetworkingConfig": {
<ide> "EndpointsConfig": {
<ide> Return low-level information on the container `id`
<ide> "VolumesFrom": null,
<ide> "Ulimits": [{}],
<ide> "VolumeDriver": "",
<del> "ShmSize": 67108864
<add> "ShmSize": 67108864,
<add> "Mounts": []
<ide> },
<ide> "HostnamePath": "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hostname",
<ide> "HostsPath": "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hosts", | 2 |
Javascript | Javascript | fix argument order for assert.strictequal | 446aadd2e23bb91709644c493f20f7c5ae103ff8 | <ide><path>test/sequential/test-inspector-scriptparsed-context.js
<ide> async function runTests() {
<ide> await session.waitForBreakOnLine(0, 'evalmachine.<anonymous>');
<ide>
<ide> await session.runToCompletion();
<del> assert.strictEqual(0, (await instance.expectShutdown()).exitCode);
<add> assert.strictEqual((await instance.expectShutdown()).exitCode, 0);
<ide> }
<ide>
<ide> runTests(); | 1 |
Text | Text | fix lint errors for docs/api | 9bfefed90bf9954be773c85a408decd6e2e355b9 | <ide><path>docs/api/Store.md
<ide> To learn how to describe asynchronous API calls, read the current state inside a
<ide> #### Example
<ide>
<ide> ```js
<del>import { createStore } from 'redux';
<del>let store = createStore(todos, ['Use Redux']);
<add>import { createStore } from 'redux'
<add>let store = createStore(todos, [ 'Use Redux' ])
<ide>
<ide> function addTodo(text) {
<ide> return {
<ide> type: 'ADD_TODO',
<ide> text
<del> };
<add> }
<ide> }
<ide>
<del>store.dispatch(addTodo('Read the docs'));
<del>store.dispatch(addTodo('Read about the middleware'));
<add>store.dispatch(addTodo('Read the docs'))
<add>store.dispatch(addTodo('Read about the middleware'))
<ide> ```
<ide>
<ide> <hr>
<ide> To unsubscribe the change listener, invoke the function returned by `subscribe`.
<ide>
<ide> ```js
<ide> function select(state) {
<del> return state.some.deep.property;
<add> return state.some.deep.property
<ide> }
<ide>
<del>let currentValue;
<add>let currentValue
<ide> function handleChange() {
<del> let previousValue = currentValue;
<del> currentValue = select(store.getState());
<add> let previousValue = currentValue
<add> currentValue = select(store.getState())
<ide>
<ide> if (previousValue !== currentValue) {
<del> console.log('Some deep nested property changed from', previousValue, 'to', currentValue);
<add> console.log('Some deep nested property changed from', previousValue, 'to', currentValue)
<ide> }
<ide> }
<ide>
<del>let unsubscribe = store.subscribe(handleChange);
<del>handleChange();
<add>let unsubscribe = store.subscribe(handleChange)
<add>handleChange()
<ide> ```
<ide>
<ide> <hr>
<ide><path>docs/api/applyMiddleware.md
<ide> Middleware is not baked into [`createStore`](createStore.md) and is not a fundam
<ide> #### Example: Custom Logger Middleware
<ide>
<ide> ```js
<del>import { createStore, applyMiddleware } from 'redux';
<del>import todos from './reducers';
<add>import { createStore, applyMiddleware } from 'redux'
<add>import todos from './reducers'
<ide>
<ide> function logger({ getState }) {
<ide> return (next) => (action) => {
<del> console.log('will dispatch', action);
<add> console.log('will dispatch', action)
<ide>
<ide> // Call the next dispatch method in the middleware chain.
<del> let returnValue = next(action);
<add> let returnValue = next(action)
<ide>
<del> console.log('state after dispatch', getState());
<add> console.log('state after dispatch', getState())
<ide>
<ide> // This will likely be the action itself, unless
<ide> // a middleware further in chain changed it.
<del> return returnValue;
<del> };
<add> return returnValue
<add> }
<ide> }
<ide>
<del>let createStoreWithMiddleware = applyMiddleware(logger)(createStore);
<del>let store = createStoreWithMiddleware(todos, ['Use Redux']);
<add>let createStoreWithMiddleware = applyMiddleware(logger)(createStore)
<add>let store = createStoreWithMiddleware(todos, [ 'Use Redux' ])
<ide>
<ide> store.dispatch({
<ide> type: 'ADD_TODO',
<ide> text: 'Understand the middleware'
<del>});
<add>})
<ide> // (These lines will be logged by the middleware:)
<ide> // will dispatch: { type: 'ADD_TODO', text: 'Understand the middleware' }
<del>// state after dispatch: ['Use Redux', 'Understand the middleware']
<add>// state after dispatch: [ 'Use Redux', 'Understand the middleware' ]
<ide> ```
<ide>
<ide> #### Example: Using Thunk Middleware for Async Actions
<ide>
<ide> ```js
<del>import { createStore, combineReducers, applyMiddleware } from 'redux';
<del>import thunk from 'redux-thunk';
<del>import * as reducers from './reducers';
<add>import { createStore, combineReducers, applyMiddleware } from 'redux'
<add>import thunk from 'redux-thunk'
<add>import * as reducers from './reducers'
<ide>
<ide> // applyMiddleware supercharges createStore with middleware:
<del>let createStoreWithMiddleware = applyMiddleware(thunk)(createStore);
<add>let createStoreWithMiddleware = applyMiddleware(thunk)(createStore)
<ide>
<ide> // We can use it exactly like “vanilla” createStore.
<del>let reducer = combineReducers(reducers);
<del>let store = createStoreWithMiddleware(reducer);
<add>let reducer = combineReducers(reducers)
<add>let store = createStoreWithMiddleware(reducer)
<ide>
<ide> function fetchSecretSauce() {
<del> return fetch('https://www.google.com/search?q=secret+sauce');
<add> return fetch('https://www.google.com/search?q=secret+sauce')
<ide> }
<ide>
<ide> // These are the normal action creators you have seen so far.
<ide> function makeASandwich(forPerson, secretSauce) {
<ide> type: 'MAKE_SANDWICH',
<ide> forPerson,
<ide> secretSauce
<del> };
<add> }
<ide> }
<ide>
<ide> function apologize(fromPerson, toPerson, error) {
<ide> function apologize(fromPerson, toPerson, error) {
<ide> fromPerson,
<ide> toPerson,
<ide> error
<del> };
<add> }
<ide> }
<ide>
<ide> function withdrawMoney(amount) {
<ide> return {
<ide> type: 'WITHDRAW',
<ide> amount
<del> };
<add> }
<ide> }
<ide>
<ide> // Even without middleware, you can dispatch an action:
<del>store.dispatch(withdrawMoney(100));
<add>store.dispatch(withdrawMoney(100))
<ide>
<ide> // But what do you do when you need to start an asynchronous action,
<ide> // such as an API call, or a router transition?
<ide> function makeASandwichWithSecretSauce(forPerson) {
<ide> return fetchSecretSauce().then(
<ide> sauce => dispatch(makeASandwich(forPerson, sauce)),
<ide> error => dispatch(apologize('The Sandwich Shop', forPerson, error))
<del> );
<del> };
<add> )
<add> }
<ide> }
<ide>
<ide> // Thunk middleware lets me dispatch thunk async actions
<ide> // as if they were actions!
<ide>
<ide> store.dispatch(
<ide> makeASandwichWithSecretSauce('Me')
<del>);
<add>)
<ide>
<ide> // It even takes care to return the thunk’s return value
<ide> // from the dispatch, so I can chain Promises as long as I return them.
<ide>
<ide> store.dispatch(
<ide> makeASandwichWithSecretSauce('My wife')
<ide> ).then(() => {
<del> console.log('Done!');
<del>});
<add> console.log('Done!')
<add>})
<ide>
<ide> // In fact I can write action creators that dispatch
<ide> // actions and async actions from other action creators,
<ide> function makeSandwichesForEverybody() {
<ide> // You don’t have to return Promises, but it’s a handy convention
<ide> // so the caller can always call .then() on async dispatch result.
<ide>
<del> return Promise.resolve();
<add> return Promise.resolve()
<ide> }
<ide>
<ide> // We can dispatch both plain object actions and other thunks,
<ide> function makeSandwichesForEverybody() {
<ide> withdrawMoney(42) :
<ide> apologize('Me', 'The Sandwich Shop')
<ide> )
<del> );
<del> };
<add> )
<add> }
<ide> }
<ide>
<ide> // This is very useful for server side rendering, because I can wait
<ide> // until data is available, then synchronously render the app.
<ide>
<del>import { renderToString } from 'react-dom/server';
<add>import { renderToString } from 'react-dom/server'
<ide>
<ide> store.dispatch(
<ide> makeSandwichesForEverybody()
<ide> ).then(() =>
<ide> response.send(renderToString(<MyApp store={store} />))
<del>);
<add>)
<ide>
<ide> // I can also dispatch a thunk async action from a component
<ide> // any time its props change to load the missing data.
<ide>
<del>import { connect } from 'react-redux';
<del>import { Component } from 'react';
<add>import { connect } from 'react-redux'
<add>import { Component } from 'react'
<ide>
<ide> class SandwichShop extends Component {
<ide> componentDidMount() {
<ide> this.props.dispatch(
<ide> makeASandwichWithSecretSauce(this.props.forPerson)
<del> );
<add> )
<ide> }
<ide>
<ide> componentWillReceiveProps(nextProps) {
<ide> if (nextProps.forPerson !== this.props.forPerson) {
<ide> this.props.dispatch(
<ide> makeASandwichWithSecretSauce(nextProps.forPerson)
<del> );
<add> )
<ide> }
<ide> }
<ide>
<ide> export default connect(
<ide> state => ({
<ide> sandwiches: state.sandwiches
<ide> })
<del>)(SandwichShop);
<add>)(SandwichShop)
<ide> ```
<ide>
<ide> #### Tips
<ide> export default connect(
<ide> * If you want to conditionally apply a middleware, make sure to only import it when it’s needed:
<ide>
<ide> ```js
<del> let middleware = [a, b];
<add> let middleware = [ a, b ]
<ide> if (process.env.NODE_ENV !== 'production') {
<ide> let c = require('some-debug-middleware');
<ide> let d = require('another-debug-middleware');
<del> middleware = [...middleware, c, d];
<add> middleware = [ ...middleware, c, d ];
<ide> }
<ide> const createStoreWithMiddleware = applyMiddleware(...middleware)(createStore);
<ide> ```
<ide><path>docs/api/bindActionCreators.md
<ide> export function addTodo(text) {
<ide> return {
<ide> type: 'ADD_TODO',
<ide> text
<del> };
<add> }
<ide> }
<ide>
<ide> export function removeTodo(id) {
<ide> return {
<ide> type: 'REMOVE_TODO',
<ide> id
<del> };
<add> }
<ide> }
<ide> ```
<ide>
<ide> #### `SomeComponent.js`
<ide>
<ide> ```js
<del>import { Component } from 'react';
<del>import { bindActionCreators } from 'redux';
<del>import { connect } from 'react-redux';
<add>import { Component } from 'react'
<add>import { bindActionCreators } from 'redux'
<add>import { connect } from 'react-redux'
<ide>
<del>import * as TodoActionCreators from './TodoActionCreators';
<del>console.log(TodoActionCreators);
<add>import * as TodoActionCreators from './TodoActionCreators'
<add>console.log(TodoActionCreators)
<ide> // {
<ide> // addTodo: Function,
<ide> // removeTodo: Function
<ide> console.log(TodoActionCreators);
<ide> class TodoListContainer extends Component {
<ide> componentDidMount() {
<ide> // Injected by react-redux:
<del> let { dispatch } = this.props;
<add> let { dispatch } = this.props
<ide>
<ide> // Note: this won’t work:
<del> // TodoActionCreators.addTodo('Use Redux');
<add> // TodoActionCreators.addTodo('Use Redux')
<ide>
<ide> // You’re just calling a function that creates an action.
<ide> // You must dispatch the action, too!
<ide>
<ide> // This will work:
<del> let action = TodoActionCreators.addTodo('Use Redux');
<del> dispatch(action);
<add> let action = TodoActionCreators.addTodo('Use Redux')
<add> dispatch(action)
<ide> }
<ide>
<ide> render() {
<ide> // Injected by react-redux:
<del> let { todos, dispatch } = this.props;
<add> let { todos, dispatch } = this.props
<ide>
<ide> // Here’s a good use case for bindActionCreators:
<ide> // You want a child component to be completely unaware of Redux.
<ide>
<del> let boundActionCreators = bindActionCreators(TodoActionCreators, dispatch);
<del> console.log(boundActionCreators);
<add> let boundActionCreators = bindActionCreators(TodoActionCreators, dispatch)
<add> console.log(boundActionCreators)
<ide> // {
<ide> // addTodo: Function,
<ide> // removeTodo: Function
<ide> class TodoListContainer extends Component {
<ide> return (
<ide> <TodoList todos={todos}
<ide> {...boundActionCreators} />
<del> );
<add> )
<ide>
<ide> // An alternative to bindActionCreators is to pass
<ide> // just the dispatch function down, but then your child component
<ide> // needs to import action creators and know about them.
<ide>
<del> // return <TodoList todos={todos} dispatch={dispatch} />;
<add> // return <TodoList todos={todos} dispatch={dispatch} />
<ide> }
<ide> }
<ide>
<ide> export default connect(
<ide> state => ({ todos: state.todos })
<del>)(TodoListContainer);
<add>)(TodoListContainer)
<ide> ```
<ide>
<ide> #### Tips
<ide><path>docs/api/combineReducers.md
<ide> While `combineReducers` attempts to check that your reducers conform to some of
<ide> ```js
<ide> export default function todos(state = [], action) {
<ide> switch (action.type) {
<del> case 'ADD_TODO':
<del> return state.concat([action.text]);
<del> default:
<del> return state;
<add> case 'ADD_TODO':
<add> return state.concat([ action.text ])
<add> default:
<add> return state
<ide> }
<ide> }
<ide> ```
<ide> export default function todos(state = [], action) {
<ide> ```js
<ide> export default function counter(state = 0, action) {
<ide> switch (action.type) {
<del> case 'INCREMENT':
<del> return state + 1;
<del> case 'DECREMENT':
<del> return state - 1;
<del> default:
<del> return state;
<add> case 'INCREMENT':
<add> return state + 1
<add> case 'DECREMENT':
<add> return state - 1
<add> default:
<add> return state
<ide> }
<ide> }
<ide> ```
<ide>
<ide> #### `reducers/index.js`
<ide>
<ide> ```js
<del>import { combineReducers } from 'redux';
<del>import todos from './todos';
<del>import counter from './counter';
<add>import { combineReducers } from 'redux'
<add>import todos from './todos'
<add>import counter from './counter'
<ide>
<ide> export default combineReducers({
<ide> todos,
<ide> counter
<del>});
<add>})
<ide> ```
<ide>
<ide> #### `App.js`
<ide>
<ide> ```js
<del>import { createStore } from 'redux';
<del>import reducer from './reducers/index';
<add>import { createStore } from 'redux'
<add>import reducer from './reducers/index'
<ide>
<del>let store = createStore(reducer);
<del>console.log(store.getState());
<add>let store = createStore(reducer)
<add>console.log(store.getState())
<ide> // {
<ide> // counter: 0,
<ide> // todos: []
<ide> console.log(store.getState());
<ide> store.dispatch({
<ide> type: 'ADD_TODO',
<ide> text: 'Use Redux'
<del>});
<del>console.log(store.getState());
<add>})
<add>console.log(store.getState())
<ide> // {
<ide> // counter: 0,
<del>// todos: ['Use Redux']
<add>// todos: [ 'Use Redux' ]
<ide> // }
<ide> ```
<ide>
<ide><path>docs/api/compose.md
<ide> You might want to use it to apply several [store enhancers](../Glossary.md#store
<ide> This example demonstrates how to use `compose` to enhance a [store](Store.md) with [`applyMiddleware`](applyMiddleware.md) and a few developer tools from the [redux-devtools](https://github.com/gaearon/redux-devtools) package.
<ide>
<ide> ```js
<del>import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
<del>import thunk from 'redux-thunk';
<del>import * as reducers from '../reducers/index';
<add>import { createStore, combineReducers, applyMiddleware, compose } from 'redux'
<add>import thunk from 'redux-thunk'
<add>import * as reducers from '../reducers/index'
<ide>
<del>let reducer = combineReducers(reducers);
<del>let middleware = [thunk];
<add>let reducer = combineReducers(reducers)
<add>let middleware = [ thunk ]
<ide>
<del>let finalCreateStore;
<add>let finalCreateStore
<ide>
<ide> // In production, we want to use just the middleware.
<ide> // In development, we want to use some store enhancers from redux-devtools.
<ide> // UglifyJS will eliminate the dead code depending on the build environment.
<ide>
<ide> if (process.env.NODE_ENV === 'production') {
<del> finalCreateStore = applyMiddleware(...middleware)(createStore);
<add> finalCreateStore = applyMiddleware(...middleware)(createStore)
<ide> } else {
<ide> finalCreateStore = compose(
<ide> applyMiddleware(...middleware),
<ide> require('redux-devtools').devTools(),
<ide> require('redux-devtools').persistState(
<ide> window.location.href.match(/[?&]debug_session=([^&]+)\b/)
<ide> )
<del> )(createStore);
<add> )(createStore)
<ide>
<ide> // Same code without the `compose` helper:
<ide> //
<ide> if (process.env.NODE_ENV === 'production') {
<ide> // window.location.href.match(/[?&]debug_session=([^&]+)\b/)
<ide> // )(createStore)
<ide> // )
<del> // );
<add> // )
<ide> }
<ide>
<del>let store = finalCreateStore(reducer);
<add>let store = finalCreateStore(reducer)
<ide> ```
<ide>
<ide> #### Tips
<ide><path>docs/api/createStore.md
<ide> There should only be a single store in your app.
<ide> #### Example
<ide>
<ide> ```js
<del>import { createStore } from 'redux';
<add>import { createStore } from 'redux'
<ide>
<ide> function todos(state = [], action) {
<ide> switch (action.type) {
<del> case 'ADD_TODO':
<del> return state.concat([action.text]);
<del> default:
<del> return state;
<add> case 'ADD_TODO':
<add> return state.concat([ action.text ])
<add> default:
<add> return state
<ide> }
<ide> }
<ide>
<del>let store = createStore(todos, ['Use Redux']);
<add>let store = createStore(todos, [ 'Use Redux' ])
<ide>
<ide> store.dispatch({
<ide> type: 'ADD_TODO',
<ide> text: 'Read the docs'
<del>});
<add>})
<ide>
<del>console.log(store.getState());
<del>// ['Use Redux', 'Read the docs']
<add>console.log(store.getState())
<add>// [ 'Use Redux', 'Read the docs' ]
<ide> ```
<ide>
<ide> #### Tips | 6 |
Go | Go | add tail and since to service logs | 8dc437bd9b474c24a2cf802c2779dace2f91194a | <ide><path>cli/command/service/logs.go
<ide> func newLogsCommand(dockerCli *command.DockerCli) *cobra.Command {
<ide> flags := cmd.Flags()
<ide> flags.BoolVar(&opts.noResolve, "no-resolve", false, "Do not map IDs to Names")
<ide> flags.BoolVarP(&opts.follow, "follow", "f", false, "Follow log output")
<del> flags.StringVar(&opts.since, "since", "", "Show logs since timestamp")
<add> flags.StringVar(&opts.since, "since", "", "Show logs since timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)")
<ide> flags.BoolVarP(&opts.timestamps, "timestamps", "t", false, "Show timestamps")
<ide> flags.BoolVar(&opts.details, "details", false, "Show extra details provided to logs")
<ide> flags.StringVar(&opts.tail, "tail", "all", "Number of lines to show from the end of the logs")
<ide><path>daemon/cluster/executor/container/adapter.go
<ide> func (c *containerAdapter) logs(ctx context.Context, options api.LogSubscription
<ide> if err != nil {
<ide> return nil, err
<ide> }
<del> apiOptions.Since = since.Format(time.RFC3339Nano)
<add> // print since as this formatted string because the docker container
<add> // logs interface expects it like this.
<add> // see github.com/docker/docker/api/types/time.ParseTimestamps
<add> apiOptions.Since = fmt.Sprintf("%d.%09d", since.Unix(), int64(since.Nanosecond()))
<ide> }
<ide>
<ide> if options.Tail < 0 {
<ide><path>daemon/cluster/services.go
<ide> import (
<ide> "fmt"
<ide> "io"
<ide> "os"
<add> "strconv"
<ide> "strings"
<add> "time"
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/distribution/reference"
<ide> apierrors "github.com/docker/docker/api/errors"
<ide> apitypes "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/backend"
<ide> types "github.com/docker/docker/api/types/swarm"
<add> timetypes "github.com/docker/docker/api/types/time"
<ide> "github.com/docker/docker/daemon/cluster/convert"
<ide> "github.com/docker/docker/daemon/logger"
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> func (c *Cluster) ServiceLogs(ctx context.Context, input string, config *backend
<ide> stdStreams = append(stdStreams, swarmapi.LogStreamStderr)
<ide> }
<ide>
<add> // Get tail value squared away - the number of previous log lines we look at
<add> var tail int64
<add> if config.Tail == "all" {
<add> // tail of 0 means send all logs on the swarmkit side
<add> tail = 0
<add> } else {
<add> t, err := strconv.Atoi(config.Tail)
<add> if err != nil {
<add> return errors.New("tail value must be a positive integer or \"all\"")
<add> }
<add> if t < 0 {
<add> return errors.New("negative tail values not supported")
<add> }
<add> // we actually use negative tail in swarmkit to represent messages
<add> // backwards starting from the beginning. also, -1 means no logs. so,
<add> // basically, for api compat with docker container logs, add one and
<add> // flip the sign. we error above if you try to negative tail, which
<add> // isn't supported by docker (and would error deeper in the stack
<add> // anyway)
<add> //
<add> // See the logs protobuf for more information
<add> tail = int64(-(t + 1))
<add> }
<add>
<add> // get the since value - the time in the past we're looking at logs starting from
<add> var sinceProto *gogotypes.Timestamp
<add> if config.Since != "" {
<add> s, n, err := timetypes.ParseTimestamps(config.Since, 0)
<add> if err != nil {
<add> return errors.Wrap(err, "could not parse since timestamp")
<add> }
<add> since := time.Unix(s, n)
<add> sinceProto, err = gogotypes.TimestampProto(since)
<add> if err != nil {
<add> return errors.Wrap(err, "could not parse timestamp to proto")
<add> }
<add> }
<add>
<ide> stream, err := state.logsClient.SubscribeLogs(ctx, &swarmapi.SubscribeLogsRequest{
<ide> Selector: &swarmapi.LogSelector{
<ide> ServiceIDs: []string{service.ID},
<ide> },
<ide> Options: &swarmapi.LogSubscriptionOptions{
<ide> Follow: config.Follow,
<ide> Streams: stdStreams,
<add> Tail: tail,
<add> Since: sinceProto,
<ide> },
<ide> })
<ide> if err != nil {
<ide><path>integration-cli/docker_cli_service_logs_experimental_test.go
<ide> import (
<ide> "io"
<ide> "os/exec"
<ide> "strings"
<add> "time"
<ide>
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/daemon"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> func (s *DockerSwarmSuite) TestServiceLogs(c *check.C) {
<ide> }
<ide> }
<ide>
<add>// countLogLines returns a closure that can be used with waitAndAssert to
<add>// verify that a minimum number of expected container log messages have been
<add>// output.
<add>func countLogLines(d *daemon.Swarm, name string) func(*check.C) (interface{}, check.CommentInterface) {
<add> return func(c *check.C) (interface{}, check.CommentInterface) {
<add> out, err := d.Cmd("service", "logs", "-t", name)
<add> c.Assert(err, checker.IsNil)
<add> lines := strings.Split(strings.TrimSpace(out), "\n")
<add> return len(lines), check.Commentf("output, %q", string(out))
<add> }
<add>}
<add>
<add>func (s *DockerSwarmSuite) TestServiceLogsCompleteness(c *check.C) {
<add> testRequires(c, ExperimentalDaemon)
<add> d := s.AddDaemon(c, true, true)
<add>
<add> name := "TestServiceLogsCompleteness"
<add>
<add> // make a service that prints 6 lines
<add> out, err := d.Cmd("service", "create", "--name", name, "busybox", "sh", "-c", "for line in $(seq 1 6); do echo log test $line; done; sleep 100000")
<add> c.Assert(err, checker.IsNil)
<add> c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
<add>
<add> // make sure task has been deployed.
<add> waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
<add> // and make sure we have all the log lines
<add> waitAndAssert(c, defaultReconciliationTimeout, countLogLines(d, name), checker.Equals, 6)
<add>
<add> args := []string{"service", "logs", name}
<add> cmd := exec.Command(dockerBinary, d.PrependHostArg(args)...)
<add> r, w := io.Pipe()
<add> cmd.Stdout = w
<add> cmd.Stderr = w
<add> c.Assert(cmd.Start(), checker.IsNil)
<add>
<add> reader := bufio.NewReader(r)
<add> // i have heard anecdotal reports that logs may come back from the engine
<add> // mis-ordered. if this tests fails, consider the possibility that that
<add> // might be occurring
<add> for i := 1; i <= 6; i++ {
<add> msg := &logMessage{}
<add> msg.data, _, msg.err = reader.ReadLine()
<add> c.Assert(msg.err, checker.IsNil)
<add> c.Assert(string(msg.data), checker.Contains, fmt.Sprintf("log test %v", i))
<add> }
<add>}
<add>
<add>func (s *DockerSwarmSuite) TestServiceLogsTail(c *check.C) {
<add> testRequires(c, ExperimentalDaemon)
<add> d := s.AddDaemon(c, true, true)
<add>
<add> name := "TestServiceLogsTail"
<add>
<add> // make a service that prints 6 lines
<add> out, err := d.Cmd("service", "create", "--name", name, "busybox", "sh", "-c", "for line in $(seq 1 6); do echo log test $line; done; sleep 100000")
<add> c.Assert(err, checker.IsNil)
<add> c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
<add>
<add> // make sure task has been deployed.
<add> waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
<add> waitAndAssert(c, defaultReconciliationTimeout, countLogLines(d, name), checker.Equals, 6)
<add>
<add> args := []string{"service", "logs", "--tail=2", name}
<add> cmd := exec.Command(dockerBinary, d.PrependHostArg(args)...)
<add> r, w := io.Pipe()
<add> cmd.Stdout = w
<add> cmd.Stderr = w
<add> c.Assert(cmd.Start(), checker.IsNil)
<add>
<add> reader := bufio.NewReader(r)
<add> // see TestServiceLogsCompleteness for comments about logs being well-
<add> // ordered, if this flakes
<add> for i := 5; i <= 6; i++ {
<add> msg := &logMessage{}
<add> msg.data, _, msg.err = reader.ReadLine()
<add> c.Assert(msg.err, checker.IsNil)
<add> c.Assert(string(msg.data), checker.Contains, fmt.Sprintf("log test %v", i))
<add> }
<add>}
<add>
<add>func (s *DockerSwarmSuite) TestServiceLogsSince(c *check.C) {
<add> // See DockerSuite.TestLogsSince, which is where this comes from
<add> testRequires(c, ExperimentalDaemon)
<add> d := s.AddDaemon(c, true, true)
<add>
<add> name := "TestServiceLogsSince"
<add>
<add> out, err := d.Cmd("service", "create", "--name", name, "busybox", "sh", "-c", "for i in $(seq 1 3); do sleep .1; echo log$i; done; sleep 10000000")
<add> c.Assert(err, checker.IsNil)
<add> c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
<add> waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
<add> // wait a sec for the logs to come in
<add> waitAndAssert(c, defaultReconciliationTimeout, countLogLines(d, name), checker.Equals, 3)
<add>
<add> out, err = d.Cmd("service", "logs", "-t", name)
<add> c.Assert(err, checker.IsNil)
<add>
<add> log2Line := strings.Split(strings.Split(out, "\n")[1], " ")
<add> t, err := time.Parse(time.RFC3339Nano, log2Line[0]) // timestamp log2 is written
<add> c.Assert(err, checker.IsNil)
<add> u := t.Add(50 * time.Millisecond) // add .05s so log1 & log2 don't show up
<add> since := u.Format(time.RFC3339Nano)
<add>
<add> out, err = d.Cmd("service", "logs", "-t", fmt.Sprintf("--since=%v", since), name)
<add> c.Assert(err, checker.IsNil)
<add>
<add> unexpected := []string{"log1", "log2"}
<add> expected := []string{"log3"}
<add> for _, v := range unexpected {
<add> c.Assert(out, checker.Not(checker.Contains), v, check.Commentf("unexpected log message returned, since=%v", u))
<add> }
<add> for _, v := range expected {
<add> c.Assert(out, checker.Contains, v, check.Commentf("expected log message %v, was not present, since=%v", u))
<add> }
<add>}
<add>
<ide> func (s *DockerSwarmSuite) TestServiceLogsFollow(c *check.C) {
<ide> testRequires(c, ExperimentalDaemon)
<ide> | 4 |
PHP | PHP | add minor changes to http client | 380d8c692b1448c6b701cc3c94abf98c81715e54 | <ide><path>src/Illuminate/Http/Client/Factory.php
<ide> namespace Illuminate\Http\Client;
<ide>
<ide> use Closure;
<add>use GuzzleHttp\Psr7\Response as Psr7Response;
<ide> use Illuminate\Support\Str;
<ide> use Illuminate\Support\Traits\Macroable;
<ide> use PHPUnit\Framework\Assert as PHPUnit;
<add>use function GuzzleHttp\Promise\promise_for;
<ide>
<ide> class Factory
<ide> {
<ide> class Factory
<ide> /**
<ide> * The stub callables that will handle requests.
<ide> *
<del> * @var \Illuminate\Support\Collection|null
<add> * @var \Illuminate\Support\Collection
<ide> */
<ide> protected $stubCallbacks;
<ide>
<ide> class Factory
<ide> */
<ide> protected $responseSequences = [];
<ide>
<add> /**
<add> * The record array.
<add> *
<add> * @var array
<add> */
<add> protected $recorded;
<add>
<ide> /**
<ide> * Create a new factory instance.
<ide> *
<ide> public static function response($body = null, $status = 200, $headers = [])
<ide> $headers['Content-Type'] = 'application/json';
<ide> }
<ide>
<del> return \GuzzleHttp\Promise\promise_for(new \GuzzleHttp\Psr7\Response($status, $headers, $body));
<add> return promise_for(new Psr7Response($status, $headers, $body));
<ide> }
<ide>
<ide> /**
<ide> public function fake($callback = null)
<ide> $this->stubUrl($url, $callable);
<ide> }
<ide>
<del> return;
<add> return $this;
<ide> }
<ide>
<ide> $this->stubCallbacks = $this->stubCallbacks->merge(collect([
<ide><path>src/Illuminate/Http/Client/Request.php
<ide> public function __construct($request)
<ide> /**
<ide> * Get the request method.
<ide> *
<del> * @return strign
<add> * @return string
<ide> */
<ide> public function method()
<ide> {
<ide> public function hasHeader($key, $value = null)
<ide> /**
<ide> * Get the values for the header with the given name.
<ide> *
<add> * @param string $key
<ide> * @return array
<ide> */
<ide> public function header($key)
<ide><path>src/Illuminate/Http/Client/Response.php
<ide> public function json()
<ide> /**
<ide> * Get a header from the response.
<ide> *
<add> * @param string $header
<ide> * @return string
<ide> */
<ide> public function header(string $header)
<ide> public function redirect()
<ide> }
<ide>
<ide> /**
<del> * Detemine if the response indicates a client error occurred.
<add> * Determine if the response indicates a client error occurred.
<ide> *
<ide> * @return bool
<ide> */
<ide> public function clientError()
<ide> }
<ide>
<ide> /**
<del> * Detemine if the response indicates a server error occurred.
<add> * Determine if the response indicates a server error occurred.
<ide> *
<ide> * @return bool
<ide> */
<ide> public function toPsrResponse()
<ide> * Throw an exception if a server or client error occurred.
<ide> *
<ide> * @return $this
<add> *
<add> * @throws \Illuminate\Http\Client\RequestException
<ide> */
<ide> public function throw()
<ide> {
<ide><path>src/Illuminate/Http/Client/ResponseSequence.php
<ide> class ResponseSequence
<ide> protected $failWhenEmpty = true;
<ide>
<ide> /**
<del> * The repsonse that should be returned when the sequence is empty.
<add> * The response that should be returned when the sequence is empty.
<ide> *
<ide> * @var \GuzzleHttp\Promise\PromiseInterface
<ide> */
<ide> public function __construct(array $responses)
<ide> */
<ide> public function push($body = '', int $status = 200, array $headers = [])
<ide> {
<del> if (is_array($body)) {
<del> return $this->pushResponse(
<del> Factory::response(json_encode($body), $status, $headers)
<del> );
<del> }
<add> $body = is_array($body) ? json_encode($body) : $body;
<ide>
<ide> return $this->pushResponse(
<ide> Factory::response($body, $status, $headers) | 4 |
Python | Python | remove actual model downloading from tests | be9daefbdd80380a7fdb8369bf32208ef61a6615 | <ide><path>spacy/tests/test_download.py
<ide> def test_download_fetch_compatibility():
<ide> assert type(compatibility) == dict
<ide>
<ide>
<del>@pytest.mark.slow
<del>@pytest.mark.parametrize('model', ['en_core_web_md-1.2.0'])
<del>def test_download_direct_download(model):
<del> download(model, direct=True)
<del>
<del>
<ide> @pytest.mark.parametrize('model', ['en_core_web_md'])
<ide> def test_download_get_matching_version_succeeds(model):
<ide> comp = { model: ['1.7.0', '0.100.0'] } | 1 |
Python | Python | check lengths match | e50047f1c5e9949894bbba0a3183295fc79f2f2b | <ide><path>spacy/ml/models/tok2vec.py
<ide> def MultiHashEmbed(
<ide> include_static_vectors (bool): Whether to also use static word vectors.
<ide> Requires a vectors table to be loaded in the Doc objects' vocab.
<ide> """
<add> if len(rows) != len(attrs):
<add> raise ValueError(f"Mismatched lengths: {len(rows)} vs {len(attrs)}")
<ide> seed = 7
<ide>
<ide> def make_hash_embed(index): | 1 |
Javascript | Javascript | require callback in read | 8e1b6e771867fc4e89715cf22501dfe2f01cf8d0 | <ide><path>lib/fs.js
<ide> function openSync(path, flags, mode) {
<ide> function read(fd, buffer, offset, length, position, callback) {
<ide> validateUint32(fd, 'fd');
<ide> validateBuffer(buffer);
<add> callback = maybeCallback(callback);
<ide>
<ide> offset |= 0;
<ide> length |= 0;
<ide>
<ide> if (length === 0) {
<ide> return process.nextTick(function tick() {
<del> callback && callback(null, 0, buffer);
<add> callback(null, 0, buffer);
<ide> });
<ide> }
<ide>
<ide> function read(fd, buffer, offset, length, position, callback) {
<ide>
<ide> function wrapper(err, bytesRead) {
<ide> // Retain a reference to buffer so that it can't be GC'ed too soon.
<del> callback && callback(err, bytesRead || 0, buffer);
<add> callback(err, bytesRead || 0, buffer);
<ide> }
<ide>
<ide> const req = new FSReqCallback();
<ide><path>test/parallel/test-fs-read.js
<ide> test(new Uint8Array(expected.length),
<ide> // Reading beyond file length (3 in this case) should return no data.
<ide> // This is a test for a bug where reads > uint32 would return data
<ide> // from the current position in the file.
<del> const fd = fs.openSync(filepath, 'r');
<ide> const pos = 0xffffffff + 1; // max-uint32 + 1
<ide> const nRead = fs.readSync(fd, Buffer.alloc(1), 0, 1, pos);
<ide> assert.strictEqual(nRead, 0);
<ide> test(new Uint8Array(expected.length),
<ide> assert.strictEqual(nRead, 0);
<ide> }));
<ide> }
<add>
<add>assert.throws(
<add> () => fs.read(fd, Buffer.alloc(1), 0, 1, 0),
<add> {
<add> message: 'Callback must be a function',
<add> code: 'ERR_INVALID_CALLBACK',
<add> }
<add>); | 2 |
Javascript | Javascript | remove the ignorefont variable | 1de54365611f0132f9ac1a5f10ea99f03ef91f94 | <ide><path>pdf.js
<ide> var CanvasGraphics = (function() {
<ide> error("FontFile not found for font: " + fontName);
<ide> fontFile = xref.fetchIfRef(fontFile);
<ide>
<del> // Fonts with an embedded cmap but without any assignment in
<del> // it are not yet supported, so ask the fonts loader to ignore
<del> // them to not pay a stupid one sec latence.
<del> var ignoreFont = false;
<del>
<ide> var encodingMap = {};
<ide> var charset = [];
<ide> if (fontDict.has("Encoding")) {
<del> ignoreFont = false;
<del>
<ide> var encoding = xref.fetchIfRef(fontDict.get("Encoding"));
<ide> if (IsDict(encoding)) {
<ide> // Build a map between codes and glyphs
<ide> var CanvasGraphics = (function() {
<ide> break;
<ide>
<ide> case "beginbfrange":
<del> ignoreFont = false;
<ide> case "begincodespacerange":
<ide> token = "";
<ide> tokens = [];
<ide> var CanvasGraphics = (function() {
<ide> type: subType.name,
<ide> encoding: encodingMap,
<ide> charset: charset,
<del> bbox: bbox,
<del> ignore: ignoreFont
<add> bbox: bbox
<ide> };
<ide>
<ide> return { | 1 |
Ruby | Ruby | add audit for leading 'v' in version numbers | d9487a96ea9fc7b76954b5e04781d87618844ef2 | <ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit_specs
<ide> end
<ide> end
<ide>
<add> if s.version.to_s =~ /^v/
<add> problem "#{spec} version #{s.version} should not have a leading 'v'"
<add> end
<add>
<ide> cksum = s.checksum
<ide> next if cksum.nil?
<ide> | 1 |
Javascript | Javascript | replace fixturesdir in tls-env-bad-extra-ca | 4457f4feb98d891f8f9343c69c53e0a2552b35de | <ide><path>test/parallel/test-tls-env-bad-extra-ca.js
<ide> if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<ide>
<ide> const assert = require('assert');
<del>const tls = require('tls');
<add>const fixtures = require('../common/fixtures');
<ide> const fork = require('child_process').fork;
<add>const tls = require('tls');
<ide>
<ide> if (process.env.CHILD) {
<ide> // This will try to load the extra CA certs, and emit a warning when it fails.
<ide> if (process.env.CHILD) {
<ide>
<ide> const env = Object.assign({}, process.env, {
<ide> CHILD: 'yes',
<del> NODE_EXTRA_CA_CERTS: `${common.fixturesDir}/no-such-file-exists`,
<add> NODE_EXTRA_CA_CERTS: `${fixtures.fixturesDir}/no-such-file-exists`,
<ide> });
<ide>
<ide> const opts = { | 1 |
Javascript | Javascript | support custom params serializers | 6c8464ad14dd308349f632245c1a064c9aae242a | <ide><path>src/AngularPublic.js
<ide> $IntervalProvider,
<ide> $$HashMapProvider,
<ide> $HttpProvider,
<add> $HttpParamSerializerProvider,
<add> $HttpParamSerializerJQLikeProvider,
<ide> $HttpBackendProvider,
<ide> $LocationProvider,
<ide> $LogProvider,
<ide> function publishExternalAPI(angular) {
<ide> $interpolate: $InterpolateProvider,
<ide> $interval: $IntervalProvider,
<ide> $http: $HttpProvider,
<add> $httpParamSerializer: $HttpParamSerializerProvider,
<add> $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
<ide> $httpBackend: $HttpBackendProvider,
<ide> $location: $LocationProvider,
<ide> $log: $LogProvider,
<ide><path>src/ng/http.js
<ide> var JSON_ENDS = {
<ide> };
<ide> var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
<ide>
<add>function paramSerializerFactory(jQueryMode) {
<add>
<add> function serializeValue(v) {
<add> if (isObject(v)) {
<add> return isDate(v) ? v.toISOString() : toJson(v);
<add> }
<add> return v;
<add> }
<add>
<add> return function paramSerializer(params) {
<add> if (!params) return '';
<add> var parts = [];
<add> forEachSorted(params, function(value, key) {
<add> if (value === null || isUndefined(value)) return;
<add> if (isArray(value) || isObject(value) && jQueryMode) {
<add> forEach(value, function(v, k) {
<add> var keySuffix = jQueryMode ? '[' + (!isArray(value) ? k : '') + ']' : '';
<add> parts.push(encodeUriQuery(key + keySuffix) + '=' + encodeUriQuery(serializeValue(v)));
<add> });
<add> } else {
<add> parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
<add> }
<add> });
<add>
<add> return parts.length > 0 ? parts.join('&') : '';
<add> };
<add>}
<add>
<add>function $HttpParamSerializerProvider() {
<add> /**
<add> * @ngdoc service
<add> * @name $httpParamSerializer
<add> * @description
<add> *
<add> * Default $http params serializer that converts objects to a part of a request URL
<add> * according to the following rules:
<add> * * `{'foo': 'bar'}` results in `foo=bar`
<add> * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
<add> * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
<add> * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object)
<add> * */
<add> this.$get = function() {
<add> return paramSerializerFactory(false);
<add> };
<add>}
<add>
<add>function $HttpParamSerializerJQLikeProvider() {
<add> /**
<add> * @ngdoc service
<add> * @name $httpParamSerializerJQLike
<add> *
<add> * Alternative $http params serializer that follows jQuerys `param()` method {http://api.jquery.com/jquery.param/} logic.
<add> * */
<add> this.$get = function() {
<add> return paramSerializerFactory(true);
<add> };
<add>}
<add>
<ide> function defaultHttpResponseTransform(data, headers) {
<ide> if (isString(data)) {
<ide> // Strip json vulnerability protection prefix and trim whitespace
<ide> function $HttpProvider() {
<ide> * - **`defaults.headers.put`**
<ide> * - **`defaults.headers.patch`**
<ide> *
<add> * - **`defaults.paramSerializer`** - {string|function(Object<string,string>):string} - A function used to prepare string representation
<add> * of request parameters (specified as an object).
<add> * Is specified as string, it is interpreted as function registered in with the {$injector}.
<add> * Defaults to {$httpParamSerializer}.
<add> *
<ide> **/
<ide> var defaults = this.defaults = {
<ide> // transform incoming response data
<ide> function $HttpProvider() {
<ide> },
<ide>
<ide> xsrfCookieName: 'XSRF-TOKEN',
<del> xsrfHeaderName: 'X-XSRF-TOKEN'
<add> xsrfHeaderName: 'X-XSRF-TOKEN',
<add>
<add> paramSerializer: '$httpParamSerializer'
<ide> };
<ide>
<ide> var useApplyAsync = false;
<ide> function $HttpProvider() {
<ide> * significant performance improvement for bigger applications that make many HTTP requests
<ide> * concurrently (common during application bootstrap).
<ide> *
<del> * Defaults to false. If no value is specifed, returns the current configured value.
<add> * Defaults to false. If no value is specified, returns the current configured value.
<ide> *
<ide> * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
<ide> * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
<ide> function $HttpProvider() {
<ide>
<ide> var defaultCache = $cacheFactory('$http');
<ide>
<add> /**
<add> * Make sure that default param serializer is exposed as a function
<add> */
<add> defaults.paramSerializer = isString(defaults.paramSerializer) ?
<add> $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
<add>
<ide> /**
<ide> * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
<ide> * The reversal is needed so that we can build up the interception chain around the
<ide> function $HttpProvider() {
<ide> * response body, headers and status and returns its transformed (typically deserialized) version.
<ide> * See {@link ng.$http#overriding-the-default-transformations-per-request
<ide> * Overriding the Default Transformations}
<add> * - **paramSerializer** - {string|function(Object<string,string>):string} - A function used to prepare string representation
<add> * of request parameters (specified as an object).
<add> * Is specified as string, it is interpreted as function registered in with the {$injector}.
<ide> * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
<ide> * GET request, otherwise if a cache instance built with
<ide> * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
<ide> function $HttpProvider() {
<ide> var config = extend({
<ide> method: 'get',
<ide> transformRequest: defaults.transformRequest,
<del> transformResponse: defaults.transformResponse
<add> transformResponse: defaults.transformResponse,
<add> paramSerializer: defaults.paramSerializer
<ide> }, requestConfig);
<ide>
<ide> config.headers = mergeHeaders(requestConfig);
<ide> config.method = uppercase(config.method);
<add> config.paramSerializer = isString(config.paramSerializer) ?
<add> $injector.get(config.paramSerializer) : config.paramSerializer;
<ide>
<ide> var serverRequest = function(config) {
<ide> var headers = config.headers;
<ide> function $HttpProvider() {
<ide> cache,
<ide> cachedResp,
<ide> reqHeaders = config.headers,
<del> url = buildUrl(config.url, config.params);
<add> url = buildUrl(config.url, config.paramSerializer(config.params));
<ide>
<ide> $http.pendingRequests.push(config);
<ide> promise.then(removePendingReq, removePendingReq);
<ide> function $HttpProvider() {
<ide> }
<ide>
<ide>
<del> function buildUrl(url, params) {
<del> if (!params) return url;
<del> var parts = [];
<del> forEachSorted(params, function(value, key) {
<del> if (value === null || isUndefined(value)) return;
<del> if (!isArray(value)) value = [value];
<del>
<del> forEach(value, function(v) {
<del> if (isObject(v)) {
<del> if (isDate(v)) {
<del> v = v.toISOString();
<del> } else {
<del> v = toJson(v);
<del> }
<del> }
<del> parts.push(encodeUriQuery(key) + '=' +
<del> encodeUriQuery(v));
<del> });
<del> });
<del> if (parts.length > 0) {
<del> url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
<add> function buildUrl(url, serializedParams) {
<add> if (serializedParams.length > 0) {
<add> url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;
<ide> }
<ide> return url;
<ide> }
<ide><path>test/ng/httpSpec.js
<ide> describe('$http', function() {
<ide>
<ide> var callback, mockedCookies;
<add> var customParamSerializer = function(params) {
<add> return Object.keys(params).join('_');
<add> };
<ide>
<ide> beforeEach(function() {
<ide> callback = jasmine.createSpy('done');
<ide> describe('$http', function() {
<ide> });
<ide> });
<ide>
<add> beforeEach(module({
<add> customParamSerializer: customParamSerializer
<add> }));
<ide> beforeEach(module(function($exceptionHandlerProvider) {
<ide> $exceptionHandlerProvider.mode('log');
<ide> }));
<ide> describe('$http', function() {
<ide> $httpBackend.expect('GET', '/url?date=2014-07-15T17:30:00.000Z').respond('');
<ide> $http({url: '/url', params: {date:new Date('2014-07-15T17:30:00.000Z')}, method: 'GET'});
<ide> });
<add>
<add>
<add> describe('custom params serialization', function() {
<add>
<add> it('should allow specifying custom paramSerializer as function', function() {
<add> $httpBackend.expect('GET', '/url?foo_bar').respond('');
<add> $http({url: '/url', params: {foo: 'fooVal', bar: 'barVal'}, paramSerializer: customParamSerializer});
<add> });
<add>
<add> it('should allow specifying custom paramSerializer as function from DI', function() {
<add> $httpBackend.expect('GET', '/url?foo_bar').respond('');
<add> $http({url: '/url', params: {foo: 'fooVal', bar: 'barVal'}, paramSerializer: 'customParamSerializer'});
<add> });
<add> });
<ide> });
<ide>
<ide>
<ide> describe('$http', function() {
<ide> $httpBackend.flush();
<ide> });
<ide>
<del> it('should have separate opbjects for defaults PUT and POST', function() {
<add> it('should have separate objects for defaults PUT and POST', function() {
<ide> expect($http.defaults.headers.post).not.toBe($http.defaults.headers.put);
<ide> expect($http.defaults.headers.post).not.toBe($http.defaults.headers.patch);
<ide> expect($http.defaults.headers.put).not.toBe($http.defaults.headers.patch);
<ide> });
<add>
<add> it('should expose default param serializer at runtime', function() {
<add> var paramSerializer = $http.defaults.paramSerializer;
<add> expect(paramSerializer({foo: 'foo', bar: ['bar', 'baz']})).toEqual('bar=bar&bar=baz&foo=foo');
<add> });
<ide> });
<ide> });
<ide>
<ide> describe('$http with $applyAsync', function() {
<ide> expect(log).toEqual(['response 1', 'response 2', 'response 3']);
<ide> });
<ide> });
<add>
<add>describe('$http param serializers', function() {
<add>
<add> var defSer, jqrSer;
<add> beforeEach(inject(function($httpParamSerializer, $httpParamSerializerJQLike) {
<add> defSer = $httpParamSerializer;
<add> jqrSer = $httpParamSerializerJQLike;
<add> }));
<add>
<add> describe('common functionality', function() {
<add>
<add> it('should return empty string for null or undefined params', function() {
<add> expect(defSer(undefined)).toEqual('');
<add> expect(jqrSer(undefined)).toEqual('');
<add> expect(defSer(null)).toEqual('');
<add> expect(jqrSer(null)).toEqual('');
<add> });
<add>
<add> it('should serialize objects', function() {
<add> expect(defSer({foo: 'foov', bar: 'barv'})).toEqual('bar=barv&foo=foov');
<add> expect(jqrSer({foo: 'foov', bar: 'barv'})).toEqual('bar=barv&foo=foov');
<add> });
<add>
<add> });
<add>
<add> describe('default array serialization', function() {
<add>
<add> it('should serialize arrays by repeating param name', function() {
<add> expect(defSer({a: 'b', foo: ['bar', 'baz']})).toEqual('a=b&foo=bar&foo=baz');
<add> });
<add> });
<add>
<add> describe('jquery array and objects serialization', function() {
<add>
<add> it('should serialize arrays by repeating param name with [] suffix', function() {
<add> expect(jqrSer({a: 'b', foo: ['bar', 'baz']})).toEqual('a=b&foo%5B%5D=bar&foo%5B%5D=baz');
<add> expect(decodeURIComponent(jqrSer({a: 'b', foo: ['bar', 'baz']}))).toEqual('a=b&foo[]=bar&foo[]=baz');
<add> });
<add>
<add> it('should serialize objects by repeating param name with [kay] suffix', function() {
<add> expect(jqrSer({a: 'b', foo: {'bar': 'barv', 'baz': 'bazv'}})).toEqual('a=b&foo%5Bbar%5D=barv&foo%5Bbaz%5D=bazv');
<add> //a=b&foo[bar]=barv&foo[baz]=bazv
<add> });
<add> });
<add>
<add>}); | 3 |
Ruby | Ruby | remove unused `missingrequesterror` | 952eb506ebbfac24665a3a3429d1db9663cbb77a | <ide><path>actionview/lib/action_view.rb
<ide> module ActionView
<ide> autoload :MissingTemplate
<ide> autoload :ActionViewError
<ide> autoload :EncodingError
<del> autoload :MissingRequestError
<ide> autoload :TemplateError
<ide> autoload :WrongEncodingError
<ide> end
<ide><path>actionview/lib/action_view/template/error.rb
<ide> class ActionViewError < StandardError #:nodoc:
<ide> class EncodingError < StandardError #:nodoc:
<ide> end
<ide>
<del> class MissingRequestError < StandardError #:nodoc:
<del> end
<del>
<ide> class WrongEncodingError < EncodingError #:nodoc:
<ide> def initialize(string, encoding)
<ide> @string, @encoding = string, encoding | 2 |
Ruby | Ruby | convert tty test to spec | 8736b6cee0d94c1927b7abaa3dbde0d3a0239b85 | <ide><path>Library/Homebrew/test/utils/tty_spec.rb
<add>require "utils"
<add>
<add>describe Tty do
<add> describe "::strip_ansi" do
<add> it "removes ANSI escape codes from a string" do
<add> expect(subject.strip_ansi("\033\[36;7mhello\033\[0m")).to eq("hello")
<add> end
<add> end
<add>
<add> describe "::width" do
<add> it "returns an Integer" do
<add> expect(subject.width).to be_kind_of(Integer)
<add> end
<add>
<add> it "cannot be negative" do
<add> expect(subject.width).to be >= 0
<add> end
<add> end
<add>
<add> describe "::truncate" do
<add> it "truncates the text to the terminal width, minus 4, to account for '==> '" do
<add> allow(subject).to receive(:width).and_return(15)
<add>
<add> expect(subject.truncate("foobar something very long")).to eq("foobar some")
<add> expect(subject.truncate("truncate")).to eq("truncate")
<add> end
<add>
<add> it "doesn't truncate the text if the terminal is unsupported, i.e. the width is 0" do
<add> allow(subject).to receive(:width).and_return(0)
<add> expect(subject.truncate("foobar something very long")).to eq("foobar something very long")
<add> end
<add> end
<add>
<add> context "when $stdout is not a TTY" do
<add> before(:each) do
<add> allow($stdout).to receive(:tty?).and_return(false)
<add> end
<add>
<add> it "returns an empty string for all colors" do
<add> expect(subject.to_s).to eq("")
<add> expect(subject.red.to_s).to eq("")
<add> expect(subject.green.to_s).to eq("")
<add> expect(subject.yellow.to_s).to eq("")
<add> expect(subject.blue.to_s).to eq("")
<add> expect(subject.magenta.to_s).to eq("")
<add> expect(subject.cyan.to_s).to eq("")
<add> expect(subject.default.to_s).to eq("")
<add> end
<add> end
<add>
<add> context "when $stdout is a TTY" do
<add> before(:each) do
<add> allow($stdout).to receive(:tty?).and_return(true)
<add> end
<add>
<add> it "returns an empty string for all colors" do
<add> expect(subject.to_s).to eq("")
<add> expect(subject.red.to_s).to eq("\033[31m")
<add> expect(subject.green.to_s).to eq("\033[32m")
<add> expect(subject.yellow.to_s).to eq("\033[33m")
<add> expect(subject.blue.to_s).to eq("\033[34m")
<add> expect(subject.magenta.to_s).to eq("\033[35m")
<add> expect(subject.cyan.to_s).to eq("\033[36m")
<add> expect(subject.default.to_s).to eq("\033[39m")
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/test/utils/tty_test.rb
<del>require "testing_env"
<del>require "utils"
<del>
<del>class TtyTests < Homebrew::TestCase
<del> def test_strip_ansi
<del> assert_equal "hello", Tty.strip_ansi("\033\[36;7mhello\033\[0m")
<del> end
<del>
<del> def test_width
<del> assert_kind_of Integer, Tty.width
<del> end
<del>
<del> def test_truncate
<del> Tty.stubs(:width).returns 15
<del> assert_equal "foobar some", Tty.truncate("foobar something very long")
<del> assert_equal "truncate", Tty.truncate("truncate")
<del>
<del> # When the terminal is unsupported, we report 0 width
<del> Tty.stubs(:width).returns 0
<del> assert_equal "foobar something very long", Tty.truncate("foobar something very long")
<del> end
<del>
<del> def test_no_tty_formatting
<del> $stdout.stubs(:tty?).returns false
<del> assert_equal "", Tty.to_s
<del> assert_equal "", Tty.red.to_s
<del> assert_equal "", Tty.green.to_s
<del> assert_equal "", Tty.yellow.to_s
<del> assert_equal "", Tty.blue.to_s
<del> assert_equal "", Tty.magenta.to_s
<del> assert_equal "", Tty.cyan.to_s
<del> assert_equal "", Tty.default.to_s
<del> end
<del>
<del> def test_formatting
<del> $stdout.stubs(:tty?).returns(true)
<del> assert_equal "", Tty.to_s
<del> assert_equal "\033[31m", Tty.red.to_s
<del> assert_equal "\033[32m", Tty.green.to_s
<del> assert_equal "\033[33m", Tty.yellow.to_s
<del> assert_equal "\033[34m", Tty.blue.to_s
<del> assert_equal "\033[35m", Tty.magenta.to_s
<del> assert_equal "\033[36m", Tty.cyan.to_s
<del> assert_equal "\033[39m", Tty.default.to_s
<del> end
<del>end | 2 |
Text | Text | remove duplicate asterik | a3329db7db7d0f0ee672fc44bfdd41767cda6446 | <ide><path>docs/build-instructions/windows.md
<ide> To also install the newly built application, use `script\build --create-windows-
<ide> * See the next item.
<ide>
<ide> * `error MSB8020: The build tools for Visual Studio 201? (Platform Toolset = 'v1?0') cannot be found.`
<del> * * Try setting the `GYP_MSVS_VERSION` environment variable to 2013 or 2015 depending on what version of Visual Studio/Build Tools is installed and then `script\clean` followed by `script\build` (re-open the Command Prompt if you set the variable using the GUI)
<add> * Try setting the `GYP_MSVS_VERSION` environment variable to 2013 or 2015 depending on what version of Visual Studio/Build Tools is installed and then `script\clean` followed by `script\build` (re-open the Command Prompt if you set the variable using the GUI)
<ide>
<ide> * `'node-gyp' is not recognized as an internal or external command, operable program or batch file.`
<ide> * Try running `npm install -g node-gyp`, and run `script\build` again. | 1 |
PHP | PHP | use the new google fonts api | b9b282a71933e0279fea63fa0302e9a30a4c2efe | <ide><path>resources/views/welcome.blade.php
<ide> <title>Laravel</title>
<ide>
<ide> <!-- Fonts -->
<del> <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
<add> <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@200;600&display=swap" rel="stylesheet">
<ide>
<ide> <!-- Styles -->
<ide> <style> | 1 |
Ruby | Ruby | use cflags setter | 2cb8c443e4bd44ea660657a3159268664f77a173 | <ide><path>Library/Homebrew/extend/ENV/std.rb
<ide> def macosxsdk version=MacOS.version
<ide> end
<ide>
<ide> def minimal_optimization
<del> self['CFLAGS'] = self['CXXFLAGS'] = "-Os #{SAFE_CFLAGS_FLAGS}"
<add> set_cflags "-Os #{SAFE_CFLAGS_FLAGS}"
<ide> macosxsdk unless MacOS::CLT.installed?
<ide> end
<ide> def no_optimization
<del> self['CFLAGS'] = self['CXXFLAGS'] = SAFE_CFLAGS_FLAGS
<add> set_cflags SAFE_CFLAGS_FLAGS
<ide> macosxsdk unless MacOS::CLT.installed?
<ide> end
<ide> | 1 |
Javascript | Javascript | remove legacy code to support ie8 and older | 8f10dca300c7bcc55ff1613326b84b9c460ca7c2 | <ide><path>src/jqLite.js
<ide> JQLite.expando = 'ng339';
<ide>
<ide> var jqCache = JQLite.cache = {},
<ide> jqId = 1,
<del> addEventListenerFn = (window.document.addEventListener
<del> ? function(element, type, fn) {element.addEventListener(type, fn, false);}
<del> : function(element, type, fn) {element.attachEvent('on' + type, fn);}),
<del> removeEventListenerFn = (window.document.removeEventListener
<del> ? function(element, type, fn) {element.removeEventListener(type, fn, false); }
<del> : function(element, type, fn) {element.detachEvent('on' + type, fn); });
<add> addEventListenerFn = function(element, type, fn) {
<add> element.addEventListener(type, fn, false);
<add> },
<add> removeEventListenerFn = function(element, type, fn) {
<add> element.removeEventListener(type, fn, false);
<add> };
<ide>
<ide> /*
<ide> * !!! This is an undocumented "private" function !!!
<ide> */
<del>var jqData = JQLite._data = function(node) {
<add>JQLite._data = function(node) {
<ide> //jQuery always returns an object on cache miss
<ide> return this.cache[node[this.expando]] || {};
<ide> };
<ide> function jqLiteAcceptsData(node) {
<ide> }
<ide>
<ide> function jqLiteBuildFragment(html, context) {
<del> var elem, tmp, tag, wrap,
<add> var tmp, tag, wrap,
<ide> fragment = context.createDocumentFragment(),
<ide> nodes = [], i;
<ide>
<ide> function jqLiteExpandoStore(element, key, value) {
<ide> }
<ide> expandoStore[key] = value;
<ide> } else {
<del> return expandoStore && expandoStore[key];
<add> return key ? expandoStore && expandoStore[key] : expandoStore;
<ide> }
<ide> }
<ide>
<ide> function jqLiteRemove(element, keepData) {
<ide> //////////////////////////////////////////
<ide> var JQLitePrototype = JQLite.prototype = {
<ide> ready: function(fn) {
<del> var fired = false;
<del>
<del> function trigger() {
<del> if (fired) return;
<del> fired = true;
<del> fn();
<del> }
<del>
<ide> // check if document already is loaded
<ide> if (document.readyState === 'complete'){
<del> setTimeout(trigger);
<add> setTimeout(fn);
<ide> } else {
<del> this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
<del> // we can not use jqLite since we are not done loading and jQuery could be loaded later.
<del> // jshint -W064
<del> JQLite(window).on('load', trigger); // fallback to window.onload for others
<del> // jshint +W064
<add> this.on('DOMContentLoaded', fn);
<ide> }
<ide> },
<ide> toString: function() {
<ide> forEach({
<ide> if (isDefined(value)) {
<ide> element.style[name] = value;
<ide> } else {
<del> var val;
<del>
<del> if (msie <= 8) {
<del> // this is some IE specific weirdness that jQuery 1.6.4 does not sure why
<del> val = element.currentStyle && element.currentStyle[name];
<del> if (val === '') val = 'auto';
<del> }
<del>
<del> val = val || element.style[name];
<del>
<del> if (msie <= 8) {
<del> // jquery weirdness :-/
<del> val = (val === '') ? undefined : val;
<del> }
<del>
<del> return val;
<add> return element.style[name];
<ide> }
<ide> },
<ide>
<ide> forEach({
<ide>
<ide> function createEventHandler(element, events) {
<ide> var eventHandler = function (event, type) {
<del> if (!event.preventDefault) {
<del> event.preventDefault = function() {
<del> event.returnValue = false; //ie
<del> };
<del> }
<del>
<del> if (!event.stopPropagation) {
<del> event.stopPropagation = function() {
<del> event.cancelBubble = true; //ie
<del> };
<del> }
<del>
<del> if (!event.target) {
<del> event.target = event.srcElement || document;
<del> }
<del>
<del> if (isUndefined(event.defaultPrevented)) {
<del> var prevent = event.preventDefault;
<del> event.preventDefault = function() {
<del> event.defaultPrevented = true;
<del> prevent.call(event);
<del> };
<del> event.defaultPrevented = false;
<del> }
<ide>
<add> // jQuery specific api
<ide> event.isDefaultPrevented = function() {
<del> return event.defaultPrevented || event.returnValue === false;
<add> return event.defaultPrevented;
<ide> };
<ide>
<ide> // Copy event handlers in case event handlers array is modified during execution.
<ide> function createEventHandler(element, events) {
<ide> for (var i = 0, ii = eventHandlersCopy.length; i < ii; i++) {
<ide> eventHandlersCopy[i].call(element, event);
<ide> }
<del>
<del> // Remove monkey-patched methods (IE),
<del> // as they would cause memory leaks in IE8.
<del> if (msie <= 8) {
<del> // IE7/8 does not allow to delete property on native object
<del> event.preventDefault = null;
<del> event.stopPropagation = null;
<del> event.isDefaultPrevented = null;
<del> } else {
<del> // It shouldn't affect normal browsers (native methods are defined on prototype).
<del> delete event.preventDefault;
<del> delete event.stopPropagation;
<del> delete event.isDefaultPrevented;
<del> }
<ide> };
<add>
<add> // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
<add> // events on `element`
<ide> eventHandler.elem = element;
<ide> return eventHandler;
<ide> }
<ide> forEach({
<ide> return;
<ide> }
<ide>
<del> var events = jqLiteExpandoStore(element, 'events'),
<del> handle = jqLiteExpandoStore(element, 'handle');
<add> var expandoStore = jqLiteExpandoStore(element);
<add> var events = expandoStore && expandoStore.events;
<add> var handle = expandoStore && expandoStore.handle;
<ide>
<ide> if (!events) jqLiteExpandoStore(element, 'events', events = {});
<ide> if (!handle) jqLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events));
<ide> forEach({
<ide> },
<ide>
<ide> next: function(element) {
<del> if (element.nextElementSibling) {
<del> return element.nextElementSibling;
<del> }
<del>
<del> // IE8 doesn't have nextElementSibling
<del> var elm = element.nextSibling;
<del> while (elm != null && elm.nodeType !== 1) {
<del> elm = elm.nextSibling;
<del> }
<del> return elm;
<add> return element.nextElementSibling;
<ide> },
<ide>
<ide> find: function(element, selector) { | 1 |
Text | Text | add default tags for issue templates | 5c97b9775517705eeed88623097343d43b64f760 | <ide><path>.github/ISSUE_TEMPLATE/1.Bug_report.md
<ide> ---
<ide> name: Bug report
<ide> about: Create a bug report for the Next.js core / examples
<add>labels: 'template: bug'
<ide> ---
<ide>
<ide> # Bug report
<ide><path>.github/ISSUE_TEMPLATE/2.Feature_request.md
<ide> ---
<ide> name: Feature request
<ide> about: Create a feature request for the Next.js core
<add>labels: 'template: story'
<ide> ---
<ide>
<ide> # Feature request | 2 |
Ruby | Ruby | enhance many? one? | 02d9f31a4a113277a9d84ea8fb32d819b48dad50 | <ide><path>activerecord/lib/active_record/relation.rb
<ide> def any?
<ide> # Returns true if there is exactly one record.
<ide> def one?
<ide> return super if block_given?
<del> return records.one? if limit_value || loaded?
<add> return records.one? if loaded?
<ide> limited_count == 1
<ide> end
<ide>
<ide> # Returns true if there is more than one record.
<ide> def many?
<ide> return super if block_given?
<del> return records.many? if limit_value || loaded?
<add> return records.many? if loaded?
<ide> limited_count > 1
<ide> end
<ide>
<ide> def tables_in_string(string)
<ide> end
<ide>
<ide> def limited_count
<del> @limited_count ||= limit(2).count
<add> @limited_count ||= limit_value ? count : limit(2).count
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/relations_test.rb
<ide> def test_many
<ide> end
<ide>
<ide> def test_many_with_limits
<del> posts = Post.all
<add> posts_with_limit = Post.limit(5)
<add> posts_with_limit_one = Post.limit(1)
<ide>
<del> assert_predicate posts, :many?
<del> assert_not_predicate posts.limit(1), :many?
<add> assert_predicate posts_with_limit, :many?
<add> assert_not_predicate posts_with_limit, :loaded?
<add>
<add> assert_not_predicate posts_with_limit_one, :many?
<add> assert_not_predicate posts_with_limit_one, :loaded?
<ide> end
<ide>
<ide> def test_none? | 2 |
Ruby | Ruby | remove cask’s `which` method | 6e1c132f99166c716c991d687e4017167c2a37d0 | <ide><path>Library/Homebrew/cask/lib/hbc/cli.rb
<ide> def self.run_command(command, *rest)
<ide> if command.respond_to?(:run)
<ide> # usual case: built-in command verb
<ide> command.run(*rest)
<del> elsif require? Utils.which("brewcask-#{command}.rb").to_s
<add> elsif require? which("brewcask-#{command}.rb").to_s
<ide> # external command as Ruby library on PATH, Homebrew-style
<ide> elsif command.to_s.include?("/") && require?(command.to_s)
<ide> # external command as Ruby library with literal path, useful
<ide> def self.run_command(command, *rest)
<ide> # other Ruby libraries must do everything via "require"
<ide> klass.run(*rest)
<ide> end
<del> elsif Utils.which "brewcask-#{command}"
<add> elsif which("brewcask-#{command}")
<ide> # arbitrary external executable on PATH, Homebrew-style
<ide> exec "brewcask-#{command}", *ARGV[1..-1]
<ide> elsif Pathname.new(command.to_s).executable? &&
<ide><path>Library/Homebrew/cask/lib/hbc/utils.rb
<ide> def odebug(title, *sput)
<ide>
<ide> module Hbc
<ide> module Utils
<del> def self.which(cmd, path = ENV["PATH"])
<del> unless File.basename(cmd) == cmd.to_s
<del> # cmd contains a directory element
<del> cmd_pn = Pathname(cmd)
<del> return nil unless cmd_pn.absolute?
<del> return resolve_executable(cmd_pn)
<del> end
<del> path.split(File::PATH_SEPARATOR).each do |elt|
<del> fq_cmd = Pathname(elt).expand_path.join(cmd)
<del> resolved = resolve_executable fq_cmd
<del> return resolved if resolved
<del> end
<del> nil
<del> end
<del>
<del> def self.resolve_executable(cmd)
<del> cmd_pn = Pathname(cmd)
<del> return nil unless cmd_pn.exist?
<del> return nil unless cmd_pn.executable?
<del> begin
<del> cmd_pn = Pathname(cmd_pn.realpath)
<del> rescue RuntimeError
<del> return nil
<del> end
<del> return nil unless cmd_pn.file?
<del> cmd_pn
<del> end
<del>
<ide> def self.gain_permissions_remove(path, command: SystemCommand)
<ide> if path.respond_to?(:rmtree) && path.exist?
<ide> gain_permissions(path, ["-R"], command, &:rmtree) | 2 |
Python | Python | standardize future imports | 04c11f8c13b1182b43eaed36dbfdedb23efd38b9 | <ide><path>keras/activations.py
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> import six
<ide> import warnings
<ide> from . import backend as K
<ide><path>keras/applications/densenet.py
<ide> - [Torch DenseNets](https://github.com/liuzhuang13/DenseNet/blob/master/models/densenet.lua)
<ide> - [TensorNets](https://github.com/taehoonlee/tensornets/blob/master/tensornets/densenets.py)
<ide> """
<del>from __future__ import print_function
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<ide>
<ide> import os
<ide>
<ide><path>keras/applications/imagenet_utils.py
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> import json
<ide> import warnings
<ide> import numpy as np
<ide><path>keras/applications/inception_resnet_v2.py
<ide> Residual Connections on Learning](https://arxiv.org/abs/1602.07261)
<ide>
<ide> """
<del>from __future__ import print_function
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<ide>
<ide> import os
<ide> import warnings
<ide><path>keras/applications/inception_v3.py
<ide> - [Rethinking the Inception Architecture for Computer Vision](http://arxiv.org/abs/1512.00567)
<ide>
<ide> """
<del>from __future__ import print_function
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<ide>
<ide> import os
<ide> import warnings
<ide><path>keras/applications/resnet50.py
<ide>
<ide> Adapted from code contributed by BigMoyan.
<ide> """
<del>from __future__ import print_function
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<ide>
<ide> import os
<ide> import warnings
<ide><path>keras/applications/vgg16.py
<ide> - [Very Deep Convolutional Networks for Large-Scale Image Recognition](https://arxiv.org/abs/1409.1556)
<ide>
<ide> """
<del>from __future__ import print_function
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<ide>
<ide> import os
<ide> import warnings
<ide><path>keras/applications/vgg19.py
<ide> - [Very Deep Convolutional Networks for Large-Scale Image Recognition](https://arxiv.org/abs/1409.1556)
<ide>
<ide> """
<del>from __future__ import print_function
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<ide>
<ide> import os
<ide> import warnings
<ide><path>keras/applications/xception.py
<ide> - [Xception: Deep Learning with Depthwise Separable Convolutions](https://arxiv.org/abs/1610.02357)
<ide>
<ide> """
<del>from __future__ import print_function
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<ide>
<ide> import os
<ide> import warnings
<ide><path>keras/backend/cntk_backend.py
<add>from __future__ import absolute_import
<add>from __future__ import division
<ide> from __future__ import print_function
<add>
<ide> import cntk as C
<ide> import numpy as np
<ide> from .common import floatx, epsilon, image_dim_ordering, image_data_format
<ide><path>keras/backend/common.py
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> import numpy as np
<ide>
<ide> # the type of float to use throughout the session.
<ide><path>keras/backend/tensorflow_backend.py
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> import tensorflow as tf
<ide> from tensorflow.python.training import moving_averages
<ide> from tensorflow.python.ops import tensor_array_ops
<ide><path>keras/backend/theano_backend.py
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> from collections import defaultdict
<ide> from contextlib import contextmanager
<ide> import theano
<ide><path>keras/callbacks.py
<ide> from __future__ import absolute_import
<add>from __future__ import division
<ide> from __future__ import print_function
<ide>
<ide> import os
<ide><path>keras/constraints.py
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> import six
<ide> from . import backend as K
<ide> from .utils.generic_utils import serialize_keras_object
<ide><path>keras/datasets/boston_housing.py
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> from ..utils.data_utils import get_file
<ide> import numpy as np
<ide>
<ide><path>keras/datasets/cifar.py
<ide> # -*- coding: utf-8 -*-
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> import sys
<ide> from six.moves import cPickle
<ide>
<ide><path>keras/datasets/cifar10.py
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> from .cifar import load_batch
<ide> from ..utils.data_utils import get_file
<ide> from .. import backend as K
<ide><path>keras/datasets/cifar100.py
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> from .cifar import load_batch
<ide> from ..utils.data_utils import get_file
<ide> from .. import backend as K
<ide><path>keras/datasets/fashion_mnist.py
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> import gzip
<ide> import os
<ide>
<ide><path>keras/datasets/imdb.py
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> from ..utils.data_utils import get_file
<ide> from ..preprocessing.sequence import _remove_long_seq
<ide> import numpy as np
<ide><path>keras/datasets/mnist.py
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> from ..utils.data_utils import get_file
<ide> import numpy as np
<ide>
<ide><path>keras/datasets/reuters.py
<ide> # -*- coding: utf-8 -*-
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> from ..utils.data_utils import get_file
<ide> from ..preprocessing.sequence import _remove_long_seq
<ide> from six.moves import zip
<ide><path>keras/engine/training.py
<ide> # -*- coding: utf-8 -*-
<del>from __future__ import print_function
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<ide>
<ide> import warnings
<ide> import copy
<ide><path>keras/initializers.py
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> import numpy as np
<ide> import six
<ide> from . import backend as K
<ide><path>keras/layers/advanced_activations.py
<ide> # -*- coding: utf-8 -*-
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<ide>
<ide> from .. import activations
<ide> from .. import initializers
<ide><path>keras/layers/convolutional.py
<ide> # -*- coding: utf-8 -*-
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<ide>
<ide> from .. import backend as K
<ide> from .. import activations
<ide><path>keras/layers/convolutional_recurrent.py
<ide> # -*- coding: utf-8 -*-
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<ide>
<ide> from .. import backend as K
<ide> from .. import activations
<ide><path>keras/layers/core.py
<ide> # -*- coding: utf-8 -*-
<ide> from __future__ import absolute_import
<ide> from __future__ import division
<add>from __future__ import print_function
<ide>
<ide> import numpy as np
<ide>
<ide><path>keras/layers/cudnn_recurrent.py
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> from .. import backend as K
<ide> from .. import initializers
<ide> from .. import regularizers
<ide><path>keras/layers/embeddings.py
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<ide>
<ide> from .. import backend as K
<ide> from .. import initializers
<ide><path>keras/layers/local.py
<ide> # -*- coding: utf-8 -*-
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<ide>
<ide> from .. import backend as K
<ide> from .. import activations
<ide><path>keras/layers/merge.py
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> from ..engine.topology import Layer
<ide> from .. import backend as K
<ide>
<ide><path>keras/layers/noise.py
<ide> # -*- coding: utf-8 -*-
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<ide>
<ide> from ..engine import Layer
<ide> from .. import backend as K
<ide><path>keras/layers/normalization.py
<ide> # -*- coding: utf-8 -*-
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<ide>
<ide> from ..engine import Layer, InputSpec
<ide> from .. import initializers
<ide><path>keras/layers/pooling.py
<ide> # -*- coding: utf-8 -*-
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<ide>
<ide> from .. import backend as K
<ide> from ..engine import Layer
<ide><path>keras/layers/recurrent.py
<ide> # -*- coding: utf-8 -*-
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> import numpy as np
<ide> import warnings
<ide>
<ide><path>keras/layers/wrappers.py
<ide> # -*- coding: utf-8 -*-
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<ide>
<ide> import copy
<ide> from ..engine import Layer
<ide><path>keras/legacy/interfaces.py
<ide> """Interface converters for Keras 1 support in Keras 2.
<ide> """
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> import six
<ide> import warnings
<ide> import functools
<ide><path>keras/legacy/layers.py
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> import numpy as np
<ide> import types as python_types
<ide> import warnings
<ide><path>keras/legacy/models.py
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> from .layers import Merge
<ide>
<ide>
<ide><path>keras/losses.py
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> import six
<ide> from . import backend as K
<ide> from .utils.generic_utils import deserialize_keras_object
<ide><path>keras/metrics.py
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> import six
<ide> from . import backend as K
<ide> from .losses import mean_squared_error
<ide><path>keras/models.py
<ide> # -*- coding: utf-8 -*-
<ide> from __future__ import absolute_import
<add>from __future__ import division
<ide> from __future__ import print_function
<ide>
<ide> import warnings
<ide><path>keras/optimizers.py
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> import six
<ide> import copy
<ide> from six.moves import zip
<ide><path>keras/preprocessing/image.py
<ide> """Fairly basic set of tools for real-time data augmentation on image data.
<add>
<ide> Can easily be extended to include new transformations,
<ide> new preprocessing methods, etc...
<ide> """
<ide> from __future__ import absolute_import
<add>from __future__ import division
<ide> from __future__ import print_function
<ide>
<ide> import numpy as np
<ide><path>keras/preprocessing/sequence.py
<ide> # -*- coding: utf-8 -*-
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<ide>
<ide> import numpy as np
<ide> import random
<ide><path>keras/preprocessing/text.py
<ide> # -*- coding: utf-8 -*-
<ide> """Utilities for text input preprocessing.
<del>
<del>May benefit from a fast Cython rewrite.
<ide> """
<ide> from __future__ import absolute_import
<ide> from __future__ import division
<add>from __future__ import print_function
<ide>
<ide> import string
<ide> import sys
<ide><path>keras/regularizers.py
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> import six
<ide> from . import backend as K
<ide> from .utils.generic_utils import serialize_keras_object
<ide><path>keras/utils/conv_utils.py
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> from six.moves import range
<ide> import numpy as np
<ide> from .. import backend as K
<ide><path>keras/utils/data_utils.py
<ide> """Utilities for file download and caching."""
<ide> from __future__ import absolute_import
<add>from __future__ import division
<ide> from __future__ import print_function
<ide>
<ide> import hashlib
<ide><path>keras/utils/generic_utils.py
<ide> """Python utilities required by Keras."""
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<ide>
<ide> import binascii
<ide> import numpy as np
<ide><path>keras/utils/io_utils.py
<ide> """Utilities related to disk I/O."""
<ide> from __future__ import absolute_import
<add>from __future__ import division
<ide> from __future__ import print_function
<ide>
<ide> import numpy as np
<ide><path>keras/utils/layer_utils.py
<add>from __future__ import absolute_import
<add>from __future__ import division
<ide> from __future__ import print_function
<ide>
<ide> from .conv_utils import convert_kernel
<ide><path>keras/utils/np_utils.py
<ide> """Numpy-related utilities."""
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<ide>
<ide> import numpy as np
<ide>
<ide><path>keras/utils/test_utils.py
<ide> """Utilities related to Keras unit tests."""
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> import numpy as np
<ide> from numpy.testing import assert_allclose
<ide> import six
<ide><path>keras/utils/training_utils.py
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> from ..layers.merge import concatenate
<ide> from .. import backend as K
<ide> from ..layers.core import Lambda
<ide><path>keras/utils/vis_utils.py
<ide> """Utilities related to model visualization."""
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> import os
<ide>
<ide> try:
<ide><path>keras/wrappers/scikit_learn.py
<ide> from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<ide>
<ide> import copy
<ide> import types | 59 |
Javascript | Javascript | hide correct dataset from legend | 6942e9058c06494105b42f4efd18f80b2ab64ac1 | <ide><path>src/plugins/plugin.legend.js
<ide> defaults._set('global', {
<ide> var options = chart.options.legend || {};
<ide> var usePointStyle = options.labels && options.labels.usePointStyle;
<ide>
<del> return chart._getSortedDatasetMetas().map(function(meta, i) {
<add> return chart._getSortedDatasetMetas().map(function(meta) {
<ide> var style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
<ide>
<ide> return {
<ide> text: datasets[meta.index].label,
<ide> fillStyle: style.backgroundColor,
<del> hidden: !chart.isDatasetVisible(i),
<add> hidden: !chart.isDatasetVisible(meta.index),
<ide> lineCap: style.borderCapStyle,
<ide> lineDash: style.borderDash,
<ide> lineDashOffset: style.borderDashOffset,
<ide> defaults._set('global', {
<ide> rotation: style.rotation,
<ide>
<ide> // Below is extra data used for toggling the datasets
<del> datasetIndex: i
<add> datasetIndex: meta.index
<ide> };
<ide> }, this);
<ide> } | 1 |
Python | Python | fix gce_demo for loadbalancing and python 3 | 26a54f158392e07e75fb1fd9a808db635ee35e2c | <ide><path>demos/gce_demo.py
<ide> def main_load_balancer():
<ide> name = '%s-firewall' % DEMO_BASE_NAME
<ide> allowed = [{'IPProtocol': 'tcp',
<ide> 'ports': ['80']}]
<del> firewall = gce.ex_create_firewall(name, allowed, source_tags=[tag])
<add> firewall = gce.ex_create_firewall(name, allowed, target_tags=[tag])
<ide> display(' Firewall %s created' % firewall.name)
<ide>
<ide> # == Create a Health Check ==
<ide> def main_load_balancer():
<ide> sys.stdout.flush()
<ide> time.sleep(.25)
<ide>
<del> print ""
<add> print('')
<ide> if CLEANUP:
<ide> balancers = gcelb.list_balancers()
<ide> healthchecks = gcelb.ex_list_healthchecks() | 1 |
Mixed | Javascript | fix border style without borderradius | 58876d5a03b2c709b83ae212010b623d1c51c9cf | <ide><path>Examples/UIExplorer/ViewExample.js
<ide> var ViewBorderStyleExample = React.createClass({
<ide> <View>
<ide> <View style={{
<ide> borderWidth: 1,
<del> borderRadius: 5,
<ide> borderStyle: this.state.showBorder ? 'dashed' : null,
<ide> padding: 5
<ide> }}>
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewBackgroundDrawable.java
<ide> private static enum BorderStyle {
<ide>
<ide> @Override
<ide> public void draw(Canvas canvas) {
<del> if ((!CSSConstants.isUndefined(mBorderRadius) && mBorderRadius > 0) || mBorderCornerRadii != null) {
<del> drawRoundedBackgroundWithBorders(canvas);
<del> } else {
<add> updatePathEffect();
<add> boolean roundedBorders = mBorderCornerRadii != null ||
<add> (!CSSConstants.isUndefined(mBorderRadius) && mBorderRadius > 0);
<add>
<add> if ((mBorderStyle == null || mBorderStyle == BorderStyle.SOLID) && !roundedBorders) {
<ide> drawRectangularBackgroundWithBorders(canvas);
<add> } else {
<add> drawRoundedBackgroundWithBorders(canvas);
<ide> }
<ide> }
<ide>
<ide> private void drawRoundedBackgroundWithBorders(Canvas canvas) {
<ide> mPaint.setColor(ColorUtil.multiplyColorAlpha(borderColor, mAlpha));
<ide> mPaint.setStyle(Paint.Style.STROKE);
<ide> mPaint.setStrokeWidth(fullBorderWidth);
<del> mPaint.setPathEffect(mPathEffectForBorderStyle);
<ide> canvas.drawPath(mPathForBorderRadius, mPaint);
<ide> }
<ide> }
<ide> private void updatePath() {
<ide> bottomLeftRadius + extraRadiusForOutline
<ide> },
<ide> Path.Direction.CW);
<add> }
<ide>
<add> /**
<add> * Set type of border
<add> */
<add> private void updatePathEffect() {
<ide> mPathEffectForBorderStyle = mBorderStyle != null
<ide> ? mBorderStyle.getPathEffect(getFullBorderWidth())
<ide> : null;
<add>
<add> mPaint.setPathEffect(mPathEffectForBorderStyle);
<ide> }
<ide>
<ide> /** | 2 |
Javascript | Javascript | use synchook for afterfinishassets | 90971dc0e61077516e333737d70612487bed0718 | <ide><path>lib/Compilation.js
<ide> class Compilation {
<ide>
<ide> /** @type {AsyncSeriesHook<[CompilationAssets]>} */
<ide> finishAssets: new AsyncSeriesHook(["assets"]),
<del> /** @type {AsyncSeriesHook<[CompilationAssets]>} */
<del> afterFinishAssets: new AsyncSeriesHook(["assets"]),
<add> /** @type {SyncHook<[CompilationAssets]>} */
<add> afterFinishAssets: new SyncHook(["assets"]),
<ide>
<ide> /** @type {SyncBailHook<[], boolean>} */
<ide> needAdditionalSeal: new SyncBailHook([]),
<ide> class Compilation {
<ide> makeWebpackError(err, "Compilation.hooks.finishAssets")
<ide> );
<ide> }
<del> this.hooks.afterFinishAssets.callAsync(this.assets, err => {
<del> if (err) {
<del> return callback(
<del> makeWebpackError(
<del> err,
<del> "Compilation.hooks.afterFinishAssets"
<del> )
<del> );
<del> }
<del> this.cache.storeBuildDependencies(
<del> this.buildDependencies,
<del> err => {
<del> if (err) {
<del> return callback(err);
<del> }
<del> return this.hooks.afterSeal.callAsync(callback);
<add> this.hooks.afterFinishAssets.call(this.assets);
<add> this.cache.storeBuildDependencies(
<add> this.buildDependencies,
<add> err => {
<add> if (err) {
<add> return callback(err);
<ide> }
<del> );
<del> });
<add> return this.hooks.afterSeal.callAsync(callback);
<add> }
<add> );
<ide> });
<ide> });
<ide> });
<ide><path>lib/SourceMapDevToolPlugin.js
<ide> class SourceMapDevToolPlugin {
<ide> compiler.hooks.compilation.tap("SourceMapDevToolPlugin", compilation => {
<ide> new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation);
<ide>
<del> compilation.hooks.afterFinishAssets.tapAsync(
<add> compilation.hooks.finishAssets.tapAsync(
<ide> "SourceMapDevToolPlugin",
<ide> (assets, callback) => {
<ide> const chunkGraph = compilation.chunkGraph; | 2 |
Text | Text | add first content on redux middleware | e321ca535c9651c2c02ff9601b5e94af341d6fe1 | <ide><path>client/src/pages/guide/english/redux/redux-middleware/index.md
<ide> title: Redux Middleware
<ide> ---
<ide> ## Redux Middleware
<ide>
<del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/redux/redux-middleware/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add>One of the great things about redux is that it provides an interface to plug in different middleware packages to add additional functionality to redux. Redux middleware basically acts like pipes that your actions will flow through after getting dispatched but before being handled by your reducers. There are a large amount of popular redux middleware packages for adding features like logging and handling asynchronous action flows.
<ide>
<del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>[Redux Thunk](https://github.com/reduxjs/redux-thunk) for example allows you to dispatch functions to delay the dispatching of actions.
<ide>
<del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>Adding middleware to redux is as simple as adding another argument when calling "createStore". Just pass the result of calling "applyMiddleware" with each middleware package you want to use. In the example below we add redux-thunk and redux-logger to our app.
<add>
<add>```js
<add>import { createStore, applyMiddleware } from 'redux';
<add>import thunk from 'redux-thunk';
<add>import logger from 'redux-logger'
<add>
<add>const store = createStore(
<add> rootReducer,
<add> applyMiddleware(thunk, logger)
<add>);
<add>```
<ide>
<ide> #### More Information:
<ide> <!-- Please add any articles you think might be helpful to read before writing the article -->
<add>[Middleware - Redux docs](https://redux.js.org/advanced/middleware)
<ide>
<del>
<add>[Redux Logger](https://github.com/evgenyrodionov/redux-logger)
<add>[Redux Thunk](https://github.com/reduxjs/redux-thunk) | 1 |
PHP | PHP | apply fixes from styleci | 65b304e52f92759c3e8233767e2755c7b763fd99 | <ide><path>tests/Filesystem/FilesystemTest.php
<ide>
<ide> namespace Illuminate\Tests\Filesystem;
<ide>
<del>use Illuminate\Filesystem\FilesystemManager;
<del>use Illuminate\Foundation\Application;
<del>use League\Flysystem\Adapter\Ftp;
<ide> use PHPUnit\Framework\TestCase;
<add>use League\Flysystem\Adapter\Ftp;
<ide> use Illuminate\Filesystem\Filesystem;
<add>use Illuminate\Foundation\Application;
<add>use Illuminate\Filesystem\FilesystemManager;
<ide>
<ide> class FilesystemTest extends TestCase
<ide> {
<ide> public function testCreateFtpDriver()
<ide> 'host' => 'ftp.example.com',
<ide> 'username' => 'admin',
<ide> 'permPublic' => 0700,
<del> 'unsopertedParam' => true
<add> 'unsopertedParam' => true,
<ide> ]);
<ide>
<ide> /** @var Ftp $adapter */ | 1 |
Text | Text | add changelogs for child_process | d6a3cfab77e45f2e7466ffa653537379c00b0165 | <ide><path>doc/api/child_process.md
<ide> encoding, `Buffer` objects will be passed to the callback instead.
<ide> ### child_process.fork(modulePath[, args][, options])
<ide> <!-- YAML
<ide> added: v0.5.0
<add>changes:
<add> - version: v6.4.0
<add> pr-url: https://github.com/nodejs/node/pull/7811
<add> description: The `stdio` option is supported now.
<ide> -->
<ide>
<ide> * `modulePath` {String} The module to run in the child
<ide> not clone the current process.*
<ide> ### child_process.spawn(command[, args][, options])
<ide> <!-- YAML
<ide> added: v0.1.90
<add>changes:
<add> - version: v6.4.0
<add> pr-url: https://github.com/nodejs/node/pull/7696
<add> description: The `argv0` option is supported now.
<add> - version: v5.7.0
<add> pr-url: https://github.com/nodejs/node/pull/4598
<add> description: The `shell` option is supported now.
<ide> -->
<ide>
<ide> * `command` {String} The command to run
<ide> child.unref();
<ide> #### options.stdio
<ide> <!-- YAML
<ide> added: v0.7.10
<add>changes:
<add> - version: v3.3.1
<add> pr-url: https://github.com/nodejs/node/pull/2727
<add> description: The value `0` is now accepted as a file descriptor.
<ide> -->
<ide>
<ide> The `options.stdio` option is used to configure the pipes that are established
<ide> configuration at startup.
<ide> ### child_process.execFileSync(file[, args][, options])
<ide> <!-- YAML
<ide> added: v0.11.12
<add>changes:
<add> - version: v6.2.1, v4.5.0
<add> pr-url: https://github.com/nodejs/node/pull/6939
<add> description: The `encoding` option can now explicitly be set to `buffer`.
<ide> -->
<ide>
<ide> * `file` {String} The name or path of the executable file to run
<ide> execution.**
<ide> ### child_process.spawnSync(command[, args][, options])
<ide> <!-- YAML
<ide> added: v0.11.12
<add>changes:
<add> - version: v6.2.1, v4.5.0
<add> pr-url: https://github.com/nodejs/node/pull/6939
<add> description: The `encoding` option can now explicitly be set to `buffer`.
<add> - version: v5.7.0
<add> pr-url: https://github.com/nodejs/node/pull/4598
<add> description: The `shell` option is supported now.
<ide> -->
<ide>
<ide> * `command` {String} The command to run
<ide> grep.stdin.end();
<ide> ### child.send(message[, sendHandle[, options]][, callback])
<ide> <!-- YAML
<ide> added: v0.5.9
<add>changes:
<add> - version: v5.8.0
<add> pr-url: https://github.com/nodejs/node/pull/5283
<add> description: The `options` parameter, and the `keepOpen` option
<add> in particular, is supported now.
<add> - version: v5.0.0
<add> pr-url: https://github.com/nodejs/node/pull/3516
<add> description: This method returns a boolean for flow control now.
<add> - version: v4.0.0
<add> pr-url: https://github.com/nodejs/node/pull/2620
<add> description: The `callback` parameter is supported now.
<ide> -->
<ide>
<ide> * `message` {Object} | 1 |
Python | Python | fix issue with python 3.x on windows [issue #291] | 4cac5f1f94cb6535947132aeebaaa76aa42cf97a | <ide><path>glances/glances.py
<ide> def run(self):
<ide>
<ide> def stop(self):
<ide> self.Terminated = True
<del> msvcrt.putch(' ')
<ide> while not self.q.empty():
<ide> self.q.get()
<ide> | 1 |
Javascript | Javascript | fix prompt value in ie8 | e4b1b073b12f5baf2800cffab47d1f828988d58d | <ide><path>packages/ember-handlebars/lib/controls/select.js
<ide> Ember.Select = Ember.View.extend(
<ide>
<ide> tagName: 'select',
<ide> classNames: ['ember-select'],
<del> defaultTemplate: Ember.Handlebars.compile('{{#if view.prompt}}<option value>{{view.prompt}}</option>{{/if}}{{#each view.content}}{{view Ember.SelectOption contentBinding="this"}}{{/each}}'),
<add> defaultTemplate: Ember.Handlebars.compile('{{#if view.prompt}}<option value="">{{view.prompt}}</option>{{/if}}{{#each view.content}}{{view Ember.SelectOption contentBinding="this"}}{{/each}}'),
<ide> attributeBindings: ['multiple', 'disabled', 'tabindex'],
<ide>
<ide> /** | 1 |
Java | Java | use array map from android support library | 1ece46b42cd94a10eb18b2b0eb1045794982a315 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModule.java
<ide> import android.content.Context;
<ide> import android.content.res.Configuration;
<ide> import android.media.AudioManager;
<del>import android.util.ArrayMap;
<ide> import android.view.View;
<add>import androidx.collection.ArrayMap;
<ide> import com.facebook.common.logging.FLog;
<ide> import com.facebook.debug.holder.PrinterHolder;
<ide> import com.facebook.debug.tags.ReactDebugOverlayTags; | 1 |
PHP | PHP | make connection on optional | 257f53f45a85ed4834bbb6505b4e403d64a0c2c5 | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public static function create(array $attributes)
<ide> * @param string $connection
<ide> * @return \Illuminate\Database\Eloquent\Builder
<ide> */
<del> public static function on($connection)
<add> public static function on($connection = null)
<ide> {
<ide> // First we will just create a fresh instance of this model, and then we can
<ide> // set the connection on the model so that it is be used for the queries | 1 |
Python | Python | update model conversion | fea15cc9f5939bbd1cb162921ae273da9de49c14 | <ide><path>pytorch_pretrained_bert/convert_transfo_xl_checkpoint_to_pytorch.py
<ide> def build_tf_to_pytorch_map(model, config):
<ide> layer_str + "ff/layer_2/bias": b.pos_ff.CoreNet[3].bias,
<ide> })
<ide>
<del> # Softmax cutoffs
<add> # Adaptive Softmax
<add> tf_to_pt_map.update({
<add> "transformer/adaptive_softmax/cutoff_0/cluster_W": model.crit.cluster_weight,
<add> "transformer/adaptive_softmax/cutoff_0/cluster_b": model.crit.cluster_bias})
<ide> for i, (out_l, proj_l, tie_proj) in enumerate(zip(
<ide> model.crit.out_layers,
<ide> model.crit.out_projs,
<ide> def convert_transfo_xl_checkpoint_to_pytorch(tf_checkpoint_path,
<ide> raise
<ide> print("Initialize PyTorch weight {} for layer {}".format(name, i))
<ide> p_i.data = torch.from_numpy(arr_i)
<del> continue
<del> try:
<del> assert pointer.shape == array.shape
<del> except AssertionError as e:
<del> e.args += (pointer.shape, array.shape)
<del> raise
<del> print("Initialize PyTorch weight {}".format(name))
<del> pointer.data = torch.from_numpy(array)
<add> else:
<add> try:
<add> assert pointer.shape == array.shape
<add> except AssertionError as e:
<add> e.args += (pointer.shape, array.shape)
<add> raise
<add> print("Initialize PyTorch weight {}".format(name))
<add> pointer.data = torch.from_numpy(array)
<add> del tf_weights[name]
<add>
<add> print("Weights not copied to PyTorch model: {}".format(', '.join(tf_weights.keys())))
<ide>
<ide> # Save pytorch-model
<ide> pytorch_weights_dump_path = pytorch_dump_folder_path + '/' + WEIGHTS_NAME
<ide><path>pytorch_pretrained_bert/modeling_transfo_xl.py
<ide> def from_pretrained(cls, pretrained_model_name_or_path, state_dict=None, cache_d
<ide> if state_dict is None:
<ide> state_dict = torch.load(resolved_archive_file)
<ide>
<del> old_keys = []
<del> new_keys = []
<del> for key in state_dict.keys():
<del> new_key = None
<del> if 'gamma' in key:
<del> new_key = key.replace('gamma', 'weight')
<del> if 'beta' in key:
<del> new_key = key.replace('beta', 'bias')
<del> if new_key:
<del> old_keys.append(key)
<del> new_keys.append(new_key)
<del> for old_key, new_key in zip(old_keys, new_keys):
<del> state_dict[new_key] = state_dict.pop(old_key)
<del>
<ide> missing_keys = []
<ide> unexpected_keys = []
<ide> error_msgs = [] | 2 |
Javascript | Javascript | fix error message when invoking wrong command | 31aacd78e8e3604ccde6326ff43a36132319c52b | <ide><path>private-cli/src/cli.js
<ide> function help() {
<ide> return Promise.resolve();
<ide> }
<ide>
<del>module.exports.run = run;
<add>module.exports = {
<add> commands: documentedCommands,
<add> run: run,
<add>}; | 1 |
Javascript | Javascript | use `async` a bit more in the api | ce3f5ea2bf73ab9d4a3d86bc61576f5d14785ab0 | <ide><path>src/display/api.js
<ide> function getDocument(src) {
<ide> * @param {Object} source
<ide> * @param {PDFDataRangeTransport} pdfDataRangeTransport
<ide> * @param {string} docId - Unique document ID, used in `MessageHandler`.
<del> * @returns {Promise} A promise that is resolved when the worker ID of the
<del> * `MessageHandler` is known.
<add> * @returns {Promise<string>} A promise that is resolved when the worker ID of
<add> * the `MessageHandler` is known.
<ide> * @private
<ide> */
<del>function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
<add>async function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
<ide> if (worker.destroyed) {
<del> return Promise.reject(new Error("Worker was destroyed"));
<add> throw new Error("Worker was destroyed");
<ide> }
<ide>
<ide> if (pdfDataRangeTransport) {
<ide> function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
<ide> source.contentDispositionFilename =
<ide> pdfDataRangeTransport.contentDispositionFilename;
<ide> }
<del> return worker.messageHandler
<del> .sendWithPromise("GetDocRequest", {
<add> const workerId = await worker.messageHandler.sendWithPromise(
<add> "GetDocRequest",
<add> {
<ide> docId,
<ide> apiVersion:
<ide> typeof PDFJSDev !== "undefined" && !PDFJSDev.test("TESTING")
<ide> function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
<ide> standardFontDataUrl: source.useWorkerFetch
<ide> ? source.standardFontDataUrl
<ide> : null,
<del> })
<del> .then(function (workerId) {
<del> if (worker.destroyed) {
<del> throw new Error("Worker was destroyed");
<del> }
<del> return workerId;
<del> });
<add> }
<add> );
<add>
<add> if (worker.destroyed) {
<add> throw new Error("Worker was destroyed");
<add> }
<add> return workerId;
<ide> }
<ide>
<ide> /**
<ide> class PDFDocumentLoadingTask {
<ide> * @returns {Promise<void>} A promise that is resolved when destruction is
<ide> * completed.
<ide> */
<del> destroy() {
<add> async destroy() {
<ide> this.destroyed = true;
<add> await this._transport?.destroy();
<ide>
<del> const transportDestroyed = !this._transport
<del> ? Promise.resolve()
<del> : this._transport.destroy();
<del> return transportDestroyed.then(() => {
<del> this._transport = null;
<del> if (this._worker) {
<del> this._worker.destroy();
<del> this._worker = null;
<del> }
<del> });
<add> this._transport = null;
<add> if (this._worker) {
<add> this._worker.destroy();
<add> this._worker = null;
<add> }
<ide> }
<ide> }
<ide>
<ide> class WorkerTransport {
<ide> }
<ide>
<ide> getPageIndex(ref) {
<del> return this.messageHandler
<del> .sendWithPromise("GetPageIndex", {
<del> ref,
<del> })
<del> .catch(function (reason) {
<del> return Promise.reject(new Error(reason));
<del> });
<add> return this.messageHandler.sendWithPromise("GetPageIndex", {
<add> ref,
<add> });
<ide> }
<ide>
<ide> getAnnotations(pageIndex, intent) { | 1 |
Ruby | Ruby | install gcc if glibc is too old | d6368806e88b1e3a94c355bb9c1fbe2d65236708 | <ide><path>Library/Homebrew/extend/os/linux/dependency_collector.rb
<ide> class DependencyCollector
<ide>
<ide> sig { params(related_formula_names: T::Set[String]).returns(T.nilable(Dependency)) }
<ide> def gcc_dep_if_needed(related_formula_names)
<del> return unless DevelopmentTools.system_gcc_too_old?
<add> # gcc is required for libgcc_s.so.1 if glibc or gcc are too old
<add> return unless DevelopmentTools.build_system_too_old?
<ide> return if building_global_dep_tree?
<ide> return if related_formula_names.include?(GCC)
<ide> return if global_dep_tree[GCC]&.intersect?(related_formula_names) | 1 |
Python | Python | change seed range for randomstreams in theano | 76cae0ec4463d350379e1da312386d97996040c4 | <ide><path>keras/backend/theano_backend.py
<ide> def dropout(x, level, seed=None):
<ide> if level < 0. or level >= 1:
<ide> raise Exception('Dropout level must be in interval [0, 1[.')
<ide> if seed is None:
<del> seed = np.random.randint(10e6)
<add> seed = np.random.randint(1, 10e6)
<ide> rng = RandomStreams(seed=seed)
<ide> retain_prob = 1. - level
<ide> x *= rng.binomial(x.shape, p=retain_prob, dtype=x.dtype)
<ide> def pool3d(x, pool_size, strides=(1, 1, 1), border_mode='valid',
<ide>
<ide> def random_normal(shape, mean=0.0, std=1.0, dtype=_FLOATX, seed=None):
<ide> if seed is None:
<del> seed = np.random.randint(10e6)
<add> seed = np.random.randint(1, 10e6)
<ide> rng = RandomStreams(seed=seed)
<ide> return rng.normal(size=shape, avg=mean, std=std, dtype=dtype)
<ide>
<ide>
<ide> def random_uniform(shape, low=0.0, high=1.0, dtype=_FLOATX, seed=None):
<ide> if seed is None:
<del> seed = np.random.randint(10e6)
<add> seed = np.random.randint(1, 10e6)
<ide> rng = RandomStreams(seed=seed)
<ide> return rng.uniform(shape, low=low, high=high, dtype=dtype)
<ide>
<ide>
<ide> def random_binomial(shape, p=0.0, dtype=_FLOATX, seed=None):
<ide> if seed is None:
<del> seed = np.random.randint(10e6)
<add> seed = np.random.randint(1, 10e6)
<ide> rng = RandomStreams(seed=seed)
<ide> return rng.binomial(shape, p=p, dtype=dtype) | 1 |
PHP | PHP | use static instead of self | 7371846bab898dcc6a910b8eff514cc4140c1141 | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public static function withoutTouching($callback)
<ide> {
<ide> $currentClass = static::class;
<ide>
<del> self::$ignoreOnTouch[] = $currentClass;
<add> static::$ignoreOnTouch[] = $currentClass;
<ide>
<ide> try {
<ide> call_user_func($callback);
<ide> } finally {
<del> self::$ignoreOnTouch = array_values(array_diff(self::$ignoreOnTouch, [$currentClass]));
<add> static::$ignoreOnTouch = array_values(array_diff(static::$ignoreOnTouch, [$currentClass]));
<ide> }
<ide> }
<ide>
<ide> public static function withoutTouching($callback)
<ide> */
<ide> public function shouldTouch()
<ide> {
<del> foreach (self::$ignoreOnTouch as $ignoredClass) {
<add> foreach (static::$ignoreOnTouch as $ignoredClass) {
<ide> if ($this instanceof $ignoredClass) {
<ide> return false;
<ide> } | 1 |
Javascript | Javascript | improve textinput docs | e1497ce2b6abc8810bfcc4643e3e72ceec3bd3a3 | <ide><path>Libraries/Components/TextInput/TextInput.js
<ide> const TextInput = React.createClass({
<ide> * - `default`
<ide> * - `numeric`
<ide> * - `email-address`
<add> * - `phone-pad`
<ide> */
<ide> keyboardType: PropTypes.oneOf([
<ide> // Cross-platform | 1 |
Ruby | Ruby | use map! instead of map for <association>_ids | 40b387580ff251e06632fbcc87c2a78c027a6b27 | <ide><path>activerecord/lib/active_record/associations.rb
<ide> def collection_reader_method(reflection, association_proxy_class)
<ide> if reflection.through_reflection && reflection.source_reflection.belongs_to?
<ide> through = reflection.through_reflection
<ide> primary_key = reflection.source_reflection.primary_key_name
<del> send(through.name).all(:select => "DISTINCT #{through.quoted_table_name}.#{primary_key}").map(&:"#{primary_key}")
<add> send(through.name).all(:select => "DISTINCT #{through.quoted_table_name}.#{primary_key}").map!(&:"#{primary_key}")
<ide> else
<del> send(reflection.name).all(:select => "#{reflection.quoted_table_name}.#{reflection.klass.primary_key}").map(&:id)
<add> send(reflection.name).all(:select => "#{reflection.quoted_table_name}.#{reflection.klass.primary_key}").map!(&:id)
<ide> end
<ide> end
<ide> end | 1 |
Python | Python | fix the dataset flag | eaf2bd1bf694a52236e6abd40cfbfed3ef041aa6 | <ide><path>official/resnet/keras/keras_main.py
<ide> def parse_record_keras(raw_record, is_training, dtype):
<ide> Returns:
<ide> Tuple with processed image tensor and one-hot-encoded label tensor.
<ide> """
<del> if shining.dataset == IMAGENET_DATASET:
<add> if flags_obj.dataset == IMAGENET_DATASET:
<ide> image_buffer, label, bbox = imagenet_main._parse_example_proto(raw_record)
<ide>
<ide> image = imagenet_preprocessing.preprocess_image(
<ide> def parse_record_keras(raw_record, is_training, dtype):
<ide> image = tf.cast(image, dtype)
<ide> label = tf.sparse_to_dense(label, (imagenet_main._NUM_CLASSES,), 1)
<ide>
<del> elif shining.dataset == CIFAR_DATASET:
<add> elif flags_obj.dataset == CIFAR_DATASET:
<ide> image, label = cifar_main.parse_record(raw_record, is_training, dtype)
<ide> label = tf.sparse_to_dense(label, (cifar_main._NUM_CLASSES,), 1)
<ide> else:
<del> raise ValueError("Unknown dataset: {%s}".format(shining.dataset))
<add> raise ValueError("Unknown dataset: {%s}".format(flags_obj.dataset))
<ide>
<ide> return image, label
<ide>
<ide> def run_imagenet_with_keras(flags_obj):
<ide> flags_obj.batch_size, flags_core.get_num_gpus(flags_obj))
<ide>
<ide> train_input_dataset, eval_input_dataset = get_data(
<del> shining.dataset, flags_obj.use_synthetic_data)
<add> flags_obj.dataset, flags_obj.use_synthetic_data)
<ide>
<ide> # Use Keras ResNet50 applications model and native keras APIs
<ide> # initialize RMSprop optimizer
<ide> def run_imagenet_with_keras(flags_obj):
<ide> strategy = distribution_utils.get_distribution_strategy(
<ide> num_gpus=flags_obj.num_gpus)
<ide>
<del> if shining.dataset == IMAGENET_DATASET:
<add> if flags_obj.dataset == IMAGENET_DATASET:
<ide> model = resnet_model_tpu.ResNet50(num_classes=imagenet_main._NUM_CLASSES)
<ide> steps_per_epoch = imagenet_main._NUM_IMAGES['train'] // flags_obj.batch_size
<ide>
<ide> def run_imagenet_with_keras(flags_obj):
<ide>
<ide> num_eval_steps = (imagenet_main._NUM_IMAGES['validation'] //
<ide> flags_obj.batch_size)
<del> elif shining.dataset = CIFAR_DATASET:
<add> elif flags_obj.dataset = CIFAR_DATASET:
<ide> model = keras_resnet_model.ResNet56(input_shape=(32, 32, 3),
<ide> include_top=True,
<ide> classes=cifar_main._NUM_CLASSES,
<ide> def run_imagenet_with_keras(flags_obj):
<ide> num_eval_steps = (cifar_main._NUM_IMAGES['validation'] //
<ide> flags_obj.batch_size)
<ide> else:
<del> raise ValueError("Unknown dataset: {%s}".format(shining.dataset))
<add> raise ValueError("Unknown dataset: {%s}".format(flags_obj.dataset))
<ide>
<ide> loss = 'categorical_crossentropy'
<ide> accuracy = 'categorical_accuracy'
<ide> def main(_):
<ide> tf.logging.set_verbosity(tf.logging.INFO)
<ide> define_keras_flags()
<ide>
<del> if shining.dataset == IMAGENET_DATASET:
<add> if flags_obj.dataset == IMAGENET_DATASET:
<ide> imagenet_main.define_imagenet_flags()
<del> elif shining.dataset == CIFAR_DATASET:
<add> elif flags_obj.dataset == CIFAR_DATASET:
<ide> cifar_main.define_cifar_flags()
<ide>
<ide> absl_app.run(main) | 1 |
Javascript | Javascript | add german translation for week | 57f9a8fdf532415a788328be3709a088c0321717 | <ide><path>src/locale/de-at.js
<ide> function processRelativeTime(number, withoutSuffix, key, isFuture) {
<ide> h: ['eine Stunde', 'einer Stunde'],
<ide> d: ['ein Tag', 'einem Tag'],
<ide> dd: [number + ' Tage', number + ' Tagen'],
<add> w: ['eine Woche', 'einer Woche'],
<ide> M: ['ein Monat', 'einem Monat'],
<ide> MM: [number + ' Monate', number + ' Monaten'],
<ide> y: ['ein Jahr', 'einem Jahr'],
<ide> export default moment.defineLocale('de-at', {
<ide> hh: '%d Stunden',
<ide> d: processRelativeTime,
<ide> dd: processRelativeTime,
<add> w: processRelativeTime,
<add> ww: '%d Wochen',
<ide> M: processRelativeTime,
<ide> MM: processRelativeTime,
<ide> y: processRelativeTime,
<ide><path>src/locale/de-ch.js
<ide> function processRelativeTime(number, withoutSuffix, key, isFuture) {
<ide> h: ['eine Stunde', 'einer Stunde'],
<ide> d: ['ein Tag', 'einem Tag'],
<ide> dd: [number + ' Tage', number + ' Tagen'],
<add> w: ['eine Woche', 'einer Woche'],
<ide> M: ['ein Monat', 'einem Monat'],
<ide> MM: [number + ' Monate', number + ' Monaten'],
<ide> y: ['ein Jahr', 'einem Jahr'],
<ide> export default moment.defineLocale('de-ch', {
<ide> hh: '%d Stunden',
<ide> d: processRelativeTime,
<ide> dd: processRelativeTime,
<add> w: processRelativeTime,
<add> ww: '%d Wochen',
<ide> M: processRelativeTime,
<ide> MM: processRelativeTime,
<ide> y: processRelativeTime,
<ide><path>src/locale/de.js
<ide> function processRelativeTime(number, withoutSuffix, key, isFuture) {
<ide> h: ['eine Stunde', 'einer Stunde'],
<ide> d: ['ein Tag', 'einem Tag'],
<ide> dd: [number + ' Tage', number + ' Tagen'],
<add> w: ['eine Woche', 'einer Woche'],
<ide> M: ['ein Monat', 'einem Monat'],
<ide> MM: [number + ' Monate', number + ' Monaten'],
<ide> y: ['ein Jahr', 'einem Jahr'],
<ide> export default moment.defineLocale('de', {
<ide> hh: '%d Stunden',
<ide> d: processRelativeTime,
<ide> dd: processRelativeTime,
<add> w: processRelativeTime,
<add> ww: '%d Wochen',
<ide> M: processRelativeTime,
<ide> MM: processRelativeTime,
<ide> y: processRelativeTime,
<ide><path>src/test/locale/de-at.js
<ide> test('weeks year starting sunday formatted', function (assert) {
<ide> 'Jan 15 2012 should be week 2'
<ide> );
<ide> });
<add>
<add>test('duration humanize week threshold', function (assert) {
<add> assert.equal(
<add> moment.duration(1, 'week').humanize({ d: 7, w: 4 }),
<add> 'eine Woche',
<add> 'a week'
<add> );
<add> assert.equal(
<add> moment.duration(-1, 'week').humanize({ d: 7, w: 4 }),
<add> 'eine Woche',
<add> 'a week'
<add> );
<add> assert.equal(
<add> moment.duration(-1, 'week').humanize(true, { d: 7, w: 4 }),
<add> 'vor einer Woche',
<add> 'a week ago'
<add> );
<add> assert.equal(
<add> moment.duration(1, 'week').humanize(true, { d: 7, w: 4 }),
<add> 'in einer Woche',
<add> 'in a week'
<add> );
<add> assert.equal(
<add> moment.duration(2, 'week').humanize({ d: 7, w: 4 }),
<add> '2 Wochen',
<add> '2 weeks'
<add> );
<add> assert.equal(
<add> moment.duration(-2, 'week').humanize({ d: 7, w: 4 }),
<add> '2 Wochen',
<add> '2 weeks'
<add> );
<add> assert.equal(
<add> moment.duration(2, 'week').humanize(true, { d: 7, w: 4 }),
<add> 'in 2 Wochen',
<add> 'in 2 week'
<add> );
<add> assert.equal(
<add> moment.duration(-2, 'week').humanize(true, { d: 7, w: 4 }),
<add> 'vor 2 Wochen',
<add> '2 weeks ago'
<add> );
<add>});
<ide><path>src/test/locale/de-ch.js
<ide> test('weeks year starting sunday formatted', function (assert) {
<ide> 'Jan 15 2012 should be week 2'
<ide> );
<ide> });
<add>
<add>test('duration humanize week threshold', function (assert) {
<add> assert.equal(
<add> moment.duration(1, 'week').humanize({ d: 7, w: 4 }),
<add> 'eine Woche',
<add> 'a week'
<add> );
<add> assert.equal(
<add> moment.duration(-1, 'week').humanize({ d: 7, w: 4 }),
<add> 'eine Woche',
<add> 'a week'
<add> );
<add> assert.equal(
<add> moment.duration(-1, 'week').humanize(true, { d: 7, w: 4 }),
<add> 'vor einer Woche',
<add> 'a week ago'
<add> );
<add> assert.equal(
<add> moment.duration(1, 'week').humanize(true, { d: 7, w: 4 }),
<add> 'in einer Woche',
<add> 'in a week'
<add> );
<add> assert.equal(
<add> moment.duration(2, 'week').humanize({ d: 7, w: 4 }),
<add> '2 Wochen',
<add> '2 weeks'
<add> );
<add> assert.equal(
<add> moment.duration(-2, 'week').humanize({ d: 7, w: 4 }),
<add> '2 Wochen',
<add> '2 weeks'
<add> );
<add> assert.equal(
<add> moment.duration(2, 'week').humanize(true, { d: 7, w: 4 }),
<add> 'in 2 Wochen',
<add> 'in 2 week'
<add> );
<add> assert.equal(
<add> moment.duration(-2, 'week').humanize(true, { d: 7, w: 4 }),
<add> 'vor 2 Wochen',
<add> '2 weeks ago'
<add> );
<add>});
<ide><path>src/test/locale/de.js
<ide> test('weeks year starting sunday formatted', function (assert) {
<ide> 'Jan 15 2012 should be week 2'
<ide> );
<ide> });
<add>
<add>test('duration humanize week threshold', function (assert) {
<add> assert.equal(
<add> moment.duration(1, 'week').humanize({ d: 7, w: 4 }),
<add> 'eine Woche',
<add> 'a week'
<add> );
<add> assert.equal(
<add> moment.duration(-1, 'week').humanize({ d: 7, w: 4 }),
<add> 'eine Woche',
<add> 'a week'
<add> );
<add> assert.equal(
<add> moment.duration(-1, 'week').humanize(true, { d: 7, w: 4 }),
<add> 'vor einer Woche',
<add> 'a week ago'
<add> );
<add> assert.equal(
<add> moment.duration(1, 'week').humanize(true, { d: 7, w: 4 }),
<add> 'in einer Woche',
<add> 'in a week'
<add> );
<add> assert.equal(
<add> moment.duration(2, 'week').humanize({ d: 7, w: 4 }),
<add> '2 Wochen',
<add> '2 weeks'
<add> );
<add> assert.equal(
<add> moment.duration(-2, 'week').humanize({ d: 7, w: 4 }),
<add> '2 Wochen',
<add> '2 weeks'
<add> );
<add> assert.equal(
<add> moment.duration(2, 'week').humanize(true, { d: 7, w: 4 }),
<add> 'in 2 Wochen',
<add> 'in 2 week'
<add> );
<add> assert.equal(
<add> moment.duration(-2, 'week').humanize(true, { d: 7, w: 4 }),
<add> 'vor 2 Wochen',
<add> '2 weeks ago'
<add> );
<add>}); | 6 |
Javascript | Javascript | add flow types in reactcontrolledcomponent | 409e472fcaae2b6c171f4e9a0c4b5ad88ec2bf21 | <ide><path>packages/events/ReactControlledComponent.js
<ide> *
<ide> * This source code is licensed under the MIT license found in the
<ide> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow
<ide> */
<ide>
<ide> import invariant from 'shared/invariant';
<ide> function restoreStateOfTarget(target) {
<ide> restoreImpl(internalInstance.stateNode, internalInstance.type, props);
<ide> }
<ide>
<del>export function setRestoreImplementation(impl) {
<add>export function setRestoreImplementation(
<add> impl: (domElement: Element, tag: string, props: Object) => void,
<add>): void {
<ide> restoreImpl = impl;
<ide> }
<ide>
<del>export function enqueueStateRestore(target) {
<add>export function enqueueStateRestore(target: EventTarget): void {
<ide> if (restoreTarget) {
<ide> if (restoreQueue) {
<ide> restoreQueue.push(target); | 1 |
Javascript | Javascript | remove output field from debugger | 5545d43bc46886aa38ded62f6b24bb4a5952b198 | <ide><path>examples/fiber/debugger/src/describeFibers.js
<ide> export default function describeFibers(rootFiber, workInProgress) {
<ide> tag: getFriendlyTag(fiber.tag),
<ide> type: (fiber.type && ('<' + (fiber.type.name || fiber.type) + '>')),
<ide> stateNode: `[${typeof fiber.stateNode}]`,
<del> output: `[${typeof fiber.output}]`,
<ide> return: acknowledgeFiber(fiber.return),
<ide> child: acknowledgeFiber(fiber.child),
<ide> sibling: acknowledgeFiber(fiber.sibling), | 1 |
Ruby | Ruby | return false for exists? with new records - fixes | fa21b73ebb8339ad388f149c817c433b6254d490 | <ide><path>activerecord/lib/active_record/relation/finder_methods.rb
<ide> def all
<ide> # Person.exists?(['name LIKE ?', "%#{query}%"])
<ide> # Person.exists?
<ide> def exists?(id = false)
<del> return false if id.nil?
<del>
<ide> id = id.id if ActiveRecord::Model === id
<add> return false if id.nil?
<ide>
<ide> join_dependency = construct_join_dependency_for_association_find
<ide> relation = construct_relation_for_association_find(join_dependency)
<ide><path>activerecord/test/cases/finder_test.rb
<ide> def test_exists
<ide> assert Topic.exists?(:author_name => "Mary", :approved => true)
<ide> assert Topic.exists?(["parent_id = ?", 1])
<ide> assert !Topic.exists?(45)
<add> assert !Topic.exists?(Topic.new)
<ide>
<ide> begin
<ide> assert !Topic.exists?("foo")
<ide><path>activerecord/test/cases/relations_test.rb
<ide> def test_exists
<ide> assert ! davids.exists?(authors(:mary).id)
<ide> assert ! davids.exists?("42")
<ide> assert ! davids.exists?(42)
<add> assert ! davids.exists?(davids.new)
<ide>
<ide> fake = Author.where(:name => 'fake author')
<ide> assert ! fake.exists? | 3 |
Text | Text | remove confusing "cats" from style guide | cca12ee3216a418642518d066d8b2684634b4121 | <ide><path>doc/STYLE_GUIDE.md
<ide> * Pronouns are acceptable in more colloquial documentation, like guides.
<ide> * Use gender-neutral pronouns and mass nouns. Non-comprehensive
<ide> examples:
<del> * OK: "they", "their", "them", "folks", "people", "developers", "cats"
<add> * OK: "they", "their", "them", "folks", "people", "developers"
<ide> * NOT OK: "his", "hers", "him", "her", "guys", "dudes"
<ide> * When combining wrapping elements (parentheses and quotes), terminal
<ide> punctuation should be placed: | 1 |
Python | Python | add tests for serializing parser | 0051c05964220ef8e80bddda2a1010a088aa60c7 | <ide><path>spacy/tests/serialize/test_serialize_parser.py
<add># coding: utf-8
<add>from __future__ import unicode_literals
<add>
<add>from ..util import make_tempdir
<add>from ...pipeline import NeuralDependencyParser as Parser
<add>
<add>import pytest
<add>
<add>
<add>def test_serialize_parser_roundtrip_bytes(en_vocab):
<add> parser = Parser(en_vocab)
<add> parser.model, _ = parser.Model(0)
<add> parser_b = parser.to_bytes()
<add> new_parser = Parser(en_vocab)
<add> new_parser.model, _ = new_parser.Model(0)
<add> new_parser = new_parser.from_bytes(parser_b)
<add> assert new_parser.to_bytes() == parser_b
<add>
<add>
<add>def test_serialize_parser_roundtrip_disk(en_vocab):
<add> parser = Parser(en_vocab)
<add> parser.model, _ = parser.Model(0)
<add> with make_tempdir() as d:
<add> file_path = d / 'parser'
<add> parser.to_disk(file_path)
<add> parser_d = Parser(en_vocab)
<add> parser_d.model, _ = parser_d.Model(0)
<add> parser_d = parser_d.from_disk(file_path)
<add> assert parser.to_bytes() == parser_d.to_bytes() | 1 |
PHP | PHP | fix tests that broke when rebasing | 53843dd1c72dc62b7c962cc37cf114d9e5967f3b | <ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testSelectMultiple() {
<ide> '/select'
<ide> );
<ide> $this->assertTags($result, $expected);
<add> }
<ide>
<ide> /**
<ide> * Test that a checkbox can have 0 for the value and 1 for the hidden input.
<ide> *
<ide> * @return void
<ide> */
<ide> public function testCheckboxZeroValue() {
<add> $this->markTestIncomplete('Need to revisit once models work again.');
<ide> $result = $this->Form->input('User.get_spam', array(
<ide> 'type' => 'checkbox',
<ide> 'value' => '0',
<ide> public function testCheckboxZeroValue() {
<ide> $this->assertTags($result, $expected);
<ide> }
<ide>
<del>/**
<del> * testDateTime method
<del> *
<del> * Test generation of date/time select elements
<del> *
<del> * @return void
<del> */
<del> public function testDateTime() {
<del> $this->markTestIncomplete('Need to revisit once models work again.');
<del> $result = $this->Form->select(
<del> 'Model.multi_field', $options, array('multiple' => true, 'value' => array(0, 1))
<del> );
<del> $expected = array(
<del> 'input' => array(
<del> 'type' => 'hidden', 'name' => 'Model[multi_field]', 'value' => '', 'id' => 'ModelMultiField_'
<del> ),
<del> 'select' => array(
<del> 'name' => 'Model[multi_field][]', 'id' => 'ModelMultiField',
<del> 'multiple' => 'multiple'
<del> ),
<del> array('option' => array('value' => '0', 'selected' => 'selected')),
<del> 'first',
<del> '/option',
<del> array('option' => array('value' => '1', 'selected' => 'selected')),
<del> 'second',
<del> '/option',
<del> array('option' => array('value' => '2')),
<del> 'third',
<del> '/option',
<del> '/select'
<del> );
<del> $this->assertTags($result, $expected);
<del>
<del> $result = $this->Form->select(
<del> 'Model.multi_field', $options, array('multiple' => false, 'value' => array(0, 1))
<del> );
<del> $expected = array(
<del> 'select' => array(
<del> 'name' => 'Model[multi_field]', 'id' => 'ModelMultiField'
<del> ),
<del> array('option' => array('value' => '0', 'selected' => 'selected')),
<del> 'first',
<del> '/option',
<del> array('option' => array('value' => '1', 'selected' => 'selected')),
<del> 'second',
<del> '/option',
<del> array('option' => array('value' => '2')),
<del> 'third',
<del> '/option',
<del> '/select'
<del> );
<del> $this->assertTags($result, $expected);
<del>
<del> $options = array(1 => 'One', 2 => 'Two', '3' => 'Three', '3x' => 'Stringy');
<del> $selected = array('2', '3x');
<del> $result = $this->Form->select(
<del> 'Model.multi_field', $options, array('multiple' => true, 'value' => $selected)
<del> );
<del> $expected = array(
<del> 'input' => array(
<del> 'type' => 'hidden', 'name' => 'Model[multi_field]', 'value' => '', 'id' => 'ModelMultiField_'
<del> ),
<del> 'select' => array(
<del> 'name' => 'Model[multi_field][]', 'multiple' => 'multiple', 'id' => 'ModelMultiField'
<del> ),
<del> array('option' => array('value' => '1')),
<del> 'One',
<del> '/option',
<del> array('option' => array('value' => '2', 'selected' => 'selected')),
<del> 'Two',
<del> '/option',
<del> array('option' => array('value' => '3')),
<del> 'Three',
<del> '/option',
<del> array('option' => array('value' => '3x', 'selected' => 'selected')),
<del> 'Stringy',
<del> '/option',
<del> '/select'
<del> );
<del> $this->assertTags($result, $expected);
<del>
<del> $result = $this->Form->select('Contact.required_one', array(
<del> '1' => 'option A',
<del> '2' => 'option B'
<del> ), array('multiple' => true));
<del> $expected = array(
<del> 'input' => array(
<del> 'type' => 'hidden', 'name' => 'data[Contact][required_one]', 'value' => '', 'id' => 'ContactRequiredOne_'
<del> ),
<del> 'select' => array(
<del> 'name' => 'data[Contact][required_one][]',
<del> 'id' => 'ContactRequiredOne',
<del> 'required' => 'required',
<del> 'multiple' => 'multiple'
<del> ),
<del> array('option' => array('value' => '1')), 'option A', '/option',
<del> array('option' => array('value' => '2')), 'option B', '/option',
<del> '/select'
<del> );
<del> $this->assertTags($result, $expected);
<del>
<del> $result = $this->Form->select(
<del> 'Model.multi_field',
<del> array('a>b' => 'first', 'a<b' => 'second', 'a"b' => 'third'),
<del> array('multiple' => true)
<del> );
<del> $expected = array(
<del> 'input' => array(
<del> 'type' => 'hidden', 'name' => 'data[Model][multi_field]', 'value' => '',
<del> 'id' => 'ModelMultiField_'
<del> ),
<del> array('select' => array('name' => 'data[Model][multi_field][]',
<del> 'multiple' => 'multiple', 'id' => 'ModelMultiField'
<del> )),
<del> array('option' => array('value' => 'a>b')),
<del> 'first',
<del> '/option',
<del> array('option' => array('value' => 'a<b')),
<del> 'second',
<del> '/option',
<del> array('option' => array(
<del> 'value' => 'a"b'
<del> )),
<del> 'third',
<del> '/option',
<del> '/select'
<del> );
<del> $this->assertTags($result, $expected);
<del> }
<del>
<ide> /**
<ide> * Test generating multiple select with disabled elements.
<ide> * | 1 |
Ruby | Ruby | use respond_to? instead of nomethoderror | 0472b3f34048b7396631d33d4e1cda506ce1a5b1 | <ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def doctor
<ide>
<ide> first_warning = true
<ide> methods.each do |method|
<del> begin
<del> out = checks.send(method)
<del> rescue NoMethodError
<add> unless checks.respond_to?(method)
<ide> Homebrew.failed = true
<ide> puts "No check available by the name: #{method}"
<ide> next
<ide> end
<add>
<add> out = checks.send(method)
<ide> unless out.nil? || out.empty?
<ide> if first_warning
<ide> $stderr.puts <<-EOS.undent | 1 |
Text | Text | add parentheses to function and move reference | ab42ef39300a986fee7149a8578fbac564798ae4 | <ide><path>doc/api/readline.md
<ide> will not terminate until it receives `EOF` (<kbd>Ctrl</kbd>+<kbd>D</kbd> on
<ide> Linux/macOS, <kbd>Ctrl</kbd>+<kbd>Z</kbd> followed by <kbd>Return</kbd> on
<ide> Windows).
<ide> If you want your application to exit without waiting for user input, you can
<del>[`unref`][] the standard input stream:
<add>[`unref()`][] the standard input stream:
<ide>
<ide> ```js
<ide> process.stdin.unref();
<ide> const { createInterface } = require('readline');
<ide> [`process.stdin`]: process.md#process_process_stdin
<ide> [`process.stdout`]: process.md#process_process_stdout
<ide> [`rl.close()`]: #readline_rl_close
<add>[`unref()`]: net.md#net_socket_unref
<ide> [reading files]: #readline_example_read_file_stream_line_by_line
<del>[`unref`]: net.md#net_socket_unref | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.