content_type stringclasses 8
values | main_lang stringclasses 7
values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Javascript | Javascript | fix --debug-brk; hacky solution | b5b83b210bb9873cd6b5052e5f5d260eb1f9d2f9 | <ide><path>lib/module.js
<ide> Module.prototype._compile = function (content, filename) {
<ide> + "\n});";
<ide>
<ide> var compiledWrapper = process.compile(wrapper, filename);
<add> if (filename === process.argv[1]) process.checkBreak();
<ide> compiledWrapper.apply(self.exports, [self.exports, require, self, filename, dirname]);
<ide> } else {
<ide> self.exports = content; | 1 |
Javascript | Javascript | remove unused rctrenderingperf | 94d9f00dd681af817a316c648c3da462b08ae0d3 | <ide><path>Libraries/Core/InitializeCore.js
<ide> if (__DEV__) {
<ide>
<ide> require('RCTDebugComponentOwnership');
<ide>
<del> // In order to use Cmd+P to record/dump perf data, we need to make sure
<del> // this module is available in the bundle
<del> require('RCTRenderingPerf');
<del>
<ide> // Set up inspector
<ide> const JSInspector = require('JSInspector');
<ide> JSInspector.registerAgent(require('NetworkAgent'));
<ide><path>Libraries/Performance/RCTRenderingPerf.js
<del>/**
<del> * Copyright (c) 2015-present, Facebook, Inc.
<del> * All rights reserved.
<del> *
<del> * This source code is licensed under the BSD-style license found in the
<del> * LICENSE file in the root directory of this source tree. An additional grant
<del> * of patent rights can be found in the PATENTS file in the same directory.
<del> *
<del> * @providesModule RCTRenderingPerf
<del> * @flow
<del> */
<del>'use strict';
<del>
<del>var invariant = require('fbjs/lib/invariant');
<del>var performanceNow = require('fbjs/lib/performanceNow');
<del>
<del>type perfModule = {
<del> start: () => void,
<del> stop: () => void,
<del>}
<del>
<del>var perfModules = [];
<del>var enabled = false;
<del>
<del>var RCTRenderingPerf = {
<del> // Once perf is enabled, it stays enabled
<del> toggle: function() {
<del> console.log('Render perfomance measurements enabled');
<del> enabled = true;
<del> },
<del>
<del> start: function() {
<del> if (!enabled) {
<del> return;
<del> }
<del>
<del> perfModules.forEach((module) => module.start());
<del> },
<del>
<del> stop: function() {
<del> if (!enabled) {
<del> return;
<del> }
<del>
<del> perfModules.forEach((module) => module.stop());
<del> },
<del>
<del> register: function(module: perfModule) {
<del> invariant(
<del> typeof module.start === 'function',
<del> 'Perf module should have start() function'
<del> );
<del> invariant(
<del> typeof module.stop === 'function',
<del> 'Perf module should have stop() function'
<del> );
<del> perfModules.push(module);
<del> }
<del>};
<del>
<del>module.exports = RCTRenderingPerf; | 2 |
PHP | PHP | move empty key detection above starts_with check | 8f1a966925e28cf32274727013c7efa72868c96a | <ide><path>src/Illuminate/Encryption/EncryptionServiceProvider.php
<ide> public function register()
<ide> $this->app->singleton('encrypter', function ($app) {
<ide> $config = $app->make('config')->get('app');
<ide>
<del> // If the key starts with "base64:", we will need to decode the key before handing
<del> // it off to the encrypter. Keys may be base-64 encoded for presentation and we
<del> // want to make sure to convert them back to the raw bytes before encrypting.
<del> if (Str::startsWith($key = $config['key'], 'base64:')) {
<del> $key = base64_decode(substr($key, 7));
<del> }
<add> $key = $config['key'];
<ide>
<ide> if (is_null($key) || $key === '') {
<ide> throw new RuntimeException(
<ide> 'The application encryption key is missing. Run php artisan key:generate to generate it.'
<ide> );
<ide> }
<ide>
<add> // If the key starts with "base64:", we will need to decode the key before handing
<add> // it off to the encrypter. Keys may be base-64 encoded for presentation and we
<add> // want to make sure to convert them back to the raw bytes before encrypting.
<add> if (Str::startsWith($key, 'base64:')) {
<add> $key = base64_decode(substr($key, 7));
<add> }
<add>
<ide> return new Encrypter($key, $config['cipher']);
<ide> });
<ide> } | 1 |
Text | Text | add correct commands for installing and running mo | b96c4d39f52d1c496dfc18947e3e4ec5433250ef | <ide><path>CONTRIBUTING.md
<ide> node -v
<ide> mongo --version
<ide> ```
<ide>
<add>To check your MongoDB version on Windows, you have to locate the installation directory. It is probably located at something like `C:\Program Files\MongoDB\Server\3.4\` where 3.4 is your version number.
<add>
<ide> If your versions are lower than the prerequisite versions, you should update.
<ide>
<ide> Platform-specific guides to setting up a development environment:
<ide> Now you will need to start MongoDB, and then seed the database, then you can sta
<ide>
<ide> ```bash
<ide> # Start the mongo server in a separate terminal
<add># On OS X:
<ide> mongod
<ide>
<add># If you are using Windows, you have to instead specify the full path to the mongod binary
<add># Make sure to replace 3.4 with the version you have installed
<add>"C:\Program Files\MongoDB\Server\3.4\bin\mongod"
<add>
<ide> # Initialize freeCodeCamp
<ide> # This will seed the database for the first time.
<ide> # This command should only be run once. | 1 |
Text | Text | fix typo in xlnet readme | 0ba8a3b0d0139ad94cebf0f4596beae355fa437c | <ide><path>official/nlp/xlnet/README.md
<ide> Setup commands:
<ide> export SPIECE_DIR=~/cased_spiece/
<ide> export SPIECE_MODEL=${SPIECE_DIR}/cased_spiece.model
<ide> export DATASETS_DIR=gs://some_bucket/datasets
<del>mkdir -p ${SPIECE_MODEL}
<add>mkdir -p ${SPIECE_DIR}
<ide> gsutil cp gs://cloud-tpu-checkpoints/xlnet/cased_spiece.model ${SPIECE_DIR}
<ide> ```
<ide> | 1 |
PHP | PHP | use more atomic options when creating directories | c666593663bbea6c5ed05abb9986de2d98815669 | <ide><path>src/Cache/Engine/FileEngine.php
<ide> protected function _setKey($key, $createKey = false)
<ide> }
<ide> $dir = $this->_config['path'] . $groups;
<ide>
<del> if (!is_dir($dir)) {
<del> mkdir($dir, 0775, true);
<del> }
<add> // @codingStandardsIgnoreStart
<add> @mkdir($dir, 0775, true);
<add> // @codingStandardsIgnoreEnd
<add>
<ide> $path = new SplFileInfo($dir . $key);
<ide>
<ide> if (!$createKey && !$path->isFile()) { | 1 |
Python | Python | fix a bug with parse_qsl and python 2.5 | 1446a99ea9ef56354d2f6cea3f1613ac5e1071b0 | <ide><path>test/common/test_cloudstack.py
<ide> except:
<ide> import simplejson as json
<ide>
<add>try:
<add> parse_qsl = urlparse.parse_qsl
<add>except AttributeError:
<add> import cgi
<add> parse_qsl = cgi.parse_qsl
<add>
<ide> from libcloud.common.cloudstack import CloudStackConnection, CloudStackResponse
<ide> from libcloud.common.types import MalformedResponseError
<ide>
<ide> def _response(self, status, result, response):
<ide>
<ide> def _check_request(self, url):
<ide> url = urlparse.urlparse(url)
<del> query = dict(urlparse.parse_qsl(url.query))
<add> query = dict(parse_qsl(url.query))
<ide>
<ide> self.assertTrue('apiKey' in query)
<ide> self.assertTrue('command' in query)
<ide><path>test/compute/test_cloudstack.py
<ide> except:
<ide> import simplejson as json
<ide>
<add>try:
<add> parse_qsl = urlparse.parse_qsl
<add>except AttributeError:
<add> import cgi
<add> parse_qsl = cgi.parse_qsl
<add>
<ide> from libcloud.compute.drivers.cloudstack import CloudStackNodeDriver
<ide> from libcloud.compute.types import DeploymentError
<ide>
<ide> def _load_fixture(self, fixture):
<ide>
<ide> def _test_path(self, method, url, body, headers):
<ide> url = urlparse.urlparse(url)
<del> query = dict(urlparse.parse_qsl(url.query))
<add> query = dict(parse_qsl(url.query))
<ide>
<ide> self.assertTrue('apiKey' in query)
<ide> self.assertTrue('command' in query)
<ide><path>test/loadbalancer/test_cloudstack.py
<ide> except:
<ide> import simplejson as json
<ide>
<add>try:
<add> parse_qsl = urlparse.parse_qsl
<add>except AttributeError:
<add> import cgi
<add> parse_qsl = cgi.parse_qsl
<add>
<ide> from libcloud.common.types import LibcloudError
<ide> from libcloud.loadbalancer.base import LoadBalancer, Member, Algorithm
<ide> from libcloud.loadbalancer.drivers.cloudstack import CloudStackLBDriver
<ide> def _load_fixture(self, fixture):
<ide>
<ide> def _test_path(self, method, url, body, headers):
<ide> url = urlparse.urlparse(url)
<del> query = dict(urlparse.parse_qsl(url.query))
<add> query = dict(parse_qsl(url.query))
<ide>
<ide> self.assertTrue('apiKey' in query)
<ide> self.assertTrue('command' in query) | 3 |
PHP | PHP | fix beanstalkd tests | a656d2d8ac3906347ad838b95de5c3d9b2e12066 | <ide><path>tests/Queue/QueueBeanstalkdQueueTest.php
<ide> public function tearDown()
<ide>
<ide> public function testPushProperlyPushesJobOntoBeanstalkd()
<ide> {
<del> $queue = new Illuminate\Queue\BeanstalkdQueue(m::mock('Pheanstalk_Pheanstalk'), 'default');
<add> $queue = new Illuminate\Queue\BeanstalkdQueue(m::mock('Pheanstalk_Pheanstalk'), 'default', 60);
<ide> $pheanstalk = $queue->getPheanstalk();
<ide> $pheanstalk->shouldReceive('useTube')->once()->with('stack')->andReturn($pheanstalk);
<ide> $pheanstalk->shouldReceive('useTube')->once()->with('default')->andReturn($pheanstalk);
<ide> public function testPushProperlyPushesJobOntoBeanstalkd()
<ide>
<ide> public function testDelayedPushProperlyPushesJobOntoBeanstalkd()
<ide> {
<del> $queue = new Illuminate\Queue\BeanstalkdQueue(m::mock('Pheanstalk_Pheanstalk'), 'default');
<add> $queue = new Illuminate\Queue\BeanstalkdQueue(m::mock('Pheanstalk_Pheanstalk'), 'default', 60);
<ide> $pheanstalk = $queue->getPheanstalk();
<ide> $pheanstalk->shouldReceive('useTube')->once()->with('stack')->andReturn($pheanstalk);
<ide> $pheanstalk->shouldReceive('useTube')->once()->with('default')->andReturn($pheanstalk);
<ide> public function testDelayedPushProperlyPushesJobOntoBeanstalkd()
<ide>
<ide> public function testPopProperlyPopsJobOffOfBeanstalkd()
<ide> {
<del> $queue = new Illuminate\Queue\BeanstalkdQueue(m::mock('Pheanstalk_Pheanstalk'), 'default');
<add> $queue = new Illuminate\Queue\BeanstalkdQueue(m::mock('Pheanstalk_Pheanstalk'), 'default', 60);
<ide> $queue->setContainer(m::mock('Illuminate\Container\Container'));
<ide> $pheanstalk = $queue->getPheanstalk();
<ide> $pheanstalk->shouldReceive('watchOnly')->once()->with('default')->andReturn($pheanstalk); | 1 |
Go | Go | skip dockersuite.testruncapaddchown on lxc | 0547b5fb2ac98d67eea3ed56f4afae87dff3079c | <ide><path>integration-cli/docker_cli_run_test.go
<ide> func (s *DockerSuite) TestDevicePermissions(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunCapAddCHOWN(c *check.C) {
<add> testRequires(c, NativeExecDriver)
<ide> out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=CHOWN", "busybox", "sh", "-c", "adduser -D -H newuser && chown newuser /home && echo ok")
<ide>
<ide> if actual := strings.Trim(out, "\r\n"); actual != "ok" { | 1 |
Go | Go | implement docker system df | 8d0dc6902788f36254bde052e867bdea98c4d42e | <ide><path>api/server/router/system/system_routes.go
<ide> func (s *systemRouter) getDiskUsage(ctx context.Context, w http.ResponseWriter,
<ide> var getContainers, getImages, getVolumes, getBuildCache bool
<ide> typeStrs, ok := r.Form["type"]
<ide> if versions.LessThan(version, "1.42") || !ok {
<del> getContainers, getImages, getVolumes, getBuildCache = true, true, true, true
<add> getContainers, getImages, getVolumes, getBuildCache = true, true, true, s.builder != nil
<ide> } else {
<ide> for _, typ := range typeStrs {
<ide> switch types.DiskUsageObject(typ) {
<ide><path>daemon/containerd/service.go
<ide> package containerd
<ide>
<ide> import (
<ide> "context"
<del> "errors"
<ide>
<ide> "github.com/containerd/containerd"
<ide> "github.com/containerd/containerd/plugin"
<add> "github.com/containerd/containerd/snapshots"
<ide> "github.com/docker/docker/api/types"
<add> "github.com/docker/docker/api/types/filters"
<ide> "github.com/docker/docker/container"
<ide> "github.com/docker/docker/daemon/images"
<ide> "github.com/docker/docker/errdefs"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/layer"
<add> "github.com/pkg/errors"
<add> "golang.org/x/sync/singleflight"
<ide> )
<ide>
<ide> // ImageService implements daemon.ImageService
<ide> type ImageService struct {
<ide> client *containerd.Client
<ide> snapshotter string
<add> usage singleflight.Group
<ide> }
<ide>
<ide> // NewService creates a new ImageService.
<ide> func (i *ImageService) ReleaseLayer(rwlayer layer.RWLayer) error {
<ide> // LayerDiskUsage returns the number of bytes used by layer stores
<ide> // called from disk_usage.go
<ide> func (i *ImageService) LayerDiskUsage(ctx context.Context) (int64, error) {
<del> return 0, errdefs.NotImplemented(errors.New("not implemented"))
<add> ch := i.usage.DoChan("LayerDiskUsage", func() (interface{}, error) {
<add> var allLayersSize int64
<add> snapshotter := i.client.SnapshotService(i.snapshotter)
<add> snapshotter.Walk(ctx, func(ctx context.Context, info snapshots.Info) error {
<add> usage, err := snapshotter.Usage(ctx, info.Name)
<add> if err != nil {
<add> return err
<add> }
<add> allLayersSize += usage.Size
<add> return nil
<add> })
<add> return allLayersSize, nil
<add> })
<add> select {
<add> case <-ctx.Done():
<add> return 0, ctx.Err()
<add> case res := <-ch:
<add> if res.Err != nil {
<add> return 0, res.Err
<add> }
<add> return res.Val.(int64), nil
<add> }
<ide> }
<ide>
<ide> // ImageDiskUsage returns information about image data disk usage.
<ide> func (i *ImageService) ImageDiskUsage(ctx context.Context) ([]*types.ImageSummary, error) {
<del> return nil, errdefs.NotImplemented(errors.New("not implemented"))
<add> ch := i.usage.DoChan("ImageDiskUsage", func() (interface{}, error) {
<add> // Get all top images with extra attributes
<add> imgs, err := i.Images(ctx, types.ImageListOptions{
<add> Filters: filters.NewArgs(),
<add> SharedSize: true,
<add> ContainerCount: true,
<add> })
<add> if err != nil {
<add> return nil, errors.Wrap(err, "failed to retrieve image list")
<add> }
<add> return imgs, nil
<add> })
<add> select {
<add> case <-ctx.Done():
<add> return nil, ctx.Err()
<add> case res := <-ch:
<add> if res.Err != nil {
<add> return nil, res.Err
<add> }
<add> return res.Val.([]*types.ImageSummary), nil
<add> }
<ide> }
<ide>
<ide> // UpdateConfig values
<ide><path>daemon/images/service.go
<ide> package images // import "github.com/docker/docker/daemon/images"
<ide>
<ide> import (
<ide> "context"
<del> "fmt"
<ide> "os"
<ide>
<ide> "github.com/containerd/containerd/content"
<ide> func (i *ImageService) getLayerRefs() map[layer.ChainID]int {
<ide> func (i *ImageService) ImageDiskUsage(ctx context.Context) ([]*types.ImageSummary, error) {
<ide> ch := i.usage.DoChan("ImageDiskUsage", func() (interface{}, error) {
<ide> // Get all top images with extra attributes
<del> images, err := i.Images(ctx, types.ImageListOptions{
<add> imgs, err := i.Images(ctx, types.ImageListOptions{
<ide> Filters: filters.NewArgs(),
<ide> SharedSize: true,
<ide> ContainerCount: true,
<ide> })
<ide> if err != nil {
<del> return nil, fmt.Errorf("failed to retrieve image list: %v", err)
<add> return nil, errors.Wrap(err, "failed to retrieve image list")
<ide> }
<del> return images, nil
<add> return imgs, nil
<ide> })
<ide> select {
<ide> case <-ctx.Done(): | 3 |
Java | Java | fix unused import warning | 461816735fe7414d5883ec1f013bc3339c69b021 | <ide><path>spring-core/src/main/java/org/springframework/core/ResolvableType.java
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.ClassUtils;
<ide> import org.springframework.util.ConcurrentReferenceHashMap;
<del>import org.springframework.util.ConcurrentReferenceHashMap.ReferenceType;
<ide> import org.springframework.util.ObjectUtils;
<ide> import org.springframework.util.StringUtils;
<ide> | 1 |
Javascript | Javascript | add newline before jsx spread when appropriate | cc9735f8897df40a6c79343cbb6a77123b1df9ad | <ide><path>vendor/fbtransform/transforms/__tests__/react-test.js
<ide> describe('react jsx', function() {
<ide> '<Component { ... x } y\n' +
<ide> '={2 } z />';
<ide> var result =
<del> 'React.createElement(Component, Object.assign({}, x , {y: \n' +
<add> 'React.createElement(Component, Object.assign({}, x , {y: \n' +
<ide> '2, z: true}))';
<ide>
<ide> expect(transform(code).code).toBe(result);
<ide> });
<ide>
<add> it('adds appropriate newlines when using spread attribute', function() {
<add> var code =
<add> '<Component\n' +
<add> ' {...this.props}\n' +
<add> ' sound="moo" />';
<add> var result =
<add> 'React.createElement(Component, Object.assign({}, \n' +
<add> ' this.props, \n' +
<add> ' {sound: "moo"}))';
<add>
<add> expect(transform(code).code).toBe(result);
<add> });
<add>
<ide> it('should transform known hyphenated tags', function() {
<ide> var code = [
<ide> '/**',
<ide><path>vendor/fbtransform/transforms/react.js
<ide> function visitReactTag(traverse, object, path, state) {
<ide> var isLast = index === attributesObject.length - 1;
<ide>
<ide> if (attr.type === Syntax.XJSSpreadAttribute) {
<del> // Plus 1 to skip `{`.
<del> utils.move(attr.range[0] + 1, state);
<del>
<ide> // Close the previous object or initial object
<ide> if (!previousWasSpread) {
<ide> utils.append('}, ', state);
<ide> }
<ide>
<add>
<ide> // Move to the expression start, ignoring everything except parenthesis
<ide> // and whitespace.
<add> utils.catchup(attr.range[0], state, stripNonWhiteParen);
<add> // Plus 1 to skip `{`.
<add> utils.move(attr.range[0] + 1, state);
<ide> utils.catchup(attr.argument.range[0], state, stripNonWhiteParen);
<ide>
<ide> traverse(attr.argument, path, state); | 2 |
Ruby | Ruby | create empty zshrc when zsh is shell" | 274f21388e3db056069fc176b24e543d666854c6 | <ide><path>Library/Homebrew/formula.rb
<ide> def stage
<ide> @buildpath = Pathname.pwd
<ide> env_home = buildpath/".brew_home"
<ide> mkdir_p env_home
<del> touch env_home/".zshrc" if ENV["SHELL"].include? "zsh"
<ide>
<ide> old_home, ENV["HOME"] = ENV["HOME"], env_home
<ide> | 1 |
Ruby | Ruby | change the version to 7.0.0.alpha | 2345b80c0cfa0766875274a9e4e237a09e08b302 | <ide><path>lib/arel.rb
<ide> require 'arel/nodes'
<ide>
<ide> module Arel
<del> VERSION = '6.0.0'
<add> VERSION = '7.0.0.alpha'
<ide>
<ide> def self.sql raw_sql
<ide> Arel::Nodes::SqlLiteral.new raw_sql | 1 |
Go | Go | add unit test to cover changes | 027297a60f5f5a70e1e3eb3a68280f64c66bc877 | <ide><path>builder/dockerfile/copy_test.go
<ide> package dockerfile
<ide>
<ide> import (
<add> "net/http"
<ide> "testing"
<ide>
<ide> "github.com/gotestyourself/gotestyourself/fs"
<ide> func TestIsExistingDirectory(t *testing.T) {
<ide> assert.Equal(t, testcase.expected, result, testcase.doc)
<ide> }
<ide> }
<add>
<add>func TestGetFilenameForDownload(t *testing.T) {
<add> var testcases = []struct {
<add> path string
<add> disposition string
<add> expected string
<add> }{
<add> {
<add> path: "http://www.example.com/",
<add> expected: "",
<add> },
<add> {
<add> path: "http://www.example.com/xyz",
<add> expected: "xyz",
<add> },
<add> {
<add> path: "http://www.example.com/xyz.html",
<add> expected: "xyz.html",
<add> },
<add> {
<add> path: "http://www.example.com/xyz/",
<add> expected: "",
<add> },
<add> {
<add> path: "http://www.example.com/xyz/uvw",
<add> expected: "uvw",
<add> },
<add> {
<add> path: "http://www.example.com/xyz/uvw.html",
<add> expected: "uvw.html",
<add> },
<add> {
<add> path: "http://www.example.com/xyz/uvw/",
<add> expected: "",
<add> },
<add> {
<add> path: "/",
<add> expected: "",
<add> },
<add> {
<add> path: "/xyz",
<add> expected: "xyz",
<add> },
<add> {
<add> path: "/xyz.html",
<add> expected: "xyz.html",
<add> },
<add> {
<add> path: "/xyz/",
<add> expected: "",
<add> },
<add> {
<add> path: "/xyz/",
<add> disposition: "attachment; filename=xyz.html",
<add> expected: "xyz.html",
<add> },
<add> {
<add> disposition: "",
<add> expected: "",
<add> },
<add> {
<add> disposition: "attachment; filename=xyz",
<add> expected: "xyz",
<add> },
<add> {
<add> disposition: "attachment; filename=xyz.html",
<add> expected: "xyz.html",
<add> },
<add> {
<add> disposition: "attachment; filename=\"xyz\"",
<add> expected: "xyz",
<add> },
<add> {
<add> disposition: "attachment; filename=\"xyz.html\"",
<add> expected: "xyz.html",
<add> },
<add> {
<add> disposition: "attachment; filename=\"/xyz.html\"",
<add> expected: "xyz.html",
<add> },
<add> {
<add> disposition: "attachment; filename=\"/xyz/uvw\"",
<add> expected: "uvw",
<add> },
<add> {
<add> disposition: "attachment; filename=\"Naïve file.txt\"",
<add> expected: "Naïve file.txt",
<add> },
<add> }
<add> for _, testcase := range testcases {
<add> resp := http.Response{
<add> Header: make(map[string][]string),
<add> }
<add> if testcase.disposition != "" {
<add> resp.Header.Add("Content-Disposition", testcase.disposition)
<add> }
<add> filename := getFilenameForDownload(testcase.path, &resp)
<add> assert.Equal(t, testcase.expected, filename)
<add> }
<add>}
<ide><path>integration-cli/docker_cli_build_test.go
<ide> RUN touch /foop
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(d.String(), checker.Equals, getIDByName(c, name))
<ide> }
<del>
<del>// Test case for #34208
<del>func (s *DockerSuite) TestBuildAddHTTPRoot(c *check.C) {
<del> testRequires(c, Network, DaemonIsLinux)
<del> buildImageSuccessfully(c, "buildaddhttproot", build.WithDockerfile(`
<del> FROM scratch
<del> ADD http://example.com/index.html /example1
<del> ADD http://example.com /example2
<del> ADD http://example.com /example3`))
<del> buildImage("buildaddhttprootfailure", build.WithDockerfile(`
<del> FROM scratch
<del> ADD http://example.com/ /`)).Assert(c, icmd.Expected{
<del> ExitCode: 1,
<del> Err: "cannot determine filename for source http://example.com/",
<del> })
<del>} | 2 |
Mixed | Go | add filter by event type and documentation | 851fe00c64ffafeb27b12f7b0ed8e41f7720b477 | <ide><path>api/client/events.go
<ide> func (cli *DockerCli) CmdEvents(args ...string) error {
<ide>
<ide> // streamEvents decodes prints the incoming events in the provided output.
<ide> func streamEvents(input io.Reader, output io.Writer) error {
<add> return decodeEvents(input, func(event eventtypes.Message, err error) error {
<add> if err != nil {
<add> return err
<add> }
<add> printOutput(event, output)
<add> return nil
<add> })
<add>}
<add>
<add>type eventProcessor func(event eventtypes.Message, err error) error
<add>
<add>func decodeEvents(input io.Reader, ep eventProcessor) error {
<ide> dec := json.NewDecoder(input)
<ide> for {
<ide> var event eventtypes.Message
<del> if err := dec.Decode(&event); err != nil {
<del> if err == io.EOF {
<del> break
<del> }
<del> return err
<add> err := dec.Decode(&event)
<add> if err != nil && err == io.EOF {
<add> break
<add> }
<add>
<add> if procErr := ep(event, err); procErr != nil {
<add> return procErr
<ide> }
<del> printOutput(event, output)
<ide> }
<ide> return nil
<ide> }
<ide><path>api/client/stats.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/docker/docker/api/types"
<add> "github.com/docker/docker/api/types/events"
<add> "github.com/docker/docker/api/types/filters"
<ide> Cli "github.com/docker/docker/cli"
<del> "github.com/docker/docker/pkg/jsonmessage"
<ide> "github.com/docker/go-units"
<ide> )
<ide>
<ide> func (cli *DockerCli) CmdStats(args ...string) error {
<ide> err error
<ide> }
<ide> getNewContainers := func(c chan<- watch) {
<del> options := types.EventsOptions{}
<add> f := filters.NewArgs()
<add> f.Add("type", "container")
<add> options := types.EventsOptions{
<add> Filters: f,
<add> }
<ide> resBody, err := cli.client.Events(options)
<ide> if err != nil {
<ide> c <- watch{err: err}
<ide> return
<ide> }
<ide> defer resBody.Close()
<ide>
<del> dec := json.NewDecoder(resBody)
<del> for {
<del> var j *jsonmessage.JSONMessage
<del> if err := dec.Decode(&j); err != nil {
<add> decodeEvents(resBody, func(event events.Message, err error) error {
<add> if err != nil {
<ide> c <- watch{err: err}
<del> return
<add> return nil
<ide> }
<del> c <- watch{j.ID[:12], j.Status, nil}
<del> }
<add>
<add> c <- watch{event.ID[:12], event.Action, nil}
<add> return nil
<add> })
<ide> }
<ide> go func(stopChan chan<- error) {
<ide> cChan := make(chan watch)
<ide><path>daemon/events/filter.go
<ide> func NewFilter(filter filters.Args) *Filter {
<ide>
<ide> // Include returns true when the event ev is included by the filters
<ide> func (ef *Filter) Include(ev events.Message) bool {
<del> if ev.Type != events.ContainerEventType && ev.Type != events.ImageEventType {
<del> return false
<del> }
<ide> return ef.filter.ExactMatch("event", ev.Action) &&
<add> ef.filter.ExactMatch("type", ev.Type) &&
<ide> ef.matchContainer(ev) &&
<del> ef.isImageIncluded(ev) &&
<del> ef.isLabelFieldIncluded(ev.Actor.Attributes)
<add> ef.matchVolume(ev) &&
<add> ef.matchNetwork(ev) &&
<add> ef.matchImage(ev) &&
<add> ef.matchLabels(ev.Actor.Attributes)
<ide> }
<ide>
<del>func (ef *Filter) isLabelFieldIncluded(attributes map[string]string) bool {
<add>func (ef *Filter) matchLabels(attributes map[string]string) bool {
<ide> if !ef.filter.Include("label") {
<ide> return true
<ide> }
<ide> return ef.filter.MatchKVList("label", attributes)
<ide> }
<ide>
<ide> func (ef *Filter) matchContainer(ev events.Message) bool {
<del> return ef.filter.FuzzyMatch("container", ev.Actor.ID) ||
<del> ef.filter.FuzzyMatch("container", ev.Actor.Attributes["name"])
<add> return ef.fuzzyMatchName(ev, events.ContainerEventType)
<add>}
<add>
<add>func (ef *Filter) matchVolume(ev events.Message) bool {
<add> return ef.fuzzyMatchName(ev, events.VolumeEventType)
<add>}
<add>
<add>func (ef *Filter) matchNetwork(ev events.Message) bool {
<add> return ef.fuzzyMatchName(ev, events.NetworkEventType)
<ide> }
<ide>
<del>// The image filter will be matched against both event.ID (for image events)
<del>// and event.From (for container events), so that any container that was created
<add>func (ef *Filter) fuzzyMatchName(ev events.Message, eventType string) bool {
<add> return ef.filter.FuzzyMatch(eventType, ev.Actor.ID) ||
<add> ef.filter.FuzzyMatch(eventType, ev.Actor.Attributes["name"])
<add>}
<add>
<add>// matchImage matches against both event.Actor.ID (for image events)
<add>// and event.Actor.Attributes["image"] (for container events), so that any container that was created
<ide> // from an image will be included in the image events. Also compare both
<ide> // against the stripped repo name without any tags.
<del>func (ef *Filter) isImageIncluded(ev events.Message) bool {
<del> id := ev.ID
<add>func (ef *Filter) matchImage(ev events.Message) bool {
<add> id := ev.Actor.ID
<add> nameAttr := "image"
<ide> var imageName string
<del> if n, ok := ev.Actor.Attributes["image"]; ok {
<add>
<add> if ev.Type == events.ImageEventType {
<add> nameAttr = "name"
<add> }
<add>
<add> if n, ok := ev.Actor.Attributes[nameAttr]; ok {
<ide> imageName = n
<ide> }
<ide> return ef.filter.ExactMatch("image", id) ||
<ide><path>docs/misc/deprecated.md
<ide> parent = "mn_use_docker"
<ide>
<ide> The following list of features are deprecated.
<ide>
<add>### Ambiguous event fields in API
<add>**Deprecated In Release: v1.10**
<add>
<add>The fields `ID`, `Status` and `From` in the events API have been deprecated in favor of a more rich structure.
<add>See the events API documentation for the new format.
<add>
<ide> ### `-f` flag on `docker tag`
<ide> **Deprecated In Release: v1.10**
<ide>
<ide><path>docs/reference/api/docker_remote_api_v1.22.md
<ide> Status Codes:
<ide>
<ide> `GET /events`
<ide>
<del>Get container events from docker, either in real time via streaming, or via
<del>polling (using since).
<add>Get container events from docker, either in real time via streaming, or via polling (using since).
<ide>
<ide> Docker containers report the following events:
<ide>
<del> attach, commit, copy, create, destroy, die, exec_create, exec_start, export, kill, oom, pause, rename, resize, restart, start, stop, top, unpause
<add> attach, commit, copy, create, destroy, die, exec_create, exec_start, export, kill, oom, pause, rename, resize, restart, start, stop, top, unpause, update
<ide>
<del>and Docker images report:
<add>Docker images report the following events:
<ide>
<ide> delete, import, pull, push, tag, untag
<ide>
<add>Docker volumes report the following events:
<add>
<add> create, mount, unmount, destroy
<add>
<add>Docker networks report the following events:
<add>
<add> create, connect, disconnect, destroy
<add>
<ide> **Example request**:
<ide>
<ide> GET /events?since=1374067924
<ide> and Docker images report:
<ide> HTTP/1.1 200 OK
<ide> Content-Type: application/json
<ide>
<del> {"status":"pull","id":"busybox:latest","time":1442421700,"timeNano":1442421700598988358}
<del> {"status":"create","id":"5745704abe9caa5","from":"busybox","time":1442421716,"timeNano":1442421716853979870}
<del> {"status":"attach","id":"5745704abe9caa5","from":"busybox","time":1442421716,"timeNano":1442421716894759198}
<del> {"status":"start","id":"5745704abe9caa5","from":"busybox","time":1442421716,"timeNano":1442421716983607193}
<add> [
<add> {
<add> "action": "pull",
<add> "type": "image",
<add> "actor": {
<add> "id": "busybox:latest",
<add> "attributes": {}
<add> }
<add> "time": 1442421700,
<add> "timeNano": 1442421700598988358
<add> },
<add> {
<add> "action": "create",
<add> "type": "container",
<add> "actor": {
<add> "id": "5745704abe9caa5",
<add> "attributes": {"image": "busybox"}
<add> }
<add> "time": 1442421716,
<add> "timeNano": 1442421716853979870
<add> },
<add> {
<add> "action": "attach",
<add> "type": "container",
<add> "actor": {
<add> "id": "5745704abe9caa5",
<add> "attributes": {"image": "busybox"}
<add> }
<add> "time": 1442421716,
<add> "timeNano": 1442421716894759198
<add> },
<add> {
<add> "action": "start",
<add> "type": "container",
<add> "actor": {
<add> "id": "5745704abe9caa5",
<add> "attributes": {"image": "busybox"}
<add> }
<add> "time": 1442421716,
<add> "timeNano": 1442421716983607193
<add> }
<add> ]
<ide>
<ide> Query Parameters:
<ide>
<ide> Query Parameters:
<ide> - `event=<string>`; -- event to filter
<ide> - `image=<string>`; -- image to filter
<ide> - `label=<string>`; -- image and container label to filter
<add> - `type=<string>`; -- either `container` or `image` or `volume` or `network`
<add> - `volume=<string>`; -- volume to filter
<add> - `network=<string>`; -- network to filter
<ide>
<ide> Status Codes:
<ide>
<ide><path>docs/reference/commandline/events.md
<ide> parent = "smn_cli"
<ide> --since="" Show all events created since timestamp
<ide> --until="" Stream events until this timestamp
<ide>
<del>Docker containers will report the following events:
<add>Docker containers report the following events:
<ide>
<del> attach, commit, copy, create, destroy, die, exec_create, exec_start, export, kill, oom, pause, rename, resize, restart, start, stop, top, unpause
<add> attach, commit, copy, create, destroy, die, exec_create, exec_start, export, kill, oom, pause, rename, resize, restart, start, stop, top, unpause, update
<ide>
<del>and Docker images will report:
<add>Docker images report the following events:
<ide>
<ide> delete, import, pull, push, tag, untag
<ide>
<add>Docker volumes report the following events:
<add>
<add> create, mount, unmount, destroy
<add>
<add>Docker networks report the following events:
<add>
<add> create, connect, disconnect, destroy
<add>
<ide> The `--since` and `--until` parameters can be Unix timestamps, date formatted
<ide> timestamps, or Go duration strings (e.g. `10m`, `1h30m`) computed
<ide> relative to the client machine’s time. If you do not provide the --since option,
<ide> container container 588a23dac085 *AND* the event type is *start*
<ide> The currently supported filters are:
<ide>
<ide> * container (`container=<name or id>`)
<del>* event (`event=<event type>`)
<add>* event (`event=<event action>`)
<ide> * image (`image=<tag or id>`)
<ide> * label (`label=<key>` or `label=<key>=<value>`)
<add>* type (`type=<container or image or volume or network>`)
<add>* volume (`volume=<name or id>`)
<add>* network (`network=<name or id>`)
<ide>
<ide> ## Examples
<ide>
<ide> You'll need two shells for this example.
<ide>
<ide> **Shell 1: (Again .. now showing events):**
<ide>
<del> 2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) start
<del> 2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) die
<del> 2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) stop
<del> 2014-05-10T17:42:14.999999999Z07:00 7805c1d35632: (from redis:2.8) die
<del> 2014-05-10T17:42:14.999999999Z07:00 7805c1d35632: (from redis:2.8) stop
<add> 2015-05-12T11:51:30.999999999Z07:00 container start 4386fb97867d (image=ubuntu-1:14.04)
<add> 2015-05-12T11:51:30.999999999Z07:00 container die 4386fb97867d (image=ubuntu-1:14.04)
<add> 2015-05-12T15:52:12.999999999Z07:00 container stop 4386fb97867d (image=ubuntu-1:14.04)
<add> 2015-05-12T15:53:45.999999999Z07:00 container die 7805c1d35632 (image=redis:2.8)
<add> 2015-05-12T15:54:03.999999999Z07:00 container stop 7805c1d35632 (image=redis:2.8)
<ide>
<ide> **Show events in the past from a specified time:**
<ide>
<ide> $ docker events --since 1378216169
<del> 2014-03-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) die
<del> 2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) stop
<del> 2014-05-10T17:42:14.999999999Z07:00 7805c1d35632: (from redis:2.8) die
<del> 2014-03-10T17:42:14.999999999Z07:00 7805c1d35632: (from redis:2.8) stop
<add> 2015-05-12T11:51:30.999999999Z07:00 container die 4386fb97867d (image=ubuntu-1:14.04)
<add> 2015-05-12T15:52:12.999999999Z07:00 container stop 4386fb97867d (image=ubuntu-1:14.04)
<add> 2015-05-12T15:53:45.999999999Z07:00 container die 7805c1d35632 (image=redis:2.8)
<add> 2015-05-12T15:54:03.999999999Z07:00 container stop 7805c1d35632 (image=redis:2.8)
<ide>
<ide> $ docker events --since '2013-09-03'
<del> 2014-09-03T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) start
<del> 2014-09-03T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) die
<del> 2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) stop
<del> 2014-05-10T17:42:14.999999999Z07:00 7805c1d35632: (from redis:2.8) die
<del> 2014-09-03T17:42:14.999999999Z07:00 7805c1d35632: (from redis:2.8) stop
<add> 2015-05-12T11:51:30.999999999Z07:00 container start 4386fb97867d (image=ubuntu-1:14.04)
<add> 2015-05-12T11:51:30.999999999Z07:00 container die 4386fb97867d (image=ubuntu-1:14.04)
<add> 2015-05-12T15:52:12.999999999Z07:00 container stop 4386fb97867d (image=ubuntu-1:14.04)
<add> 2015-05-12T15:53:45.999999999Z07:00 container die 7805c1d35632 (image=redis:2.8)
<add> 2015-05-12T15:54:03.999999999Z07:00 container stop 7805c1d35632 (image=redis:2.8)
<ide>
<ide> $ docker events --since '2013-09-03T15:49:29'
<del> 2014-09-03T15:49:29.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) die
<del> 2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) stop
<del> 2014-05-10T17:42:14.999999999Z07:00 7805c1d35632: (from redis:2.8) die
<del> 2014-09-03T15:49:29.999999999Z07:00 7805c1d35632: (from redis:2.8) stop
<add> 2015-05-12T11:51:30.999999999Z07:00 container die 4386fb97867d (image=ubuntu-1:14.04)
<add> 2015-05-12T15:52:12.999999999Z07:00 container stop 4386fb97867d (image=ubuntu-1:14.04)
<add> 2015-05-12T15:53:45.999999999Z07:00 container die 7805c1d35632 (image=redis:2.8)
<add> 2015-05-12T15:54:03.999999999Z07:00 container stop 7805c1d35632 (image=redis:2.8)
<ide>
<ide> This example outputs all events that were generated in the last 3 minutes,
<ide> relative to the current time on the client machine:
<ide>
<ide> $ docker events --since '3m'
<del> 2015-05-12T11:51:30.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) die
<del> 2015-05-12T15:52:12.999999999Z07:00 4 4386fb97867d: (from ubuntu-1:14.04) stop
<del> 2015-05-12T15:53:45.999999999Z07:00 7805c1d35632: (from redis:2.8) die
<del> 2015-05-12T15:54:03.999999999Z07:00 7805c1d35632: (from redis:2.8) stop
<add> 2015-05-12T11:51:30.999999999Z07:00 container die 4386fb97867d (image=ubuntu-1:14.04)
<add> 2015-05-12T15:52:12.999999999Z07:00 container stop 4386fb97867d (image=ubuntu-1:14.04)
<add> 2015-05-12T15:53:45.999999999Z07:00 container die 7805c1d35632 (image=redis:2.8)
<add> 2015-05-12T15:54:03.999999999Z07:00 container stop 7805c1d35632 (image=redis:2.8)
<ide>
<ide> **Filter events:**
<ide>
<ide> $ docker events --filter 'event=stop'
<del> 2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) stop
<del> 2014-09-03T17:42:14.999999999Z07:00 7805c1d35632: (from redis:2.8) stop
<add> 2014-05-10T17:42:14.999999999Z07:00 container stop 4386fb97867d (image=ubuntu-1:14.04)
<add> 2014-09-03T17:42:14.999999999Z07:00 container stop 7805c1d35632 (image=redis:2.8)
<ide>
<ide> $ docker events --filter 'image=ubuntu-1:14.04'
<del> 2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) start
<del> 2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) die
<del> 2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) stop
<add> 2014-05-10T17:42:14.999999999Z07:00 container start 4386fb97867d (image=ubuntu-1:14.04)
<add> 2014-05-10T17:42:14.999999999Z07:00 container die 4386fb97867d (image=ubuntu-1:14.04)
<add> 2014-05-10T17:42:14.999999999Z07:00 container stop 4386fb97867d (image=ubuntu-1:14.04)
<ide>
<ide> $ docker events --filter 'container=7805c1d35632'
<del> 2014-05-10T17:42:14.999999999Z07:00 7805c1d35632: (from redis:2.8) die
<del> 2014-09-03T15:49:29.999999999Z07:00 7805c1d35632: (from redis:2.8) stop
<add> 2014-05-10T17:42:14.999999999Z07:00 container die 7805c1d35632 (image=redis:2.8)
<add> 2014-09-03T15:49:29.999999999Z07:00 container stop 7805c1d35632 (image= redis:2.8)
<ide>
<ide> $ docker events --filter 'container=7805c1d35632' --filter 'container=4386fb97867d'
<del> 2014-09-03T15:49:29.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) die
<del> 2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) stop
<del> 2014-05-10T17:42:14.999999999Z07:00 7805c1d35632: (from redis:2.8) die
<del> 2014-09-03T15:49:29.999999999Z07:00 7805c1d35632: (from redis:2.8) stop
<add> 2014-09-03T15:49:29.999999999Z07:00 container die 4386fb97867d (image=ubuntu-1:14.04)
<add> 2014-05-10T17:42:14.999999999Z07:00 container stop 4386fb97867d (image=ubuntu-1:14.04)
<add> 2014-05-10T17:42:14.999999999Z07:00 container die 7805c1d35632 (image=redis:2.8)
<add> 2014-09-03T15:49:29.999999999Z07:00 container stop 7805c1d35632 (image=redis:2.8)
<ide>
<ide> $ docker events --filter 'container=7805c1d35632' --filter 'event=stop'
<del> 2014-09-03T15:49:29.999999999Z07:00 7805c1d35632: (from redis:2.8) stop
<add> 2014-09-03T15:49:29.999999999Z07:00 container stop 7805c1d35632 (image=redis:2.8)
<ide>
<ide> $ docker events --filter 'container=container_1' --filter 'container=container_2'
<del> 2014-09-03T15:49:29.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) die
<del> 2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) stop
<del> 2014-05-10T17:42:14.999999999Z07:00 7805c1d35632: (from redis:2.8) die
<del> 2014-09-03T15:49:29.999999999Z07:00 7805c1d35632: (from redis:2.8) stop
<add> 2014-09-03T15:49:29.999999999Z07:00 container die 4386fb97867d (image=ubuntu-1:14.04)
<add> 2014-05-10T17:42:14.999999999Z07:00 container stop 4386fb97867d (image=ubuntu-1:14.04)
<add> 2014-05-10T17:42:14.999999999Z07:00 container die 7805c1d35632 (imager=redis:2.8)
<add> 2014-09-03T15:49:29.999999999Z07:00 container stop 7805c1d35632 (image=redis:2.8)
<add>
<add> $ docker events --filter 'type=volume'
<add> 2015-12-23T21:05:28.136212689Z volume create test-event-volume-local (driver=local)
<add> 2015-12-23T21:05:28.383462717Z volume mount test-event-volume-local (read/write=true, container=562fe10671e9273da25eed36cdce26159085ac7ee6707105fd534866340a5025, destination=/foo, driver=local, propagation=rprivate)
<add> 2015-12-23T21:05:28.650314265Z volume unmount test-event-volume-local (container=562fe10671e9273da25eed36cdce26159085ac7ee6707105fd534866340a5025, driver=local)
<add> 2015-12-23T21:05:28.716218405Z volume destroy test-event-volume-local (driver=local)
<add>
<add> $ docker events --filter 'type=network'
<add> 2015-12-23T21:38:24.705709133Z network create 8b111217944ba0ba844a65b13efcd57dc494932ee2527577758f939315ba2c5b (name=test-event-network-local, type=bridge)
<add> 2015-12-23T21:38:25.119625123Z network connect 8b111217944ba0ba844a65b13efcd57dc494932ee2527577758f939315ba2c5b (name=test-event-network-local, container=b4be644031a3d90b400f88ab3d4bdf4dc23adb250e696b6328b85441abe2c54e, type=bridge)
<ide><path>integration-cli/docker_cli_build_test.go
<ide> package main
<ide>
<ide> import (
<ide> "archive/tar"
<del> "bufio"
<ide> "bytes"
<ide> "encoding/json"
<ide> "fmt"
<ide> func (s *DockerSuite) TestBuildForceRm(c *check.C) {
<ide>
<ide> }
<ide>
<del>// Test that an infinite sleep during a build is killed if the client disconnects.
<del>// This test is fairly hairy because there are lots of ways to race.
<del>// Strategy:
<del>// * Monitor the output of docker events starting from before
<del>// * Run a 1-year-long sleep from a docker build.
<del>// * When docker events sees container start, close the "docker build" command
<del>// * Wait for docker events to emit a dying event.
<del>func (s *DockerSuite) TestBuildCancellationKillsSleep(c *check.C) {
<del> testRequires(c, DaemonIsLinux)
<del> name := "testbuildcancellation"
<del>
<del> observer, err := newEventObserver(c)
<del> c.Assert(err, checker.IsNil)
<del> err = observer.Start()
<del> c.Assert(err, checker.IsNil)
<del> defer observer.Stop()
<del>
<del> // (Note: one year, will never finish)
<del> ctx, err := fakeContext("FROM busybox\nRUN sleep 31536000", nil)
<del> if err != nil {
<del> c.Fatal(err)
<del> }
<del> defer ctx.Close()
<del>
<del> buildCmd := exec.Command(dockerBinary, "build", "-t", name, ".")
<del> buildCmd.Dir = ctx.Dir
<del>
<del> stdoutBuild, err := buildCmd.StdoutPipe()
<del> if err := buildCmd.Start(); err != nil {
<del> c.Fatalf("failed to run build: %s", err)
<del> }
<del>
<del> matchCID := regexp.MustCompile("Running in (.+)")
<del> scanner := bufio.NewScanner(stdoutBuild)
<del>
<del> outputBuffer := new(bytes.Buffer)
<del> var buildID string
<del> for scanner.Scan() {
<del> line := scanner.Text()
<del> outputBuffer.WriteString(line)
<del> outputBuffer.WriteString("\n")
<del> if matches := matchCID.FindStringSubmatch(line); len(matches) > 0 {
<del> buildID = matches[1]
<del> break
<del> }
<del> }
<del>
<del> if buildID == "" {
<del> c.Fatalf("Unable to find build container id in build output:\n%s", outputBuffer.String())
<del> }
<del>
<del> testActions := map[string]chan bool{
<del> "start": make(chan bool),
<del> "die": make(chan bool),
<del> }
<del>
<del> go observer.Match(matchEventLine(buildID, "container", testActions))
<del>
<del> select {
<del> case <-time.After(10 * time.Second):
<del> c.Fatal(observer.TimeoutError(buildID, "start"))
<del> case <-testActions["start"]:
<del> // ignore, done
<del> }
<del>
<del> // Send a kill to the `docker build` command.
<del> // Causes the underlying build to be cancelled due to socket close.
<del> if err := buildCmd.Process.Kill(); err != nil {
<del> c.Fatalf("error killing build command: %s", err)
<del> }
<del>
<del> // Get the exit status of `docker build`, check it exited because killed.
<del> if err := buildCmd.Wait(); err != nil && !isKilled(err) {
<del> c.Fatalf("wait failed during build run: %T %s", err, err)
<del> }
<del>
<del> select {
<del> case <-time.After(10 * time.Second):
<del> c.Fatal(observer.TimeoutError(buildID, "die"))
<del> case <-testActions["die"]:
<del> // ignore, done
<del> }
<del>}
<del>
<ide> func (s *DockerSuite) TestBuildRm(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<ide> name := "testbuildrm"
<ide><path>integration-cli/docker_cli_build_unix_test.go
<ide> package main
<ide>
<ide> import (
<add> "bufio"
<add> "bytes"
<ide> "encoding/json"
<ide> "io/ioutil"
<ide> "os"
<ide> "os/exec"
<ide> "path/filepath"
<add> "regexp"
<ide> "strings"
<add> "time"
<ide>
<ide> "github.com/docker/docker/pkg/integration/checker"
<ide> "github.com/docker/go-units"
<ide> func (s *DockerSuite) TestBuildAddChangeOwnership(c *check.C) {
<ide> if _, err := buildImageFromContext(name, ctx, true); err != nil {
<ide> c.Fatalf("build failed to complete for TestBuildAddChangeOwnership: %v", err)
<ide> }
<add>}
<add>
<add>// Test that an infinite sleep during a build is killed if the client disconnects.
<add>// This test is fairly hairy because there are lots of ways to race.
<add>// Strategy:
<add>// * Monitor the output of docker events starting from before
<add>// * Run a 1-year-long sleep from a docker build.
<add>// * When docker events sees container start, close the "docker build" command
<add>// * Wait for docker events to emit a dying event.
<add>func (s *DockerSuite) TestBuildCancellationKillsSleep(c *check.C) {
<add> testRequires(c, DaemonIsLinux)
<add> name := "testbuildcancellation"
<add>
<add> observer, err := newEventObserver(c)
<add> c.Assert(err, checker.IsNil)
<add> err = observer.Start()
<add> c.Assert(err, checker.IsNil)
<add> defer observer.Stop()
<ide>
<add> // (Note: one year, will never finish)
<add> ctx, err := fakeContext("FROM busybox\nRUN sleep 31536000", nil)
<add> if err != nil {
<add> c.Fatal(err)
<add> }
<add> defer ctx.Close()
<add>
<add> buildCmd := exec.Command(dockerBinary, "build", "-t", name, ".")
<add> buildCmd.Dir = ctx.Dir
<add>
<add> stdoutBuild, err := buildCmd.StdoutPipe()
<add> if err := buildCmd.Start(); err != nil {
<add> c.Fatalf("failed to run build: %s", err)
<add> }
<add>
<add> matchCID := regexp.MustCompile("Running in (.+)")
<add> scanner := bufio.NewScanner(stdoutBuild)
<add>
<add> outputBuffer := new(bytes.Buffer)
<add> var buildID string
<add> for scanner.Scan() {
<add> line := scanner.Text()
<add> outputBuffer.WriteString(line)
<add> outputBuffer.WriteString("\n")
<add> if matches := matchCID.FindStringSubmatch(line); len(matches) > 0 {
<add> buildID = matches[1]
<add> break
<add> }
<add> }
<add>
<add> if buildID == "" {
<add> c.Fatalf("Unable to find build container id in build output:\n%s", outputBuffer.String())
<add> }
<add>
<add> testActions := map[string]chan bool{
<add> "start": make(chan bool),
<add> "die": make(chan bool),
<add> }
<add>
<add> matcher := matchEventLine(buildID, "container", testActions)
<add> go observer.Match(matcher)
<add>
<add> select {
<add> case <-time.After(10 * time.Second):
<add> observer.CheckEventError(c, buildID, "start", matcher)
<add> case <-testActions["start"]:
<add> // ignore, done
<add> }
<add>
<add> // Send a kill to the `docker build` command.
<add> // Causes the underlying build to be cancelled due to socket close.
<add> if err := buildCmd.Process.Kill(); err != nil {
<add> c.Fatalf("error killing build command: %s", err)
<add> }
<add>
<add> // Get the exit status of `docker build`, check it exited because killed.
<add> if err := buildCmd.Wait(); err != nil && !isKilled(err) {
<add> c.Fatalf("wait failed during build run: %T %s", err, err)
<add> }
<add>
<add> select {
<add> case <-time.After(10 * time.Second):
<add> observer.CheckEventError(c, buildID, "die", matcher)
<add> case <-testActions["die"]:
<add> // ignore, done
<add> }
<ide> }
<ide><path>integration-cli/docker_cli_events_test.go
<ide> func (s *DockerSuite) TestEventsContainerFailStartDie(c *check.C) {
<ide> c.Assert(err, checker.NotNil, check.Commentf("Container run with command blerg should have failed, but it did not, out=%s", out))
<ide>
<ide> out, _ = dockerCmd(c, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<del> events := strings.Split(out, "\n")
<add> events := strings.Split(strings.TrimSpace(out), "\n")
<ide>
<ide> nEvents := len(events)
<ide> c.Assert(nEvents, checker.GreaterOrEqualThan, 1) //Missing expected event
<ide>
<del> c.Assert(parseEventAction(c, events[nEvents-3]), checker.Equals, "start")
<del> c.Assert(parseEventAction(c, events[nEvents-2]), checker.Equals, "die")
<add> actions := eventActionsByIDAndType(c, events, "testeventdie", "container")
<add>
<add> var startEvent bool
<add> var dieEvent bool
<add> for _, a := range actions {
<add> switch a {
<add> case "start":
<add> startEvent = true
<add> case "die":
<add> dieEvent = true
<add> }
<add> }
<add> c.Assert(startEvent, checker.True, check.Commentf("Start event not found: %v\n%v", actions, events))
<add> c.Assert(dieEvent, checker.True, check.Commentf("Die event not found: %v\n%v", actions, events))
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsLimit(c *check.C) {
<ide> func (s *DockerSuite) TestEventsContainerEventsSinceUnixEpoch(c *check.C) {
<ide> c.Assert(containerEvents[4], checker.Equals, "destroy", check.Commentf(out))
<ide> }
<ide>
<del>func (s *DockerSuite) TestEventsImageUntagDelete(c *check.C) {
<del> testRequires(c, DaemonIsLinux)
<del>
<del> observer, err := newEventObserver(c)
<del> c.Assert(err, checker.IsNil)
<del> err = observer.Start()
<del> c.Assert(err, checker.IsNil)
<del> defer observer.Stop()
<del>
<del> name := "testimageevents"
<del> imageID, err := buildImage(name,
<del> `FROM scratch
<del> MAINTAINER "docker"`,
<del> true)
<del> c.Assert(err, checker.IsNil)
<del> c.Assert(deleteImages(name), checker.IsNil)
<del>
<del> testActions := map[string]chan bool{
<del> "untag": make(chan bool),
<del> "delete": make(chan bool),
<del> }
<del>
<del> go observer.Match(matchEventLine(imageID, "image", testActions))
<del>
<del> select {
<del> case <-time.After(10 * time.Second):
<del> c.Fatal(observer.TimeoutError(imageID, "untag"))
<del> case <-testActions["untag"]:
<del> // ignore, done
<del> }
<del>
<del> select {
<del> case <-time.After(10 * time.Second):
<del> c.Fatal(observer.TimeoutError(imageID, "delete"))
<del> case <-testActions["delete"]:
<del> // ignore, done
<del> }
<del>}
<del>
<ide> func (s *DockerSuite) TestEventsImageTag(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<ide> time.Sleep(1 * time.Second) // because API has seconds granularity
<ide> func (s *DockerSuite) TestEventsImageTag(c *check.C) {
<ide> event := strings.TrimSpace(events[0])
<ide>
<ide> matches := parseEventText(event)
<del> c.Assert(matches, checker.Not(checker.IsNil))
<ide> c.Assert(matchEventID(matches, image), checker.True, check.Commentf("matches: %v\nout:\n%s", matches, out))
<ide> c.Assert(matches["action"], checker.Equals, "tag")
<ide> }
<ide> func (s *DockerSuite) TestEventsImagePull(c *check.C) {
<ide> events := strings.Split(strings.TrimSpace(out), "\n")
<ide> event := strings.TrimSpace(events[len(events)-1])
<ide> matches := parseEventText(event)
<del> c.Assert(matches, checker.Not(checker.IsNil))
<ide> c.Assert(matches["id"], checker.Equals, "hello-world:latest")
<ide> c.Assert(matches["action"], checker.Equals, "pull")
<ide>
<ide> func (s *DockerSuite) TestEventsFilterImageLabels(c *check.C) {
<ide> "events",
<ide> fmt.Sprintf("--since=%d", since),
<ide> fmt.Sprintf("--until=%d", daemonTime(c).Unix()),
<del> "--filter", fmt.Sprintf("label=%s", label))
<add> "--filter", fmt.Sprintf("label=%s", label),
<add> "--filter", "type=image")
<ide>
<ide> events := strings.Split(strings.TrimSpace(out), "\n")
<ide>
<ide> func (s *DockerSuite) TestEventsFilterContainer(c *check.C) {
<ide> }
<ide> }
<ide>
<del>func (s *DockerSuite) TestEventsStreaming(c *check.C) {
<del> testRequires(c, DaemonIsLinux)
<del>
<del> observer, err := newEventObserver(c)
<del> c.Assert(err, checker.IsNil)
<del> err = observer.Start()
<del> c.Assert(err, checker.IsNil)
<del> defer observer.Stop()
<del>
<del> out, _ := dockerCmd(c, "run", "-d", "busybox:latest", "true")
<del> containerID := strings.TrimSpace(out)
<del>
<del> testActions := map[string]chan bool{
<del> "create": make(chan bool),
<del> "start": make(chan bool),
<del> "die": make(chan bool),
<del> "destroy": make(chan bool),
<del> }
<del>
<del> go observer.Match(matchEventLine(containerID, "container", testActions))
<del>
<del> select {
<del> case <-time.After(5 * time.Second):
<del> c.Fatal(observer.TimeoutError(containerID, "create/start/die"))
<del> case <-testActions["create"]:
<del> case <-testActions["start"]:
<del> case <-testActions["die"]:
<del> // ignore, done
<del> }
<del>
<del> dockerCmd(c, "rm", containerID)
<del>
<del> select {
<del> case <-time.After(5 * time.Second):
<del> c.Fatal(observer.TimeoutError(containerID, "destroy"))
<del> case <-testActions["destroy"]:
<del> // ignore, done
<del> }
<del>}
<del>
<ide> func (s *DockerSuite) TestEventsCommit(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<ide> since := daemonTime(c).Unix()
<ide> func (s *DockerRegistrySuite) TestEventsImageFilterPush(c *check.C) {
<ide> out, _ = dockerCmd(c, "events", "--since=0", "-f", "image="+repoName, "-f", "event=push", "--until="+strconv.Itoa(int(since)))
<ide> c.Assert(out, checker.Contains, repoName, check.Commentf("Missing 'push' log event for %s", repoName))
<ide> }
<add>
<add>func (s *DockerSuite) TestEventsFilterType(c *check.C) {
<add> testRequires(c, DaemonIsLinux)
<add> since := daemonTime(c).Unix()
<add> name := "labelfiltertest"
<add> label := "io.docker.testing=image"
<add>
<add> // Build a test image.
<add> _, err := buildImage(name, fmt.Sprintf(`
<add> FROM busybox:latest
<add> LABEL %s`, label), true)
<add> c.Assert(err, checker.IsNil, check.Commentf("Couldn't create image"))
<add>
<add> dockerCmd(c, "tag", name, "labelfiltertest:tag1")
<add> dockerCmd(c, "tag", name, "labelfiltertest:tag2")
<add> dockerCmd(c, "tag", "busybox:latest", "labelfiltertest:tag3")
<add>
<add> out, _ := dockerCmd(
<add> c,
<add> "events",
<add> fmt.Sprintf("--since=%d", since),
<add> fmt.Sprintf("--until=%d", daemonTime(c).Unix()),
<add> "--filter", fmt.Sprintf("label=%s", label),
<add> "--filter", "type=image")
<add>
<add> events := strings.Split(strings.TrimSpace(out), "\n")
<add>
<add> // 2 events from the "docker tag" command, another one is from "docker build"
<add> c.Assert(events, checker.HasLen, 3, check.Commentf("Events == %s", events))
<add> for _, e := range events {
<add> c.Assert(e, checker.Contains, "labelfiltertest")
<add> }
<add>
<add> out, _ = dockerCmd(
<add> c,
<add> "events",
<add> fmt.Sprintf("--since=%d", since),
<add> fmt.Sprintf("--until=%d", daemonTime(c).Unix()),
<add> "--filter", fmt.Sprintf("label=%s", label),
<add> "--filter", "type=container")
<add> events = strings.Split(strings.TrimSpace(out), "\n")
<add>
<add> // Events generated by the container that builds the image
<add> c.Assert(events, checker.HasLen, 3, check.Commentf("Events == %s", events))
<add>
<add> out, _ = dockerCmd(
<add> c,
<add> "events",
<add> fmt.Sprintf("--since=%d", since),
<add> fmt.Sprintf("--until=%d", daemonTime(c).Unix()),
<add> "--filter", "type=network")
<add> events = strings.Split(strings.TrimSpace(out), "\n")
<add> c.Assert(len(events), checker.GreaterOrEqualThan, 1, check.Commentf("Events == %s", events))
<add>}
<add>
<add>func (s *DockerSuite) TestEventsFilterImageInContainerAction(c *check.C) {
<add> testRequires(c, DaemonIsLinux)
<add>
<add> since := daemonTime(c).Unix()
<add> dockerCmd(c, "run", "--name", "test-container", "-d", "busybox", "true")
<add> waitRun("test-container")
<add>
<add> out, _ := dockerCmd(c, "events", "--filter", "image=busybox", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<add> events := strings.Split(strings.TrimSpace(out), "\n")
<add> c.Assert(len(events), checker.GreaterThan, 1, check.Commentf(out))
<add>}
<ide><path>integration-cli/docker_cli_events_unix_test.go
<ide> func (s *DockerSuite) TestNetworkEvents(c *check.C) {
<ide> c.Assert(netEvents[2], checker.Equals, "disconnect")
<ide> c.Assert(netEvents[3], checker.Equals, "destroy")
<ide> }
<add>
<add>func (s *DockerSuite) TestEventsStreaming(c *check.C) {
<add> testRequires(c, DaemonIsLinux)
<add>
<add> observer, err := newEventObserver(c)
<add> c.Assert(err, checker.IsNil)
<add> err = observer.Start()
<add> c.Assert(err, checker.IsNil)
<add> defer observer.Stop()
<add>
<add> out, _ := dockerCmd(c, "run", "-d", "busybox:latest", "true")
<add> containerID := strings.TrimSpace(out)
<add>
<add> testActions := map[string]chan bool{
<add> "create": make(chan bool),
<add> "start": make(chan bool),
<add> "die": make(chan bool),
<add> "destroy": make(chan bool),
<add> }
<add>
<add> matcher := matchEventLine(containerID, "container", testActions)
<add> go observer.Match(matcher)
<add>
<add> select {
<add> case <-time.After(5 * time.Second):
<add> observer.CheckEventError(c, containerID, "create", matcher)
<add> case <-testActions["create"]:
<add> // ignore, done
<add> }
<add>
<add> select {
<add> case <-time.After(5 * time.Second):
<add> observer.CheckEventError(c, containerID, "start", matcher)
<add> case <-testActions["start"]:
<add> // ignore, done
<add> }
<add>
<add> select {
<add> case <-time.After(5 * time.Second):
<add> observer.CheckEventError(c, containerID, "die", matcher)
<add> case <-testActions["die"]:
<add> // ignore, done
<add> }
<add>
<add> dockerCmd(c, "rm", containerID)
<add>
<add> select {
<add> case <-time.After(5 * time.Second):
<add> observer.CheckEventError(c, containerID, "destroy", matcher)
<add> case <-testActions["destroy"]:
<add> // ignore, done
<add> }
<add>}
<add>
<add>func (s *DockerSuite) TestEventsImageUntagDelete(c *check.C) {
<add> testRequires(c, DaemonIsLinux)
<add>
<add> observer, err := newEventObserver(c)
<add> c.Assert(err, checker.IsNil)
<add> err = observer.Start()
<add> c.Assert(err, checker.IsNil)
<add> defer observer.Stop()
<add>
<add> name := "testimageevents"
<add> imageID, err := buildImage(name,
<add> `FROM scratch
<add> MAINTAINER "docker"`,
<add> true)
<add> c.Assert(err, checker.IsNil)
<add> c.Assert(deleteImages(name), checker.IsNil)
<add>
<add> testActions := map[string]chan bool{
<add> "untag": make(chan bool),
<add> "delete": make(chan bool),
<add> }
<add>
<add> matcher := matchEventLine(imageID, "image", testActions)
<add> go observer.Match(matcher)
<add>
<add> select {
<add> case <-time.After(10 * time.Second):
<add> observer.CheckEventError(c, imageID, "untag", matcher)
<add> case <-testActions["untag"]:
<add> // ignore, done
<add> }
<add>
<add> select {
<add> case <-time.After(10 * time.Second):
<add> observer.CheckEventError(c, imageID, "delete", matcher)
<add> case <-testActions["delete"]:
<add> // ignore, done
<add> }
<add>}
<add>
<add>func (s *DockerSuite) TestEventsFilterVolumeAndNetworkType(c *check.C) {
<add> testRequires(c, DaemonIsLinux)
<add>
<add> since := daemonTime(c).Unix()
<add>
<add> dockerCmd(c, "network", "create", "test-event-network-type")
<add> dockerCmd(c, "volume", "create", "--name", "test-event-volume-type")
<add>
<add> out, _ := dockerCmd(c, "events", "--filter", "type=volume", "--filter", "type=network", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<add> events := strings.Split(strings.TrimSpace(out), "\n")
<add> c.Assert(len(events), checker.GreaterOrEqualThan, 2, check.Commentf(out))
<add>
<add> networkActions := eventActionsByIDAndType(c, events, "test-event-network-type", "network")
<add> volumeActions := eventActionsByIDAndType(c, events, "test-event-volume-type", "volume")
<add>
<add> c.Assert(volumeActions[0], checker.Equals, "create")
<add> c.Assert(networkActions[0], checker.Equals, "create")
<add>}
<add>
<add>func (s *DockerSuite) TestEventsFilterVolumeID(c *check.C) {
<add> testRequires(c, DaemonIsLinux)
<add>
<add> since := daemonTime(c).Unix()
<add>
<add> dockerCmd(c, "volume", "create", "--name", "test-event-volume-id")
<add> out, _ := dockerCmd(c, "events", "--filter", "volume=test-event-volume-id", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<add> events := strings.Split(strings.TrimSpace(out), "\n")
<add> c.Assert(events, checker.HasLen, 1)
<add>
<add> c.Assert(events[0], checker.Contains, "test-event-volume-id")
<add> c.Assert(events[0], checker.Contains, "driver=local")
<add>}
<add>
<add>func (s *DockerSuite) TestEventsFilterNetworkID(c *check.C) {
<add> testRequires(c, DaemonIsLinux)
<add>
<add> since := daemonTime(c).Unix()
<add>
<add> dockerCmd(c, "network", "create", "test-event-network-local")
<add> out, _ := dockerCmd(c, "events", "--filter", "network=test-event-network-local", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<add> events := strings.Split(strings.TrimSpace(out), "\n")
<add> c.Assert(events, checker.HasLen, 1)
<add>
<add> c.Assert(events[0], checker.Contains, "test-event-network-local")
<add> c.Assert(events[0], checker.Contains, "type=bridge")
<add>}
<ide><path>integration-cli/events_utils.go
<ide> import (
<ide> "strconv"
<ide> "strings"
<ide>
<add> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/pkg/integration/checker"
<ide> "github.com/go-check/check"
<ide> )
<ide> var (
<ide> )
<ide>
<ide> // eventMatcher is a function that tries to match an event input.
<del>type eventMatcher func(text string)
<add>type eventMatcher func(text string) bool
<ide>
<ide> // eventObserver runs an events commands and observes its output.
<ide> type eventObserver struct {
<del> buffer *bytes.Buffer
<del> command *exec.Cmd
<del> stdout io.Reader
<add> buffer *bytes.Buffer
<add> command *exec.Cmd
<add> scanner *bufio.Scanner
<add> startTime string
<add> disconnectionError error
<ide> }
<ide>
<ide> // newEventObserver creates the observer and initializes the command
<ide> func newEventObserver(c *check.C, args ...string) (*eventObserver, error) {
<ide>
<ide> // newEventObserverWithBacklog creates a new observer changing the start time of the backlog to return.
<ide> func newEventObserverWithBacklog(c *check.C, since int64, args ...string) (*eventObserver, error) {
<del> cmdArgs := []string{"events", "--since", strconv.FormatInt(since, 10)}
<add> startTime := strconv.FormatInt(since, 10)
<add> cmdArgs := []string{"events", "--since", startTime}
<ide> if len(args) > 0 {
<ide> cmdArgs = append(cmdArgs, args...)
<ide> }
<ide> func newEventObserverWithBacklog(c *check.C, since int64, args ...string) (*even
<ide> }
<ide>
<ide> return &eventObserver{
<del> buffer: new(bytes.Buffer),
<del> command: eventsCmd,
<del> stdout: stdout,
<add> buffer: new(bytes.Buffer),
<add> command: eventsCmd,
<add> scanner: bufio.NewScanner(stdout),
<add> startTime: startTime,
<ide> }, nil
<ide> }
<ide>
<ide> func (e *eventObserver) Stop() {
<ide>
<ide> // Match tries to match the events output with a given matcher.
<ide> func (e *eventObserver) Match(match eventMatcher) {
<del> scanner := bufio.NewScanner(e.stdout)
<del>
<del> for scanner.Scan() {
<del> text := scanner.Text()
<add> for e.scanner.Scan() {
<add> text := e.scanner.Text()
<ide> e.buffer.WriteString(text)
<ide> e.buffer.WriteString("\n")
<ide>
<ide> match(text)
<ide> }
<del>}
<ide>
<del>// TimeoutError generates an error for a given containerID and event type.
<del>// It attaches the events command output to the error.
<del>func (e *eventObserver) TimeoutError(id, event string) error {
<del> return fmt.Errorf("failed to observe event `%s` for %s\n%v", event, id, e.output())
<add> err := e.scanner.Err()
<add> if err == nil {
<add> err = io.EOF
<add> }
<add>
<add> logrus.Debug("EventObserver scanner loop finished: %v", err)
<add> e.disconnectionError = err
<ide> }
<ide>
<del>// output returns the events command output read until now by the Match goroutine.
<del>func (e *eventObserver) output() string {
<del> return e.buffer.String()
<add>func (e *eventObserver) CheckEventError(c *check.C, id, event string, match eventMatcher) {
<add> var foundEvent bool
<add> scannerOut := e.buffer.String()
<add>
<add> if e.disconnectionError != nil {
<add> until := strconv.FormatInt(daemonTime(c).Unix(), 10)
<add> out, _ := dockerCmd(c, "events", "--since", e.startTime, "--until", until)
<add> events := strings.Split(strings.TrimSpace(out), "\n")
<add> for _, e := range events {
<add> if match(e) {
<add> foundEvent = true
<add> break
<add> }
<add> }
<add> scannerOut = out
<add> }
<add> if !foundEvent {
<add> c.Fatalf("failed to observe event `%s` for %s. Disconnection error: %v\nout:\n%v", event, id, e.disconnectionError, scannerOut)
<add> }
<ide> }
<ide>
<ide> // matchEventLine matches a text with the event regular expression.
<ide> // It returns the action and true if the regular expression matches with the given id and event type.
<ide> // It returns an empty string and false if there is no match.
<ide> func matchEventLine(id, eventType string, actions map[string]chan bool) eventMatcher {
<del> return func(text string) {
<add> return func(text string) bool {
<ide> matches := parseEventText(text)
<del> if matches == nil {
<del> return
<add> if len(matches) == 0 {
<add> return false
<ide> }
<ide>
<ide> if matchIDAndEventType(matches, id, eventType) {
<ide> if ch, ok := actions[matches["action"]]; ok {
<ide> close(ch)
<add> return true
<ide> }
<ide> }
<add> return false
<ide> }
<ide> }
<ide>
<ide> // parseEventText parses a line of events coming from the cli and returns
<ide> // the matchers in a map.
<ide> func parseEventText(text string) map[string]string {
<ide> matches := eventCliRegexp.FindAllStringSubmatch(text, -1)
<add> md := map[string]string{}
<ide> if len(matches) == 0 {
<del> return nil
<add> return md
<ide> }
<ide>
<ide> names := eventCliRegexp.SubexpNames()
<del> md := map[string]string{}
<ide> for i, n := range matches[0] {
<ide> md[names[i]] = n
<ide> }
<ide> func parseEventText(text string) map[string]string {
<ide> // It fails if the text is not in the event format.
<ide> func parseEventAction(c *check.C, text string) string {
<ide> matches := parseEventText(text)
<del> c.Assert(matches, checker.Not(checker.IsNil))
<ide> return matches["action"]
<ide> }
<ide>
<ide> func parseEvents(c *check.C, out, match string) {
<ide> events := strings.Split(strings.TrimSpace(out), "\n")
<ide> for _, event := range events {
<ide> matches := parseEventText(event)
<del> c.Assert(matches, checker.Not(checker.IsNil))
<ide> matched, err := regexp.MatchString(match, matches["action"])
<ide> c.Assert(err, checker.IsNil)
<del> c.Assert(matched, checker.True)
<add> c.Assert(matched, checker.True, check.Commentf("Matcher: %s did not match %s", match, matches["action"]))
<ide> }
<ide> }
<ide>
<ide> func parseEventsWithID(c *check.C, out, match, id string) {
<ide> events := strings.Split(strings.TrimSpace(out), "\n")
<ide> for _, event := range events {
<ide> matches := parseEventText(event)
<del> c.Assert(matches, checker.Not(checker.IsNil))
<ide> c.Assert(matchEventID(matches, id), checker.True)
<ide>
<ide> matched, err := regexp.MatchString(match, matches["action"])
<ide> c.Assert(err, checker.IsNil)
<del> c.Assert(matched, checker.True)
<add> c.Assert(matched, checker.True, check.Commentf("Matcher: %s did not match %s", match, matches["action"]))
<ide> }
<ide> } | 11 |
Javascript | Javascript | add label to pr and log summary | c14f6df47cee14f00539a692803f1d7e3d7a6bb9 | <ide><path>script/lib/update-dependency/main.js
<ide> const {
<ide> runApmInstall,
<ide> sleep
<ide> } = require('./util');
<del>const { createPR, findPR } = require('./pull-request');
<add>const { createPR, findPR, addLabel } = require('./pull-request');
<ide> module.exports = async function() {
<ide> try {
<ide> // ensure we are on master
<ide> module.exports = async function() {
<ide> }
<ide> // create PRs here
<ide> for (const { dependency, branch, branchIsRemote } of pendingPRs) {
<del> const { status } = await createPR(dependency, branch);
<del> status === 201
<del> ? successfullBumps.push(dependency)
<del> : failedBumps.push({
<del> module: dependency.moduleName,
<del> reason: `couldn't create pull request`
<del> });
<add> const { status, data = {} } = await createPR(dependency, branch);
<add> if (status === 201) {
<add> successfullBumps.push(dependency);
<add> await addLabel(data.number);
<add> } else {
<add> failedBumps.push(dependency);
<add> }
<ide>
<ide> if (!branchIsRemote) {
<ide> await deleteBranch(branch);
<ide> }
<ide> // https://developer.github.com/v3/guides/best-practices-for-integrators/#dealing-with-abuse-rate-limits
<ide> await sleep(2000);
<ide> }
<del> console.log(
<del> `Total dependencies: ${totalDependencies} Sucessfull: ${
<del> successfullBumps.length
<del> } Failed: ${failedBumps.length}`
<del> );
<del> // TODO: log other useful information
<add> console.table([
<add> {
<add> totalDependencies,
<add> totalSuccessfullBumps: successfullBumps.length,
<add> totalFailedBumps: failedBumps.length
<add> }
<add> ]);
<add> console.log('Successfull bumps');
<add> console.table(successfullBumps);
<add> console.log('Failed bumps');
<add> console.table(failedBumps);
<ide> } catch (ex) {
<del> // TODO: handle errors
<ide> console.log(ex.message);
<ide> }
<ide> };
<ide><path>script/lib/update-dependency/pull-request.js
<ide> module.exports = {
<ide> return requestWithAuth('GET /search/issues', {
<ide> q: `${moduleName} type:pr ${moduleName}@${latest} in:title repo:atom/atom head:${branch} state:open`
<ide> });
<add> },
<add> addLabel: async pullRequestNumber => {
<add> return requestWithAuth('PATCH /repos/:owner/:repo/issues/:issue_number', {
<add> labels: ['depency ⬆️'],
<add> issue_number: pullRequestNumber
<add> });
<ide> }
<ide> }; | 2 |
Text | Text | add django-restql to 3rd party packages in docs | 5b990d40920fb1a0fc74ecd262e1cc1ac5e5394f | <ide><path>docs/community/third-party-packages.md
<ide> To submit new content, [open an issue][drf-create-issue] or [create a pull reque
<ide> * [drf-flex-fields][drf-flex-fields] - Serializer providing dynamic field expansion and sparse field sets via URL parameters.
<ide> * [drf-action-serializer][drf-action-serializer] - Serializer providing per-action fields config for use with ViewSets to prevent having to write multiple serializers.
<ide> * [djangorestframework-dataclasses][djangorestframework-dataclasses] - Serializer providing automatic field generation for Python dataclasses, like the built-in ModelSerializer does for models.
<add>* [django-restql][django-restql] - Turn your REST API into a GraphQL like API(It allows clients to control which fields will be sent in a response, uses GraphQL like syntax, supports read and write on both flat and nested fields).
<ide>
<ide> ### Serializer fields
<ide>
<ide> To submit new content, [open an issue][drf-create-issue] or [create a pull reque
<ide> [drf-flex-fields]: https://github.com/rsinger86/drf-flex-fields
<ide> [drf-action-serializer]: https://github.com/gregschmit/drf-action-serializer
<ide> [djangorestframework-dataclasses]: https://github.com/oxan/djangorestframework-dataclasses
<add>[django-restql]: https://github.com/yezyilomo/django-restql
<ide> [djangorestframework-mvt]: https://github.com/corteva/djangorestframework-mvt
<ide> [django-rest-framework-guardian]: https://github.com/rpkilby/django-rest-framework-guardian | 1 |
Ruby | Ruby | add deprecated_option to software_spec | 02e10beb7c79f29d5c8a17d89649af344034d541 | <ide><path>Library/Homebrew/options.rb
<ide> def old_flag
<ide> def current_flag
<ide> "--#{current}"
<ide> end
<add>
<add> def ==(other)
<add> instance_of?(other.class) && old == other.old && current == other.current
<add> end
<add> alias_method :eql?, :==
<ide> end
<ide>
<ide> class Options
<ide><path>Library/Homebrew/software_spec.rb
<ide> class SoftwareSpec
<ide>
<ide> attr_reader :name, :owner
<ide> attr_reader :build, :resources, :patches, :options
<add> attr_reader :deprecated_flags, :deprecated_options
<ide> attr_reader :dependency_collector
<ide> attr_reader :bottle_specification
<ide> attr_reader :compiler_failures
<ide> def initialize
<ide> @bottle_specification = BottleSpecification.new
<ide> @patches = []
<ide> @options = Options.new
<del> @build = BuildOptions.new(Options.create(ARGV.flags_only), options)
<add> @flags = ARGV.flags_only
<add> @deprecated_flags = []
<add> @deprecated_options = []
<add> @build = BuildOptions.new(Options.create(@flags), options)
<ide> @compiler_failures = []
<ide> end
<ide>
<ide> def option(name, description="")
<ide> options << opt
<ide> end
<ide>
<add> def deprecated_option hash
<add> raise ArgumentError, "deprecated_option hash must not be empty" if hash.empty?
<add> hash.each do |old_options, new_options|
<add> Array(old_options).each do |old_option|
<add> Array(new_options).each do |new_option|
<add> deprecated_option = DeprecatedOption.new(old_option, new_option)
<add> deprecated_options << deprecated_option
<add>
<add> old_flag = deprecated_option.old_flag
<add> new_flag = deprecated_option.current_flag
<add> next unless @flags.include? old_flag
<add> @flags -= [old_flag]
<add> @flags |= [new_flag]
<add> @deprecated_flags << deprecated_option
<add> end
<add> end
<add> end
<add> @build = BuildOptions.new(Options.create(@flags), options)
<add> end
<add>
<ide> def depends_on spec
<ide> dep = dependency_collector.add(spec)
<ide> add_dep_option(dep) if dep
<ide><path>Library/Homebrew/test/test_options.rb
<ide> def test_old
<ide> def test_current
<ide> assert_equal "bar", @deprecated_option.current
<ide> end
<add>
<add> def test_old
<add> assert_equal "--foo", @deprecated_option.old_flag
<add> end
<add>
<add> def test_current
<add> assert_equal "--bar", @deprecated_option.current_flag
<add> end
<add>
<add> def test_equality
<add> foobar = DeprecatedOption.new("foo", "bar")
<add> boofar = DeprecatedOption.new("boo", "far")
<add> assert_equal foobar, @deprecated_option
<add> refute_equal boofar, @deprecated_option
<add> assert_eql @deprecated_option, foobar
<add> refute_eql @deprecated_option, boofar
<add> end
<ide> end
<ide>
<ide> class OptionsTests < Homebrew::TestCase
<ide><path>Library/Homebrew/test/test_software_spec.rb
<ide> def test_option_description_defaults_to_empty_string
<ide> assert_equal "", @spec.options.first.description
<ide> end
<ide>
<add> def test_deprecated_option
<add> @spec.deprecated_option('foo' => 'bar')
<add> assert @spec.deprecated_options.any?
<add> assert_equal "foo", @spec.deprecated_options.first.old
<add> assert_equal "bar", @spec.deprecated_options.first.current
<add> end
<add>
<add> def test_deprecated_options
<add> @spec.deprecated_option(['foo1', 'foo2'] => 'bar1', 'foo3' => ['bar2', 'bar3'])
<add> refute_empty @spec.deprecated_options
<add> assert_equal "foo1", @spec.deprecated_options.first.old
<add> assert_equal "bar1", @spec.deprecated_options.first.current
<add> assert_equal "foo2", @spec.deprecated_options[1].old
<add> assert_equal "bar1", @spec.deprecated_options[1].current
<add> assert_equal "foo3", @spec.deprecated_options[2].old
<add> assert_equal "bar2", @spec.deprecated_options[2].current
<add> assert_equal "foo3", @spec.deprecated_options.last.old
<add> assert_equal "bar3", @spec.deprecated_options.last.current
<add> end
<add>
<add> def test_deprecated_option_raises_when_empty
<add> assert_raises(ArgumentError) { @spec.deprecated_option({}) }
<add> end
<add>
<ide> def test_depends_on
<ide> @spec.depends_on('foo')
<ide> assert_equal 'foo', @spec.deps.first.name | 4 |
Text | Text | add changelogs for os | ebb2d99a10b82fc8ed23caa2923d7e983e4e58c8 | <ide><path>doc/api/os.md
<ide> https://en.wikipedia.org/wiki/Uname#Examples for more information.
<ide> ## os.tmpdir()
<ide> <!-- YAML
<ide> added: v0.9.9
<add>changes:
<add> - version: v2.0.0
<add> pr-url: https://github.com/nodejs/node/pull/747
<add> description: This function is now cross-platform consistent and no longer
<add> returns a path with a trailing slash on any platform
<ide> -->
<ide>
<ide> * Returns: {String}
<ide> The following constants are exported by `os.constants`. **Note:** Not all
<ide> constants will be available on every operating system.
<ide>
<ide> ### Signal Constants
<add><!-- YAML
<add>changes:
<add> - version: v5.11.0
<add> pr-url: https://github.com/nodejs/node/pull/6093
<add> description: Added support for `SIGINFO`.
<add>-->
<ide>
<ide> The following signal constants are exported by `os.constants.signals`:
<ide> | 1 |
PHP | PHP | add additional tests for array args | 35aa70e6bb287392526b34764f1587e0ca27f648 | <ide><path>tests/TestCase/I18n/I18nTest.php
<ide> public function testBasicTranslateFunction()
<ide> I18n::defaultFormatter('sprintf');
<ide> $this->assertEquals('%d is 1 (po translated)', __('%d = 1'));
<ide> $this->assertEquals('1 is 1 (po translated)', __('%d = 1', 1));
<add> $this->assertEquals('1 is 1 (po translated)', __('%d = 1', [1]));
<add> $this->assertEquals('The red dog, and blue cat', __('The %s dog, and %s cat', ['red', 'blue']));
<add> $this->assertEquals('The red dog, and blue cat', __('The %s dog, and %s cat', 'red', 'blue'));
<ide> }
<ide>
<ide> /**
<ide> public function testBasicTranslatePluralFunction()
<ide>
<ide> $result = __n('singular msg', '%d = 0 or > 1', 2);
<ide> $this->assertEquals('2 is 2-4 (po translated)', $result);
<add>
<add> $result = __n('%s %s and %s are good', '%s and %s are best', 1, ['red', 'blue']);
<add> $this->assertEquals('1 red and blue are good', $result);
<add>
<add> $result = __n('%s %s and %s are good', '%s and %s are best', 1, 'red', 'blue');
<add> $this->assertEquals('1 red and blue are good', $result);
<ide> }
<ide>
<ide> /**
<ide> public function testBasicDomainFunction()
<ide> $result = __d('custom', 'The {0} is tasty', ['fruit']);
<ide> $this->assertEquals('The fruit is delicious', $result);
<ide>
<add> $result = __d('custom', 'The {0} is tasty', 'fruit');
<add> $this->assertEquals('The fruit is delicious', $result);
<add>
<ide> $result = __d('custom', 'Average price {0}', ['9.99']);
<ide> $this->assertEquals('Price Average 9.99', $result);
<ide> }
<ide> public function testBasicContextFunction()
<ide> $this->assertEquals('The letters A and B', __x('character', 'letters', ['A', 'B']));
<ide> $this->assertEquals('The letter A', __x('character', 'letter', ['A']));
<ide>
<add> $this->assertEquals('The letters A and B', __x('character', 'letters', 'A', 'B'));
<add> $this->assertEquals('The letter A', __x('character', 'letter', 'A'));
<add>
<ide> $this->assertEquals(
<ide> 'She wrote a letter to Thomas and Sara',
<ide> __x('communication', 'letters', ['Thomas', 'Sara']) | 1 |
Text | Text | add v3.8.0 to changelog | b71a2a5aea97bed538310faacdfc60540cb6965f | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<del>### v3.8.0-beta.5 (February 11, 2019)
<del>
<del>- [#17563](https://github.com/emberjs/ember.js/pull/17563) [BUGFIX] Transition.send/trigger call signature
<del>
<del>### v3.8.0-beta.4 (February 4, 2019)
<del>
<del>- [#17552](https://github.com/emberjs/ember.js/pull/17552) [BUGFIX] Support numbers in component names for Angle Brackets
<del>
<del>### v3.8.0-beta.3 (January 28, 2019)
<del>
<del>- [#17498](https://github.com/emberjs/ember.js/pull/17498) [BUGFIX] Don't remove dep keys in `didUnwatch`
<del>- [#17499](https://github.com/emberjs/ember.js/pull/17499) [BUGFIX] Update to glimmer-vm 0.37.1.
<del>
<del>### v3.8.0-beta.2 (January 14, 2019)
<del>
<del>- [#17467](https://github.com/emberjs/ember.js/pull/17467) [BUGFIX] Fix substate interactions with aborts
<del>
<del>### v3.8.0-beta.1 (January 7, 2019)
<add>### v3.8.0 (February 18, 2019)
<ide>
<ide> - [#17143](https://github.com/emberjs/ember.js/pull/17143) / [#17375](https://github.com/emberjs/ember.js/pull/17375) [FEATURE] Implement Element Modifier Manager RFC (see [emberjs/rfcs#0373](https://github.com/emberjs/rfcs/blob/master/text/0373-Element-Modifier-Managers.md)).
<ide> - [#17054](https://github.com/emberjs/ember.js/pull/17054) / [#17376](https://github.com/emberjs/ember.js/pull/17376) [FEATURE] Implement `array` helper RFC (see [emberjs/rfcs#0318](https://github.com/emberjs/rfcs/blob/master/text/0318-array-helper.md))
<ide> - [#16735](https://github.com/emberjs/ember.js/pull/16735) [BUGFIX] Observed properties not being marked as enum
<add>- [#17498](https://github.com/emberjs/ember.js/pull/17498) [BUGFIX] Don't remove dep keys in `didUnwatch`
<add>- [#17467](https://github.com/emberjs/ember.js/pull/17467) [BUGFIX] Fix substate interactions with aborts
<add>- [#17413](https://github.com/emberjs/ember.js/pull/17413) [BUGFIX] Fix missing import in instance-initializer blueprint for ember-mocha
<ide> - [#17319](https://github.com/emberjs/ember.js/pull/17319) [CLEANUP] Remove deprecated 'POSITIONAL_PARAM_CONFLICT'
<ide> - [#17394](https://github.com/emberjs/ember.js/pull/17394) [CLEANUP] Remove deprecated code in mixins/array
<add>- [#17244](https://github.com/emberjs/ember.js/pull/17244) / [#17499](https://github.com/emberjs/ember.js/pull/17499) Upgrade to Glimmer VM 0.37.1
<add>Fixes a few issues:
<add> * Usage of positional arguments with custom components.
<add> * Forwarding attributes via `...attributes` to a dynamic component.
<add> * Prevent errors when rendering many template blocks (`Error: Operand over 16-bits. Got 65536`).
<ide> - [#17166](https://github.com/emberjs/ember.js/pull/17166) Improve performance of get() / set()
<del>- [#16710](https://github.com/emberjs/ember.js/pull/16710) Deprecation of (private) `NAME_KEY`
<del>- [#17244](https://github.com/emberjs/ember.js/pull/17244) Upgrade to Glimmer VM 0.37.0
<add>- [#16710](https://github.com/emberjs/ember.js/pull/16710) Deprecation of private `NAME_KEY`
<ide> - [#17216](https://github.com/emberjs/ember.js/pull/17216) Use native Error instead of custom Error subclass.
<ide> - [#17340](https://github.com/emberjs/ember.js/pull/17340) Remove unused `hooks` variable from qunit-rfc-232 util-test blueprint
<ide> - [#17357](https://github.com/emberjs/ember.js/pull/17357) Allow notifyPropertyChange to be imported from @ember/object
<del>- [#17413](https://github.com/emberjs/ember.js/pull/17413) Fix missing import in instance-initializer blueprint for ember-mocha
<ide>
<ide> ### v3.7.3 (February 6, 2019)
<ide>
<ide>
<ide> ### v3.7.2 (January 22, 2019)
<ide>
<del>* Upgrade @glimmer/* packages to 0.35.10. Fixes a few issues:
<add>* Upgrade @glimmer/* packages to 0.36.6. Fixes a few issues:
<ide> * Usage of positional arguments with custom components.
<ide> * Forwarding attributes via `...attributes` to a dynamic component.
<ide> * Prevent errors when rendering many template blocks (`Error: Operand over 16-bits. Got 65536`). | 1 |
Java | Java | update uritemplate javadoc | 5859649af7180d63f000b42c75a5b557063dca2e | <ide><path>spring-web/src/main/java/org/springframework/web/util/UriTemplate.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public List<String> getVariableNames() {
<ide> * UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}");
<ide> * Map<String, String> uriVariables = new HashMap<String, String>();
<ide> * uriVariables.put("booking", "42");
<del> * uriVariables.put("hotel", "1");
<add> * uriVariables.put("hotel", "Rest & Relax");
<ide> * System.out.println(template.expand(uriVariables));
<ide> * </pre>
<del> * will print: <blockquote>{@code http://example.com/hotels/1/bookings/42}</blockquote>
<add> * will print: <blockquote>{@code http://example.com/hotels/Rest%20%26%20Relax/bookings/42}</blockquote>
<ide> * @param uriVariables the map of URI variables
<ide> * @return the expanded URI
<ide> * @throws IllegalArgumentException if {@code uriVariables} is {@code null};
<ide> public URI expand(Map<String, ?> uriVariables) {
<ide> * <p>Example:
<ide> * <pre class="code">
<ide> * UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}");
<del> * System.out.println(template.expand("1", "42));
<add> * System.out.println(template.expand("Rest & Relax", "42));
<ide> * </pre>
<del> * will print: <blockquote>{@code http://example.com/hotels/1/bookings/42}</blockquote>
<add> * will print: <blockquote>{@code http://example.com/hotels/Rest%20%26%20Relax/bookings/42}</blockquote>
<ide> * @param uriVariableValues the array of URI variables
<ide> * @return the expanded URI
<ide> * @throws IllegalArgumentException if {@code uriVariables} is {@code null} | 1 |
PHP | PHP | reduce is_null call | 51249415072614aada9f2bb51d9340d687f71a24 | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public function touchOwners()
<ide> {
<ide> $this->$relation()->touch();
<ide>
<del> if ( ! is_null($this->$relation) && $this->$relation instanceof Model)
<add> if ( ! is_null($this->$relation))
<ide> {
<del> $this->$relation->touchOwners();
<del> }
<del> elseif ( ! is_null($this->$relation) && $this->$relation instanceof Collection)
<del> {
<del> $this->$relation->each(function (Model $relation)
<add> if ($this->$relation instanceof Model)
<add> {
<add> $this->$relation->touchOwners();
<add> }
<add> elseif ($this->$relation instanceof Collection)
<ide> {
<del> $relation->touchOwners();
<del> });
<add> $this->$relation->each(function (Model $relation)
<add> {
<add> $relation->touchOwners();
<add> });
<add> }
<ide> }
<ide> }
<ide> } | 1 |
Python | Python | add bulk_dump abstract method to dbapihook | aff5d8c8a2370413e29ca8a75e31a89ee3c836d0 | <ide><path>airflow/hooks/dbapi_hook.py
<ide> def _serialize_cell(cell):
<ide> else:
<ide> return str(cell)
<ide>
<add> def bulk_dump(self, table, tmp_file):
<add> """
<add> Dumps a database table into a tab-delimited file
<add>
<add> :param table: The name of the source table
<add> :type table: str
<add> :param tmp_file: The path of the target file
<add> :type tmp_file: str
<add> """
<add> raise NotImplementedError()
<add>
<ide> def bulk_load(self, table, tmp_file):
<ide> """
<ide> Loads a tab-delimited file into a database table | 1 |
Ruby | Ruby | fix typos, update documentation | 49542ae88697fd708a76c48f6a8c3bcde4591df2 | <ide><path>actionmailer/lib/action_mailer/inline_preview_interceptor.rb
<ide>
<ide> module ActionMailer
<ide> # Implements a mailer preview interceptor that converts image tag src attributes
<del> # that use inline cid: style urls to data: style urls so that they are visible
<add> # that use inline cid: style URLs to data: style URLs so that they are visible
<ide> # when previewing an HTML email in a web browser.
<ide> #
<ide> # This interceptor is enabled by default. To disable it, delete it from the
<ide><path>actionpack/lib/action_controller/metal/force_ssl.rb
<ide> module ClassMethods
<ide> # end
<ide> #
<ide> # ==== URL Options
<del> # You can pass any of the following options to affect the redirect url
<add> # You can pass any of the following options to affect the redirect URL
<ide> # * <tt>host</tt> - Redirect to a different host name
<ide> # * <tt>subdomain</tt> - Redirect to a different subdomain
<ide> # * <tt>domain</tt> - Redirect to a different domain
<ide> def force_ssl(options = {})
<ide> # Redirect the existing request to use the HTTPS protocol.
<ide> #
<ide> # ==== Parameters
<del> # * <tt>host_or_options</tt> - Either a host name or any of the url and
<add> # * <tt>host_or_options</tt> - Either a host name or any of the URL and
<ide> # redirect options available to the <tt>force_ssl</tt> method.
<ide> def force_ssl_redirect(host_or_options = nil)
<ide> unless request.ssl?
<ide><path>actionview/lib/action_view/helpers/asset_tag_helper.rb
<ide> module AssetTagHelper
<ide> # When the last parameter is a hash you can add HTML attributes using that
<ide> # parameter. The following options are supported:
<ide> #
<del> # * <tt>:extname</tt> - Append an extension to the generated url unless the extension
<del> # already exists. This only applies for relative urls.
<del> # * <tt>:protocol</tt> - Sets the protocol of the generated url, this option only
<del> # applies when a relative url and +host+ options are provided.
<del> # * <tt>:host</tt> - When a relative url is provided the host is added to the
<add> # * <tt>:extname</tt> - Append an extension to the generated URL unless the extension
<add> # already exists. This only applies for relative URLs.
<add> # * <tt>:protocol</tt> - Sets the protocol of the generated URL. This option only
<add> # applies when a relative URL and +host+ options are provided.
<add> # * <tt>:host</tt> - When a relative URL is provided the host is added to the
<ide> # that path.
<ide> # * <tt>:skip_pipeline</tt> - This option is used to bypass the asset pipeline
<ide> # when it is set to true.
<ide> def favicon_link_tag(source = "favicon.ico", options = {})
<ide> end
<ide>
<ide> # Returns a link tag that browsers can use to preload the +source+.
<del> # The +source+ can be the path of an resource managed by asset pipeline,
<del> # a full path or an URI.
<add> # The +source+ can be the path of a resource managed by asset pipeline,
<add> # a full path, or an URI.
<ide> #
<ide> # ==== Options
<ide> #
<ide> def preload_link_tag(source, options = {})
<ide> end
<ide>
<ide> # Returns an HTML image tag for the +source+. The +source+ can be a full
<del> # path, a file or an Active Storage attachment.
<add> # path, a file, or an Active Storage attachment.
<ide> #
<ide> # ==== Options
<ide> #
<ide> def image_alt(src)
<ide> # Returns an HTML video tag for the +sources+. If +sources+ is a string,
<ide> # a single video tag will be returned. If +sources+ is an array, a video
<ide> # tag with nested source tags for each source will be returned. The
<del> # +sources+ can be full paths or files that exists in your public videos
<add> # +sources+ can be full paths or files that exist in your public videos
<ide> # directory.
<ide> #
<ide> # ==== Options
<del> # You can add HTML attributes using the +options+. The +options+ supports
<del> # two additional keys for convenience and conformance:
<add> #
<add> # When the last parameter is a hash you can add HTML attributes using that
<add> # parameter. The following options are supported:
<ide> #
<ide> # * <tt>:poster</tt> - Set an image (like a screenshot) to be shown
<ide> # before the video loads. The path is calculated like the +src+ of +image_tag+.
<ide> def image_alt(src)
<ide> # video_tag("trailer.ogg")
<ide> # # => <video src="/videos/trailer.ogg"></video>
<ide> # video_tag("trailer.ogg", controls: true, preload: 'none')
<del> # # => <video preload="none" controls="controls" src="/videos/trailer.ogg" ></video>
<add> # # => <video preload="none" controls="controls" src="/videos/trailer.ogg"></video>
<ide> # video_tag("trailer.m4v", size: "16x10", poster: "screenshot.png")
<ide> # # => <video src="/videos/trailer.m4v" width="16" height="10" poster="/assets/screenshot.png"></video>
<ide> # video_tag("trailer.m4v", size: "16x10", poster: "screenshot.png", poster_skip_pipeline: true)
<ide> def video_tag(*sources)
<ide> end
<ide> end
<ide>
<del> # Returns an HTML audio tag for the +source+.
<del> # The +source+ can be full path or file that exists in
<del> # your public audios directory.
<add> # Returns an HTML audio tag for the +sources+. If +sources+ is a string,
<add> # a single audio tag will be returned. If +sources+ is an array, an audio
<add> # tag with nested source tags for each source will be returned. The
<add> # +sources+ can be full paths or files that exist in your public audios
<add> # directory.
<add> #
<add> # When the last parameter is a hash you can add HTML attributes using that
<add> # parameter.
<ide> #
<ide> # audio_tag("sound")
<ide> # # => <audio src="/audios/sound"></audio>
<ide><path>actionview/lib/action_view/helpers/asset_url_helper.rb
<ide> module ActionView
<ide> # = Action View Asset URL Helpers
<ide> module Helpers #:nodoc:
<ide> # This module provides methods for generating asset paths and
<del> # urls.
<add> # URLs.
<ide> #
<ide> # image_path("rails.png")
<ide> # # => "/assets/rails.png"
<ide> module Helpers #:nodoc:
<ide> # You can read more about setting up your DNS CNAME records from your ISP.
<ide> #
<ide> # Note: This is purely a browser performance optimization and is not meant
<del> # for server load balancing. See http://www.die.net/musings/page_load_time/
<del> # for background and http://www.browserscope.org/?category=network for
<add> # for server load balancing. See https://www.die.net/musings/page_load_time/
<add> # for background and https://www.browserscope.org/?category=network for
<ide> # connection limit data.
<ide> #
<ide> # Alternatively, you can exert more control over the asset host by setting
<ide> module Helpers #:nodoc:
<ide> # still sending assets for plain HTTP requests from asset hosts. If you don't
<ide> # have SSL certificates for each of the asset hosts this technique allows you
<ide> # to avoid warnings in the client about mixed media.
<del> # Note that the request parameter might not be supplied, e.g. when the assets
<add> # Note that the +request+ parameter might not be supplied, e.g. when the assets
<ide> # are precompiled via a Rake task. Make sure to use a +Proc+ instead of a lambda,
<ide> # since a +Proc+ allows missing parameters and sets them to +nil+.
<ide> #
<ide> module AssetUrlHelper
<ide> # Below lists scenarios that apply to +asset_path+ whether or not you're
<ide> # using the asset pipeline.
<ide> #
<del> # - All fully qualified urls are returned immediately. This bypasses the
<add> # - All fully qualified URLs are returned immediately. This bypasses the
<ide> # asset pipeline and all other behavior described.
<ide> #
<ide> # asset_path("http://www.example.com/js/xmlhr.js") # => "http://www.example.com/js/xmlhr.js"
<ide> #
<ide> # - All assets that begin with a forward slash are assumed to be full
<del> # urls and will not be expanded. This will bypass the asset pipeline.
<add> # URLs and will not be expanded. This will bypass the asset pipeline.
<ide> #
<ide> # asset_path("/foo.png") # => "/foo.png"
<ide> #
<ide><path>actionview/lib/action_view/helpers/form_helper.rb
<ide> module Helpers #:nodoc:
<ide> # compared to using vanilla HTML.
<ide> #
<ide> # Typically, a form designed to create or update a resource reflects the
<del> # identity of the resource in several ways: (i) the url that the form is
<add> # identity of the resource in several ways: (i) the URL that the form is
<ide> # sent to (the form element's +action+ attribute) should result in a request
<ide> # being routed to the appropriate controller action (with the appropriate <tt>:id</tt>
<ide> # parameter in the case of an existing resource), (ii) input fields should
<ide> module FormHelper
<ide> # So for example you may use a named route directly. When the model is
<ide> # represented by a string or symbol, as in the example above, if the
<ide> # <tt>:url</tt> option is not specified, by default the form will be
<del> # sent back to the current url (We will describe below an alternative
<add> # sent back to the current URL (We will describe below an alternative
<ide> # resource-oriented usage of +form_for+ in which the URL does not need
<ide> # to be specified explicitly).
<ide> # * <tt>:namespace</tt> - A namespace for your form to ensure uniqueness of
<ide> def apply_form_for_options!(record, object, options) #:nodoc:
<ide> # This is helpful when fragment-caching the form. Remote forms
<ide> # get the authenticity token from the <tt>meta</tt> tag, so embedding is
<ide> # unnecessary unless you support browsers without JavaScript.
<del> # * <tt>:local</tt> - By default form submits are remote and unobstrusive XHRs.
<add> # * <tt>:local</tt> - By default form submits are remote and unobtrusive XHRs.
<ide> # Disable remote submits with <tt>local: true</tt>.
<ide> # * <tt>:skip_enforcing_utf8</tt> - By default a hidden field named +utf8+
<ide> # is output to enforce UTF-8 submits. Set to true to skip the field. | 5 |
Ruby | Ruby | add destroyed records to the currend transaction | 58410b3d566e6b93c7b71c0eec0fc11ec906b68e | <ide><path>activerecord/lib/active_record/persistence.rb
<ide> def delete
<ide> def destroy
<ide> raise ReadOnlyRecord, "#{self.class} is marked as readonly" if readonly?
<ide> destroy_associations
<add> self.class.connection.add_transaction_record(self)
<ide> destroy_row if persisted?
<ide> @destroyed = true
<ide> freeze
<ide><path>activerecord/lib/active_record/transactions.rb
<ide> def restore_transaction_record_state(force = false) #:nodoc:
<ide> thaw unless restore_state[:frozen?]
<ide> @new_record = restore_state[:new_record]
<ide> @destroyed = restore_state[:destroyed]
<del> write_attribute(self.class.primary_key, restore_state[:id]) if self.class.primary_key
<add> pk = self.class.primary_key
<add> if pk && read_attribute(pk) != restore_state[:id]
<add> write_attribute(pk, restore_state[:id])
<add> end
<ide> end
<ide> end
<ide> end | 2 |
PHP | PHP | update doc blocks and expand tests | 4f3f90c2c74d4aa91cf1f020f14a1a0d1bbd8a5c | <ide><path>lib/Cake/Database/ConnectionManager.php
<ide> use Cake\Error;
<ide>
<ide> /**
<del> * Manages loaded instances of DataSource objects
<add> * Manages and loads instances of Connection
<ide> *
<del> * Provides an interface to loading and creating connection objects. Acts as
<add> * Provides an interface to loading and creating connection objects. Acts as
<ide> * a registry for the connections defined in an application.
<ide> *
<ide> * Provides an interface for loading and enumerating connections defined in
<ide> public static function configured() {
<ide> * @return boolean true
<ide> */
<ide> public static function drop($name) {
<del> static::$_registry->unload($name);
<add> if (isset(static::$_registry)) {
<add> static::$_registry->unload($name);
<add> }
<ide> unset(static::$_config[$name]);
<ide> return true;
<ide> }
<ide><path>lib/Cake/Database/ConnectionRegistry.php
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> * @link http://cakephp.org CakePHP(tm) Project
<del> * @since CakePHP(tm) v 0.10.x.1402
<add> * @since CakePHP(tm) v3.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide> namespace Cake\Database;
<ide> protected function _resolveClassName($class) {
<ide> * Part of the template method for Cake\Utility\ObjectRegistry::load()
<ide> *
<ide> * @param string $class The classname that is missing.
<del> * @param string $plugin The plugin the cache is missing in.
<add> * @param string $plugin The plugin the driver is missing in.
<ide> * @throws Cake\Database\Exception\MissingDriverException
<ide> */
<ide> protected function _throwMissingClassError($class, $plugin) {
<del> throw new MissingDriverException(array(
<add> throw new MissingDriverException([
<ide> 'class' => $class,
<ide> 'plugin' => $plugin,
<del> 'message' => 'Driver "%s" was not found in.'
<del> ));
<add> ]);
<ide> }
<ide>
<ide> /**
<ide> protected function _throwMissingClassError($class, $plugin) {
<ide> * Part of the template method for Cake\Utility\ObjectRegistry::load()
<ide> *
<ide> * @param string|Driver $class The classname or object to make.
<del> * @param array $settings An array of settings to use for the driver engine.
<add> * @param array $settings An array of settings to use for the driver.
<ide> * @return Connection A connection with the correct driver.
<ide> */
<ide> protected function _create($class, $settings) {
<del> $isObject = is_object($class);
<ide> if (is_object($class)) {
<ide> $instance = $class;
<ide> }
<ide><path>lib/Cake/Error/MissingDatasourceConfigException.php
<ide> <?php
<ide> /**
<del> * MissingDatasourceConfigException class
<del> *
<ide> * PHP 5
<ide> *
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> *
<ide> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> * @link http://book.cakephp.org/2.0/en/development/testing.html
<del> * @package Cake.Error
<ide> * @since CakePHP(tm) v 3.0
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<ide> namespace Cake\Error;
<ide>
<ide> /**
<ide> * Exception class to be thrown when a datasource configuration is not found
<del> *
<del> * @package Cake.Error
<ide> */
<ide> class MissingDatasourceConfigException extends Exception {
<ide>
<del> protected $_messageTemplate = 'The datasource configuration "%s" was not found in datasources.php';
<add> protected $_messageTemplate = 'The datasource configuration "%s" was not found.';
<ide>
<ide> }
<ide><path>lib/Cake/Test/TestCase/Database/ConnectionManagerTest.php
<ide> public function testConfigInvalidOptions() {
<ide> * Test for errors on duplicate config.
<ide> *
<ide> * @expectedException Cake\Error\Exception
<add> * @expectedExceptionMessage Cannot reconfigure existing adapter "test_variant"
<ide> * @return void
<ide> */
<ide> public function testConfigDuplicateConfig() {
<ide> public function testConfigDuplicateConfig() {
<ide> * Test get() failing on missing config.
<ide> *
<ide> * @expectedException Cake\Error\Exception
<add> * @expectedExceptionMessage The datasource configuration "test_variant" was not found.
<ide> * @return void
<ide> */
<ide> public function testGetFailOnMissingConfig() {
<ide> public function testDrop() {
<ide> $this->assertTrue(ConnectionManager::drop('test_variant'));
<ide> $result = ConnectionManager::configured();
<ide> $this->assertNotContains('test_variant', $result);
<add>
<add> $this->assertTrue(ConnectionManager::drop('probably_does_not_exist'), 'Should always return true.');
<ide> }
<ide>
<ide> } | 4 |
Text | Text | remove leftover head from merge | c7af3da371b1252623790451451b45dad0cdf961 | <ide><path>CONTRIBUTING.md
<del><<<<<<< HEAD
<ide> # How to contribute
<ide>
<ide> CakePHP loves to welcome your contributions. There are several ways to help out: | 1 |
Java | Java | prevent duplicate @import processing | 6d8b37d8bbce8c6e6cb4890291469c80742132f7 | <ide><path>spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java
<ide> package org.springframework.context.annotation;
<ide>
<ide> import java.io.IOException;
<del>import java.lang.annotation.Annotation;
<del>import java.util.ArrayList;
<add>import java.util.Arrays;
<ide> import java.util.Collections;
<ide> import java.util.Comparator;
<ide> import java.util.HashMap;
<add>import java.util.HashSet;
<ide> import java.util.Iterator;
<ide> import java.util.LinkedHashSet;
<del>import java.util.List;
<ide> import java.util.Map;
<ide> import java.util.Set;
<ide> import java.util.Stack;
<ide> protected AnnotationMetadata doProcessConfigurationClass(
<ide> }
<ide>
<ide> // process any @Import annotations
<del> List<AnnotationAttributes> imports =
<del> findAllAnnotationAttributes(Import.class, metadata.getClassName(), true);
<del> for (AnnotationAttributes importAnno : imports) {
<del> processImport(configClass, importAnno.getStringArray("value"), true);
<add> Set<String> imports = getImports(metadata.getClassName(), null, new HashSet<String>());
<add> if (imports != null && !imports.isEmpty()) {
<add> processImport(configClass, imports.toArray(new String[imports.size()]), true);
<ide> }
<ide>
<ide> // process any @ImportResource annotations
<ide> protected AnnotationMetadata doProcessConfigurationClass(
<ide> }
<ide>
<ide> /**
<del> * Return a list of attribute maps for all declarations of the given annotation
<del> * on the given annotated class using the given MetadataReaderFactory to introspect
<del> * annotation metadata. Meta-annotations are ordered first in the list, and if the
<del> * target annotation is declared directly on the class, its map of attributes will be
<del> * ordered last in the list.
<del> * @param targetAnnotation the annotation to search for, both locally and as a meta-annotation
<del> * @param annotatedClassName the class to inspect
<del> * @param classValuesAsString whether class attributes should be returned as strings
<add> * Recursively collect all declared {@code @Import} values. Unlike most
<add> * meta-annotations it is valid to have several {@code @Import}s declared with
<add> * different values, the usual process or returning values from the first
<add> * meta-annotation on a class is not sufficient.
<add> * <p>For example, it is common for a {@code @Configuration} class to declare direct
<add> * {@code @Import}s in addition to meta-imports originating from an {@code @Enable}
<add> * annotation.
<add> * @param className the class name to search
<add> * @param imports the imports collected so far or {@code null}
<add> * @param visited used to track visited classes to prevent infinite recursion (must not be null)
<add> * @return a set of all {@link Import#value() import values} or {@code null}
<add> * @throws IOException if there is any problem reading metadata from the named class
<ide> */
<del> private List<AnnotationAttributes> findAllAnnotationAttributes(
<del> Class<? extends Annotation> targetAnnotation, String annotatedClassName,
<del> boolean classValuesAsString) throws IOException {
<del>
<del> List<AnnotationAttributes> allAttribs = new ArrayList<AnnotationAttributes>();
<del>
<del> MetadataReader reader = this.metadataReaderFactory.getMetadataReader(annotatedClassName);
<del> AnnotationMetadata metadata = reader.getAnnotationMetadata();
<del> String targetAnnotationType = targetAnnotation.getName();
<del>
<del> for (String annotationType : metadata.getAnnotationTypes()) {
<del> if (annotationType.equals(targetAnnotationType)) {
<del> continue;
<add> private Set<String> getImports(String className, Set<String> imports,
<add> Set<String> visited) throws IOException {
<add> if (visited.add(className)) {
<add> AnnotationMetadata metadata = metadataReaderFactory.getMetadataReader(className).getAnnotationMetadata();
<add> Map<String, Object> attributes = metadata.getAnnotationAttributes(Import.class.getName(), true);
<add> if (attributes != null) {
<add> String[] value = (String[]) attributes.get("value");
<add> if (value != null && value.length > 0) {
<add> imports = (imports == null ? new LinkedHashSet<String>() : imports);
<add> imports.addAll(Arrays.asList(value));
<add> }
<ide> }
<del> AnnotationMetadata metaAnnotations =
<del> this.metadataReaderFactory.getMetadataReader(annotationType).getAnnotationMetadata();
<del> AnnotationAttributes targetAttribs =
<del> AnnotationAttributes.fromMap(metaAnnotations.getAnnotationAttributes(targetAnnotationType, classValuesAsString));
<del> if (targetAttribs != null) {
<del> allAttribs.add(targetAttribs);
<add> for (String annotationType : metadata.getAnnotationTypes()) {
<add> getImports(annotationType, imports, visited);
<ide> }
<ide> }
<del>
<del> AnnotationAttributes localAttribs =
<del> AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(targetAnnotationType, classValuesAsString));
<del> if (localAttribs != null) {
<del> allAttribs.add(localAttribs);
<del> }
<del>
<del> return allAttribs;
<add> return imports;
<ide> }
<ide>
<ide> private void processImport(ConfigurationClass configClass, String[] classesToImport, boolean checkForCircularImports) throws IOException {
<ide> public CircularImportProblem(ConfigurationClass attemptedImport, Stack<Configura
<ide> new Location(importStack.peek().getResource(), metadata));
<ide> }
<ide> }
<del>
<ide> }
<ide><path>spring-context/src/test/java/org/springframework/context/annotation/ImportAwareTests.java
<ide> import org.springframework.beans.BeansException;
<ide> import org.springframework.beans.factory.BeanFactory;
<ide> import org.springframework.beans.factory.BeanFactoryAware;
<add>import org.springframework.beans.factory.config.BeanDefinition;
<ide> import org.springframework.beans.factory.config.BeanPostProcessor;
<add>import org.springframework.beans.factory.support.BeanDefinitionRegistry;
<add>import org.springframework.beans.factory.support.GenericBeanDefinition;
<ide> import org.springframework.core.annotation.AnnotationAttributes;
<ide> import org.springframework.core.type.AnnotationMetadata;
<ide> import org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor;
<add>import org.springframework.util.Assert;
<ide>
<ide> import static org.hamcrest.CoreMatchers.*;
<ide> import static org.junit.Assert.*;
<ide> public void indirectlyAnnotatedWithImport() {
<ide> assertThat(foo, is("xyz"));
<ide> }
<ide>
<add> @Test
<add> public void importRegistrar() throws Exception {
<add> ImportedRegistrar.called = false;
<add> AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
<add> ctx.register(ImportingRegistrarConfig.class);
<add> ctx.refresh();
<add> assertNotNull(ctx.getBean("registrarImportedBean"));
<add> }
<add>
<add> @Test
<add> public void importRegistrarWithImport() throws Exception {
<add> ImportedRegistrar.called = false;
<add> AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
<add> ctx.register(ImportingRegistrarConfigWithImport.class);
<add> ctx.refresh();
<add> assertNotNull(ctx.getBean("registrarImportedBean"));
<add> assertNotNull(ctx.getBean(ImportedConfig.class));
<add> }
<ide>
<ide> @Configuration
<ide> @Import(ImportedConfig.class)
<ide> public Object postProcessAfterInitialization(Object bean, String beanName) throw
<ide> public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
<ide> }
<ide> }
<add>
<add> @Configuration
<add> @EnableImportRegistrar
<add> static class ImportingRegistrarConfig {
<add> }
<add>
<add> @Configuration
<add> @EnableImportRegistrar
<add> @Import(ImportedConfig.class)
<add> static class ImportingRegistrarConfigWithImport {
<add> }
<add>
<add> @Target(ElementType.TYPE)
<add> @Retention(RetentionPolicy.RUNTIME)
<add> @Import(ImportedRegistrar.class)
<add> public @interface EnableImportRegistrar {
<add> }
<add>
<add> static class ImportedRegistrar implements ImportBeanDefinitionRegistrar {
<add>
<add> static boolean called;
<add>
<add> public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
<add> BeanDefinitionRegistry registry) {
<add> BeanDefinition beanDefinition = new GenericBeanDefinition();
<add> beanDefinition.setBeanClassName(String.class.getName());
<add> registry.registerBeanDefinition("registrarImportedBean", beanDefinition );
<add> Assert.state(called == false, "ImportedRegistrar called twice");
<add> called = true;
<add> }
<add> }
<ide> } | 2 |
Javascript | Javascript | fix coding style in web/text_layer_builder.js | 5dcc92430c486c686ca3a53375bda18a12992b34 | <ide><path>web/text_layer_builder.js
<ide> var TextLayerBuilder = function textLayerBuilder(options) {
<ide> this.viewport = options.viewport;
<ide> this.isViewerInPresentationMode = options.isViewerInPresentationMode;
<ide>
<del> if(typeof PDFFindController === 'undefined') {
<del> window.PDFFindController = null;
<add> if (typeof PDFFindController === 'undefined') {
<add> window.PDFFindController = null;
<ide> }
<ide>
<del> if(typeof this.lastScrollSource === 'undefined') {
<del> this.lastScrollSource = null;
<add> if (typeof this.lastScrollSource === 'undefined') {
<add> this.lastScrollSource = null;
<ide> }
<ide>
<ide> this.beginLayout = function textLayerBuilderBeginLayout() {
<ide> var TextLayerBuilder = function textLayerBuilder(options) {
<ide> // No point in rendering so many divs as it'd make the browser unusable
<ide> // even after the divs are rendered
<ide> var MAX_TEXT_DIVS_TO_RENDER = 100000;
<del> if (textDivs.length > MAX_TEXT_DIVS_TO_RENDER)
<add> if (textDivs.length > MAX_TEXT_DIVS_TO_RENDER) {
<ide> return;
<add> }
<ide>
<ide> for (var i = 0, ii = textDivs.length; i < ii; i++) {
<ide> var textDiv = textDivs[i];
<ide> var TextLayerBuilder = function textLayerBuilder(options) {
<ide> // run it right away
<ide> var RENDER_DELAY = 200; // in ms
<ide> var self = this;
<del> var lastScroll = this.lastScrollSource === null ?
<del> 0 : this.lastScrollSource.lastScroll;
<add> var lastScroll = (this.lastScrollSource === null ?
<add> 0 : this.lastScrollSource.lastScroll);
<ide>
<ide> if (Date.now() - lastScroll > RENDER_DELAY) {
<ide> // Render right away
<ide> this.renderLayer();
<ide> } else {
<ide> // Schedule
<del> if (this.renderTimer)
<add> if (this.renderTimer) {
<ide> clearTimeout(this.renderTimer);
<add> }
<ide> this.renderTimer = setTimeout(function() {
<ide> self.setupRenderLayoutTimer();
<ide> }, RENDER_DELAY);
<ide> var TextLayerBuilder = function textLayerBuilder(options) {
<ide>
<ide> textDiv.style.fontSize = fontHeight + 'px';
<ide> textDiv.style.fontFamily = geom.fontFamily;
<del> var fontAscent = geom.ascent ? geom.ascent * fontHeight :
<del> geom.descent ? (1 + geom.descent) * fontHeight : fontHeight;
<add> var fontAscent = (geom.ascent ? geom.ascent * fontHeight :
<add> (geom.descent ? (1 + geom.descent) * fontHeight : fontHeight));
<ide> textDiv.style.left = (geom.x + (fontAscent * Math.sin(geom.angle))) + 'px';
<ide> textDiv.style.top = (geom.y - (fontAscent * Math.cos(geom.angle))) + 'px';
<ide>
<ide> var TextLayerBuilder = function textLayerBuilder(options) {
<ide> this.insertDivContent = function textLayerUpdateTextContent() {
<ide> // Only set the content of the divs once layout has finished, the content
<ide> // for the divs is available and content is not yet set on the divs.
<del> if (!this.layoutDone || this.divContentDone || !this.textContent)
<add> if (!this.layoutDone || this.divContentDone || !this.textContent) {
<ide> return;
<add> }
<ide>
<ide> this.divContentDone = true;
<ide>
<ide> var TextLayerBuilder = function textLayerBuilder(options) {
<ide> var iIndex = 0;
<ide> var bidiTexts = this.textContent;
<ide> var end = bidiTexts.length - 1;
<del> var queryLen = PDFFindController === null ?
<del> 0 : PDFFindController.state.query.length;
<add> var queryLen = (PDFFindController === null ?
<add> 0 : PDFFindController.state.query.length);
<ide>
<ide> var lastDivIdx = -1;
<ide> var pos;
<ide> var TextLayerBuilder = function textLayerBuilder(options) {
<ide> var bidiTexts = this.textContent;
<ide> var textDivs = this.textDivs;
<ide> var prevEnd = null;
<del> var isSelectedPage = PDFFindController === null ?
<del> false : (this.pageIdx === PDFFindController.selected.pageIdx);
<add> var isSelectedPage = (PDFFindController === null ?
<add> false : (this.pageIdx === PDFFindController.selected.pageIdx));
<ide>
<del> var selectedMatchIdx = PDFFindController === null ?
<del> -1 : PDFFindController.selected.matchIdx;
<add> var selectedMatchIdx = (PDFFindController === null ?
<add> -1 : PDFFindController.selected.matchIdx);
<ide>
<del> var highlightAll = PDFFindController === null ?
<del> false : PDFFindController.state.highlightAll;
<add> var highlightAll = (PDFFindController === null ?
<add> false : PDFFindController.state.highlightAll);
<ide>
<ide> var infty = {
<ide> divIdx: -1,
<ide> var TextLayerBuilder = function textLayerBuilder(options) {
<ide>
<ide> this.updateMatches = function textLayerUpdateMatches() {
<ide> // Only show matches, once all rendering is done.
<del> if (!this.renderingDone)
<add> if (!this.renderingDone) {
<ide> return;
<add> }
<ide>
<ide> // Clear out all matches.
<ide> var matches = this.matches;
<ide> var TextLayerBuilder = function textLayerBuilder(options) {
<ide> clearedUntilDivIdx = match.end.divIdx + 1;
<ide> }
<ide>
<del> if (PDFFindController === null || !PDFFindController.active)
<add> if (PDFFindController === null || !PDFFindController.active) {
<ide> return;
<add> }
<ide>
<ide> // Convert the matches on the page controller into the match format used
<ide> // for the textLayer.
<del> this.matches = matches =
<del> this.convertMatches(PDFFindController === null ?
<del> [] : (PDFFindController.pageMatches[this.pageIdx] || []));
<add> this.matches = matches = (this.convertMatches(PDFFindController === null ?
<add> [] : (PDFFindController.pageMatches[this.pageIdx] || [])));
<ide>
<ide> this.renderMatches(this.matches);
<ide> }; | 1 |
PHP | PHP | add test for append() | 0a9a0de562e90e24815389427b482ec323002822 | <ide><path>tests/TestCase/Collection/CollectionTest.php
<ide> public function testAppend()
<ide> $collection = new Collection(['a' => 1, 'b' => 2]);
<ide> $combined = $collection->append(['c' => 3, 'a' => 4]);
<ide> $this->assertEquals(['a' => 4, 'b' => 2, 'c' => 3], $combined->toArray());
<add>
<add> $collection = new Collection([1, 2]);
<add> $collection = $collection->append([3, 4]);
<add> $combined = $collection->append([5, 6]);
<add> $this->assertEquals([1, 2, 3, 4, 5, 6], $combined->toList());
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | improve description and tests description | f06b56f101132583ff7d8ceae370dd7db5c38018 | <ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/align-columns.md
<ide> dashedName: align-columns
<ide>
<ide> # --description--
<ide>
<del>Given a text file of many lines, where fields within a line are delineated by a single `$` character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, or center justified within its column.
<add>Given an array of many lines, where fields within a line are delineated by a single `$` character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, or center justified within its column.
<ide>
<ide> # --instructions--
<ide>
<ide> Use the following text to test your programs:
<ide>
<del><pre>
<del>Given$a$text$file$of$many$lines
<del>where$fields$within$a$line$
<del>are$delineated$by$a$single$'dollar'$character
<del>write$a$program
<del>that$aligns$each$column$of$fields
<del>by$ensuring$that$words$in$each$
<del>column$are$separated$by$at$least$one$space.
<del>Further,$allow$for$each$word$in$a$column$to$be$either$left$
<del>justified,$right$justified
<del>or$center$justified$within$its$column.
<del></pre>
<add>```js
<add>const testText = [
<add> 'Given$a$text$file$of$many$lines',
<add> 'where$fields$within$a$line$',
<add> 'are$delineated$by$a$single$"dollar"$character',
<add> 'write$a$program',
<add> 'that$aligns$each$column$of$fields',
<add> 'by$ensuring$that$words$in$each$',
<add> 'column$are$separated$by$at$least$one$space.',
<add> 'Further,$allow$for$each$word$in$a$column$to$be$either$left$',
<add> 'justified,$right$justified',
<add> 'or$center$justified$within$its$column.'
<add>];
<add>```
<ide>
<ide> **Note that:**
<ide>
<del><ul>
<del> <li>The example input texts lines may, or may not, have trailing dollar characters.</li>
<del> <li>All columns should share the same alignment.</li>
<del> <li>Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.</li>
<del> <li>Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.</li>
<del> <li>The minimum space between columns should be computed from the text and not hard-coded.</li>
<del> <li>It is not a requirement to add separating characters between or around columns.</li>
<del></ul>
<add>- The example input texts lines may, or may not, have trailing dollar characters.
<add>- All columns should share the same alignment.
<add>- Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
<add>- Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal. Lines in it should be joined using new line character (`\n`).
<add>- The minimum space between columns should be computed from the text and not hard-coded.
<add>- It is not a requirement to add separating characters between or around columns.
<add>
<add>For example, one of the lines from the `testText`, after jusitifing to the right, left and center respectivelly:
<add>
<add>```js
<add>' column are separated by at least one space.\n'
<add>'column are separated by at least one space.\n'
<add>' column are separated by at least one space.\n'
<add>```
<ide>
<ide> # --hints--
<ide>
<ide> or$center$justified$within$its$column.
<ide> assert(typeof formatText === 'function');
<ide> ```
<ide>
<del>`formatText` with the above input and "right" justification should produce the following:
<add>`formatText(testText, 'right')` should produce text with columns justified to the right.
<ide>
<ide> ```js
<del>assert.strictEqual(formatText(testInput, 'right'), rightAligned);
<add>assert.strictEqual(formatText(_testText, 'right'), rightAligned);
<ide> ```
<ide>
<del>`formatText` with the above input and "left" justification should produce the following:
<add>`formatText(testText, 'left')` should produce text with columns justified to the left.
<ide>
<ide> ```js
<del>assert.strictEqual(formatText(testInput, 'left'), leftAligned);
<add>assert.strictEqual(formatText(_testText, 'left'), leftAligned);
<ide> ```
<ide>
<del>`formatText` with the above input and "center" justification should produce the following:
<add>`formatText(testText, 'center')` should produce text with columns justified to the center.
<ide>
<ide> ```js
<del>assert.strictEqual(formatText(testInput, 'center'), centerAligned);
<add>assert.strictEqual(formatText(_testText, 'center'), centerAligned);
<ide> ```
<ide>
<ide> # --seed--
<ide>
<ide> ## --after-user-code--
<ide>
<ide> ```js
<del>const testInput = [
<add>const _testText = [
<ide> 'Given$a$text$file$of$many$lines',
<ide> 'where$fields$within$a$line$',
<del> 'are$delineated$by$a$single$\"dollar\"$character',
<add> 'are$delineated$by$a$single$"dollar"$character',
<ide> 'write$a$program',
<ide> 'that$aligns$each$column$of$fields$',
<ide> 'by$ensuring$that$words$in$each$',
<ide> const centerAligned = ' Given a text file of many
<ide> ## --seed-contents--
<ide>
<ide> ```js
<del>const testArr = [
<del> 'Given$a$text$file$of$many$lines',
<del> 'where$fields$within$a$line$',
<del> 'are$delineated$by$a$single$"dollar"$character',
<del> 'write$a$program',
<del> 'that$aligns$each$column$of$fields$',
<del> 'by$ensuring$that$words$in$each$',
<del> 'column$are$separated$by$at$least$one$space.',
<del> 'Further,$allow$for$each$word$in$a$column$to$be$either$left$',
<del> 'justified,$right$justified',
<del> 'or$center$justified$within$its$column.'
<del>];
<del>
<ide> function formatText(input, justification) {
<ide>
<ide> }
<del>```
<ide>
<del># --solutions--
<del>
<del>```js
<del>const testArr = [
<add>const testText = [
<ide> 'Given$a$text$file$of$many$lines',
<ide> 'where$fields$within$a$line$',
<ide> 'are$delineated$by$a$single$"dollar"$character',
<ide> const testArr = [
<ide> 'justified,$right$justified',
<ide> 'or$center$justified$within$its$column.'
<ide> ];
<add>```
<add>
<add># --solutions--
<ide>
<add>```js
<ide> String.prototype.repeat = function (n) { return new Array(1 + parseInt(n)).join(this); };
<ide>
<ide> function formatText(input, justification) { | 1 |
Text | Text | add undici to glossary | c977ad6baacaf6442b0d66be2eae1b31da490c87 | <ide><path>glossary.md
<ide> You may also need to check <https://chromium.googlesource.com/chromiumos/docs/+/
<ide> primarily administrated by Matt Godbolt.
<ide> * primordials: Pristine built-ins that are not affected by prototype pollution
<ide> and tampering with built-ins.
<add>* undici: An alternative HTTP client used in Node.js. See more details
<add> on the [undici repository](https://github.com/nodejs/undici). | 1 |
Text | Text | add a contributing.md file for github | 2d13b3d50475cef73ba8068cc6477be5f6575f52 | <ide><path>CONTRIBUTING.md
<add># Pull request guidelines
<add>
<add>[GitHub pull requests](https://help.github.com/articles/using-pull-requests) are a great way for everyone in the community to contribute to the Laravel codebase. Found a bug? Just fix it in your fork and submit a pull request. This will then be reviewed, and, if found as good, merged into the main repository.
<add>
<add>In order to keep the codebase clean, stable and at high quality, even with so many people contributing, some guidelines are necessary for high-quality pull requests:
<add>
<add>- **Branch:** Unless they are immediate documentation fixes relevant for old versions, pull requests should be sent to the `develop` branch only. Make sure to select that branch as target when creating the pull request (GitHub will not automatically select it.)
<add>- **Documentation:** If you are adding a new feature or changing the API in any relevant way, this should be documented. The documentation files can be found directly in the core repository.
<add>- **Unit tests:** To keep old bugs from re-appearing and generally hold quality at a high level, the Laravel core is thoroughly unit-tested. Thus, when you create a pull request, it is expected that you unit test any new code you add. For any bug you fix, you should also add regression tests to make sure the bug will never appear again. If you are unsure about how to write tests, the core team or other contributors will gladly help.
<ide>\ No newline at end of file | 1 |
PHP | PHP | fix misaligned comment | f8426d333a7a9a2b7489a31bb34d2c1e9f4cfaac | <ide><path>src/Mailer/Transport/SmtpTransport.php
<ide> public function __destruct()
<ide> try {
<ide> $this->disconnect();
<ide> } catch (Exception $e) {
<del>// avoid fatal error on script termination
<add> // avoid fatal error on script termination
<ide> }
<ide> }
<ide> | 1 |
Mixed | Go | use explicit format when using secrets | 2adbdcdf5a83b45b4e191413d3aa14158535085b | <ide><path>cli/command/service/create.go
<ide> func newCreateCommand(dockerCli *command.DockerCli) *cobra.Command {
<ide> flags.Var(&opts.mounts, flagMount, "Attach a filesystem mount to the service")
<ide> flags.Var(&opts.constraints, flagConstraint, "Placement constraints")
<ide> flags.Var(&opts.networks, flagNetwork, "Network attachments")
<add> flags.Var(&opts.secrets, flagSecret, "Specify secrets to expose to the service")
<ide> flags.VarP(&opts.endpoint.ports, flagPublish, "p", "Publish a port as a node port")
<ide> flags.Var(&opts.groups, flagGroup, "Set one or more supplementary user groups for the container")
<ide> flags.Var(&opts.dns, flagDNS, "Set custom DNS servers")
<ide> func runCreate(dockerCli *command.DockerCli, opts *serviceOptions) error {
<ide> }
<ide>
<ide> // parse and validate secrets
<del> secrets, err := parseSecrets(apiClient, opts.secrets)
<add> secrets, err := parseSecrets(apiClient, opts.secrets.Value())
<ide> if err != nil {
<ide> return err
<ide> }
<ide><path>cli/command/service/opts.go
<ide> package service
<ide>
<ide> import (
<add> "encoding/csv"
<ide> "fmt"
<add> "os"
<add> "path/filepath"
<ide> "strconv"
<ide> "strings"
<ide> "time"
<ide> func (f *floatValue) Value() float32 {
<ide> return float32(*f)
<ide> }
<ide>
<add>// SecretRequestSpec is a type for requesting secrets
<add>type SecretRequestSpec struct {
<add> source string
<add> target string
<add> uid string
<add> gid string
<add> mode os.FileMode
<add>}
<add>
<add>// SecretOpt is a Value type for parsing secrets
<add>type SecretOpt struct {
<add> values []*SecretRequestSpec
<add>}
<add>
<add>// Set a new secret value
<add>func (o *SecretOpt) Set(value string) error {
<add> csvReader := csv.NewReader(strings.NewReader(value))
<add> fields, err := csvReader.Read()
<add> if err != nil {
<add> return err
<add> }
<add>
<add> spec := &SecretRequestSpec{
<add> source: "",
<add> target: "",
<add> uid: "0",
<add> gid: "0",
<add> mode: 0444,
<add> }
<add>
<add> for _, field := range fields {
<add> parts := strings.SplitN(field, "=", 2)
<add> key := strings.ToLower(parts[0])
<add>
<add> if len(parts) != 2 {
<add> return fmt.Errorf("invalid field '%s' must be a key=value pair", field)
<add> }
<add>
<add> value := parts[1]
<add> switch key {
<add> case "source":
<add> spec.source = value
<add> case "target":
<add> tDir, _ := filepath.Split(value)
<add> if tDir != "" {
<add> return fmt.Errorf("target must not have a path")
<add> }
<add> spec.target = value
<add> case "uid":
<add> spec.uid = value
<add> case "gid":
<add> spec.gid = value
<add> case "mode":
<add> m, err := strconv.ParseUint(value, 0, 32)
<add> if err != nil {
<add> return fmt.Errorf("invalid mode specified: %v", err)
<add> }
<add>
<add> spec.mode = os.FileMode(m)
<add> default:
<add> return fmt.Errorf("invalid field in secret request: %s", key)
<add> }
<add> }
<add>
<add> if spec.source == "" {
<add> return fmt.Errorf("source is required")
<add> }
<add>
<add> o.values = append(o.values, spec)
<add> return nil
<add>}
<add>
<add>// Type returns the type of this option
<add>func (o *SecretOpt) Type() string {
<add> return "secret"
<add>}
<add>
<add>// String returns a string repr of this option
<add>func (o *SecretOpt) String() string {
<add> secrets := []string{}
<add> for _, secret := range o.values {
<add> repr := fmt.Sprintf("%s -> %s", secret.source, secret.target)
<add> secrets = append(secrets, repr)
<add> }
<add> return strings.Join(secrets, ", ")
<add>}
<add>
<add>// Value returns the secret requests
<add>func (o *SecretOpt) Value() []*SecretRequestSpec {
<add> return o.values
<add>}
<add>
<ide> type updateOptions struct {
<ide> parallelism uint64
<ide> delay time.Duration
<ide> type serviceOptions struct {
<ide> logDriver logDriverOptions
<ide>
<ide> healthcheck healthCheckOptions
<del> secrets []string
<add> secrets SecretOpt
<ide> }
<ide>
<ide> func newServiceOptions() *serviceOptions {
<ide><path>cli/command/service/opts_test.go
<ide> package service
<ide>
<ide> import (
<add> "os"
<ide> "reflect"
<ide> "testing"
<ide> "time"
<ide> func TestHealthCheckOptionsToHealthConfigConflict(t *testing.T) {
<ide> _, err := opt.toHealthConfig()
<ide> assert.Error(t, err, "--no-healthcheck conflicts with --health-* options")
<ide> }
<add>
<add>func TestSecretOptionsSimple(t *testing.T) {
<add> var opt SecretOpt
<add>
<add> testCase := "source=/foo,target=testing"
<add> assert.NilError(t, opt.Set(testCase))
<add>
<add> reqs := opt.Value()
<add> assert.Equal(t, len(reqs), 1)
<add> req := reqs[0]
<add> assert.Equal(t, req.source, "/foo")
<add> assert.Equal(t, req.target, "testing")
<add>}
<add>
<add>func TestSecretOptionsCustomUidGid(t *testing.T) {
<add> var opt SecretOpt
<add>
<add> testCase := "source=/foo,target=testing,uid=1000,gid=1001"
<add> assert.NilError(t, opt.Set(testCase))
<add>
<add> reqs := opt.Value()
<add> assert.Equal(t, len(reqs), 1)
<add> req := reqs[0]
<add> assert.Equal(t, req.source, "/foo")
<add> assert.Equal(t, req.target, "testing")
<add> assert.Equal(t, req.uid, "1000")
<add> assert.Equal(t, req.gid, "1001")
<add>}
<add>
<add>func TestSecretOptionsCustomMode(t *testing.T) {
<add> var opt SecretOpt
<add>
<add> testCase := "source=/foo,target=testing,uid=1000,gid=1001,mode=0444"
<add> assert.NilError(t, opt.Set(testCase))
<add>
<add> reqs := opt.Value()
<add> assert.Equal(t, len(reqs), 1)
<add> req := reqs[0]
<add> assert.Equal(t, req.source, "/foo")
<add> assert.Equal(t, req.target, "testing")
<add> assert.Equal(t, req.uid, "1000")
<add> assert.Equal(t, req.gid, "1001")
<add> assert.Equal(t, req.mode, os.FileMode(0444))
<add>}
<ide><path>cli/command/service/parse.go
<ide> package service
<ide> import (
<ide> "context"
<ide> "fmt"
<del> "path/filepath"
<del> "strings"
<ide>
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/filters"
<ide> swarmtypes "github.com/docker/docker/api/types/swarm"
<ide> "github.com/docker/docker/client"
<ide> )
<ide>
<del>// parseSecretString parses the requested secret and returns the secret name
<del>// and target. Expects format SECRET_NAME:TARGET
<del>func parseSecretString(secretString string) (string, string, error) {
<del> tokens := strings.Split(secretString, ":")
<del>
<del> secretName := strings.TrimSpace(tokens[0])
<del> targetName := secretName
<del>
<del> if secretName == "" {
<del> return "", "", fmt.Errorf("invalid secret name provided")
<del> }
<del>
<del> if len(tokens) > 1 {
<del> targetName = strings.TrimSpace(tokens[1])
<del> if targetName == "" {
<del> return "", "", fmt.Errorf("invalid presentation name provided")
<del> }
<del> }
<del>
<del> // ensure target is a filename only; no paths allowed
<del> tDir, _ := filepath.Split(targetName)
<del> if tDir != "" {
<del> return "", "", fmt.Errorf("target must not have a path")
<del> }
<del>
<del> return secretName, targetName, nil
<del>}
<del>
<ide> // parseSecrets retrieves the secrets from the requested names and converts
<ide> // them to secret references to use with the spec
<del>func parseSecrets(client client.APIClient, requestedSecrets []string) ([]*swarmtypes.SecretReference, error) {
<add>func parseSecrets(client client.APIClient, requestedSecrets []*SecretRequestSpec) ([]*swarmtypes.SecretReference, error) {
<ide> secretRefs := make(map[string]*swarmtypes.SecretReference)
<ide> ctx := context.Background()
<ide>
<ide> for _, secret := range requestedSecrets {
<del> n, t, err := parseSecretString(secret)
<del> if err != nil {
<del> return nil, err
<del> }
<del>
<ide> secretRef := &swarmtypes.SecretReference{
<del> SecretName: n,
<del> // TODO (ehazlett): parse these from cli request
<add> SecretName: secret.source,
<ide> Target: swarmtypes.SecretReferenceFileTarget{
<del> Name: t,
<del> UID: "0",
<del> GID: "0",
<del> Mode: 0444,
<add> Name: secret.target,
<add> UID: secret.uid,
<add> GID: secret.gid,
<add> Mode: secret.mode,
<ide> },
<ide> }
<ide>
<del> if _, exists := secretRefs[t]; exists {
<del> return nil, fmt.Errorf("duplicate secret target for %s not allowed", n)
<add> if _, exists := secretRefs[secret.target]; exists {
<add> return nil, fmt.Errorf("duplicate secret target for %s not allowed", secret.source)
<ide> }
<del> secretRefs[t] = secretRef
<add> secretRefs[secret.target] = secretRef
<ide> }
<ide>
<ide> args := filters.NewArgs()
<ide><path>cli/command/service/update.go
<ide> func newUpdateCommand(dockerCli *command.DockerCli) *cobra.Command {
<ide> flags.Var(&opts.containerLabels, flagContainerLabelAdd, "Add or update a container label")
<ide> flags.Var(&opts.env, flagEnvAdd, "Add or update an environment variable")
<ide> flags.Var(newListOptsVar(), flagSecretRemove, "Remove a secret")
<del> flags.StringSliceVar(&opts.secrets, flagSecretAdd, []string{}, "Add a secret")
<add> flags.Var(&opts.secrets, flagSecretAdd, "Add or update a secret on a service")
<ide> flags.Var(&opts.mounts, flagMountAdd, "Add or update a mount on a service")
<ide> flags.Var(&opts.constraints, flagConstraintAdd, "Add or update a placement constraint")
<ide> flags.Var(&opts.endpoint.ports, flagPublishAdd, "Add or update a published port")
<ide> func updateEnvironment(flags *pflag.FlagSet, field *[]string) {
<ide>
<ide> func getUpdatedSecrets(apiClient client.APIClient, flags *pflag.FlagSet, secrets []*swarm.SecretReference) ([]*swarm.SecretReference, error) {
<ide> if flags.Changed(flagSecretAdd) {
<del> values, err := flags.GetStringSlice(flagSecretAdd)
<del> if err != nil {
<del> return nil, err
<del> }
<add> values := flags.Lookup(flagSecretAdd).Value.(*SecretOpt).Value()
<ide>
<ide> addSecrets, err := parseSecrets(apiClient, values)
<ide> if err != nil {
<ide><path>docs/reference/commandline/service_create.md
<ide> Use the `--secret` flag to give a container access to a
<ide> with two secrets named `ssh-key` and `app-key`:
<ide>
<ide> ```bash
<del>$ docker service create --name redis --secret ssh-key:ssh --secret app-key:app redis:3.0.6
<add>$ docker service create --name redis --secret source=ssh-key,target=ssh --secret source=app-key,target=app,uid=1000,gid=1001,mode=0400 redis:3.0.6
<ide> 4cdgfyky7ozwh3htjfw0d12qv
<ide> ```
<ide>
<ide><path>docs/reference/commandline/service_update.md
<ide> The following example adds a secret named `ssh-2` and removes `ssh-1`:
<ide>
<ide> ```bash
<ide> $ docker service update \
<del> --secret-add ssh-2 \
<add> --secret-add source=ssh-2,target=ssh-2 \
<ide> --secret-rm ssh-1 \
<ide> myservice
<ide> ```
<ide><path>integration-cli/docker_cli_service_create_test.go
<ide> func (s *DockerSwarmSuite) TestServiceCreateWithSecret(c *check.C) {
<ide> c.Assert(id, checker.Not(checker.Equals), "", check.Commentf("secrets: %s", id))
<ide> testTarget := "testing"
<ide>
<del> out, err := d.Cmd("service", "create", "--name", serviceName, "--secret", fmt.Sprintf("%s:%s", testName, testTarget), "busybox", "top")
<add> out, err := d.Cmd("service", "create", "--name", serviceName, "--secret", fmt.Sprintf("source=%s,target=%s", testName, testTarget), "busybox", "top")
<ide> c.Assert(err, checker.IsNil, check.Commentf(out))
<ide>
<ide> out, err = d.Cmd("service", "inspect", "--format", "{{ json .Spec.TaskTemplate.ContainerSpec.Secrets }}", serviceName)
<ide><path>integration-cli/docker_cli_service_update_test.go
<ide> func (s *DockerSwarmSuite) TestServiceUpdateSecrets(c *check.C) {
<ide> c.Assert(err, checker.IsNil, check.Commentf(out))
<ide>
<ide> // add secret
<del> out, err = d.Cmd("service", "update", "test", "--secret-add", fmt.Sprintf("%s:%s", testName, testTarget))
<add> out, err = d.Cmd("service", "update", "test", "--secret-add", fmt.Sprintf("source=%s,target=%s", testName, testTarget))
<ide> c.Assert(err, checker.IsNil, check.Commentf(out))
<ide>
<ide> out, err = d.Cmd("service", "inspect", "--format", "{{ json .Spec.TaskTemplate.ContainerSpec.Secrets }}", serviceName) | 9 |
Text | Text | add experimental documentation for stacks | ae816baa3c36aaec5e3b7c31425b620b4709ab50 | <ide><path>experimental/README.md
<ide> to build a Docker binary with the experimental features enabled:
<ide>
<ide> * [External graphdriver plugins](plugins_graphdriver.md)
<ide> * [Macvlan and Ipvlan Network Drivers](vlan-networks.md)
<del> * The user namespaces feature has graduated from experimental.
<add> * [Docker stacks](docker-stacks.md)
<ide>
<ide> ## How to comment on an experimental feature
<ide>
<ide><path>experimental/docker-stacks.md
<add># Docker Stacks
<add>
<add>## Overview
<add>
<add>Docker Stacks are an experimental feature introduced in Docker 1.12, alongside
<add>the new concepts of Swarms and Services inside the Engine.
<add>
<add>A Dockerfile can be built into an image, and containers can be created from that
<add>image. Similarly, a docker-compose.yml can be built into a **bundle**, and
<add>**stacks** can be created from that bundle. In that sense, the bundle is a
<add>multi-services distributable image format.
<add>
<add>As of 1.12, the feature is introduced as experimental, and Docker Engine doesn't
<add>support distribution of bundles.
<add>
<add>## Producing a bundle
<add>
<add>The easiest way to produce a bundle is to generate it using `docker-compose`
<add>from an existing `docker-compose.yml`. Of course, that's just *one* possible way
<add>to proceed, in the same way that `docker build` isn't the only way to produce a
<add>Docker image.
<add>
<add>From `docker-compose`:
<add>
<add> ```bash
<add> $ docker-compose bundle
<add> WARNING: Unsupported key 'network_mode' in services.nsqd - ignoring
<add> WARNING: Unsupported key 'links' in services.nsqd - ignoring
<add> WARNING: Unsupported key 'volumes' in services.nsqd - ignoring
<add> [...]
<add> Wrote bundle to vossibility-stack.dsb
<add> ```
<add>
<add>## Creating a stack from a bundle
<add>
<add>A stack is created using the `docker deploy` command:
<add>
<add> ```bash
<add> # docker deploy --help
<add>
<add> Usage: docker deploy [OPTIONS] STACK
<add>
<add> Create and update a stack
<add>
<add> Options:
<add> -f, --bundle string Path to a bundle (Default: STACK.dsb)
<add> --help Print usage
<add> ```
<add>
<add>Let's deploy the stack created before:
<add>
<add> ```bash
<add> # docker deploy vossibility-stack
<add> Loading bundle from vossibility-stack.dsb
<add> Creating service vossibility-stack_elasticsearch
<add> Creating service vossibility-stack_kibana
<add> Creating service vossibility-stack_logstash
<add> Creating service vossibility-stack_lookupd
<add> Creating service vossibility-stack_nsqd
<add> Creating service vossibility-stack_vossibility-collector
<add> ```
<add>
<add>We can verify that services were correctly created:
<add>
<add> ```bash
<add> # docker service ls
<add> ID NAME SCALE IMAGE
<add> COMMAND
<add> 29bv0vnlm903 vossibility-stack_lookupd 1 nsqio/nsq@sha256:eeba05599f31eba418e96e71e0984c3dc96963ceb66924dd37a47bf7ce18a662 /nsqlookupd
<add> 4awt47624qwh vossibility-stack_nsqd 1 nsqio/nsq@sha256:eeba05599f31eba418e96e71e0984c3dc96963ceb66924dd37a47bf7ce18a662 /nsqd --data-path=/data --lookupd-tcp-address=lookupd:4160
<add> 4tjx9biia6fs vossibility-stack_elasticsearch 1 elasticsearch@sha256:12ac7c6af55d001f71800b83ba91a04f716e58d82e748fa6e5a7359eed2301aa
<add> 7563uuzr9eys vossibility-stack_kibana 1 kibana@sha256:6995a2d25709a62694a937b8a529ff36da92ebee74bafd7bf00e6caf6db2eb03
<add> 9gc5m4met4he vossibility-stack_logstash 1 logstash@sha256:2dc8bddd1bb4a5a34e8ebaf73749f6413c101b2edef6617f2f7713926d2141fe logstash -f /etc/logstash/conf.d/logstash.conf
<add> axqh55ipl40h vossibility-stack_vossibility-collector 1 icecrime/vossibility-collector@sha256:f03f2977203ba6253988c18d04061c5ec7aab46bca9dfd89a9a1fa4500989fba --config /config/config.toml --debug
<add> ```
<add>
<add>## Managing stacks
<add>
<add>Tasks are managed using the `docker stack` command:
<add>
<add> ```bash
<add> # docker stack --help
<add>
<add> Usage: docker stack COMMAND
<add>
<add> Manage Docker stacks
<add>
<add> Options:
<add> --help Print usage
<add>
<add> Commands:
<add> config Print the stack configuration
<add> deploy Create and update a stack
<add> rm Remove the stack
<add> tasks List the tasks in the stack
<add>
<add> Run 'docker stack COMMAND --help' for more information on a command.
<add> ``` | 2 |
Text | Text | fix typo in packages.md | fda1402b794a1e6738f156e8b9a2d034d65a1afa | <ide><path>doc/api/packages.md
<ide> use in Node.js but not the browser:
<ide> ```
<ide>
<ide> Conditions continue to be matched in order as with flat conditions. If
<del>a nested conditional does not have any mapping it will continue checking
<add>a nested condition does not have any mapping it will continue checking
<ide> the remaining conditions of the parent condition. In this way nested
<ide> conditions behave analogously to nested JavaScript `if` statements.
<ide> | 1 |
Javascript | Javascript | fix typo in test description | 9db70d3959f8ff062a9e65029695f55c9c01de29 | <ide><path>test/ngRoute/routeSpec.js
<ide> describe('$route', function() {
<ide>
<ide>
<ide> describe('events', function() {
<del> it('should not fire $routeChangeStart/success during bootstrap (if no route)', function() {
<add> it('should not fire $routeChangeStart/Success during bootstrap (if no route)', function() {
<ide> var routeChangeSpy = jasmine.createSpy('route change');
<ide>
<ide> module(function($routeProvider) { | 1 |
Text | Text | fix quoting of testflags in devenvironment.md | 7aa88a4ff66aa0c256dc15e5e5a4ddda34ed0f46 | <ide><path>docs/sources/contributing/devenvironment.md
<ide> something like this
<ide> If $TESTFLAGS is set in the environment, it is passed as extra arguments
<ide> to `go test`. You can use this to select certain tests to run, e.g.,
<ide>
<del> $ TESTFLAGS=`-test.run \^TestBuild\$` make test
<add> $ TESTFLAGS='-test.run \^TestBuild\$' make test
<ide>
<ide> If the output indicates "FAIL" and you see errors like this:
<ide> | 1 |
Text | Text | add guybedford to collaborators | 2346c6389f2253b9fc4f29c0e552283ab305f702 | <ide><path>README.md
<ide> For more information about the governance of the Node.js project, see
<ide> **Gibson Fahnestock** <gibfahn@gmail.com> (he/him)
<ide> * [gireeshpunathil](https://github.com/gireeshpunathil) -
<ide> **Gireesh Punathil** <gpunathi@in.ibm.com> (he/him)
<add>* [guybedford](https://github.com/guybedford) -
<add>**Guy Bedford** <guybedford@gmail.com> (he/him)
<ide> * [hashseed](https://github.com/hashseed) -
<ide> **Yang Guo** <yangguo@chromium.org> (he/him)
<ide> * [iarna](https://github.com/iarna) - | 1 |
Mixed | Javascript | add normalized option | 4cc3079e65c47b3f7eabceec19d652937b4ce7da | <ide><path>docs/docs/axes/cartesian/timeseries.md
<ide> title: Time Series Axis
<ide> ---
<ide>
<del>The time series scale extends from the time scale and supports all the same options. However, for the time series scale, each data point is spread equidistant. Also, the data indices are expected to be unique, sorted, and consistent across datasets.
<add>The time series scale extends from the time scale and supports all the same options. However, for the time series scale, each data point is spread equidistant.
<ide>
<ide> ## Example
<ide>
<ide><path>docs/docs/general/performance.md
<ide> title: Performance
<ide>
<ide> Chart.js charts are rendered on `canvas` elements, which makes rendering quite fast. For large datasets or performance sensitive applications, you may wish to consider the tips below.
<ide>
<add>## Data structure and format
<add>
<add>### Parsing
<add>
<add>Provide prepared data in the internal format accepted by the dataset and scales and set `parsing: false`. See [Data structures](data-structures.md) for more information.
<add>
<add>### Data normalization
<add>
<add>Chart.js is fastest if you provide data with indices that are unique, sorted, and consistent across datasets and provide the `normalized: true` option to let Chart.js know that you have done so. Even without this option, it can sometimes still be faster to provide sorted data.
<add>
<add>### Decimation
<add>
<add>Decimating your data will achieve the best results. When there is a lot of data to display on the graph, it doesn't make sense to show tens of thousands of data points on a graph that is only a few hundred pixels wide.
<add>
<add>There are many approaches to data decimation and selection of an algorithm will depend on your data and the results you want to achieve. For instance, [min/max](https://digital.ni.com/public.nsf/allkb/F694FFEEA0ACF282862576020075F784) decimation will preserve peaks in your data but could require up to 4 points for each pixel. This type of decimation would work well for a very noisy signal where you need to see data peaks.
<add>
<add>Line charts are able to do [automatic data decimation during draw](#automatic-data-decimation-during-draw), when certain conditions are met. You should still consider decimating data yourself before passing it in for maximum performance since the automatic decimation occurs late in the chart life cycle.
<add>
<ide> ## Tick Calculation
<ide>
<ide> ### Rotation
<ide> new Chart(ctx, {
<ide> });
<ide> ```
<ide>
<del>## Provide ordered data
<del>
<del>If the data is unordered, Chart.js needs to sort it. This can be slow in some cases, so its always a good idea to provide ordered data.
<del>
<ide> ## Specify `min` and `max` for scales
<ide>
<ide> If you specify the `min` and `max`, the scale does not have to compute the range from the data.
<ide> new Chart(ctx, {
<ide> });
<ide> ```
<ide>
<del>## Data structure and format
<del>
<del>Provide prepared data in the internal format accepted by the dataset and scales and set `parsing: false`. See [Data structures](data-structures.md) for more information.
<del>
<del>## Data Decimation
<del>
<del>Decimating your data will achieve the best results. When there is a lot of data to display on the graph, it doesn't make sense to show tens of thousands of data points on a graph that is only a few hundred pixels wide.
<del>
<del>There are many approaches to data decimation and selection of an algorithm will depend on your data and the results you want to achieve. For instance, [min/max](https://digital.ni.com/public.nsf/allkb/F694FFEEA0ACF282862576020075F784) decimation will preserve peaks in your data but could require up to 4 points for each pixel. This type of decimation would work well for a very noisy signal where you need to see data peaks.
<del>
<del>Line charts are able to do [automatic data decimation during draw](#automatic-data-decimation-during-draw), when certain conditions are met. You should still consider decimating data yourself before passing it in for maximum performance since the automatic decimation occurs late in the chart life cycle.
<del>
<del>## Render Chart.js in a web worker (Chrome only)
<add>## Parallel rendering with web workers (Chrome only)
<ide>
<ide> Chome (in version 69) added the ability to [transfer rendering control of a canvas](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/transferControlToOffscreen) to a web worker. Web workers can use the [OffscreenCanvas API](https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas) to render from a web worker onto canvases in the DOM. Chart.js is a canvas-based library and supports rendering in a web worker - just pass an OffscreenCanvas into the Chart constructor instead of a Canvas element. Note that as of today, this API is only supported in Chrome.
<ide>
<ide> new Chart(ctx, {
<ide> });
<ide> ```
<ide>
<del>### When transpiling with Babel, cosider using `loose` mode
<add>## When transpiling with Babel, cosider using `loose` mode
<ide>
<ide> Babel 7.9 changed the way classes are constructed. It is slow, unless used with `loose` mode.
<ide> [More information](https://github.com/babel/babel/issues/11356)
<ide><path>src/controllers/controller.bar.js
<ide> export default class BarController extends DatasetController {
<ide> let i, ilen;
<ide>
<ide> for (i = 0, ilen = meta.data.length; i < ilen; ++i) {
<del> pixels.push(iScale.getPixelForValue(me.getParsed(i)[iScale.axis]));
<add> pixels.push(iScale.getPixelForValue(me.getParsed(i)[iScale.axis], i));
<ide> }
<ide>
<ide> // Note: a potential optimization would be to skip computing this
<ide><path>src/controllers/controller.line.js
<ide> export default class LineController extends DatasetController {
<ide> const index = start + i;
<ide> const point = points[i];
<ide> const parsed = me.getParsed(index);
<del> const x = xScale.getPixelForValue(parsed.x);
<del> const y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(_stacked ? me.applyStack(yScale, parsed) : parsed.y);
<add> const x = xScale.getPixelForValue(parsed.x, index);
<add> const y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(_stacked ? me.applyStack(yScale, parsed) : parsed.y, index);
<ide> const properties = {
<ide> x,
<ide> y,
<ide><path>src/core/core.controller.js
<ide> class Chart {
<ide> scales[scale.id] = scale;
<ide> }
<ide>
<del> scale.init(scaleOptions);
<add> scale.init(scaleOptions, options);
<ide>
<ide> // TODO(SB): I think we should be able to remove this custom case (options.scale)
<ide> // and consider it as a regular scale part of the "scales"" map only! This would
<ide><path>src/core/core.scale.js
<ide> export default class Scale extends Element {
<ide> * Returns the location of the given data point. Value can either be an index or a numerical value
<ide> * The coordinate (0, 0) is at the upper-left corner of the canvas
<ide> * @param {*} value
<add> * @param {number} [index]
<ide> * @return {number}
<ide> */
<del> getPixelForValue(value) { // eslint-disable-line no-unused-vars
<add> getPixelForValue(value, index) { // eslint-disable-line no-unused-vars
<ide> return NaN;
<ide> }
<ide>
<ide><path>src/scales/scale.time.js
<ide> export default class TimeScale extends Scale {
<ide> this._unit = 'day';
<ide> /** @type {Unit=} */
<ide> this._majorUnit = undefined;
<del> /** @type {object} */
<ide> this._offsets = {};
<add> this._normalized = false;
<ide> }
<ide>
<del> init(options) {
<del> const time = options.time || (options.time = {});
<del> const adapter = this._adapter = new adapters._date(options.adapters.date);
<add> init(scaleOpts, opts) {
<add> const time = scaleOpts.time || (scaleOpts.time = {});
<add> const adapter = this._adapter = new adapters._date(scaleOpts.adapters.date);
<ide>
<ide> // Backward compatibility: before introducing adapter, `displayFormats` was
<ide> // supposed to contain *all* unit/string pairs but this can't be resolved
<ide> // when loading the scale (adapters are loaded afterward), so let's populate
<ide> // missing formats on update
<ide> mergeIf(time.displayFormats, adapter.formats());
<ide>
<del> super.init(options);
<add> super.init(scaleOpts);
<add>
<add> this._normalized = opts.normalized;
<ide> }
<ide>
<ide> /**
<ide> export default class TimeScale extends Scale {
<ide>
<ide> const metas = me.getMatchingVisibleMetas();
<ide>
<add> if (me._normalized && metas.length) {
<add> return (me._cache.data = metas[0].controller.getAllParsedValues(me));
<add> }
<add>
<ide> for (i = 0, ilen = metas.length; i < ilen; ++i) {
<ide> timestamps = timestamps.concat(metas[i].controller.getAllParsedValues(me));
<ide> }
<ide>
<del> // We can not assume data is in order or unique - not even for single dataset
<del> // It seems to be somewhat faster to do sorting first
<del> return (me._cache.data = _arrayUnique(timestamps.sort(sorter)));
<add> return (me._cache.data = me.normalize(timestamps));
<ide> }
<ide>
<ide> /**
<ide> export default class TimeScale extends Scale {
<ide> timestamps.push(parse(me, labels[i]));
<ide> }
<ide>
<del> // We could assume labels are in order and unique - but let's not
<del> return (me._cache.labels = _arrayUnique(timestamps.sort(sorter)));
<add> return (me._cache.labels = me._normalized ? timestamps : me.normalize(timestamps));
<add> }
<add>
<add> /**
<add> * @param {number[]} values
<add> * @protected
<add> */
<add> normalize(values) {
<add> // It seems to be somewhat faster to do sorting first
<add> return _arrayUnique(values.sort(sorter));
<ide> }
<ide> }
<ide>
<ide><path>src/scales/scale.timeseries.js
<ide> import TimeScale from './scale.time';
<del>import {_arrayUnique, _lookupByKey} from '../helpers/helpers.collection';
<add>import {_lookup} from '../helpers/helpers.collection';
<add>import {isNullOrUndef} from '../helpers/helpers.core';
<ide>
<ide> /**
<del> * Linearly interpolates the given source `value` using the table items `skey` values and
<del> * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos')
<del> * returns the position for a timestamp equal to 42. If value is out of bounds, values at
<del> * index [0, 1] or [n - 1, n] are used for the interpolation.
<add> * Linearly interpolates the given source `val` using the table. If value is out of bounds, values
<add> * at index [0, 1] or [n - 1, n] are used for the interpolation.
<ide> * @param {object} table
<del> * @param {string} skey
<del> * @param {number} sval
<del> * @param {string} tkey
<add> * @param {number} val
<add> * @param {boolean} [reverse] lookup time based on position instead of vice versa
<ide> * @return {object}
<ide> */
<del>function interpolate(table, skey, sval, tkey) {
<del> const {lo, hi} = _lookupByKey(table, skey, sval);
<add>function interpolate(table, val, reverse) {
<add> let prevSource, nextSource, prevTarget, nextTarget;
<ide>
<ide> // Note: the lookup table ALWAYS contains at least 2 items (min and max)
<del> const prev = table[lo];
<del> const next = table[hi];
<del>
<del> const span = next[skey] - prev[skey];
<del> const ratio = span ? (sval - prev[skey]) / span : 0;
<del> const offset = (next[tkey] - prev[tkey]) * ratio;
<add> if (reverse) {
<add> prevSource = Math.floor(val);
<add> nextSource = Math.ceil(val);
<add> prevTarget = table[prevSource];
<add> nextTarget = table[nextSource];
<add> } else {
<add> const result = _lookup(table, val);
<add> prevTarget = result.lo;
<add> nextTarget = result.hi;
<add> prevSource = table[prevTarget];
<add> nextSource = table[nextTarget];
<add> }
<ide>
<del> return prev[tkey] + offset;
<del>}
<del>
<del>/**
<del> * @param {number} a
<del> * @param {number} b
<del> */
<del>function sorter(a, b) {
<del> return a - b;
<add> const span = nextSource - prevSource;
<add> return span ? prevTarget + (nextTarget - prevTarget) * (val - prevSource) / span : prevTarget;
<ide> }
<ide>
<ide> class TimeSeriesScale extends TimeScale {
<ide> class TimeSeriesScale extends TimeScale {
<ide>
<ide> /** @type {object[]} */
<ide> this._table = [];
<add> /** @type {number} */
<add> this._maxIndex = undefined;
<ide> }
<ide>
<ide> /**
<ide> class TimeSeriesScale extends TimeScale {
<ide> const me = this;
<ide> const timestamps = me._getTimestampsForTable();
<ide> me._table = me.buildLookupTable(timestamps);
<add> me._maxIndex = me._table.length - 1;
<ide> super.initOffsets(timestamps);
<ide> }
<ide>
<ide> class TimeSeriesScale extends TimeScale {
<ide> ];
<ide> }
<ide>
<del> const table = [];
<ide> const items = [min];
<del> let i, ilen, prev, curr, next;
<add> let i, ilen, curr;
<ide>
<ide> for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
<ide> curr = timestamps[i];
<ide> class TimeSeriesScale extends TimeScale {
<ide>
<ide> items.push(max);
<ide>
<del> for (i = 0, ilen = items.length; i < ilen; ++i) {
<del> next = items[i + 1];
<del> prev = items[i - 1];
<del> curr = items[i];
<del>
<del> // only add points that breaks the scale linearity
<del> if (prev === undefined || next === undefined || Math.round((next + prev) / 2) !== curr) {
<del> table.push({time: curr, pos: i / (ilen - 1)});
<del> }
<del> }
<del>
<del> return table;
<add> return items;
<ide> }
<ide>
<ide> /**
<ide> class TimeSeriesScale extends TimeScale {
<ide> if (data.length && label.length) {
<ide> // If combining labels and data (data might not contain all labels),
<ide> // we need to recheck uniqueness and sort
<del> timestamps = _arrayUnique(data.concat(label).sort(sorter));
<add> timestamps = me.normalize(data.concat(label));
<ide> } else {
<ide> timestamps = data.length ? data : label;
<ide> }
<ide> class TimeSeriesScale extends TimeScale {
<ide>
<ide> /**
<ide> * @param {number} value - Milliseconds since epoch (1 January 1970 00:00:00 UTC)
<add> * @param {number} [index]
<ide> * @return {number}
<ide> */
<del> getDecimalForValue(value) {
<del> return interpolate(this._table, 'time', value, 'pos');
<del> }
<del>
<del> /**
<del> * @return {number[]}
<del> * @protected
<del> */
<del> getDataTimestamps() {
<add> getPixelForValue(value, index) {
<ide> const me = this;
<del> const timestamps = me._cache.data || [];
<del>
<del> if (timestamps.length) {
<del> return timestamps;
<del> }
<del>
<del> const metas = me.getMatchingVisibleMetas();
<del> return (me._cache.data = metas.length ? metas[0].controller.getAllParsedValues(me) : []);
<add> const offsets = me._offsets;
<add> const pos = me._normalized && me._maxIndex > 0 && !isNullOrUndef(index)
<add> ? index / me._maxIndex : me.getDecimalForValue(value);
<add> return me.getPixelForDecimal((offsets.start + pos) * offsets.factor);
<ide> }
<ide>
<ide> /**
<del> * @return {number[]}
<del> * @protected
<add> * @param {number} value - Milliseconds since epoch (1 January 1970 00:00:00 UTC)
<add> * @return {number}
<ide> */
<del> getLabelTimestamps() {
<del> const me = this;
<del> const timestamps = me._cache.labels || [];
<del> let i, ilen;
<del>
<del> if (timestamps.length) {
<del> return timestamps;
<del> }
<del>
<del> const labels = me.getLabels();
<del> for (i = 0, ilen = labels.length; i < ilen; ++i) {
<del> timestamps.push(me.parse(labels[i]));
<del> }
<del>
<del> // We could assume labels are in order and unique - but let's not
<del> return (me._cache.labels = timestamps);
<add> getDecimalForValue(value) {
<add> return interpolate(this._table, value) / this._maxIndex;
<ide> }
<ide>
<ide> /**
<ide> class TimeSeriesScale extends TimeScale {
<ide> getValueForPixel(pixel) {
<ide> const me = this;
<ide> const offsets = me._offsets;
<del> const pos = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
<del> return interpolate(me._table, 'pos', pos, 'time');
<add> const decimal = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
<add> return interpolate(me._table, decimal * this._maxIndex, true);
<ide> }
<ide> }
<ide>
<ide><path>test/specs/scale.time.tests.js
<ide> describe('Time scale tests', function() {
<ide> });
<ide> });
<ide>
<del> describe('when scale type', function() {
<del> describe('is "timeseries"', function() {
<del> beforeEach(function() {
<del> this.chart = window.acquireChart({
<del> type: 'line',
<del> data: {
<del> labels: ['2017', '2019', '2020', '2025', '2042'],
<del> datasets: [{data: [0, 1, 2, 3, 4, 5]}]
<del> },
<del> options: {
<del> scales: {
<del> x: {
<del> type: 'timeseries',
<del> time: {
<del> parser: 'YYYY'
<add> [true, false].forEach(function(normalized) {
<add> describe('when normalized is ' + normalized + ' and scale type', function() {
<add> describe('is "timeseries"', function() {
<add> beforeEach(function() {
<add> this.chart = window.acquireChart({
<add> type: 'line',
<add> data: {
<add> labels: ['2017', '2019', '2020', '2025', '2042'],
<add> datasets: [{data: [0, 1, 2, 3, 4]}]
<add> },
<add> options: {
<add> normalized,
<add> scales: {
<add> x: {
<add> type: 'timeseries',
<add> time: {
<add> parser: 'YYYY'
<add> },
<add> ticks: {
<add> source: 'labels'
<add> }
<ide> },
<del> ticks: {
<del> source: 'labels'
<add> y: {
<add> display: false
<ide> }
<del> },
<del> y: {
<del> display: false
<ide> }
<ide> }
<del> }
<add> });
<ide> });
<del> });
<ide>
<del> it ('should space data out with the same gap, whatever their time values', function() {
<del> var scale = this.chart.scales.x;
<del> var start = scale.left;
<del> var slice = scale.width / 4;
<del>
<del> expect(scale.getPixelForValue(moment('2017').valueOf())).toBeCloseToPixel(start);
<del> expect(scale.getPixelForValue(moment('2019').valueOf())).toBeCloseToPixel(start + slice);
<del> expect(scale.getPixelForValue(moment('2020').valueOf())).toBeCloseToPixel(start + slice * 2);
<del> expect(scale.getPixelForValue(moment('2025').valueOf())).toBeCloseToPixel(start + slice * 3);
<del> expect(scale.getPixelForValue(moment('2042').valueOf())).toBeCloseToPixel(start + slice * 4);
<del> });
<del> it ('should add a step before if scale.min is before the first data', function() {
<del> var chart = this.chart;
<del> var scale = chart.scales.x;
<del> var options = chart.options.scales.x;
<add> it ('should space data out with the same gap, whatever their time values', function() {
<add> var scale = this.chart.scales.x;
<add> var start = scale.left;
<add> var slice = scale.width / 4;
<add>
<add> expect(scale.getPixelForValue(moment('2017').valueOf(), 0)).toBeCloseToPixel(start);
<add> expect(scale.getPixelForValue(moment('2019').valueOf(), 1)).toBeCloseToPixel(start + slice);
<add> expect(scale.getPixelForValue(moment('2020').valueOf(), 2)).toBeCloseToPixel(start + slice * 2);
<add> expect(scale.getPixelForValue(moment('2025').valueOf(), 3)).toBeCloseToPixel(start + slice * 3);
<add> expect(scale.getPixelForValue(moment('2042').valueOf(), 4)).toBeCloseToPixel(start + slice * 4);
<add> });
<add> it ('should add a step before if scale.min is before the first data', function() {
<add> var chart = this.chart;
<add> var scale = chart.scales.x;
<add> var options = chart.options.scales.x;
<ide>
<del> options.min = '2012';
<del> chart.update();
<add> options.min = '2012';
<add> chart.update();
<ide>
<del> var start = scale.left;
<del> var slice = scale.width / 5;
<add> var start = scale.left;
<add> var slice = scale.width / 5;
<ide>
<del> expect(scale.getPixelForValue(moment('2017').valueOf())).toBeCloseToPixel(start + slice);
<del> expect(scale.getPixelForValue(moment('2042').valueOf())).toBeCloseToPixel(start + slice * 5);
<del> });
<del> it ('should add a step after if scale.max is after the last data', function() {
<del> var chart = this.chart;
<del> var scale = chart.scales.x;
<del> var options = chart.options.scales.x;
<add> expect(scale.getPixelForValue(moment('2017').valueOf(), 1)).toBeCloseToPixel(start + slice);
<add> expect(scale.getPixelForValue(moment('2042').valueOf(), 5)).toBeCloseToPixel(start + slice * 5);
<add> });
<add> it ('should add a step after if scale.max is after the last data', function() {
<add> var chart = this.chart;
<add> var scale = chart.scales.x;
<add> var options = chart.options.scales.x;
<ide>
<del> options.max = '2050';
<del> chart.update();
<add> options.max = '2050';
<add> chart.update();
<ide>
<del> var start = scale.left;
<del> var slice = scale.width / 5;
<add> var start = scale.left;
<add> var slice = scale.width / 5;
<ide>
<del> expect(scale.getPixelForValue(moment('2017').valueOf())).toBeCloseToPixel(start);
<del> expect(scale.getPixelForValue(moment('2042').valueOf())).toBeCloseToPixel(start + slice * 4);
<del> });
<del> it ('should add steps before and after if scale.min/max are outside the data range', function() {
<del> var chart = this.chart;
<del> var scale = chart.scales.x;
<del> var options = chart.options.scales.x;
<add> expect(scale.getPixelForValue(moment('2017').valueOf(), 0)).toBeCloseToPixel(start);
<add> expect(scale.getPixelForValue(moment('2042').valueOf(), 4)).toBeCloseToPixel(start + slice * 4);
<add> });
<add> it ('should add steps before and after if scale.min/max are outside the data range', function() {
<add> var chart = this.chart;
<add> var scale = chart.scales.x;
<add> var options = chart.options.scales.x;
<ide>
<del> options.min = '2012';
<del> options.max = '2050';
<del> chart.update();
<add> options.min = '2012';
<add> options.max = '2050';
<add> chart.update();
<ide>
<del> var start = scale.left;
<del> var slice = scale.width / 6;
<add> var start = scale.left;
<add> var slice = scale.width / 6;
<ide>
<del> expect(scale.getPixelForValue(moment('2017').valueOf())).toBeCloseToPixel(start + slice);
<del> expect(scale.getPixelForValue(moment('2042').valueOf())).toBeCloseToPixel(start + slice * 5);
<add> expect(scale.getPixelForValue(moment('2017').valueOf(), 1)).toBeCloseToPixel(start + slice);
<add> expect(scale.getPixelForValue(moment('2042').valueOf(), 5)).toBeCloseToPixel(start + slice * 5);
<add> });
<ide> });
<del> });
<del> describe('is "time"', function() {
<del> beforeEach(function() {
<del> this.chart = window.acquireChart({
<del> type: 'line',
<del> data: {
<del> labels: ['2017', '2019', '2020', '2025', '2042'],
<del> datasets: [{data: [0, 1, 2, 3, 4, 5]}]
<del> },
<del> options: {
<del> scales: {
<del> x: {
<del> type: 'time',
<del> time: {
<del> parser: 'YYYY'
<add> describe('is "time"', function() {
<add> beforeEach(function() {
<add> this.chart = window.acquireChart({
<add> type: 'line',
<add> data: {
<add> labels: ['2017', '2019', '2020', '2025', '2042'],
<add> datasets: [{data: [0, 1, 2, 3, 4, 5]}]
<add> },
<add> options: {
<add> scales: {
<add> x: {
<add> type: 'time',
<add> time: {
<add> parser: 'YYYY'
<add> },
<add> ticks: {
<add> source: 'labels'
<add> }
<ide> },
<del> ticks: {
<del> source: 'labels'
<add> y: {
<add> display: false
<ide> }
<del> },
<del> y: {
<del> display: false
<ide> }
<ide> }
<del> }
<add> });
<ide> });
<del> });
<ide>
<del> it ('should space data out with a gap relative to their time values', function() {
<del> var scale = this.chart.scales.x;
<del> var start = scale.left;
<del> var slice = scale.width / (2042 - 2017);
<del>
<del> expect(scale.getPixelForValue(moment('2017').valueOf())).toBeCloseToPixel(start);
<del> expect(scale.getPixelForValue(moment('2019').valueOf())).toBeCloseToPixel(start + slice * (2019 - 2017));
<del> expect(scale.getPixelForValue(moment('2020').valueOf())).toBeCloseToPixel(start + slice * (2020 - 2017));
<del> expect(scale.getPixelForValue(moment('2025').valueOf())).toBeCloseToPixel(start + slice * (2025 - 2017));
<del> expect(scale.getPixelForValue(moment('2042').valueOf())).toBeCloseToPixel(start + slice * (2042 - 2017));
<del> });
<del> it ('should take in account scale min and max if outside the ticks range', function() {
<del> var chart = this.chart;
<del> var scale = chart.scales.x;
<del> var options = chart.options.scales.x;
<add> it ('should space data out with a gap relative to their time values', function() {
<add> var scale = this.chart.scales.x;
<add> var start = scale.left;
<add> var slice = scale.width / (2042 - 2017);
<add>
<add> expect(scale.getPixelForValue(moment('2017').valueOf(), 0)).toBeCloseToPixel(start);
<add> expect(scale.getPixelForValue(moment('2019').valueOf(), 1)).toBeCloseToPixel(start + slice * (2019 - 2017));
<add> expect(scale.getPixelForValue(moment('2020').valueOf(), 2)).toBeCloseToPixel(start + slice * (2020 - 2017));
<add> expect(scale.getPixelForValue(moment('2025').valueOf(), 3)).toBeCloseToPixel(start + slice * (2025 - 2017));
<add> expect(scale.getPixelForValue(moment('2042').valueOf(), 4)).toBeCloseToPixel(start + slice * (2042 - 2017));
<add> });
<add> it ('should take in account scale min and max if outside the ticks range', function() {
<add> var chart = this.chart;
<add> var scale = chart.scales.x;
<add> var options = chart.options.scales.x;
<ide>
<del> options.min = '2012';
<del> options.max = '2050';
<del> chart.update();
<add> options.min = '2012';
<add> options.max = '2050';
<add> chart.update();
<ide>
<del> var start = scale.left;
<del> var slice = scale.width / (2050 - 2012);
<add> var start = scale.left;
<add> var slice = scale.width / (2050 - 2012);
<ide>
<del> expect(scale.getPixelForValue(moment('2017').valueOf())).toBeCloseToPixel(start + slice * (2017 - 2012));
<del> expect(scale.getPixelForValue(moment('2019').valueOf())).toBeCloseToPixel(start + slice * (2019 - 2012));
<del> expect(scale.getPixelForValue(moment('2020').valueOf())).toBeCloseToPixel(start + slice * (2020 - 2012));
<del> expect(scale.getPixelForValue(moment('2025').valueOf())).toBeCloseToPixel(start + slice * (2025 - 2012));
<del> expect(scale.getPixelForValue(moment('2042').valueOf())).toBeCloseToPixel(start + slice * (2042 - 2012));
<add> expect(scale.getPixelForValue(moment('2017').valueOf(), 0)).toBeCloseToPixel(start + slice * (2017 - 2012));
<add> expect(scale.getPixelForValue(moment('2019').valueOf(), 1)).toBeCloseToPixel(start + slice * (2019 - 2012));
<add> expect(scale.getPixelForValue(moment('2020').valueOf(), 2)).toBeCloseToPixel(start + slice * (2020 - 2012));
<add> expect(scale.getPixelForValue(moment('2025').valueOf(), 3)).toBeCloseToPixel(start + slice * (2025 - 2012));
<add> expect(scale.getPixelForValue(moment('2042').valueOf(), 4)).toBeCloseToPixel(start + slice * (2042 - 2012));
<add> });
<ide> });
<ide> });
<ide> }); | 9 |
Javascript | Javascript | add os module to repl's built-in lib list | 6d75c06e6425f67ec5d4e44b3c440c02ddf0d1d8 | <ide><path>lib/repl.js
<ide> REPLServer.prototype.complete = function(line) {
<ide> // Kind of lame that this needs to be updated manually.
<ide> // Intentionally excluding moved modules: posix, utils.
<ide> var builtinLibs = ['assert', 'buffer', 'child_process', 'crypto', 'dgram',
<del> 'dns', 'events', 'file', 'freelist', 'fs', 'http', 'net', 'path',
<add> 'dns', 'events', 'file', 'freelist', 'fs', 'http', 'net', 'os', 'path',
<ide> 'querystring', 'readline', 'repl', 'string_decoder', 'util', 'tcp',
<ide> 'url'];
<ide> completionGroups.push(builtinLibs); | 1 |
Mixed | Ruby | provide friendlier access to request variants | 9d9cc4777be3787ed3645d704f02e5ba1228be13 | <ide><path>actionpack/CHANGELOG.md
<add>* Provide friendlier access to request variants.
<add>
<add> request.variant = :phone
<add> request.variant.phone? # true
<add> request.variant.tablet? # false
<add>
<add> request.variant = [:phone, :tablet]
<add> request.variant.phone? # true
<add> request.variant.desktop? # false
<add> request.variant.any?(:phone, :desktop) # true
<add> request.variant.any?(:desktop, :watch) # false
<add>
<add> *George Claghorn*
<add>
<ide> * Fix handling of empty X_FORWARDED_HOST header in raw_host_with_port
<ide>
<del> Previously, an empty X_FORWARDED_HOST header would cause
<del> Actiondispatch::Http:URL.raw_host_with_port to return nil, causing
<del> Actiondispatch::Http:URL.host to raise a NoMethodError.
<add> Previously, an empty X_FORWARDED_HOST header would cause
<add> Actiondispatch::Http:URL.raw_host_with_port to return nil, causing
<add> Actiondispatch::Http:URL.host to raise a NoMethodError.
<ide>
<del> *Adam Forsyth*
<add> *Adam Forsyth*
<ide>
<ide> * Drop request class from RouteSet constructor.
<del>
<add>
<ide> If you would like to use a custom request class, please subclass and implement
<ide> the `request_class` method.
<ide>
<ide><path>actionpack/lib/action_controller/metal/mime_responds.rb
<ide> def method_missing(name, *args, &block)
<ide> end
<ide>
<ide> def variant
<del> if @variant.nil?
<add> if @variant.empty?
<ide> @variants[:none] || @variants[:any]
<del> elsif (@variants.keys & @variant).any?
<del> @variant.each do |v|
<del> return @variants[v] if @variants.key?(v)
<del> end
<ide> else
<del> @variants[:any]
<add> @variants[variant_key]
<ide> end
<ide> end
<add>
<add> private
<add> def variant_key
<add> @variant.find { |variant| @variants.key?(variant) } || :any
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>actionpack/lib/action_dispatch/http/mime_negotiation.rb
<ide> module MimeNegotiation
<ide> self.ignore_accept_header = false
<ide> end
<ide>
<del> attr_reader :variant
<del>
<ide> # The MIME type of the HTTP request, such as Mime::XML.
<ide> #
<ide> # For backward compatibility, the post \format is extracted from the
<ide> def formats
<ide>
<ide> # Sets the \variant for template.
<ide> def variant=(variant)
<del> if variant.is_a?(Symbol)
<del> @variant = [variant]
<del> elsif variant.nil? || variant.is_a?(Array) && variant.any? && variant.all?{ |v| v.is_a?(Symbol) }
<del> @variant = variant
<add> variant = Array(variant)
<add>
<add> if variant.all? { |v| v.is_a?(Symbol) }
<add> @variant = VariantInquirer.new(variant)
<ide> else
<del> raise ArgumentError, "request.variant must be set to a Symbol or an Array of Symbols, not a #{variant.class}. " \
<add> raise ArgumentError, "request.variant must be set to a Symbol or an Array of Symbols. " \
<ide> "For security reasons, never directly set the variant to a user-provided value, " \
<ide> "like params[:variant].to_sym. Check user-provided value against a whitelist first, " \
<ide> "then set the variant: request.variant = :tablet if params[:variant] == 'tablet'"
<ide> end
<ide> end
<ide>
<add> def variant
<add> @variant ||= VariantInquirer.new
<add> end
<add>
<ide> # Sets the \format by string extension, which can be used to force custom formats
<ide> # that are not controlled by the extension.
<ide> #
<ide> def negotiate_mime(order)
<ide> order.include?(Mime::ALL) ? format : nil
<ide> end
<ide>
<add> class VariantInquirer # :nodoc:
<add> delegate :each, :empty?, to: :@variants
<add>
<add> def initialize(variants = [])
<add> @variants = variants
<add> end
<add>
<add> def any?(*candidates)
<add> (@variants & candidates).any?
<add> end
<add>
<add> def to_ary
<add> @variants
<add> end
<add>
<add> private
<add> def method_missing(name, *args)
<add> if name[-1] == '?'
<add> any? name[0..-2].to_sym
<add> else
<add> super
<add> end
<add> end
<add> end
<add>
<ide> protected
<ide>
<ide> BROWSER_LIKE_ACCEPTS = /,\s*\*\/\*|\*\/\*\s*,/
<ide><path>actionpack/test/dispatch/request_test.rb
<ide> class RequestEtag < BaseRequestTest
<ide> end
<ide>
<ide> class RequestVariant < BaseRequestTest
<del> test "setting variant" do
<del> request = stub_request
<add> setup do
<add> @request = stub_request
<add> end
<ide>
<del> request.variant = :mobile
<del> assert_equal [:mobile], request.variant
<add> test 'setting variant to a symbol' do
<add> @request.variant = :phone
<ide>
<del> request.variant = [:phone, :tablet]
<del> assert_equal [:phone, :tablet], request.variant
<add> assert @request.variant.phone?
<add> assert_not @request.variant.tablet?
<add> assert @request.variant.any?(:phone, :tablet)
<add> assert_not @request.variant.any?(:tablet, :desktop)
<add> end
<ide>
<del> assert_raise ArgumentError do
<del> request.variant = [:phone, "tablet"]
<del> end
<add> test 'setting variant to an array of symbols' do
<add> @request.variant = [:phone, :tablet]
<ide>
<del> assert_raise ArgumentError do
<del> request.variant = "yolo"
<del> end
<add> assert @request.variant.phone?
<add> assert @request.variant.tablet?
<add> assert_not @request.variant.desktop?
<add> assert @request.variant.any?(:tablet, :desktop)
<add> assert_not @request.variant.any?(:desktop, :watch)
<ide> end
<ide>
<del> test "reset variant" do
<del> request = stub_request
<add> test 'clearing variant' do
<add> @request.variant = nil
<ide>
<del> request.variant = nil
<del> assert_equal nil, request.variant
<add> assert @request.variant.empty?
<add> assert_not @request.variant.phone?
<add> assert_not @request.variant.any?(:phone, :tablet)
<ide> end
<ide>
<del> test "setting variant with non symbol value" do
<del> request = stub_request
<add> test 'setting variant to a non-symbol value' do
<add> assert_raise ArgumentError do
<add> @request.variant = 'phone'
<add> end
<add> end
<add>
<add> test 'setting variant to an array containing a non-symbol value' do
<ide> assert_raise ArgumentError do
<del> request.variant = "mobile"
<add> @request.variant = [:phone, 'tablet']
<ide> end
<ide> end
<ide> end | 4 |
PHP | PHP | implement incomplete tests for i18n\date | cf1a848ad2590aac13e5bc4ac9350c10c34b2bbc | <ide><path>tests/TestCase/I18n/DateTest.php
<ide>
<ide> use Cake\I18n\Date;
<ide> use Cake\TestSuite\TestCase;
<add>use DateTimeZone;
<ide>
<ide> /**
<ide> * DateTest class
<ide> public function testI18nFormat()
<ide> $this->assertEquals($expected, $result, 'Default locale should not be used');
<ide> }
<ide>
<add> /**
<add> * test __toString
<add> *
<add> * @return void
<add> */
<ide> public function testToString()
<ide> {
<del> $this->markTestIncomplete();
<add> $date = new Date('2015-11-06 11:32:45');
<add> $this->assertEquals('11/6/15', (string)$date);
<add> }
<add>
<add> /**
<add> * test nice()
<add> *
<add> * @return void
<add> */
<add> public function testNice()
<add> {
<add> $date = new Date('2015-11-06 11:32:45');
<add>
<add> $this->assertEquals('Nov 6, 2015', $date->nice());
<add> $this->assertEquals('Nov 6, 2015', $date->nice(new DateTimeZone('America/New_York')));
<add> $this->assertEquals('6 nov. 2015', $date->nice(null, 'fr-FR'));
<ide> }
<ide>
<add> /**
<add> * test jsonSerialize()
<add> *
<add> * @return void
<add> */
<ide> public function testJsonSerialize()
<ide> {
<del> $this->markTestIncomplete();
<add> $date = new Date('2015-11-06 11:32:45');
<add> $this->assertEquals('"2015-11-06T00:00:00+0000"', json_encode($date));
<ide> }
<ide>
<add> /**
<add> * test parseDate()
<add> *
<add> * @return void
<add> */
<ide> public function testParseDate()
<ide> {
<del> $this->markTestIncomplete();
<add> $date = Date::parseDate('11/6/15');
<add> $this->assertEquals('2015-11-06 00:00:00', $date->format('Y-m-d H:i:s'));
<add>
<add> Date::$defaultLocale = 'fr-FR';
<add> $date = Date::parseDate('13 10, 2015');
<add> $this->assertEquals('2015-10-13 00:00:00', $date->format('Y-m-d H:i:s'));
<ide> }
<ide>
<add> /**
<add> * test parseDateTime()
<add> *
<add> * @return void
<add> */
<ide> public function testParseDateTime()
<ide> {
<del> $this->markTestIncomplete();
<add> $date = Date::parseDate('11/6/15 12:33:12');
<add> $this->assertEquals('2015-11-06 00:00:00', $date->format('Y-m-d H:i:s'));
<add>
<add> Date::$defaultLocale = 'fr-FR';
<add> $date = Date::parseDate('13 10, 2015 12:54:12');
<add> $this->assertEquals('2015-10-13 00:00:00', $date->format('Y-m-d H:i:s'));
<ide> }
<ide> } | 1 |
PHP | PHP | remove old test | 4c0db5dd3f76e740c0635260b8f2d446988a33b5 | <ide><path>tests/Support/SupportFacadeResponseTest.php
<del><?php
<del>
<del>use Mockery as m;
<del>use Illuminate\Support\Facades\Response;
<del>
<del>class SupportFacadeResponseTest extends PHPUnit_Framework_TestCase {
<del>
<del> public function tearDown()
<del> {
<del> m::close();
<del> }
<del>
<del>
<del> public function testArrayableSendAsJson()
<del> {
<del> $data = m::mock('Illuminate\Contracts\Support\Arrayable');
<del> $data->shouldReceive('toArray')->andReturn(array('foo' => 'bar'));
<del>
<del> $response = Response::json($data);
<del> $this->assertEquals('{"foo":"bar"}', $response->getContent());
<del> }
<del>
<del>} | 1 |
Python | Python | restore un-needed axis arguments | ce7a968a7b5cdb328ca1ea222211ad9cd8e506ad | <ide><path>numpy/lib/arraysetops.py
<ide> def unique1d( ar1, retindx = False ):
<ide> if retindx:
<ide> ar = numpy.array(ar1).ravel()
<ide> perm = ar.argsort()
<del> aux = ar.take(perm,0)
<add> aux = ar.take(perm)
<ide> flag = ediff1d( aux, 1 ) != 0
<ide> return perm.compress(flag), aux.compress(flag)
<ide> else:
<ide> def setmember1d( ar1, ar2 ):
<ide> tt = concat( (zlike( ar1 ),
<ide> zlike( ar2 ) + 1) )
<ide> perm = ar.argsort()
<del> aux = ar.take(perm,0)
<del> aux2 = tt.take(perm,0)
<add> aux = ar.take(perm)
<add> aux2 = tt.take(perm)
<ide> flag = ediff1d( aux, 1 ) == 0
<ide>
<ide> ii = numpy.where( flag * aux2 )[0]
<ide> def setmember1d( ar1, ar2 ):
<ide>
<ide> indx = perm.argsort()[:len( ar1 )]
<ide>
<del> return flag.take( indx , 0)
<add> return flag.take( indx )
<ide>
<ide> ##
<ide> # 03.11.2005, c
<ide><path>numpy/lib/shape_base.py
<ide> def apply_along_axis(func1d,axis,arr,*args):
<ide> indlist = range(nd)
<ide> indlist.remove(axis)
<ide> i[axis] = slice(None,None)
<del> outshape = asarray(arr.shape).take(indlist,0)
<add> outshape = asarray(arr.shape).take(indlist)
<ide> i.put(ind, indlist)
<ide> res = func1d(arr[tuple(i.tolist())],*args)
<ide> # if res is a number, then we have a smaller output array | 2 |
Text | Text | add new style | a1d3f1fbe00aab959fd1751172e9f52355b4ada7 | <ide><path>guide/english/bootstrap/modals/index.md
<ide> h) `.modal-title` class styles the header of the modal with a proper height.
<ide> i) `.modal-body` class styles the body of the modal(dialog/popup).It can have other markups like `<p>,<img>,<video>` etc.
<ide>
<ide> j) `.modal-footer` class styles the footer of the modal.
<add>
<add>k) `.modal-dialog-centered` class styles to vertically center the modal.
<ide>
<ide>
<ide> #### More Information : | 1 |
Javascript | Javascript | fix performance regression | 558a884d4132a2e5088833de6e096e32e78d5f2b | <ide><path>lib/buffer.js
<ide> const { isArrayBuffer, isSharedArrayBuffer } = process.binding('util');
<ide> const bindingObj = {};
<ide> const internalUtil = require('internal/util');
<ide>
<del>class FastBuffer extends Uint8Array {}
<add>class FastBuffer extends Uint8Array {
<add> constructor(arg1, arg2, arg3) {
<add> super(arg1, arg2, arg3);
<add> }
<add>}
<ide>
<ide> FastBuffer.prototype.constructor = Buffer;
<ide> Buffer.prototype = FastBuffer.prototype; | 1 |
Javascript | Javascript | remove memory leak from test suite | 92ffd07d06b10d77a500c0cbe9b398de4b0bb902 | <ide><path>test/cases/context/issue-10969/index.js
<del>expect.extend({
<del> toBeValidModuleId(received, moduleIdString) {
<del> const pass = typeof received === "number" || received === moduleIdString;
<del> if (pass) {
<del> return {
<del> message: () => `expected ${received} not to be a valid module id`,
<del> pass: true
<del> };
<del> } else {
<del> return {
<del> message: () => `expected ${received} to be a valid module id`,
<del> pass: false
<del> };
<del> }
<del> }
<del>});
<del>
<ide> it("should replace ! with %21 in the module id string of the context module", function () {
<del> const moduleId = require.context("./folder", true, /^(?!file1\.js$).*$/i, "lazy").id;
<del> expect(moduleId).toBeValidModuleId("./context/issue-10969/folder lazy recursive ^(?%21file1\\.js$).*$/");
<add> const moduleId = require.context(
<add> "./folder",
<add> true,
<add> /^(?!file1\.js$).*$/i,
<add> "lazy"
<add> ).id;
<add> if (typeof moduleId !== "number")
<add> expect(moduleId).toBe(
<add> "./context/issue-10969/folder lazy recursive ^(?%21file1\\.js$).*$/"
<add> );
<ide> }); | 1 |
Text | Text | add missing function to test common doc | b5c8852ab5f44c0bc0e8ead6c3ad4c9fc25daee1 | <ide><path>test/README.md
<ide> Platform normalizes the `dd` command
<ide>
<ide> Check if there is more than 1gb of total memory.
<ide>
<add>### expectsError(code[, type[, message]])
<add>* `code` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add> expected error must have this value for its `code` property
<add>* `type` [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
<add> expected error must be an instance of `type`
<add>* `message` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add> or [<RegExp>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)
<add> if a string is provided for `message`, expected error must have it for its
<add> `message` property; if a regular expression is provided for `message`, the
<add> regular expression must match the `message` property of the expected error
<add>
<add>* return function suitable for use as a validation function passed as the second
<add> argument to `assert.throws()`
<add>
<add>The expected error should be [subclassed by the `internal/errors` module](https://github.com/nodejs/node/blob/master/doc/guides/using-internal-errors.md#api).
<add>
<ide> ### expectWarning(name, expected)
<ide> * `name` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<ide> * `expected` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [<Array>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) | 1 |
Javascript | Javascript | add tests for fadein & fadeout | afe2eec9376ec28685cbafec4685917d6c74f359 | <ide><path>test/unit/src/animation/AnimationAction.tests.js
<ide> export default QUnit.module( 'Animation', () => {
<ide>
<ide> } );
<ide>
<del> QUnit.todo( "fadeIn", ( assert ) => {
<add> QUnit.test( "fadeIn", ( assert ) => {
<ide>
<del> assert.ok( false, "everything's gonna be alright" );
<add> var {mixer, animationAction} = createAnimation();
<add> animationAction.fadeIn(1000);
<add> animationAction.play();
<add> assert.equal( animationAction.getEffectiveWeight(), 1 , "When an animation fadeIn is started, EffectiveWeight is 1." );
<add> mixer.update(250);
<add> assert.equal( animationAction.getEffectiveWeight(), 0.25, "When an animation fadeIn happened 1/4, EffectiveWeight is 0.25." );
<add> mixer.update(250);
<add> assert.equal( animationAction.getEffectiveWeight(), 0.5, "When an animation fadeIn is halfway , EffectiveWeight is 0.5." );
<add> mixer.update(250);
<add> assert.equal( animationAction.getEffectiveWeight(), 0.75, "When an animation fadeIn is halfway , EffectiveWeight is 0.75." );
<add> mixer.update(500);
<add> assert.equal( animationAction.getEffectiveWeight(), 1, "When an animation fadeIn is ended , EffectiveWeight is 1." );
<ide>
<ide> } );
<ide>
<del> QUnit.todo( "fadeOut", ( assert ) => {
<add> QUnit.test( "fadeOut", ( assert ) => {
<ide>
<del> assert.ok( false, "everything's gonna be alright" );
<add> var {mixer, animationAction} = createAnimation();
<add> animationAction.fadeOut(1000);
<add> animationAction.play();
<add> assert.equal( animationAction.getEffectiveWeight(), 1 , "When an animation fadeOut is started, EffectiveWeight is 1." );
<add> mixer.update(250);
<add> assert.equal( animationAction.getEffectiveWeight(), 0.75, "When an animation fadeOut happened 1/4, EffectiveWeight is 0.75." );
<add> mixer.update(250);
<add> assert.equal( animationAction.getEffectiveWeight(), 0.5, "When an animation fadeOut is halfway , EffectiveWeight is 0.5." );
<add> mixer.update(250);
<add> assert.equal( animationAction.getEffectiveWeight(), 0.25, "When an animation fadeOut is happened 3/4 , EffectiveWeight is 0.25." );
<add> mixer.update(500);
<add> assert.equal( animationAction.getEffectiveWeight(), 0, "When an animation fadeOut is ended , EffectiveWeight is 0." );
<ide>
<ide> } );
<ide> | 1 |
Text | Text | remove duplicated text | 5271a69411e93a2b694c84f7f8216f0d91404e07 | <ide><path>docs/reference/run.md
<ide> The `host-src` can either be an absolute path or a `name` value. If you
<ide> supply an absolute path for the `host-dir`, Docker bind-mounts to the path
<ide> you specify. If you supply a `name`, Docker creates a named volume by that `name`.
<ide>
<del>A `name` value must start with start with an alphanumeric character,
<add>A `name` value must start with an alphanumeric character,
<ide> followed by `a-z0-9`, `_` (underscore), `.` (period) or `-` (hyphen).
<ide> An absolute path starts with a `/` (forward slash).
<ide> | 1 |
Javascript | Javascript | add emittereventpromise helper | 6b92bd041a0203a4380dff938daa1fda00cd87e3 | <ide><path>spec/async-spec-helpers.js
<ide> /** @babel */
<ide>
<add>import until from 'test-until'
<add>
<ide> export function beforeEach (fn) {
<ide> global.beforeEach(function () {
<ide> const result = fn()
<ide> function waitsForPromise (fn) {
<ide> })
<ide> })
<ide> }
<add>
<add>export function emitterEventPromise (emitter, event, timeout = 5000) {
<add> let called = false
<add> emitter.once(event, () => {
<add> called = true
<add> // disposable.dispose()
<add> })
<add> return until(`${event} is emitted`, () => called, timeout)
<add>} | 1 |
PHP | PHP | add support for placeholder in log messages | 304787dda0102b50de46da927f3c31cb116fd67b | <ide><path>src/Log/Engine/BaseLog.php
<ide> namespace Cake\Log\Engine;
<ide>
<ide> use Cake\Core\InstanceConfigTrait;
<add>use JsonSerializable;
<ide> use Psr\Log\AbstractLogger;
<ide>
<ide> /**
<ide> public function scopes()
<ide> */
<ide> protected function _format(string $message, array $context = []): string
<ide> {
<del> return $message;
<add> if (strpos($message, '{') === false && strpos($message, '}') === false) {
<add> return $message;
<add> }
<add>
<add> preg_match_all('/\{([a-z][a-z0-9-_]*)\}/i', $message, $matches);
<add> if (empty($matches)) {
<add> return $message;
<add> }
<add>
<add> $placeholders = array_intersect($matches[1], array_keys($context));
<add> $replacements = [];
<add>
<add> foreach ($placeholders as $key) {
<add> $value = $context[$key];
<add>
<add> if (is_scalar($value)) {
<add> $replacements['{' . $key . '}'] = (string)$value;
<add> continue;
<add> }
<add>
<add> if (is_object($value)) {
<add> if (method_exists($value, '__toString')) {
<add> $replacements['{' . $key . '}'] = (string)$value;
<add> continue;
<add> }
<add>
<add> if ($value instanceof JsonSerializable) {
<add> $replacements['{' . $key . '}'] = json_encode($value, JSON_UNESCAPED_UNICODE);
<add> continue;
<add> }
<add>
<add> if (method_exists($value, 'toArray')) {
<add> $replacements['{' . $key . '}'] = print_r($value->toArray(), true);
<add> continue;
<add> }
<add> }
<add>
<add> $replacements['{' . $key . '}'] = print_r($value, true);
<add> }
<add>
<add> return str_replace(array_keys($replacements), $replacements, $message);
<ide> }
<ide> }
<ide><path>tests/TestCase/Log/Engine/BaseLogTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Log\Engine;
<ide>
<add>use Cake\ORM\Entity;
<ide> use Cake\TestSuite\TestCase;
<ide> use Psr\Log\LogLevel;
<ide> use TestApp\Log\Engine\TestBaseLog;
<ide> class BaseLogTest extends TestCase
<ide> {
<ide> private $testData = ['ä', 'ö', 'ü'];
<ide>
<add> /**
<add> * @var \TestApp\Log\Engine\TestBaseLog
<add> */
<ide> private $logger;
<ide>
<ide> /**
<ide> private function assertUnescapedUnicode(array $needles, $haystack)
<ide> */
<ide> public function testLogUnicodeString()
<ide> {
<del> $logged = $this->logger->log(LogLevel::INFO, implode($this->testData));
<add> $this->logger->log(LogLevel::INFO, implode($this->testData));
<add>
<add> $this->assertUnescapedUnicode($this->testData, $this->logger->getMessage());
<add> }
<add>
<add> public function testPlaceHoldersInMessage()
<add> {
<add> $context = [
<add> 'no-placholder' => 'no-placholder',
<add> 'string' => 'a-string',
<add> 'bool' => true,
<add> 'json' => new Entity(['foo' => 'bar']),
<add> 'array' => ['arr'],
<add> 'obj' => function () {
<add> },
<add> ];
<add> $this->logger->log(
<add> LogLevel::INFO,
<add> '1: {string}, 2: {bool}, 3: {json}, 4: {not a placeholder}, 5: {array}, 6: {obj}, 8: {valid-ph-not-in-context}',
<add> $context
<add> );
<add>
<add> $message = $this->logger->getMessage();
<ide>
<del> $this->assertUnescapedUnicode($this->testData, $logged);
<add> $this->assertStringContainsString('1: a-string', $message);
<add> $this->assertStringContainsString('2: 1', $message);
<add> $this->assertStringContainsString("3: {\n \"foo\": \"bar\"\n}", $message);
<add> $this->assertStringContainsString('4: {not a placeholder}', $message);
<add> $this->assertStringContainsString("5: Array\n(\n [0] => arr\n)", $message);
<add> $this->assertStringContainsString("6: Closure Object", $message);
<add> $this->assertStringContainsString('8: {valid-ph-not-in-context}', $message);
<ide> }
<ide> }
<ide><path>tests/test_app/TestApp/Log/Engine/TestBaseLog.php
<ide> */
<ide> class TestBaseLog extends BaseLog
<ide> {
<add> /**
<add> * @var string
<add> */
<add> protected $message = '';
<add>
<ide> /**
<ide> * Logs with an arbitrary level.
<ide> *
<ide> * @param mixed $level
<ide> * @param string $message
<ide> * @param array $context
<ide> *
<del> * @return string
<add> * @return void
<ide> */
<ide> public function log($level, $message, array $context = [])
<ide> {
<del> return $this->_format($message, $context);
<add> $this->message = $this->_format($message, $context);
<add> }
<add>
<add> public function getMessage()
<add> {
<add> return $this->message;
<ide> }
<ide> } | 3 |
Go | Go | fix time setting for old kernels | 75e958bf48a83de5f3f80859aee96f3356d16d4b | <ide><path>image.go
<ide> func (image *Image) TarLayer(compression Compression) (Archive, error) {
<ide> type TimeUpdate struct {
<ide> path string
<ide> time []syscall.Timeval
<add> mode uint32
<ide> }
<ide>
<ide> func (image *Image) applyLayer(layer, target string) error {
<ide> func (image *Image) applyLayer(layer, target string) error {
<ide> u := TimeUpdate{
<ide> path: targetPath,
<ide> time: ts,
<add> mode: srcStat.Mode,
<ide> }
<ide>
<ide> // Delay time updates until all other changes done, or it is
<ide> func (image *Image) applyLayer(layer, target string) error {
<ide> update := updateTimes[i]
<ide>
<ide> O_PATH := 010000000 // Not in syscall yet
<del> fd, err := syscall.Open(update.path, syscall.O_RDWR|O_PATH|syscall.O_NOFOLLOW, 0600)
<del> if err == syscall.EISDIR || err == syscall.ELOOP {
<del> // O_PATH not supported, use Utimes except on symlinks where Utimes doesn't work
<del> if err != syscall.ELOOP {
<del> err = syscall.Utimes(update.path, update.time)
<del> if err != nil {
<del> return err
<del> }
<add> var err error = nil
<add> if update.mode&syscall.S_IFLNK == syscall.S_IFLNK {
<add> // Update time on the symlink via O_PATH + futimes(), if supported by the kernel
<add>
<add> fd, err := syscall.Open(update.path, syscall.O_RDWR|O_PATH|syscall.O_NOFOLLOW, 0600)
<add> if err == syscall.EISDIR || err == syscall.ELOOP {
<add> // O_PATH not supported by kernel, nothing to do, ignore
<add> } else if err != nil {
<add> return err
<add> } else {
<add> syscall.Futimes(fd, update.time)
<add> _ = syscall.Close(fd)
<ide> }
<ide> } else {
<add> err = syscall.Utimes(update.path, update.time)
<ide> if err != nil {
<ide> return err
<ide> }
<del> syscall.Futimes(fd, update.time)
<del> _ = syscall.Close(fd)
<ide> }
<ide> }
<ide> | 1 |
Text | Text | add azure gems to readme | 8aa742ff52b4d3374f9453b566774e921189c9f7 | <ide><path>activestorage/README.md
<ide> Variation of image attachment:
<ide> 1. Run `rails activestorage:install` to create needed directories, migrations, and configuration.
<ide> 2. Optional: Add `gem "aws-sdk", "~> 2"` to your Gemfile if you want to use AWS S3.
<ide> 3. Optional: Add `gem "google-cloud-storage", "~> 1.3"` to your Gemfile if you want to use Google Cloud Storage.
<del>4. Optional: Add `gem "mini_magick"` to your Gemfile if you want to use variants.
<add>4. Optional: Add `gem 'azure-core', git: "https://github.com/dixpac/azure-ruby-asm-core.git"` and `gem 'azure-storage', require: false` to your Gemfile if you want to use Microsoft Azure.
<add>5. Optional: Add `gem "mini_magick"` to your Gemfile if you want to use variants.
<ide>
<ide> ## Direct uploads
<ide> | 1 |
Ruby | Ruby | update doc for << method of has_many association | aeced89ca5c3972fb89f8279530847cfb6959f50 | <ide><path>activerecord/lib/active_record/associations.rb
<ide> module ClassMethods
<ide> # Adds one or more objects to the collection by setting their foreign keys to the collection's primary key.
<ide> # Note that this operation instantly fires update SQL without waiting for the save or update call on the
<ide> # parent object, unless the parent object is a new record.
<add> # This will also run validations and callbacks of associated object(s).
<ide> # [collection.delete(object, ...)]
<ide> # Removes one or more objects from the collection by setting their foreign keys to +NULL+.
<ide> # Objects will be in addition destroyed if they're associated with <tt>dependent: :destroy</tt>, | 1 |
Text | Text | v2.10.0 changelog [ci skip] | 5103e1eb0e6cb19dbe32f3c3bd7d672a08f5331c | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<del>### 2.10.0-beta.3 (November 2, 2016)
<del>
<del>- [#14537](https://github.com/emberjs/ember.js/pull/14537) [BUGFIX] Improve behavior for QPs with undefined values
<del>- [#14545](https://github.com/emberjs/ember.js/pull/14545) [BUGFIX] Refactor loading/error substates. Fixes a number of issues with substate usage with ember-engines.
<add>### 2.10.0 (November 28, 2016)
<add>
<add>- [#14293](https://github.com/emberjs/ember.js/pull/14293) [BUGFIX] Remove style warning when the binding is quoted.
<add>- [#12708](https://github.com/emberjs/ember.js/pull/12708) [BUGFIX] Improve compatibility between `Ember.isArray` and the native `Array.isArray` for `FileList`.
<add>- [#14546](https://github.com/emberjs/ember.js/pull/14546) [BUGFIX] Update route-recognizer to v0.2.8.
<add>- [#14575](https://github.com/emberjs/ember.js/pull/14575) [BUGFIX] Disallow calling `Ember.get` with empty paths.
<add>- [#14591](https://github.com/emberjs/ember.js/pull/14591) [BUGFIX] Avoid run.next in `app.visit` resolve handler.
<add>- [#14537](https://github.com/emberjs/ember.js/pull/14537) [BUGFIX] Improve behavior for query params with undefined values.
<add>- [#14545](https://github.com/emberjs/ember.js/pull/14545) [BUGFIX] Fixes a number of issues with loading/error substates in ember-engines.
<ide> - [#14571](https://github.com/emberjs/ember.js/pull/14571) [BUGFIX] Prevent errors in watching infrastructure for non-object paths.
<ide> - [tildeio/router.js#197](https://github.com/tildeio/router.js/pull/197) [BUGFIX] Fix redirects performed during the routers validation stages. Properly handles `replaceWith` / `transitionTo` for initial and subsequent transitions.
<del>
<del>### 2.10.0-beta.2 (October 26, 2016)
<del>
<del>- [#14499](https://github.com/emberjs/ember.js/pull/14499) [BUGFIX] Fix "Invalid value used as weak map key" error in old versions of Node.js.
<del>- [#14519](https://github.com/emberjs/ember.js/pull/14519) [BUGFIX] Ensure `didTransition` is fired before rendering.
<ide> - [#14520](https://github.com/emberjs/ember.js/pull/14520) [BUGFIX] Ensure local variables (block params) have higher precedence over helpers.
<del>- [#14520](https://github.com/emberjs/ember.js/pull/14520) [BUGFIX] Fix an issue where class-based helpers are destroyed unexpectedly.
<del>
<del>### 2.10.0-beta.1 (October 17, 2016)
<del>
<ide> - [#14156](https://github.com/emberjs/ember.js/pull/14156) [FEATURE ember-glimmer] Enable by default.
<ide>
<ide> ### 2.9.1 (November 1, 2016) | 1 |
Javascript | Javascript | change todo to webpack 6 | 9410954ed14b22238e73138465dd0202fe0f1eaf | <ide><path>lib/Compilation.js
<ide> const { arrayToSetDeprecation } = require("./util/deprecation");
<ide> * @property {boolean=} noChunkHash
<ide> */
<ide>
<del>// TODO webpack 5: remove
<add>// TODO webpack 6: remove
<ide> const deprecatedNormalModuleLoaderHook = util.deprecate(compilation => {
<ide> return require("./NormalModule").getCompilationHooks(compilation).loader;
<ide> }, "Compilation.hooks.normalModuleLoader was moved to NormalModule.getCompilationHooks(compilation).loader"); | 1 |
Javascript | Javascript | expand frustum.contains() per @alteredq, @gero3 | b358c94547ea3948841f433ee0a84879366ee56e | <ide><path>src/math/Frustum.js
<ide> THREE.Frustum.prototype = {
<ide>
<ide> contains: function ( object ) {
<ide>
<del> var sphere = THREE.Frustum.__s0.copy( object.geometry.boundingSphere );
<del> sphere.transform( object.matrixWorld );
<add> // this method is expanded inlined for performance reasons.
<add> var matrix = object.matrixWorld;
<add> var planes = this.planes;
<add> var center = matrix.getPosition();
<add> var negRadius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
<add>
<add> for ( var i = 0; i < 6; i ++ ) {
<add>
<add> var distance = planes[ i ].distanceToPoint( center );
<add>
<add> if( distance < negRadius ) {
<ide>
<del> return this.containsSphere( sphere );
<add> return false;
<add>
<add> }
<add>
<add> }
<add>
<add> return true;
<ide>
<ide> },
<ide> | 1 |
Text | Text | restore react as name and don't traduce it | a9c4cc9a58033768c85882d4b8cbd51de8537d22 | <ide><path>guide/spanish/react/state/index.md
<ide> Cuando solo se requiere un número limitado de campos en el objeto de estado, la
<ide>
<ide> ### Más información
<ide>
<del>* [Reaccionar - Estado y Ciclo de Vida](https://reactjs.org/docs/state-and-lifecycle.html)
<del>* [Reaccionar - Levantando el Estado](https://reactjs.org/docs/lifting-state-up.html)
<del>* [Reaccionar nativo - Estado arriba](https://facebook.github.io/react-native/docs/state.html)
<ide>\ No newline at end of file
<add>* [React - Estado y Ciclo de Vida](https://reactjs.org/docs/state-and-lifecycle.html)
<add>* [React - Levantando el Estado](https://reactjs.org/docs/lifting-state-up.html)
<add>* [React native - Estado arriba](https://facebook.github.io/react-native/docs/state.html) | 1 |
Java | Java | use recent vibrator android api | aa1d31ebca778e5d1074bf3de07cbd99eadf02d7 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/vibration/VibrationModule.java
<ide>
<ide> import android.annotation.SuppressLint;
<ide> import android.content.Context;
<add>import android.os.Build;
<add>import android.os.VibrationEffect;
<ide> import android.os.Vibrator;
<ide> import com.facebook.fbreact.specs.NativeVibrationSpec;
<ide> import com.facebook.react.bridge.ReactApplicationContext;
<ide> public void vibrate(double durationDouble) {
<ide> int duration = (int) durationDouble;
<ide>
<ide> Vibrator v = (Vibrator) getReactApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
<del> if (v != null) {
<add> if (v == null) {
<add> return;
<add> }
<add>
<add> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
<add> v.vibrate(VibrationEffect.createOneShot(duration, VibrationEffect.DEFAULT_AMPLITUDE));
<add> } else {
<ide> v.vibrate(duration);
<ide> }
<ide> }
<ide> public void vibrateByPattern(ReadableArray pattern, double repeatDouble) {
<ide> int repeat = (int) repeatDouble;
<ide>
<ide> Vibrator v = (Vibrator) getReactApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
<del> if (v != null) {
<del> long[] patternLong = new long[pattern.size()];
<del> for (int i = 0; i < pattern.size(); i++) {
<del> patternLong[i] = pattern.getInt(i);
<del> }
<add> if (v == null) {
<add> return;
<add> }
<add>
<add> long[] patternLong = new long[pattern.size()];
<add> for (int i = 0; i < pattern.size(); i++) {
<add> patternLong[i] = pattern.getInt(i);
<add> }
<add>
<add> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
<add> v.vibrate(VibrationEffect.createWaveform(patternLong, repeat));
<add> } else {
<ide> v.vibrate(patternLong, repeat);
<ide> }
<ide> } | 1 |
Ruby | Ruby | make "lib/node" a real folder | 612af6b4fe763346614316f8d7e3b5b1bc69cfda | <ide><path>Library/Homebrew/keg.rb
<ide> def link
<ide> # lib/language folders also get explicitly created
<ide> when 'ghc' then :mkpath
<ide> when 'lua' then :mkpath
<add> when 'node' then :mkpath
<ide> when 'ocaml' then :mkpath
<ide> when /^perl5/ then :mkpath
<ide> when 'php' then :mkpath | 1 |
Go | Go | add check for thin_check | 58a453f3f06c1daf34544da8aa16bb95e8e18010 | <ide><path>daemon/graphdriver/devmapper/device_setup.go
<ide> func writeLVMConfig(root string, cfg directLVMConfig) error {
<ide>
<ide> func setupDirectLVM(cfg directLVMConfig) error {
<ide> lvmProfileDir := "/etc/lvm/profile"
<add> binaries := []string{"pvcreate", "vgcreate", "lvcreate", "lvconvert", "lvchange", "thin_check"}
<ide>
<del> pvCreate, err := exec.LookPath("pvcreate")
<del> if err != nil {
<del> return errors.Wrap(err, "error looking up command `pvcreate` while setting up direct lvm")
<del> }
<del>
<del> vgCreate, err := exec.LookPath("vgcreate")
<del> if err != nil {
<del> return errors.Wrap(err, "error looking up command `vgcreate` while setting up direct lvm")
<del> }
<del>
<del> lvCreate, err := exec.LookPath("lvcreate")
<del> if err != nil {
<del> return errors.Wrap(err, "error looking up command `lvcreate` while setting up direct lvm")
<del> }
<del>
<del> lvConvert, err := exec.LookPath("lvconvert")
<del> if err != nil {
<del> return errors.Wrap(err, "error looking up command `lvconvert` while setting up direct lvm")
<del> }
<del>
<del> lvChange, err := exec.LookPath("lvchange")
<del> if err != nil {
<del> return errors.Wrap(err, "error looking up command `lvchange` while setting up direct lvm")
<add> for _, bin := range binaries {
<add> if _, err := exec.LookPath(bin); err != nil {
<add> return errors.Wrap(err, "error looking up command `"+bin+"` while setting up direct lvm")
<add> }
<ide> }
<ide>
<del> err = os.MkdirAll(lvmProfileDir, 0755)
<add> err := os.MkdirAll(lvmProfileDir, 0755)
<ide> if err != nil {
<ide> return errors.Wrap(err, "error creating lvm profile directory")
<ide> }
<ide> func setupDirectLVM(cfg directLVMConfig) error {
<ide> cfg.ThinpMetaPercent = 1
<ide> }
<ide>
<del> out, err := exec.Command(pvCreate, "-f", cfg.Device).CombinedOutput()
<add> out, err := exec.Command("pvcreate", "-f", cfg.Device).CombinedOutput()
<ide> if err != nil {
<ide> return errors.Wrap(err, string(out))
<ide> }
<ide>
<del> out, err = exec.Command(vgCreate, "docker", cfg.Device).CombinedOutput()
<add> out, err = exec.Command("vgcreate", "docker", cfg.Device).CombinedOutput()
<ide> if err != nil {
<ide> return errors.Wrap(err, string(out))
<ide> }
<ide>
<del> out, err = exec.Command(lvCreate, "--wipesignatures", "y", "-n", "thinpool", "docker", "--extents", fmt.Sprintf("%d%%VG", cfg.ThinpPercent)).CombinedOutput()
<add> out, err = exec.Command("lvcreate", "--wipesignatures", "y", "-n", "thinpool", "docker", "--extents", fmt.Sprintf("%d%%VG", cfg.ThinpPercent)).CombinedOutput()
<ide> if err != nil {
<ide> return errors.Wrap(err, string(out))
<ide> }
<del> out, err = exec.Command(lvCreate, "--wipesignatures", "y", "-n", "thinpoolmeta", "docker", "--extents", fmt.Sprintf("%d%%VG", cfg.ThinpMetaPercent)).CombinedOutput()
<add> out, err = exec.Command("lvcreate", "--wipesignatures", "y", "-n", "thinpoolmeta", "docker", "--extents", fmt.Sprintf("%d%%VG", cfg.ThinpMetaPercent)).CombinedOutput()
<ide> if err != nil {
<ide> return errors.Wrap(err, string(out))
<ide> }
<ide>
<del> out, err = exec.Command(lvConvert, "-y", "--zero", "n", "-c", "512K", "--thinpool", "docker/thinpool", "--poolmetadata", "docker/thinpoolmeta").CombinedOutput()
<add> out, err = exec.Command("lvconvert", "-y", "--zero", "n", "-c", "512K", "--thinpool", "docker/thinpool", "--poolmetadata", "docker/thinpoolmeta").CombinedOutput()
<ide> if err != nil {
<ide> return errors.Wrap(err, string(out))
<ide> }
<ide> func setupDirectLVM(cfg directLVMConfig) error {
<ide> return errors.Wrap(err, "error writing docker thinp autoextend profile")
<ide> }
<ide>
<del> out, err = exec.Command(lvChange, "--metadataprofile", "docker-thinpool", "docker/thinpool").CombinedOutput()
<add> out, err = exec.Command("lvchange", "--metadataprofile", "docker-thinpool", "docker/thinpool").CombinedOutput()
<ide> return errors.Wrap(err, string(out))
<ide> } | 1 |
Text | Text | show code necessary to create emoji | ef05278537c9365f25ca051589f85ad2697355fe | <ide><path>CONTRIBUTING.md
<ide> in the proper package's repository.
<ide> * Use the present tense
<ide> * Reference issues and pull requests liberally
<ide> * Consider starting the commit message with an applicable emoji:
<del> * :lipstick: when improving the format/structure of the code
<del> * :racehorse: when improving performance
<del> * :non-potable_water: when plugging memory leaks
<del> * :memo: when writing docs
<del> * :penguin: when fixing something on Linux
<add> * :lipstick: `:lipstick:` when improving the format/structure of the code
<add> * :racehorse: `:racehorse:` when improving performance
<add> * :non-potable_water: `:non-potable_water:` when plugging memory leaks
<add> * :memo: `:memo:` when writing docs
<add> * :penguin: `:penguin:` when fixing something on Linux
<ide>
<ide> ## CoffeeScript Styleguide
<ide> | 1 |
PHP | PHP | use ternary short-cut | 24e5c2f33e70b3f6576d1906adcf058bdc34a5da | <ide><path>src/Illuminate/View/View.php
<ide> public function render(Closure $callback = null)
<ide>
<ide> if ($env->doneRendering()) $env->flushSections();
<ide>
<del> return $response !== null ? $response : $contents;
<add> return $response ?: $contents;
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | fix disparity between buffer and the count | 34dbc9e4e8725d5ff28be918a2cb608ff0668e16 | <ide><path>lib/_stream_writable.js
<ide> function clearBuffer(stream, state) {
<ide> corkReq.finish = onCorkedFinish.bind(undefined, corkReq, state);
<ide> state.corkedRequestsFree = corkReq;
<ide> }
<add> state.bufferedRequestCount = 0;
<ide> } else {
<ide> // Slow case, write chunks one-by-one
<ide> while (entry) {
<ide> function clearBuffer(stream, state) {
<ide>
<ide> doWrite(stream, state, false, len, chunk, encoding, cb);
<ide> entry = entry.next;
<add> state.bufferedRequestCount--;
<ide> // if we didn't call the onwrite immediately, then
<ide> // it means that we need to wait until it does.
<ide> // also, that means that the chunk and cb are currently
<ide> function clearBuffer(stream, state) {
<ide> state.lastBufferedRequest = null;
<ide> }
<ide>
<del> state.bufferedRequestCount = 0;
<ide> state.bufferedRequest = entry;
<ide> state.bufferProcessing = false;
<ide> }
<ide><path>test/sequential/test-stream-writable-clear-buffer.js
<add>'use strict';
<add>const common = require('../common');
<add>const Stream = require('stream');
<add>// This test ensures that the _writeableState.bufferedRequestCount and
<add>// the actual buffered request count are the same
<add>const assert = require('assert');
<add>
<add>class StreamWritable extends Stream.Writable {
<add> constructor() {
<add> super({ objectMode: true });
<add> }
<add>
<add> // We need a timeout like on the original issue thread
<add> // otherwise the code will never reach our test case
<add> // this means this should go on the sequential folder.
<add> _write(chunk, encoding, cb) {
<add> setTimeout(cb, common.platformTimeout(10));
<add> }
<add>}
<add>
<add>const testStream = new StreamWritable();
<add>testStream.cork();
<add>
<add>for (let i = 1; i <= 5; i++) {
<add> testStream.write(i, function() {
<add> assert.strictEqual(
<add> testStream._writableState.bufferedRequestCount,
<add> testStream._writableState.getBuffer().length,
<add> 'bufferedRequestCount variable is different from the actual length of' +
<add> ' the buffer');
<add> });
<add>}
<add>
<add>testStream.end(); | 2 |
Text | Text | update the secret command docs | c22821014a8d951d7028f9d2888072c4d9f7c593 | <ide><path>docs/api/v1.24.md
<ide> image](#create-an-image) section for more details.
<ide> "Placement": {},
<ide> "Resources": {
<ide> "Limits": {
<del> "MemoryBytes": 104857600.0
<add> "MemoryBytes": 104857600
<ide> },
<ide> "Reservations": {
<ide> }
<ide> },
<ide> "RestartPolicy": {
<ide> "Condition": "on-failure",
<del> "Delay": 10000000000.0,
<add> "Delay": 10000000000,
<ide> "MaxAttempts": 10
<ide> }
<ide> },
<ide> image](#create-an-image) section for more details.
<ide> }
<ide> },
<ide> "UpdateConfig": {
<del> "Delay": 30000000000.0,
<add> "Delay": 30000000000,
<ide> "Parallelism": 2,
<ide> "FailureAction": "pause"
<ide> }, | 1 |
Ruby | Ruby | remove openssl expectation | b1caa4c44bc60dc0c7f928aa62d215a2d8626551 | <ide><path>Library/Homebrew/formula_cellar_checks.rb
<ide> def check_generic_executables bin
<ide> end
<ide>
<ide> def check_shadowed_headers
<del> ["libtool", "subversion", "berkeley-db", "openssl"].each do |formula_name|
<add> ["libtool", "subversion", "berkeley-db"].each do |formula_name|
<ide> return if formula.name.start_with?(formula_name)
<ide> end
<ide> | 1 |
Python | Python | fix inplace case of alignment data generator | d555a0ad0f1191daf8ae83e10933da5556b2510e | <ide><path>numpy/core/tests/test_scalarmath.py
<ide> def test_blocked(self):
<ide> inp1[...] = np.ones_like(inp1)
<ide> inp2[...] = np.zeros_like(inp2)
<ide> assert_almost_equal(np.add(inp1, inp2), exp1, err_msg=msg)
<del> assert_almost_equal(np.add(inp1, 1), exp1 + 1, err_msg=msg)
<add> assert_almost_equal(np.add(inp1, 2), exp1 + 2, err_msg=msg)
<ide> assert_almost_equal(np.add(1, inp2), exp1, err_msg=msg)
<ide>
<ide> np.add(inp1, inp2, out=out)
<ide> def test_blocked(self):
<ide> np.divide(1, inp2), err_msg=msg)
<ide>
<ide> inp1[...] = np.ones_like(inp1)
<del> inp2[...] = np.zeros_like(inp2)
<del> np.add(inp1, 1, out=out)
<del> assert_almost_equal(out, exp1 + 1, err_msg=msg)
<del> np.add(1, inp2, out=out)
<del> assert_almost_equal(out, exp1, err_msg=msg)
<add> np.add(inp1, 2, out=out)
<add> assert_almost_equal(out, exp1 + 2, err_msg=msg)
<add> inp2[...] = np.ones_like(inp2)
<add> np.add(2, inp2, out=out)
<add> assert_almost_equal(out, exp1 + 2, err_msg=msg)
<ide>
<ide> def test_lower_align(self):
<ide> # check data that is not aligned to element size
<ide><path>numpy/core/tests/test_umath.py
<ide> def test_abs_neg_blocked(self):
<ide> assert_array_equal(out, d, err_msg=msg)
<ide>
<ide> assert_array_equal(-inp, -1*inp, err_msg=msg)
<add> d = -1 * inp
<ide> np.negative(inp, out=out)
<del> assert_array_equal(out, -1*inp, err_msg=msg)
<add> assert_array_equal(out, d, err_msg=msg)
<ide>
<ide> def test_lower_align(self):
<ide> # check data that is not aligned to element size
<ide><path>numpy/testing/utils.py
<ide> def _gen_alignment_data(dtype=float32, type='binary', max_size=24):
<ide> inp = lambda: arange(s, dtype=dtype)[o:]
<ide> out = empty((s,), dtype=dtype)[o:]
<ide> yield out, inp(), ufmt % (o, o, s, dtype, 'out of place')
<del> yield inp(), inp(), ufmt % (o, o, s, dtype, 'in place')
<add> d = inp()
<add> yield d, d, ufmt % (o, o, s, dtype, 'in place')
<ide> yield out[1:], inp()[:-1], ufmt % \
<ide> (o + 1, o, s - 1, dtype, 'out of place')
<ide> yield out[:-1], inp()[1:], ufmt % \
<ide> def _gen_alignment_data(dtype=float32, type='binary', max_size=24):
<ide> out = empty((s,), dtype=dtype)[o:]
<ide> yield out, inp1(), inp2(), bfmt % \
<ide> (o, o, o, s, dtype, 'out of place')
<del> yield inp1(), inp1(), inp2(), bfmt % \
<add> d = inp1()
<add> yield d, d, inp2(), bfmt % \
<ide> (o, o, o, s, dtype, 'in place1')
<del> yield inp2(), inp1(), inp2(), bfmt % \
<add> d = inp2()
<add> yield d, inp1(), d, bfmt % \
<ide> (o, o, o, s, dtype, 'in place2')
<ide> yield out[1:], inp1()[:-1], inp2()[:-1], bfmt % \
<ide> (o + 1, o, o, s - 1, dtype, 'out of place') | 3 |
Javascript | Javascript | make date comparison in equals() nan-aware | 693e846add5089d0e516604ae4a109e445fd3664 | <ide><path>src/Angular.js
<ide> function equals(o1, o2) {
<ide> return true;
<ide> }
<ide> } else if (isDate(o1)) {
<del> return isDate(o2) && o1.getTime() == o2.getTime();
<add> if (!isDate(o2)) return false;
<add> return (isNaN(o1.getTime()) && isNaN(o2.getTime())) || (o1.getTime() === o2.getTime());
<ide> } else if (isRegExp(o1) && isRegExp(o2)) {
<ide> return o1.toString() == o2.toString();
<ide> } else {
<ide><path>test/AngularSpec.js
<ide> describe('angular', function() {
<ide> expect(equals(new Date(0), new Date(1))).toBe(false);
<ide> expect(equals(new Date(0), 0)).toBe(false);
<ide> expect(equals(0, new Date(0))).toBe(false);
<add>
<add> expect(equals(new Date(undefined), new Date(undefined))).toBe(true);
<add> expect(equals(new Date(undefined), new Date(0))).toBe(false);
<add> expect(equals(new Date(undefined), new Date(null))).toBe(false);
<add> expect(equals(new Date(undefined), new Date('wrong'))).toBe(true);
<ide> });
<ide>
<ide> it('should correctly test for keys that are present on Object.prototype', function() { | 2 |
Javascript | Javascript | remove empty value for boolean attributes in ssr | e0c31137434d7c7df2bc3475cb7682b1d7eecc8b | <ide><path>packages/react-dom/src/__tests__/ReactDOMSelect-test.js
<ide> describe('ReactDOMSelect', () => {
<ide> </select>
<ide> );
<ide> var markup = ReactDOMServer.renderToString(stub);
<del> expect(markup).toContain('<option selected="" value="giraffe"');
<del> expect(markup).not.toContain('<option selected="" value="monkey"');
<del> expect(markup).not.toContain('<option selected="" value="gorilla"');
<add> expect(markup).toContain('<option selected value="giraffe"');
<add> expect(markup).not.toContain('<option selected value="monkey"');
<add> expect(markup).not.toContain('<option selected value="gorilla"');
<ide> });
<ide>
<ide> it('should support server-side rendering with defaultValue', () => {
<ide> describe('ReactDOMSelect', () => {
<ide> </select>
<ide> );
<ide> var markup = ReactDOMServer.renderToString(stub);
<del> expect(markup).toContain('<option selected="" value="giraffe"');
<del> expect(markup).not.toContain('<option selected="" value="monkey"');
<del> expect(markup).not.toContain('<option selected="" value="gorilla"');
<add> expect(markup).toContain('<option selected value="giraffe"');
<add> expect(markup).not.toContain('<option selected value="monkey"');
<add> expect(markup).not.toContain('<option selected value="gorilla"');
<ide> });
<ide>
<ide> it('should support server-side rendering with multiple', () => {
<ide> describe('ReactDOMSelect', () => {
<ide> </select>
<ide> );
<ide> var markup = ReactDOMServer.renderToString(stub);
<del> expect(markup).toContain('<option selected="" value="giraffe"');
<del> expect(markup).toContain('<option selected="" value="gorilla"');
<del> expect(markup).not.toContain('<option selected="" value="monkey"');
<add> expect(markup).toContain('<option selected value="giraffe"');
<add> expect(markup).toContain('<option selected value="gorilla"');
<add> expect(markup).not.toContain('<option selected value="monkey"');
<ide> });
<ide>
<ide> it('should not control defaultValue if readding options', () => {
<ide><path>packages/react-dom/src/server/DOMMarkupOperations.js
<ide> export function createMarkupForProperty(name, value) {
<ide> propertyInfo.hasBooleanValue ||
<ide> (propertyInfo.hasOverloadedBooleanValue && value === true)
<ide> ) {
<del> return attributeName + '=""';
<add> return attributeName;
<ide> } else if (
<ide> typeof value !== 'boolean' ||
<ide> shouldAttributeAcceptBooleanValue(name) | 2 |
Text | Text | add release notes for 1.5.9 | d7cc863105f75d4bd67fab3c8c44cf6de6bf6dbc | <ide><path>CHANGELOG.md
<add><a name="1.5.9"></a>
<add># 1.5.9 timeturning-lockdown (2016-11-24)
<add>
<add>This is an interim release primarily to publish some security fixes, in particular a modification to
<add>ensure that Angular 1 can pass the linter checks for Mozilla add-ons.
<add>
<add>## Security Fixes
<add>- **bootstrap:**
<add> - do not auto-bootstrap when loaded from an extension
<add> ([6ce291](https://github.com/angular/angular.js/commit/6ce2913d99bb0dade6027ba9733295d0aa13b242))
<add> - explicitly whitelist URL schemes for bootstrap (#15427)
<add> ([4edd2d](https://github.com/angular/angular.js/commit/4edd2d95c11819ece2dda6e65f95f32638fda218))
<add>- **$location:** throw if the path starts with double (back)slashes
<add> ([353e3a](https://github.com/angular/angular.js/commit/353e3a6cd8b3a785b5f73a38236155621048522f))
<add>- **$sniffer:** don't use `history.pushState` in sandboxed Chrome Packaged Apps
<add>([367da5](https://github.com/angular/angular.js/commit/367da583bc12e6f5f01edf757305409cf63fb1f4))
<add>- **$parse:**
<add> - block assigning to fields of a constructor prototype
<add> ([d7e31b](https://github.com/angular/angular.js/commit/d7e31b5dc71253edb22190a5850034934e7b778a)
<add> [#14939](https://github.com/angular/angular.js/issues/14939))
<add> - correctly escape unsafe identifier characters
<add> ([b01460](https://github.com/angular/angular.js/commit/b014607030835358ed7887e9fd1724cdada56690))
<add>- **$compile:**
<add> - ensure that hidden input values are correct after history.back
<add> ([6a2488](https://github.com/angular/angular.js/commit/6a24885771cf8c140b5d2895e92b321e60d86b55))
<add> - lower the $sce context for `src` on video, audio, source, track
<add> ([68fb70](https://github.com/angular/angular.js/commit/68fb70ed295119d7b00c670d796c1b4186091adb))
<add>
<add>
<add>## New Features
<add>- **input:**
<add> - add support for binding to `input[range]`
<add> ([2e7121](https://github.com/angular/angular.js/commit/2e7121b8e4dcac23f28e2375e775ca56b6baf252))
<add> - make support for `input[range]` opt-in
<add> ([07b876](https://github.com/angular/angular.js/commit/07b8761233aaa3d719d94698296295e51c2a1077))
<add> - fix `step` validation for `input[number][ng-range-input]`
<add> ([64f6a6](https://github.com/angular/angular.js/commit/64f6a616d401febc3f06309ed5a5efa46b131717)
<add> [#15257](https://github.com/angular/angular.js/issues/15257))
<add>- **ngMock/$httpBackend:** flush requests in any order
<add> ([098b6f](https://github.com/angular/angular.js/commit/098b6f519a53f6348127cd4ce09bca1423cbeb1a))
<add>
<add>
<add>## Bug Fixes
<add>- **$httpBackend:** complete the request on timeout
<add> ([549edc](https://github.com/angular/angular.js/commit/549edc9d0123d50657d5a03ba0c547cb0f91727f)
<add> [#14969](https://github.com/angular/angular.js/issues/14969))
<add>- **ngOptions:** remove selected attribute from unselected options
<add> ([d31b3a](https://github.com/angular/angular.js/commit/d31b3a65b65b73ab077026fc028ddf5b6232fba2)
<add> [#14892](https://github.com/angular/angular.js/issues/14892))
<add>
<add>
<add>## Performance Improvements
<add>- **$parse:** improve performance of assignment expressions
<add> ([f83c3d](https://github.com/angular/angular.js/commit/f83c3dea23f910aed25dcf9b85fadf7f11a2a366))
<add>- **$compile:** add provider option to turn off compilation of css class and comment directives
<add> ([775c24](https://github.com/angular/angular.js/commit/775c247085765e08845ae45ed19dd0120c61acc1))
<add>
<add>
<ide>
<ide> <a name="1.6.0-rc.1"></a>
<ide> # 1.6.0-rc.1 proximity-warning (2016-11-21) | 1 |
Ruby | Ruby | clarify that classes that include datehelper can | 762a2f4653a5f7408f4cb6056cd974edd12d8b61 | <ide><path>actionpack/lib/action_view/helpers/date_helper.rb
<ide> module ActionView
<ide> module Helpers
<ide> # = Action View Date Helpers
<ide> #
<del> # The Date Helper primarily creates select/option tags for different kinds of dates and date elements. All of the
<del> # select-type methods share a number of common options that are as follows:
<add> # The Date Helper primarily creates select/option tags for different kinds of dates and times or date and time
<add> # elements. All of the select-type methods share a number of common options that are as follows:
<ide> #
<ide> # * <tt>:prefix</tt> - overwrites the default prefix of "date" used for the select names. So specifying "birthday"
<ide> # would give birthday[month] instead of date[month] if passed to the <tt>select_month</tt> method. | 1 |
PHP | PHP | add replicating model event | 7d24f9183fcd2bb7159470a9454fe74fd88e12f5 | <ide><path>src/Illuminate/Database/Eloquent/Concerns/HasEvents.php
<ide> public function getObservableEvents()
<ide> return array_merge(
<ide> [
<ide> 'retrieved', 'creating', 'created', 'updating', 'updated',
<del> 'saving', 'saved', 'restoring', 'restored',
<add> 'saving', 'saved', 'restoring', 'restored', 'replicating',
<ide> 'deleting', 'deleted', 'forceDeleted',
<ide> ],
<ide> $this->observables
<ide> public static function created($callback)
<ide> static::registerModelEvent('created', $callback);
<ide> }
<ide>
<add> /**
<add> * Register a replicating model event with the dispatcher.
<add> *
<add> * @param \Closure|string $callback
<add> * @return void
<add> */
<add> public static function replicating($callback)
<add> {
<add> static::registerModelEvent('replicating', $callback);
<add> }
<add>
<ide> /**
<ide> * Register a deleting model event with the dispatcher.
<ide> *
<ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public function replicate(array $except = null)
<ide> $instance->setRawAttributes($attributes);
<ide>
<ide> $instance->setRelations($this->relations);
<add>
<add> $instance->fireModelEvent('replicating', false);
<ide> });
<ide> }
<ide>
<ide><path>tests/Database/DatabaseEloquentModelTest.php
<ide> public function testReplicateCreatesANewModelInstanceWithSameAttributeValues()
<ide> $this->assertNull($replicated->updated_at);
<ide> }
<ide>
<add> public function testReplicatingEventIsFiredWhenReplicatingModel()
<add> {
<add> $model = new EloquentModelStub;
<add>
<add> $model->setEventDispatcher($events = m::mock(Dispatcher::class));
<add> $events->shouldReceive('dispatch')->once()->with('eloquent.replicating: '.get_class($model), m::on(function ($m) use ($model) {
<add> return $model->is($m);
<add> }));
<add>
<add> $model->replicate();
<add> }
<add>
<ide> public function testIncrementOnExistingModelCallsQueryAndSetsAttribute()
<ide> {
<ide> $model = m::mock(EloquentModelStub::class.'[newQueryWithoutRelationships]'); | 3 |
Ruby | Ruby | add option to disable methods on specific date | 0f8cb4ba277968fb24bf438468b37466075fd18a | <ide><path>Library/Homebrew/test/utils_test.rb
<ide> def test_odeprecated
<ide> e = assert_raises(MethodDeprecatedError) do
<ide> odeprecated("method", "replacement",
<ide> caller: ["#{HOMEBREW_LIBRARY}/Taps/homebrew/homebrew-core/"],
<del> die: true)
<add> disable: true)
<ide> end
<ide> assert_match "method", e.message
<ide> assert_match "replacement", e.message
<ide><path>Library/Homebrew/utils.rb
<ide> require "utils/inreplace"
<ide> require "utils/popen"
<ide> require "utils/tty"
<add>require "time"
<ide>
<ide> def ohai(title, *sput)
<ide> title = Tty.truncate(title) if $stdout.tty? && !ARGV.verbose?
<ide> def odie(error)
<ide> exit 1
<ide> end
<ide>
<del>def odeprecated(method, replacement = nil, options = {})
<del> verb = if options[:die]
<del> "disabled"
<del> else
<del> "deprecated"
<del> end
<del>
<add>def odeprecated(method, replacement = nil, disable: false, disable_on: nil, caller: send(:caller))
<ide> replacement_message = if replacement
<ide> "Use #{replacement} instead."
<ide> else
<ide> "There is no replacement."
<ide> end
<ide>
<add> unless disable_on.nil?
<add> if disable_on > Time.now
<add> will_be_disabled_message = " and will be disabled on #{disable_on.strftime("%Y-%m-%d")}"
<add> else
<add> disable = true
<add> end
<add> end
<add>
<add> verb = if disable
<add> "disabled"
<add> else
<add> "deprecated#{will_be_disabled_message}"
<add> end
<add>
<ide> # Try to show the most relevant location in message, i.e. (if applicable):
<ide> # - Location in a formula.
<ide> # - Location outside of 'compat/'.
<ide> # - Location of caller of deprecated method (if all else fails).
<del> backtrace = options.fetch(:caller, caller)
<add> backtrace = caller
<ide> tap_message = nil
<ide> caller_message = backtrace.detect do |line|
<ide> next unless line =~ %r{^#{Regexp.escape HOMEBREW_LIBRARY}/Taps/([^/]+/[^/]+)/}
<ide> def odeprecated(method, replacement = nil, options = {})
<ide> #{caller_message}#{tap_message}
<ide> EOS
<ide>
<del> if ARGV.homebrew_developer? || options[:die] ||
<add> if ARGV.homebrew_developer? || disable ||
<ide> Homebrew.raise_deprecation_exceptions?
<ide> raise MethodDeprecatedError, message
<ide> else
<ide> def odeprecated(method, replacement = nil, options = {})
<ide> end
<ide>
<ide> def odisabled(method, replacement = nil, options = {})
<del> options = { die: true, caller: caller }.merge(options)
<add> options = { disable: true, caller: caller }.merge(options)
<ide> odeprecated(method, replacement, options)
<ide> end
<ide> | 2 |
Java | Java | adapt fieldhint to recent graalvm versions | 1cb5f0072335cc215e3c6ebc9cde325b5b0f24c1 | <ide><path>spring-core/src/main/java/org/springframework/aot/hint/FieldHint.java
<del>/*
<del> * Copyright 2002-2022 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * https://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.aot.hint;
<del>
<del>import java.lang.reflect.Field;
<del>import java.util.function.Consumer;
<del>
<del>import org.springframework.lang.Nullable;
<del>import org.springframework.util.Assert;
<del>
<del>/**
<del> * A hint that describes the need for reflection on a {@link Field}.
<del> *
<del> * @author Stephane Nicoll
<del> * @since 6.0
<del> */
<del>public final class FieldHint extends MemberHint {
<del>
<del> private final FieldMode mode;
<del>
<del> private final boolean allowUnsafeAccess;
<del>
<del>
<del> private FieldHint(Builder builder) {
<del> super(builder.name);
<del> this.mode = (builder.mode != null ? builder.mode : FieldMode.WRITE);
<del> this.allowUnsafeAccess = builder.allowUnsafeAccess;
<del> }
<del>
<del> /**
<del> * Return whether setting the value of the field should be allowed.
<del> * @return {@code true} to allow {@link Field#set(Object, Object)}.
<del> * @deprecated in favor of {@link #getMode()}
<del> */
<del> @Deprecated
<del> public boolean isAllowWrite() {
<del> return this.mode == FieldMode.WRITE;
<del> }
<del>
<del> /**
<del> * Return the {@linkplain FieldMode mode} that applies to this hint.
<del> * @return the mode
<del> */
<del> public FieldMode getMode() {
<del> return this.mode;
<del> }
<del>
<del> /**
<del> * Return whether using {@code Unsafe} on the field should be allowed.
<del> * @return {@code true} to allow unsafe access
<del> */
<del> public boolean isAllowUnsafeAccess() {
<del> return this.allowUnsafeAccess;
<del> }
<del>
<del> /**
<del> * Return a {@link Consumer} that applies the given {@link FieldMode}
<del> * to the accepted {@link Builder}.
<del> * @param mode the mode to apply
<del> * @return a consumer to apply the mode
<del> */
<del> public static Consumer<Builder> builtWith(FieldMode mode) {
<del> return builder -> builder.withMode(mode);
<del> }
<del>
<del>
<del> /**
<del> * Builder for {@link FieldHint}.
<del> */
<del> public static class Builder {
<del>
<del> private final String name;
<del>
<del> @Nullable
<del> private FieldMode mode;
<del>
<del> private boolean allowUnsafeAccess;
<del>
<del>
<del> Builder(String name) {
<del> this.name = name;
<del> }
<del>
<del> /**
<del> * Specify if setting the value of the field should be allowed.
<del> * @param allowWrite {@code true} to allow {@link Field#set(Object, Object)}
<del> * @return {@code this}, to facilitate method chaining
<del> * @deprecated in favor of {@link #withMode(FieldMode)}
<del> */
<del> @Deprecated
<del> public Builder allowWrite(boolean allowWrite) {
<del> if (allowWrite) {
<del> return withMode(FieldMode.WRITE);
<del> }
<del> return this;
<del> }
<del>
<del> /**
<del> * Specify that the {@linkplain FieldMode mode} is required.
<del> * @param mode the required mode
<del> * @return {@code this}, to facilitate method chaining
<del> */
<del> public Builder withMode(FieldMode mode) {
<del> Assert.notNull(mode, "'mode' must not be null");
<del> if ((this.mode == null || !this.mode.includes(mode))) {
<del> this.mode = mode;
<del> }
<del> return this;
<del> }
<del>
<del> /**
<del> * Specify whether using {@code Unsafe} on the field should be allowed.
<del> * @param allowUnsafeAccess {@code true} to allow unsafe access
<del> * @return {@code this}, to facilitate method chaining
<del> */
<del> public Builder allowUnsafeAccess(boolean allowUnsafeAccess) {
<del> this.allowUnsafeAccess = allowUnsafeAccess;
<del> return this;
<del> }
<del>
<del> /**
<del> * Create a {@link FieldHint} based on the state of this builder.
<del> * @return a field hint
<del> */
<del> FieldHint build() {
<del> return new FieldHint(this);
<del> }
<del>
<del> }
<del>}
<ide><path>spring-core/src/main/java/org/springframework/aot/hint/TypeHint.java
<ide> public final class TypeHint implements ConditionalHint {
<ide> @Nullable
<ide> private final TypeReference reachableType;
<ide>
<del> private final Set<FieldHint> fields;
<add> private final Set<String> fields;
<ide>
<ide> private final Set<ExecutableHint> constructors;
<ide>
<ide> private TypeHint(Builder builder) {
<ide> this.type = builder.type;
<ide> this.reachableType = builder.reachableType;
<ide> this.memberCategories = Set.copyOf(builder.memberCategories);
<del> this.fields = builder.fields.values().stream().map(FieldHint.Builder::build).collect(Collectors.toSet());
<add> this.fields = builder.fields;
<ide> this.constructors = builder.constructors.values().stream().map(ExecutableHint.Builder::build).collect(Collectors.toSet());
<ide> this.methods = builder.methods.values().stream().map(ExecutableHint.Builder::build).collect(Collectors.toSet());
<ide> }
<ide> public TypeReference getReachableType() {
<ide>
<ide> /**
<ide> * Return the fields that require reflection.
<del> * @return a stream of {@link FieldHint}
<add> * @return a stream of Strings
<ide> */
<del> public Stream<FieldHint> fields() {
<del> return this.fields.stream();
<add> public Set<String> fields() {
<add> return this.fields;
<ide> }
<ide>
<ide> /**
<ide> public static class Builder {
<ide> @Nullable
<ide> private TypeReference reachableType;
<ide>
<del> private final Map<String, FieldHint.Builder> fields = new HashMap<>();
<add> private final Set<String> fields = new HashSet<>();
<ide>
<ide> private final Map<ExecutableKey, ExecutableHint.Builder> constructors = new HashMap<>();
<ide>
<ide> public Builder onReachableType(Class<?> reachableType) {
<ide> * @return {@code this}, to facilitate method chaining
<ide> */
<ide> public Builder withField(String name) {
<del> return withField(name, FieldMode.WRITE);
<add> return withField(name);
<ide> }
<ide>
<del> /**
<del> * Register the need for reflection on the field with the specified name
<del> * using the specified {@link FieldMode}.
<del> * @param name the name of the field
<del> * @param mode the requested mode
<del> * @return {@code this}, to facilitate method chaining
<del> */
<del> public Builder withField(String name, FieldMode mode) {
<del> return withField(name, FieldHint.builtWith(mode));
<del> }
<del>
<del> /**
<del> * Register the need for reflection on the field with the specified name.
<del> * @param name the name of the field
<del> * @param fieldHint a builder to further customize the hints of this field
<del> * @return {@code this}, to facilitate method chaining
<del> */
<del> public Builder withField(String name, Consumer<FieldHint.Builder> fieldHint) {
<del> FieldHint.Builder builder = this.fields.computeIfAbsent(name, FieldHint.Builder::new);
<del> fieldHint.accept(builder);
<del> return this;
<del> }
<ide>
<ide> /**
<ide> * Register the need for reflection on the constructor with the specified | 2 |
Javascript | Javascript | handle sign of `-undefined` consistently | c1eaf3480b9a88e5309ff4931a720f3f62bd7606 | <ide><path>src/ng/parse.js
<ide> ASTInterpreter.prototype = {
<ide> if (isDefined(arg)) {
<ide> arg = -arg;
<ide> } else {
<del> arg = 0;
<add> arg = -0;
<ide> }
<ide> return context ? {value: arg} : arg;
<ide> };
<ide><path>test/ng/parseSpec.js
<ide> describe('parser', function() {
<ide> expect(scope.$eval("+'1'")).toEqual(+'1');
<ide> expect(scope.$eval("-'1'")).toEqual(-'1');
<ide> expect(scope.$eval("+undefined")).toEqual(0);
<del> expect(scope.$eval("-undefined")).toBe(0);
<add> expect(scope.$eval("-undefined")).toEqual(-0);
<ide> expect(scope.$eval("+null")).toEqual(+null);
<ide> expect(scope.$eval("-null")).toEqual(-null);
<ide> expect(scope.$eval("+false")).toEqual(+false); | 2 |
Javascript | Javascript | use umd in lang/uz.js | 2d39f9ccb41a1901e7a2005f4a7cb489bd84d0de | <ide><path>lang/uz.js
<ide> // language : uzbek
<ide> // author : Sardor Muminov : https://github.com/muminoff
<ide>
<del>require('../moment').lang('uz', {
<del> months : "январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь".split("_"),
<del> monthsShort : "янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек".split("_"),
<del> weekdays : "Якшанба_Душанба_Сешанба_Чоршанба_Пайшанба_Жума_Шанба".split("_"),
<del> weekdaysShort : "Якш_Душ_Сеш_Чор_Пай_Жум_Шан".split("_"),
<del> weekdaysMin : "Як_Ду_Се_Чо_Па_Жу_Ша".split("_"),
<del> longDateFormat : {
<del> LT : "HH:mm",
<del> L : "DD/MM/YYYY",
<del> LL : "D MMMM YYYY",
<del> LLL : "D MMMM YYYY LT",
<del> LLLL : "D MMMM YYYY, dddd LT"
<del> },
<del> calendar : {
<del> sameDay : '[Бугун соат] LT [да]',
<del> nextDay : '[Эртага] LT [да]',
<del> nextWeek : 'dddd [куни соат] LT [да]',
<del> lastDay : '[Кеча соат] LT [да]',
<del> lastWeek : '[Утган] dddd [куни соат] LT [да]',
<del> sameElse : 'L'
<del> },
<del> relativeTime : {
<del> future : "Якин %s ичида",
<del> past : "Бир неча %s олдин",
<del> s : "фурсат",
<del> m : "бир дакика",
<del> mm : "%d дакика",
<del> h : "бир соат",
<del> hh : "%d соат",
<del> d : "бир кун",
<del> dd : "%d кун",
<del> M : "бир ой",
<del> MM : "%d ой",
<del> y : "бир йил",
<del> yy : "%d йил"
<del> },
<del> week : {
<del> dow : 1, // Monday is the first day of the week.
<del> doy : 7 // The week that contains Jan 4th is the first week of the year.
<add>(function (factory) {
<add> if (typeof define === 'function' && define.amd) {
<add> define(['moment'], factory); // AMD
<add> } else if (typeof exports === 'object') {
<add> factory(require('../moment')); // Node
<add> } else {
<add> factory(window.moment); // Browser global
<ide> }
<del>});
<add>}(function (moment) {
<add> moment.lang('uz', {
<add> months : "январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь".split("_"),
<add> monthsShort : "янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек".split("_"),
<add> weekdays : "Якшанба_Душанба_Сешанба_Чоршанба_Пайшанба_Жума_Шанба".split("_"),
<add> weekdaysShort : "Якш_Душ_Сеш_Чор_Пай_Жум_Шан".split("_"),
<add> weekdaysMin : "Як_Ду_Се_Чо_Па_Жу_Ша".split("_"),
<add> longDateFormat : {
<add> LT : "HH:mm",
<add> L : "DD/MM/YYYY",
<add> LL : "D MMMM YYYY",
<add> LLL : "D MMMM YYYY LT",
<add> LLLL : "D MMMM YYYY, dddd LT"
<add> },
<add> calendar : {
<add> sameDay : '[Бугун соат] LT [да]',
<add> nextDay : '[Эртага] LT [да]',
<add> nextWeek : 'dddd [куни соат] LT [да]',
<add> lastDay : '[Кеча соат] LT [да]',
<add> lastWeek : '[Утган] dddd [куни соат] LT [да]',
<add> sameElse : 'L'
<add> },
<add> relativeTime : {
<add> future : "Якин %s ичида",
<add> past : "Бир неча %s олдин",
<add> s : "фурсат",
<add> m : "бир дакика",
<add> mm : "%d дакика",
<add> h : "бир соат",
<add> hh : "%d соат",
<add> d : "бир кун",
<add> dd : "%d кун",
<add> M : "бир ой",
<add> MM : "%d ой",
<add> y : "бир йил",
<add> yy : "%d йил"
<add> },
<add> week : {
<add> dow : 1, // Monday is the first day of the week.
<add> doy : 7 // The week that contains Jan 4th is the first week of the year.
<add> }
<add> });
<add>})); | 1 |
Python | Python | handle invalid characters in headers | 7ae71deb845e0cbe020a4054ba46ab4bed44d6e3 | <ide><path>rest_framework/authentication.py
<ide> def authenticate(self, request):
<ide> msg = _('Invalid token header. Token string should not contain spaces.')
<ide> raise exceptions.AuthenticationFailed(msg)
<ide>
<del> return self.authenticate_credentials(auth[1])
<add> try:
<add> token = auth[1].decode()
<add> except UnicodeError:
<add> msg = _('Invalid token header. Token string should not contain invalid characters.')
<add> raise exceptions.AuthenticationFailed(msg)
<add>
<add> return self.authenticate_credentials(token)
<ide>
<ide> def authenticate_credentials(self, key):
<ide> try:
<ide><path>tests/test_authentication.py
<add># coding: utf-8
<add>
<ide> from __future__ import unicode_literals
<ide> from django.conf.urls import patterns, url, include
<ide> from django.contrib.auth.models import User
<ide> def test_post_form_passing_token_auth(self):
<ide> response = self.csrf_client.post('/token/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
<ide> self.assertEqual(response.status_code, status.HTTP_200_OK)
<ide>
<add> def test_fail_post_form_passing_invalid_token_auth(self):
<add> # add an 'invalid' unicode character
<add> auth = 'Token ' + self.key + "¸"
<add> response = self.csrf_client.post('/token/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
<add> self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
<add>
<ide> def test_post_json_passing_token_auth(self):
<ide> """Ensure POSTing form over token auth with correct credentials passes and does not require CSRF"""
<ide> auth = "Token " + self.key | 2 |
Python | Python | fix fast tokenizers too | f1e2e423ab46d65bba98757fba420eecce14ea52 | <ide><path>src/transformers/tokenization_gpt2.py
<ide> def prepare_for_tokenization(self, text, is_pretokenized=False, **kwargs):
<ide>
<ide> class GPT2TokenizerFast(PreTrainedTokenizerFast):
<ide> """
<del> Constructs a "Fast" GPT-2 BPE tokenizer (backed by HuggingFace's `tokenizers` library).
<add> Constructs a "Fast" GPT-2 BPE tokenizer (backed by HuggingFace's `tokenizers` library), using byte-level
<add> Byte-Pair-Encoding.
<ide>
<del> Peculiarities:
<del>
<del> - Byte-level Byte-Pair-Encoding
<del> - Requires a space to start the input string => the encoding methods should be called with the
<del> ``add_prefix_space`` flag set to ``True``.
<del> Otherwise, this tokenizer ``encode`` and ``decode`` method will not conserve
<del> the absence of a space at the beginning of a string:
<add> This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
<add> be encoded differently whether it is at the beginning of the sentence (without space) or not:
<ide>
<ide> ::
<ide>
<del> tokenizer.decode(tokenizer.encode("Hello")) = " Hello"
<add> >>> from transformers import GPT2TokenizerFast
<add> >>> tokenizer = GPT2TokenizerFast.from_pretrained("gpt2")
<add> >>> tokenizer("Hello world")['input_ids']
<add> [15496, 995]
<add> >>> tokenizer(" Hello world")['input_ids']
<add> [18435, 995]
<add>
<add> You can get around that behavior by passing ``add_prefix_space=True`` when instantiating this tokenizer or when you
<add> call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
<ide>
<del> This tokenizer inherits from :class:`~transformers.PreTrainedTokenizerFast` which contains most of the methods. Users
<add> .. note::
<add>
<add> When used with ``is_pretokenized=True``, this tokenizer needs to be instantiated with
<add> ``add_prefix_space=True``.
<add>
<add> This tokenizer inherits from :class:`~transformers.PreTrainedTokenizer` which contains most of the methods. Users
<ide> should refer to the superclass for more information regarding methods.
<ide>
<ide> Args:
<ide><path>src/transformers/tokenization_roberta.py
<ide> def prepare_for_tokenization(self, text, is_pretokenized=False, **kwargs):
<ide>
<ide> class RobertaTokenizerFast(GPT2TokenizerFast):
<ide> """
<del> Constructs a "Fast" RoBERTa BPE tokenizer (backed by HuggingFace's `tokenizers` library).
<add> Constructs a "Fast" RoBERTa BPE tokenizer (backed by HuggingFace's `tokenizers` library), derived from the GPT-2
<add> tokenizer, using byte-level Byte-Pair-Encoding.
<ide>
<del> Peculiarities:
<del>
<del> - Byte-level Byte-Pair-Encoding
<del> - Requires a space to start the input string => the encoding methods should be called with the
<del> ``add_prefix_space`` flag set to ``True``.
<del> Otherwise, this tokenizer ``encode`` and ``decode`` method will not conserve
<del> the absence of a space at the beginning of a string:
<add> This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
<add> be encoded differently whether it is at the beginning of the sentence (without space) or not:
<ide>
<ide> ::
<ide>
<del> tokenizer.decode(tokenizer.encode("Hello")) = " Hello"
<add> >>> from transformers import RobertaTokenizerFast
<add> >>> tokenizer = RobertaTokenizerFast.from_pretrained("roberta-base")
<add> >>> tokenizer("Hello world")['input_ids']
<add> [0, 31414, 232, 328, 2]
<add> >>> tokenizer(" Hello world")['input_ids']
<add> [0, 20920, 232, 2]
<add>
<add> You can get around that behavior by passing ``add_prefix_space=True`` when instantiating this tokenizer or when you
<add> call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
<add>
<add> .. note::
<add>
<add> When used with ``is_pretokenized=True``, this tokenizer needs to be instantiated with
<add> ``add_prefix_space=True``.
<ide>
<ide> This tokenizer inherits from :class:`~transformers.PreTrainedTokenizerFast` which contains most of the methods. Users
<ide> should refer to the superclass for more information regarding methods. | 2 |
Ruby | Ruby | fix tests for aws buckets that include a . | b9f0eb24ed6a86aec3881b43e6b0028a306465b2 | <ide><path>activestorage/test/controllers/direct_uploads_controller_test.rb
<ide> class ActiveStorage::S3DirectUploadsControllerTest < ActionDispatch::Integration
<ide> assert_equal 6, details["byte_size"]
<ide> assert_equal checksum, details["checksum"]
<ide> assert_equal "text/plain", details["content_type"]
<del> assert_match /#{SERVICE_CONFIGURATIONS[:s3][:bucket]}\.s3.(\S+)?amazonaws\.com/, details["direct_upload"]["url"]
<add> assert_match SERVICE_CONFIGURATIONS[:s3][:bucket], details["direct_upload"]["url"]
<add> assert_match /s3\.(\S+)?amazonaws\.com/, details["direct_upload"]["url"]
<ide> assert_equal({ "Content-Type" => "text/plain", "Content-MD5" => checksum }, details["direct_upload"]["headers"])
<ide> end
<ide> end
<ide><path>activestorage/test/service/s3_service_test.rb
<ide> class ActiveStorage::Service::S3ServiceTest < ActiveSupport::TestCase
<ide> end
<ide>
<ide> test "signed URL generation" do
<del> assert_match /#{SERVICE_CONFIGURATIONS[:s3][:bucket]}\.s3.(\S+)?amazonaws.com.*response-content-disposition=inline.*avatar\.png.*response-content-type=image%2Fpng/,
<del> @service.url(FIXTURE_KEY, expires_in: 5.minutes, disposition: :inline, filename: "avatar.png", content_type: "image/png")
<add> url = @service.url(FIXTURE_KEY, expires_in: 5.minutes,
<add> disposition: :inline, filename: "avatar.png", content_type: "image/png")
<add>
<add> assert_match /s3\.(\S+)?amazonaws.com.*response-content-disposition=inline.*avatar\.png.*response-content-type=image%2Fpng/, url
<add> assert_match SERVICE_CONFIGURATIONS[:s3][:bucket], url
<ide> end
<ide>
<ide> test "uploading with server-side encryption" do | 2 |
Text | Text | remove repeated definition tag in challenge | 1cdd009d7a5072dcd49a09c87279601afcbe4d90 | <ide><path>curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/basic-javascript/nest-one-array-within-another-array.md
<ide> You can also nest arrays within other arrays, like below:
<ide> [["Bulls", 23], ["White Sox", 45]]
<ide> ```
<ide>
<del>This is also called a <dfn>multi-dimensional array<dfn>.</dfn></dfn>
<add>This is also called a <dfn>multi-dimensional array</dfn>.
<ide>
<ide> # --instructions--
<ide> | 1 |
PHP | PHP | remove hack to access class scope inside closures | e2d3424cc2bfeebda0e546779bf9575f4b883578 | <ide><path>tests/Routing/RoutingRouteTest.php
<ide> public function testRoutePrefixing()
<ide>
<ide> public function testRoutePreservingOriginalParametersState()
<ide> {
<del> $phpunit = $this;
<ide> $router = $this->getRouter();
<ide> $router->bind('bar', function ($value) {
<ide> return strlen($value);
<ide> });
<ide> $router->get('foo/{bar}', [
<ide> 'middleware' => SubstituteBindings::class,
<del> 'uses' => function ($bar) use ($router, $phpunit) {
<add> 'uses' => function ($bar) use ($router) {
<ide> $route = $router->getCurrentRoute();
<ide>
<del> $phpunit->assertEquals('taylor', $route->originalParameter('bar'));
<del> $phpunit->assertEquals('default', $route->originalParameter('unexisting', 'default'));
<del> $phpunit->assertEquals(['bar' => 'taylor'], $route->originalParameters());
<add> $this->assertEquals('taylor', $route->originalParameter('bar'));
<add> $this->assertEquals('default', $route->originalParameter('unexisting', 'default'));
<add> $this->assertEquals(['bar' => 'taylor'], $route->originalParameters());
<ide>
<ide> return $bar;
<ide> },
<ide> public function testControllerMiddlewareGroups()
<ide>
<ide> public function testImplicitBindings()
<ide> {
<del> $phpunit = $this;
<ide> $router = $this->getRouter();
<ide> $router->get('foo/{bar}', [
<ide> 'middleware' => SubstituteBindings::class,
<del> 'uses' => function (RoutingTestUserModel $bar) use ($phpunit) {
<del> $phpunit->assertInstanceOf(RoutingTestUserModel::class, $bar);
<add> 'uses' => function (RoutingTestUserModel $bar) {
<add> $this->assertInstanceOf(RoutingTestUserModel::class, $bar);
<ide>
<ide> return $bar->value;
<ide> },
<ide> public function testImplicitBindings()
<ide>
<ide> public function testImplicitBindingsWithOptionalParameterWithExistingKeyInUri()
<ide> {
<del> $phpunit = $this;
<ide> $router = $this->getRouter();
<ide> $router->get('foo/{bar?}', [
<ide> 'middleware' => SubstituteBindings::class,
<del> 'uses' => function (RoutingTestUserModel $bar = null) use ($phpunit) {
<del> $phpunit->assertInstanceOf(RoutingTestUserModel::class, $bar);
<add> 'uses' => function (RoutingTestUserModel $bar = null) {
<add> $this->assertInstanceOf(RoutingTestUserModel::class, $bar);
<ide>
<ide> return $bar->value;
<ide> },
<ide> public function testImplicitBindingsWithOptionalParameterWithExistingKeyInUri()
<ide>
<ide> public function testImplicitBindingsWithOptionalParameterWithNoKeyInUri()
<ide> {
<del> $phpunit = $this;
<ide> $router = $this->getRouter();
<ide> $router->get('foo/{bar?}', [
<ide> 'middleware' => SubstituteBindings::class,
<del> 'uses' => function (RoutingTestUserModel $bar = null) use ($phpunit) {
<del> $phpunit->assertNull($bar);
<add> 'uses' => function (RoutingTestUserModel $bar = null) {
<add> $this->assertNull($bar);
<ide> },
<ide> ]);
<ide> $router->dispatch(Request::create('foo', 'GET'))->getContent();
<ide> public function testImplicitBindingsWithOptionalParameterWithNonExistingKeyInUri
<ide> {
<ide> $this->expectException(ModelNotFoundException::class);
<ide>
<del> $phpunit = $this;
<ide> $router = $this->getRouter();
<ide> $router->get('foo/{bar?}', [
<ide> 'middleware' => SubstituteBindings::class,
<del> 'uses' => function (RoutingTestNonExistingUserModel $bar = null) use ($phpunit) {
<del> $phpunit->fail('ModelNotFoundException was expected.');
<add> 'uses' => function (RoutingTestNonExistingUserModel $bar = null) {
<add> $this->fail('ModelNotFoundException was expected.');
<ide> },
<ide> ]);
<ide> $router->dispatch(Request::create('foo/nonexisting', 'GET'))->getContent();
<ide> }
<ide>
<ide> public function testImplicitBindingThroughIOC()
<ide> {
<del> $phpunit = $this;
<ide> $container = new Container;
<ide> $router = new Router(new Dispatcher, $container);
<ide> $container->singleton(Registrar::class, function () use ($router) {
<ide> public function testImplicitBindingThroughIOC()
<ide> $container->bind(RoutingTestUserModel::class, RoutingTestExtendedUserModel::class);
<ide> $router->get('foo/{bar}', [
<ide> 'middleware' => SubstituteBindings::class,
<del> 'uses' => function (RoutingTestUserModel $bar) use ($phpunit) {
<del> $phpunit->assertInstanceOf(RoutingTestExtendedUserModel::class, $bar);
<add> 'uses' => function (RoutingTestUserModel $bar) {
<add> $this->assertInstanceOf(RoutingTestExtendedUserModel::class, $bar);
<ide> },
<ide> ]);
<ide> $router->dispatch(Request::create('foo/baz', 'GET'))->getContent(); | 1 |
Java | Java | reject range starting above resource length | bc81fa520e2277b627b8fe9efcb28f3035778968 | <ide><path>spring-web/src/main/java/org/springframework/http/HttpRange.java
<ide> public ResourceRegion toResourceRegion(Resource resource) {
<ide> long contentLength = getLengthFor(resource);
<ide> long start = getRangeStart(contentLength);
<ide> long end = getRangeEnd(contentLength);
<add> Assert.isTrue(start < contentLength, "'position' exceeds the resource length " + contentLength);
<ide> return new ResourceRegion(resource, start, end - start + 1);
<ide> }
<ide>
<ide><path>spring-web/src/test/java/org/springframework/http/HttpRangeTests.java
<ide> public void toResourceRegionIllegalLength() {
<ide> ByteArrayResource resource = mock(ByteArrayResource.class);
<ide> given(resource.contentLength()).willReturn(-1L);
<ide> HttpRange range = HttpRange.createByteRange(0, 9);
<del> assertThatIllegalArgumentException().isThrownBy(() ->
<del> range.toResourceRegion(resource));
<add> assertThatIllegalArgumentException().isThrownBy(() -> range.toResourceRegion(resource));
<ide> }
<ide>
<ide> @Test
<ide> public void toResourceRegionExceptionLength() throws IOException {
<ide> InputStreamResource resource = mock(InputStreamResource.class);
<ide> given(resource.contentLength()).willThrow(IOException.class);
<ide> HttpRange range = HttpRange.createByteRange(0, 9);
<del> assertThatIllegalArgumentException().isThrownBy(() ->
<del> range.toResourceRegion(resource));
<add> assertThatIllegalArgumentException().isThrownBy(() -> range.toResourceRegion(resource));
<add> }
<add>
<add> @Test // gh-23576
<add> public void toResourceRegionStartingAtResourceByteCount() {
<add> byte[] bytes = "Spring Framework".getBytes(StandardCharsets.UTF_8);
<add> ByteArrayResource resource = new ByteArrayResource(bytes);
<add> HttpRange range = HttpRange.createByteRange(resource.contentLength());
<add> assertThatIllegalArgumentException().isThrownBy(() -> range.toResourceRegion(resource));
<ide> }
<ide>
<ide> @Test | 2 |
Text | Text | update ci requirements for landing pull requests | fbda84ef84010f7b456f526fb447b58a4d07cf7a | <ide><path>doc/guides/collaborator-guide.md
<ide> * [Consensus seeking](#consensus-seeking)
<ide> * [Waiting for approvals](#waiting-for-approvals)
<ide> * [Testing and CI](#testing-and-ci)
<del> * [Useful CI jobs](#useful-ci-jobs)
<del> * [Starting a CI job](#starting-a-ci-job)
<add> * [Useful Jenkins CI jobs](#useful-jenkins-ci-jobs)
<add> * [Starting a Jenkins CI job](#starting-a-jenkins-ci-job)
<ide> * [Internal vs. public API](#internal-vs-public-api)
<ide> * [Breaking changes](#breaking-changes)
<ide> * [Breaking changes and deprecations](#breaking-changes-and-deprecations)
<ide> the comment anyway to avoid any doubt.
<ide> All fixes must have a test case which demonstrates the defect. The test should
<ide> fail before the change, and pass after the change.
<ide>
<del>All pull requests must pass continuous integration tests. Code changes must pass
<del>on [project CI server](https://ci.nodejs.org/). Pull requests that only change
<del>documentation and comments can use GitHub Actions results.
<del>
<ide> Do not land any pull requests without a passing (green or yellow) CI run.
<del>For documentation-only changes, GitHub Actions CI is sufficient.
<del>For all other code changes, Jenkins CI must pass as well. If there are
<del>Jenkins CI failures unrelated to the change in the pull request, try "Resume
<del>Build". It is in the left navigation of the relevant `node-test-pull-request`
<del>job. It will preserve all the green results from the current job but re-run
<del>everything else. Start a fresh CI if more than seven days have elapsed since
<del>the original failing CI as the compiled binaries for the Windows and ARM
<del>platforms are only kept for seven days.
<add>A green GitHub Actions CI result is required. A passing
<add>[Jenkins CI](https://ci.nodejs.org/) is also required if PR contains changes
<add>that will affect the `node` binary. This is critical as GitHub Actions CI does
<add>not cover all the environments supported by Node.js.
<add>
<add><details>
<add><summary>Changes that affect the `node` binary</summary>
<add>
<add>Changes in the following folders (except comment-only changes) are guaranteed to
<add>affect the `node` binary:
<add>
<add>* `deps/`
<add>* `lib/`
<add>* `src/`
<add>* `test/`
<add>* `tools/code_cache/`
<add>* `tools/gyp/`
<add>* `tools/icu/`
<add>* `tools/inspector-protocol/`
<add>* `tools/msvs/`
<add>* `tools/snapshot/`
<add>* `tools/v8_gypfiles/`
<add>
<add>There are some other files that touch the build chain. Changes in the following
<add>files also qualify as affecting the `node` binary:
<add>
<add>* `tools/*.py`
<add>* `tools/build-addons.js`
<add>* `*.gyp`
<add>* `*.gypi`
<add>* `configure`
<add>* `configure.py`
<add>* `Makefile`
<add>* `vcbuilt.bat`
<add>
<add></details>
<add>
<add>If there are GitHub Actions CI failures unrelated to the change in the pull
<add>request, try "Re-run all jobs". It's under the "🔄 Re-run jobs" button, on the
<add>right-hand side of "Checks" tab.
<add>
<add>If there are Jenkins CI failures unrelated to the change in the pull request,
<add>try "Resume Build". It is in the left navigation of the relevant
<add>`node-test-pull-request` job. It will preserve all the green results from the
<add>current job but re-run everything else. Start a fresh CI if more than seven days
<add>have elapsed since the original failing CI as the compiled binaries for the
<add>Windows and ARM platforms are only kept for seven days.
<ide>
<del>#### Useful CI jobs
<add>#### Useful Jenkins CI jobs
<ide>
<ide> * [`node-test-pull-request`](https://ci.nodejs.org/job/node-test-pull-request/)
<ide> is the CI job to test pull requests. It runs the `build-ci` and `test-ci`
<ide> not used in other CI test runs (such as tests in the `internet` or `pummel`
<ide> directories). It can also make sure tests pass when provided with a flag not
<ide> used in other CI test runs (such as `--worker`).
<ide>
<del>#### Starting a CI job
<add>#### Starting a Jenkins CI job
<ide>
<ide> From the CI Job page, click "Build with Parameters" on the left side.
<ide> | 1 |
Text | Text | add `tox` note | d260f1ec15d5aa3085fa74118382bcf2fd752dca | <ide><path>docs/index.md
<ide> Run the tests:
<ide>
<ide> ./rest_framework/runtests/runtests.py
<ide>
<add>To run the tests against all supported configurations, first install [the tox testing tool][tox] globally, using `pip install tox`, then simply run `tox`:
<add>
<add> tox
<add>
<ide> ## Support
<ide>
<ide> For support please see the [REST framework discussion group][group], try the `#restframework` channel on `irc.freenode.net`, or raise a question on [Stack Overflow][stack-overflow], making sure to include the ['django-rest-framework'][django-rest-framework-tag] tag.
<ide> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
<ide> [release-notes]: topics/release-notes.md
<ide> [credits]: topics/credits.md
<ide>
<add>[tox]: http://testrun.org/tox/latest/
<add>
<ide> [group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
<ide> [stack-overflow]: http://stackoverflow.com/
<ide> [django-rest-framework-tag]: http://stackoverflow.com/questions/tagged/django-rest-framework | 1 |
PHP | PHP | add comment to better explain | f534db7388d3a7993daa8584e7d48e4961cb9119 | <ide><path>src/Mailer/Transport/SmtpTransport.php
<ide> protected function _smtpSend(?string $data, $checkCode = '250'): ?string
<ide> }
<ide> $response .= $bytes;
<ide> }
<add> // Catch empty or malformed responses.
<ide> if (substr($response, -2) !== "\r\n") {
<add> // Use response message or assume operation timed out.
<ide> throw new SocketException($response ?: 'SMTP timeout.');
<ide> }
<ide> $responseLines = explode("\r\n", rtrim($response, "\r\n")); | 1 |
PHP | PHP | fix fatal error when e_strict is enabled | 35e0984bec41b019b1a5e8da9877fe472103ff25 | <ide><path>lib/Cake/Core/Configure.php
<ide> public static function bootstrap($boot = true) {
<ide> self::$_values['Error'],
<ide> self::$_values['Exception']
<ide> );
<del> unset($error, $exception);
<add>
<add> // Preload Debugger + String in case of E_STRICT errors when loading files.
<add> if (self::$_values['debug'] > 0) {
<add> class_exists('Debugger');
<add> class_exists('String');
<add> }
<ide> }
<ide> }
<ide> | 1 |
PHP | PHP | change method visibility from public to protected | 5ab3f673990dd04ca0174eab299b6c65aa0372ce | <ide><path>src/Mailer/MailerAwareTrait.php
<ide> trait MailerAwareTrait
<ide> * @return \Cake\Mailer\Mailer
<ide> * @throws \Cake\Mailer\Exception\MissingMailerException if undefined mailer class.
<ide> */
<del> public function getMailer($name, Email $email = null)
<add> protected function getMailer($name, Email $email = null)
<ide> {
<ide> if ($email === null) {
<ide> $email = new Email();
<ide><path>src/View/CellTrait.php
<ide> trait CellTrait
<ide> * @throws \Cake\View\Exception\MissingCellException If Cell class was not found.
<ide> * @throws \BadMethodCallException If Cell class does not specified cell action.
<ide> */
<del> public function cell($cell, array $data = [], array $options = [])
<add> protected function cell($cell, array $data = [], array $options = [])
<ide> {
<ide> $parts = explode('::', $cell);
<ide>
<ide><path>src/View/View.php
<ide> class View implements EventDispatcherInterface
<ide> {
<ide>
<del> use CellTrait;
<add> use CellTrait {
<add> cell as public;
<add> }
<ide> use EventDispatcherTrait;
<ide> use LogTrait;
<ide> use RequestActionTrait;
<ide><path>tests/TestCase/Mailer/MailerAwareTraitTest.php
<ide> class Stub
<ide> {
<ide>
<del> use MailerAwareTrait;
<add> use MailerAwareTrait {
<add> getMailer as public;
<add> }
<ide> }
<ide>
<ide> /** | 4 |
Python | Python | add some benchmarks for `matmul` | e5b108c8f3fe5d60decb6a43b57c994909c8d3a8 | <ide><path>benchmarks/benchmarks/bench_linalg.py
<ide> def time_inner_trans_a_a(self):
<ide> def time_inner_trans_a_ac(self):
<ide> np.inner(self.a, self.ac)
<ide>
<add> def time_matmul_a_b(self):
<add> np.matmul(self.a, self.b)
<add>
<add> def time_matmul_d_matmul_b_c(self):
<add> np.matmul(self.d, np.matmul(self.b, self.c))
<add>
<add> def time_matmul_trans_a_at(self):
<add> np.matmul(self.a, self.at)
<add>
<add> def time_matmul_trans_a_atc(self):
<add> np.matmul(self.a, self.atc)
<add>
<add> def time_matmul_trans_at_a(self):
<add> np.matmul(self.at, self.a)
<add>
<add> def time_matmul_trans_atc_a(self):
<add> np.matmul(self.atc, self.a)
<add>
<ide> def time_tensordot_a_b_axes_1_0_0_1(self):
<ide> np.tensordot(self.a3, self.b3, axes=([1, 0], [0, 1]))
<ide> | 1 |
Java | Java | add action support | cbd9a3caa39e4829c393b851f41894552db0610d | <ide><path>rxjava-core/src/main/java/rx/subscriptions/BooleanSubscription.java
<ide>
<ide> import rx.Observable;
<ide> import rx.Subscription;
<add>import rx.util.functions.Action0;
<ide>
<ide> /**
<ide> * Subscription that can be checked for status such as in a loop inside an {@link Observable} to exit the loop if unsubscribed.
<ide> public class BooleanSubscription implements Subscription {
<ide>
<ide> private final AtomicBoolean unsubscribed = new AtomicBoolean(false);
<add> private final Action0 action;
<add>
<add> public BooleanSubscription() {
<add> action = null;
<add> }
<add>
<add> private BooleanSubscription(Action0 action) {
<add> this.action = action;
<add> }
<add>
<add> public static BooleanSubscription create() {
<add> return new BooleanSubscription();
<add> }
<add>
<add> public static BooleanSubscription create(Action0 onUnsubscribe) {
<add> return new BooleanSubscription(onUnsubscribe);
<add> }
<ide>
<ide> public boolean isUnsubscribed() {
<ide> return unsubscribed.get();
<ide> }
<ide>
<ide> @Override
<del> public void unsubscribe() {
<del> unsubscribed.set(true);
<add> public final void unsubscribe() {
<add> if (unsubscribed.compareAndSet(false, true)) {
<add> if (action != null) {
<add> action.call();
<add> }
<add> }
<ide> }
<ide>
<ide> } | 1 |
Go | Go | remove exported getter | 77ef3a606a228a688bb6a4108af7b34aa3a2aa65 | <ide><path>daemon/info.go
<ide> func (daemon *Daemon) showPluginsInfo() types.PluginsInfo {
<ide> pluginsInfo.Network = append(pluginsInfo.Network, nd)
<ide> }
<ide>
<del> pluginsInfo.Authorization = daemon.GetAuthorizationPluginsList()
<add> pluginsInfo.Authorization = daemon.configStore.AuthZPlugins
<ide>
<ide> return pluginsInfo
<ide> }
<ide>
<del>// GetAuthorizationPluginsList returns the list of plugins drivers
<del>// registered for authorization.
<del>func (daemon *Daemon) GetAuthorizationPluginsList() []string {
<del> return daemon.configStore.AuthZPlugins
<del>}
<del>
<ide> // The uppercase and the lowercase are available for the proxy settings.
<ide> // See the Go specification for details on these variables. https://golang.org/pkg/net/http/
<ide> func getProxyEnv(key string) string { | 1 |
Javascript | Javascript | remove dependence on es5 shams per | f95747b929d50227fe3fdf2a999b8fecc18cd21f | <ide><path>src/isomorphic/classic/element/ReactElement.js
<ide> var ReactElement = function(type, key, ref, self, source, owner, props) {
<ide> element._self = self;
<ide> element._source = source;
<ide> }
<del> Object.freeze(element.props);
<del> Object.freeze(element);
<add> if (Object.freeze) {
<add> Object.freeze(element.props);
<add> Object.freeze(element);
<add> }
<ide> }
<ide>
<ide> return element;
<ide><path>src/renderers/dom/ReactDOM.js
<ide> if (__DEV__) {
<ide> Object.keys,
<ide> String.prototype.split,
<ide> String.prototype.trim,
<del>
<del> // shams
<del> Object.create,
<del> Object.freeze,
<ide> ];
<ide>
<ide> for (var i = 0; i < expectedFeatures.length; i++) {
<ide> if (!expectedFeatures[i]) {
<ide> console.error(
<del> 'One or more ES5 shim/shams expected by React are not available: ' +
<add> 'One or more ES5 shims expected by React are not available: ' +
<ide> 'https://fb.me/react-warning-polyfills'
<ide> );
<ide> break;
<ide><path>src/renderers/dom/client/syntheticEvents/SyntheticEvent.js
<ide> SyntheticEvent.Interface = EventInterface;
<ide> SyntheticEvent.augmentClass = function(Class, Interface) {
<ide> var Super = this;
<ide>
<del> var prototype = Object.create(Super.prototype);
<add> var E = function () {};
<add> E.prototype = Super.prototype;
<add> var prototype = new E();
<add>
<ide> assign(prototype, Class.prototype);
<ide> Class.prototype = prototype;
<ide> Class.prototype.constructor = Class; | 3 |
Python | Python | run normal textcat train script with transformers | fbfc418745f3ce7ca807672f8b3afacdd199dbd2 | <ide><path>examples/training/pretrain_textcat.py
<ide> def train_textcat(nlp, n_texts, n_iter=10):
<ide> train_data = list(zip(train_texts, [{"cats": cats} for cats in train_cats]))
<ide>
<ide> # get names of other pipes to disable them during training
<del> other_pipes = [pipe for pipe in nlp.pipe_names if pipe != "textcat"]
<add> pipe_exceptions = ["textcat", "trf_wordpiecer", "trf_tok2vec"]
<add> other_pipes = [pipe for pipe in nlp.pipe_names if pipe not in pipe_exceptions]
<ide> with nlp.disable_pipes(*other_pipes): # only train textcat
<ide> optimizer = nlp.begin_training()
<ide> textcat.model.tok2vec.from_bytes(tok2vec_weights)
<ide><path>examples/training/rehearsal.py
<ide> def main(model_name, unlabelled_loc):
<ide> optimizer.b2 = 0.0
<ide>
<ide> # get names of other pipes to disable them during training
<del> other_pipes = [pipe for pipe in nlp.pipe_names if pipe != "ner"]
<add> pipe_exceptions = ["ner", "trf_wordpiecer", "trf_tok2vec"]
<add> other_pipes = [pipe for pipe in nlp.pipe_names if pipe not in pipe_exceptions]
<ide> sizes = compounding(1.0, 4.0, 1.001)
<ide> with nlp.disable_pipes(*other_pipes):
<ide> for itn in range(n_iter):
<ide><path>examples/training/train_entity_linker.py
<ide> def main(kb_path, vocab_path=None, output_dir=None, n_iter=50):
<ide> TRAIN_DOCS.append((doc, annotation_clean))
<ide>
<ide> # get names of other pipes to disable them during training
<del> other_pipes = [pipe for pipe in nlp.pipe_names if pipe != "entity_linker"]
<add> pipe_exceptions = ["entity_linker", "trf_wordpiecer", "trf_tok2vec"]
<add> other_pipes = [pipe for pipe in nlp.pipe_names if pipe not in pipe_exceptions]
<ide> with nlp.disable_pipes(*other_pipes): # only train entity linker
<ide> # reset and initialize the weights randomly
<ide> optimizer = nlp.begin_training()
<ide><path>examples/training/train_intent_parser.py
<ide> def main(model=None, output_dir=None, n_iter=15):
<ide> for dep in annotations.get("deps", []):
<ide> parser.add_label(dep)
<ide>
<del> other_pipes = [pipe for pipe in nlp.pipe_names if pipe != "parser"]
<add> pipe_exceptions = ["parser", "trf_wordpiecer", "trf_tok2vec"]
<add> other_pipes = [pipe for pipe in nlp.pipe_names if pipe not in pipe_exceptions]
<ide> with nlp.disable_pipes(*other_pipes): # only train parser
<ide> optimizer = nlp.begin_training()
<ide> for itn in range(n_iter):
<ide><path>examples/training/train_ner.py
<ide> def main(model=None, output_dir=None, n_iter=100):
<ide> ner.add_label(ent[2])
<ide>
<ide> # get names of other pipes to disable them during training
<del> other_pipes = [pipe for pipe in nlp.pipe_names if pipe != "ner"]
<add> pipe_exceptions = ["ner", "trf_wordpiecer", "trf_tok2vec"]
<add> other_pipes = [pipe for pipe in nlp.pipe_names if pipe not in pipe_exceptions]
<ide> with nlp.disable_pipes(*other_pipes): # only train NER
<ide> # reset and initialize the weights randomly – but only if we're
<ide> # training a new model
<ide><path>examples/training/train_new_entity_type.py
<ide> def main(model=None, new_model_name="animal", output_dir=None, n_iter=30):
<ide> optimizer = nlp.resume_training()
<ide> move_names = list(ner.move_names)
<ide> # get names of other pipes to disable them during training
<del> other_pipes = [pipe for pipe in nlp.pipe_names if pipe != "ner"]
<add> pipe_exceptions = ["ner", "trf_wordpiecer", "trf_tok2vec"]
<add> other_pipes = [pipe for pipe in nlp.pipe_names if pipe not in pipe_exceptions]
<ide> with nlp.disable_pipes(*other_pipes): # only train NER
<ide> sizes = compounding(1.0, 4.0, 1.001)
<ide> # batch up the examples using spaCy's minibatch
<ide><path>examples/training/train_parser.py
<ide> def main(model=None, output_dir=None, n_iter=15):
<ide> parser.add_label(dep)
<ide>
<ide> # get names of other pipes to disable them during training
<del> other_pipes = [pipe for pipe in nlp.pipe_names if pipe != "parser"]
<add> pipe_exceptions = ["parser", "trf_wordpiecer", "trf_tok2vec"]
<add> other_pipes = [pipe for pipe in nlp.pipe_names if pipe not in pipe_exceptions]
<ide> with nlp.disable_pipes(*other_pipes): # only train parser
<ide> optimizer = nlp.begin_training()
<ide> for itn in range(n_iter):
<ide><path>examples/training/train_textcat.py
<ide> def main(model=None, output_dir=None, n_iter=20, n_texts=2000, init_tok2vec=None
<ide> train_data = list(zip(train_texts, [{"cats": cats} for cats in train_cats]))
<ide>
<ide> # get names of other pipes to disable them during training
<del> other_pipes = [pipe for pipe in nlp.pipe_names if pipe != "textcat"]
<add> pipe_exceptions = ["textcat", "trf_wordpiecer", "trf_tok2vec"]
<add> other_pipes = [pipe for pipe in nlp.pipe_names if pipe not in pipe_exceptions]
<ide> with nlp.disable_pipes(*other_pipes): # only train textcat
<ide> optimizer = nlp.begin_training()
<ide> if init_tok2vec is not None: | 8 |
Text | Text | fix merge conflict in action cable guide [ci skip] | 4213825a9ac5111660a7818fff283b9ad659f044 | <ide><path>guides/source/action_cable_overview.md
<ide> You can change that in `config/database.yml` through the `pool` attribute.
<ide>
<ide> ## Running standalone cable servers
<ide>
<del><<<<<<< HEAD
<ide> ### In App
<ide>
<ide> Action Cable can run alongside your Rails application. For example, to
<ide> your server spawns, you will also have a new instance of ActionCable,
<ide> but the use of Redis keeps messages synced across connections.
<ide>
<ide> ### Standalone
<del>The cable server(s) can be separated from your normal application server.
<del>=======
<del>The cable servers can be separated from your normal application server.
<del>>>>>>>> Further cleanup of the cable guide
<add>
<add>The cable servers can be separated from your normal application server.
<ide> It's still a Rack application, but it is its own Rack application.
<ide> The recommended basic setup is as follows:
<ide> | 1 |
Ruby | Ruby | fix hash equality | fe3e802c500935f74d403dd7e7f0f740f89d44ba | <ide><path>Library/Homebrew/requirements/x11_dependency.rb
<ide> def <=> other
<ide> return unless X11Dependency === other
<ide> min_version <=> other.min_version
<ide> end
<add>
<add> def eql?(other)
<add> super && min_version == other.min_version
<add> end
<ide> end
<ide><path>Library/Homebrew/test/test_x11_dependency.rb
<ide> def test_not_eql_when_hashes_differ
<ide> assert !y.eql?(x)
<ide> end
<ide>
<add> def test_different_min_version
<add> x = X11Dependency.new
<add> y = X11Dependency.new("x11", %w[2.5])
<add> refute x.eql?(y)
<add> refute y.eql?(x)
<add> end
<add>
<ide> def test_x_env
<ide> x = X11Dependency.new
<ide> x.stubs(:satisfied?).returns(true) | 2 |
Python | Python | fix casing inconsistency | 6d9e820ae674a2388303eedc760602ccbeada147 | <ide><path>libcloud/loadbalancer/drivers/dimensiondata.py
<ide> def ex_create_virtual_listener(self,
<ide> ex_description,
<ide> port,
<ide> pool,
<del> listenerIpAddress=None,
<add> listener_ip_address=None,
<ide> persistence_profile=None,
<ide> fallback_persistence_profile=None,
<ide> irule=None,
<ide> def ex_create_virtual_listener(self,
<ide> :param pool: The pool to use for the listener
<ide> :type pool: :class:`DimensionDataPool`
<ide>
<del> :param listenerIpAddress: The IPv4 Address of the virtual listener
<del> :type listenerIpaddress: ``str``
<add> :param listener_ip_address: The IPv4 Address of the virtual listener
<add> :type listener_ip_address: ``str``
<ide>
<ide> :param persistence_profile: Persistence profile
<ide> :type persistence_profile: :class:`DimensionDataPersistenceProfile`
<ide> def ex_create_virtual_listener(self,
<ide> ET.SubElement(create_node_elm, "type").text = listener_type
<ide> ET.SubElement(create_node_elm, "protocol") \
<ide> .text = protocol
<del> if listenerIpAddress is not None:
<add> if listener_ip_address is not None:
<ide> ET.SubElement(create_node_elm, "listenerIpAddress").text = \
<del> str(listenerIpAddress)
<add> str(listener_ip_address)
<ide> ET.SubElement(create_node_elm, "port").text = str(port)
<ide> ET.SubElement(create_node_elm, "enabled").text = 'true'
<ide> ET.SubElement(create_node_elm, "connectionLimit") \ | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.