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 |
|---|---|---|---|---|---|
PHP | PHP | remove old drivers | 104e138f4dd65e9cd0d4cc6fc6c3f6d5327880af | <ide><path>src/Illuminate/Cache/CacheManager.php
<ide> protected function createNullDriver()
<ide> return $this->repository(new NullStore);
<ide> }
<ide>
<del> /**
<del> * Create an instance of the WinCache cache driver.
<del> *
<del> * @param array $config
<del> * @return \Illuminate\Cache\WinCacheStore
<del> */
<del> protected function createWincacheDriver(array $config)
<del> {
<del> return $this->repository(new WinCacheStore($this->getPrefix($config)));
<del> }
<del>
<del> /**
<del> * Create an instance of the XCache cache driver.
<del> *
<del> * @param array $config
<del> * @return \Illuminate\Cache\WinCacheStore
<del> */
<del> protected function createXcacheDriver(array $config)
<del> {
<del> return $this->repository(new XCacheStore($this->getPrefix($config)));
<del> }
<del>
<ide> /**
<ide> * Create an instance of the Redis cache driver.
<ide> * | 1 |
Javascript | Javascript | add taxfyle to showcase.js (apple "best new app") | d6042cbf2431075b2eaa697dd0c45629a2d8fe6f | <ide><path>website/src/react-native/showcase.js
<ide> var featured = [
<ide> link: 'https://itunes.apple.com/us/app/start-medication-manager-for/id1012099928?mt=8',
<ide> author: 'Iodine Inc.',
<ide> },
<add> {
<add> name: 'Taxfyle - taxes filed on-demand via licensed CPA',
<add> icon: 'https://s3.amazonaws.com/taxfyle-public/images/taxfyle-icon-1024px.png',
<add> link: 'https://itunes.apple.com/us/app/taxfyle/id1058033104?mt=8',
<add> author: 'Taxfyle',
<add> },
<ide> {
<ide> name: 'This AM',
<ide> icon: 'http://s3.r29static.com//bin/public/efe/x/1542038/image.png', | 1 |
Ruby | Ruby | fix documentation of pathname#existence | 223ba6f81de671b11ad3b26728b299ebcc0971b6 | <ide><path>activesupport/lib/active_support/core_ext/pathname/existence.rb
<ide> class Pathname
<ide> # Returns the receiver if the named file exists otherwise returns +nil+.
<ide> # <tt>pathname.existence</tt> is equivalent to
<ide> #
<del> # pathname.existence? ? object : nil
<add> # pathname.exists? ? object : nil
<ide> #
<ide> # For example, something like
<ide> # | 1 |
Python | Python | fix some typing imports | 8ca96b2c949d23dd9fbfc7896845aa79dd2f0181 | <ide><path>numpy/_array_api/_array_object.py
<ide> from ._creation_functions import asarray
<ide> from ._dtypes import _boolean_dtypes, _integer_dtypes, _floating_dtypes
<ide>
<del>from typing import TYPE_CHECKING
<add>from typing import TYPE_CHECKING, Any, Optional, Tuple, Union
<ide> if TYPE_CHECKING:
<del> from ._typing import Any, Optional, PyCapsule, Tuple, Union, Device, Dtype
<add> from ._typing import PyCapsule, Device, Dtype
<ide>
<ide> import numpy as np
<ide>
<ide><path>numpy/_array_api/_creation_functions.py
<ide>
<ide> from typing import TYPE_CHECKING, List, Optional, Tuple, Union
<ide> if TYPE_CHECKING:
<del> from ._typing import (NestedSequence, SupportsDLPack,
<del> SupportsBufferProtocol, Array, Device, Dtype)
<add> from ._typing import (Array, Device, Dtype, NestedSequence,
<add> SupportsDLPack, SupportsBufferProtocol)
<ide> from collections.abc import Sequence
<ide> from ._dtypes import _all_dtypes
<ide>
<ide><path>numpy/_array_api/_data_type_functions.py
<ide> from ._array_object import Array
<ide>
<ide> from dataclasses import dataclass
<del>from typing import TYPE_CHECKING
<add>from typing import TYPE_CHECKING, List, Tuple, Union
<ide> if TYPE_CHECKING:
<del> from ._typing import List, Tuple, Union, Dtype
<add> from ._typing import Dtype
<ide> from collections.abc import Sequence
<ide>
<ide> import numpy as np
<ide><path>numpy/_array_api/_searching_functions.py
<ide>
<ide> from ._array_object import Array
<ide>
<del>from typing import TYPE_CHECKING
<del>if TYPE_CHECKING:
<del> from ._typing import Tuple
<add>from typing import Optional, Tuple
<ide>
<ide> import numpy as np
<ide>
<ide><path>numpy/_array_api/_set_functions.py
<ide>
<ide> from ._array_object import Array
<ide>
<del>from typing import TYPE_CHECKING
<del>if TYPE_CHECKING:
<del> from ._typing import Tuple, Union
<add>from typing import Tuple, Union
<ide>
<ide> import numpy as np
<ide>
<ide><path>numpy/_array_api/_statistical_functions.py
<ide>
<ide> from ._array_object import Array
<ide>
<del>from typing import TYPE_CHECKING
<del>if TYPE_CHECKING:
<del> from ._typing import Optional, Tuple, Union
<add>from typing import Optional, Tuple, Union
<ide>
<ide> import numpy as np
<ide>
<ide><path>numpy/_array_api/_utility_functions.py
<ide>
<ide> from ._array_object import Array
<ide>
<del>from typing import TYPE_CHECKING
<del>if TYPE_CHECKING:
<del> from ._typing import Optional, Tuple, Union
<add>from typing import Optional, Tuple, Union
<ide>
<ide> import numpy as np
<ide> | 7 |
Python | Python | update extra_kwargs on model serializer | af08c7024299e837a4b52edfd03f0d675f453a47 | <ide><path>rest_framework/serializers.py
<ide> def include_extra_kwargs(self, kwargs, extra_kwargs):
<ide> if extra_kwargs.get('default') and kwargs.get('required') is False:
<ide> kwargs.pop('required')
<ide>
<del> if kwargs.get('read_only', False):
<del> extra_kwargs.pop('required', None)
<add> if extra_kwargs.get('read_only', kwargs.get('read_only', False)):
<add> extra_kwargs.pop('required', None) # Read only fields should always omit the 'required' argument.
<ide>
<ide> kwargs.update(extra_kwargs)
<ide>
<ide><path>tests/test_model_serializer.py
<ide> class Meta:
<ide> """)
<ide> self.assertEqual(repr(TestSerializer()), expected)
<ide>
<add> def test_extra_field_kwargs_required(self):
<add> """
<add> Ensure `extra_kwargs` are passed to generated fields.
<add> """
<add> class TestSerializer(serializers.ModelSerializer):
<add> class Meta:
<add> model = RegularFieldsModel
<add> fields = ('auto_field', 'char_field')
<add> extra_kwargs = {'auto_field': {'required': False, 'read_only': False}}
<add>
<add> expected = dedent("""
<add> TestSerializer():
<add> auto_field = IntegerField(read_only=False, required=False)
<add> char_field = CharField(max_length=100)
<add> """)
<add> self.assertEqual(repr(TestSerializer()), expected)
<add>
<ide> def test_invalid_field(self):
<ide> """
<ide> Field names that do not map to a model field or relationship should | 2 |
Python | Python | fix a typo | 3e3bcade231f27a4e1ac3755e2279475009a39cf | <ide><path>libcloud/compute/base.py
<ide> def __init__(self, id, name, state, public_ips, private_ips,
<ide> :param image: Image of this node. (optional)
<ide> :type size: :class:`.NodeImage:
<ide>
<del> :param extra: Optional provided specific attributes associated with
<add> :param extra: Optional provider specific attributes associated with
<ide> this node.
<ide> :type extra: ``dict``
<ide> | 1 |
PHP | PHP | finish doc blocks | b865abfea9803978f5da51ae42b4fa8b09e3686f | <ide><path>src/Illuminate/Database/Eloquent/Factories/BelongsToManyRelationship.php
<ide>
<ide> class BelongsToManyRelationship
<ide> {
<add> /**
<add> * The related factory instance.
<add> *
<add> * @var \Illuminate\Database\Eloquent\Factories\Factory
<add> */
<ide> protected $factory;
<ide>
<ide> /**
<ide> class BelongsToManyRelationship
<ide> */
<ide> protected $relationship;
<ide>
<add> /**
<add> * Create a new attached relationship definition.
<add> *
<add> * @param \Illuminate\Database\Eloquent\Factories\Factory $factory
<add> * @param callable\array $pivot
<add> * @param string $relationship
<add> * @return void
<add> */
<ide> public function __construct(Factory $factory, $pivot, $relationship)
<ide> {
<ide> $this->factory = $factory;
<ide><path>src/Illuminate/Database/Eloquent/Factories/BelongsToRelationship.php
<ide>
<ide> class BelongsToRelationship
<ide> {
<add> /**
<add> * The related factory instance.
<add> *
<add> * @var \Illuminate\Database\Eloquent\Factories\Factory
<add> */
<ide> protected $factory;
<ide>
<ide> /**
<ide> class BelongsToRelationship
<ide> */
<ide> protected $resolved;
<ide>
<add> /**
<add> * Create a new "belongs to" relationship definition.
<add> *
<add> * @param \Illuminate\Database\Eloquent\Factories\Factory $factory
<add> * @param string $relationship
<add> * @return void
<add> */
<ide> public function __construct(Factory $factory, $relationship)
<ide> {
<ide> $this->factory = $factory;
<ide><path>src/Illuminate/Database/Eloquent/Factories/Factory.php
<ide> public function sequence(...$sequence)
<ide> return $this->state(new Sequence(...$sequence));
<ide> }
<ide>
<add> /**
<add> * Define a child relationship for the model.
<add> *
<add> * @param \Illuminate\Database\Eloquent\Factories\Factory $factory
<add> * @param string|null $relationship
<add> * @return static
<add> */
<ide> public function has(Factory $factory, $relationship = null)
<ide> {
<ide> return $this->newInstance([
<ide> public function has(Factory $factory, $relationship = null)
<ide> ]);
<ide> }
<ide>
<add> /**
<add> * Define an attached relationship for the model.
<add> *
<add> * @param \Illuminate\Database\Eloquent\Factories\Factory $factory
<add> * @param callable|array $pivot
<add> * @param string|null $relationship
<add> * @return static
<add> */
<ide> public function hasAttached(Factory $factory, $pivot = [], $relationship = null)
<ide> {
<ide> return $this->newInstance([
<ide> public function hasAttached(Factory $factory, $pivot = [], $relationship = null)
<ide> ]);
<ide> }
<ide>
<add> /**
<add> * Define a parent relationship for the model.
<add> *
<add> * @param \Illuminate\Database\Eloquent\Factories\Factory $factory
<add> * @param string|null $relationship
<add> * @return static
<add> */
<ide> public function for(Factory $factory, $relationship = null)
<ide> {
<ide> return $this->newInstance(['for' => $this->for->concat([new BelongsToRelationship(
<ide><path>src/Illuminate/Database/Eloquent/Factories/Relationship.php
<ide>
<ide> class Relationship
<ide> {
<add> /**
<add> * The related factory instance.
<add> *
<add> * @var \Illuminate\Database\Eloquent\Factories\Factory
<add> */
<ide> protected $factory;
<ide>
<ide> /**
<ide> class Relationship
<ide> */
<ide> protected $relationship;
<ide>
<add> /**
<add> * Create a new child relationship instance.
<add> *
<add> * @param \Illuminate\Database\Eloquent\Factories\Factory $factory
<add> * @param string $relationship
<add> * @return void
<add> */
<ide> public function __construct(Factory $factory, $relationship)
<ide> {
<ide> $this->factory = $factory; | 4 |
Python | Python | drop radix benchmark as it is not included yet | 86565347e523951a7bc54658f0b06a258ae2e0a0 | <ide><path>benchmarks/benchmarks/bench_function_base.py
<ide> def time_select_larger(self):
<ide>
<ide> class Sort(Benchmark):
<ide> params = [
<del> ['quick', 'merge', 'heap', 'radix', None],
<add> ['quick', 'merge', 'heap', None],
<ide> ['float32', 'int32', 'uint32']
<ide> ]
<ide> param_names = ['kind', 'dtype'] | 1 |
Go | Go | remove meaningless warnings on docker info | 615681f5177cef974d516d5814195c768e773dd2 | <ide><path>api/client/attach.go
<ide> func (cli *DockerCli) CmdAttach(args ...string) error {
<ide>
<ide> cmd.ParseFlags(args, true)
<ide>
<del> stream, _, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, nil)
<add> serverResp, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, nil)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> defer stream.Close()
<add> defer serverResp.body.Close()
<ide>
<ide> var c types.ContainerJSON
<del> if err := json.NewDecoder(stream).Decode(&c); err != nil {
<add> if err := json.NewDecoder(serverResp.body).Decode(&c); err != nil {
<ide> return err
<ide> }
<ide>
<ide><path>api/client/commit.go
<ide> func (cli *DockerCli) CmdCommit(args ...string) error {
<ide> return err
<ide> }
<ide> }
<del> stream, _, _, err := cli.call("POST", "/commit?"+v.Encode(), config, nil)
<add> serverResp, err := cli.call("POST", "/commit?"+v.Encode(), config, nil)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> defer stream.Close()
<add> defer serverResp.body.Close()
<ide>
<del> if err := json.NewDecoder(stream).Decode(&response); err != nil {
<add> if err := json.NewDecoder(serverResp.body).Decode(&response); err != nil {
<ide> return err
<ide> }
<ide>
<ide><path>api/client/cp.go
<ide> func (cli *DockerCli) CmdCp(args ...string) error {
<ide> cfg := &types.CopyConfig{
<ide> Resource: info[1],
<ide> }
<del> stream, _, statusCode, err := cli.call("POST", "/containers/"+info[0]+"/copy", cfg, nil)
<del> if stream != nil {
<del> defer stream.Close()
<add> serverResp, err := cli.call("POST", "/containers/"+info[0]+"/copy", cfg, nil)
<add> if serverResp.body != nil {
<add> defer serverResp.body.Close()
<ide> }
<del> if statusCode == 404 {
<add> if serverResp.statusCode == 404 {
<ide> return fmt.Errorf("No such container: %v", info[0])
<ide> }
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<ide> hostPath := cmd.Arg(1)
<del> if statusCode == 200 {
<add> if serverResp.statusCode == 200 {
<ide> if hostPath == "-" {
<del> _, err = io.Copy(cli.out, stream)
<add> _, err = io.Copy(cli.out, serverResp.body)
<ide> } else {
<del> err = archive.Untar(stream, hostPath, &archive.TarOptions{NoLchown: true})
<add> err = archive.Untar(serverResp.body, hostPath, &archive.TarOptions{NoLchown: true})
<ide> }
<ide> if err != nil {
<ide> return err
<ide><path>api/client/create.go
<ide> func (cli *DockerCli) createContainer(config *runconfig.Config, hostConfig *runc
<ide> }
<ide>
<ide> //create the container
<del> stream, _, statusCode, err := cli.call("POST", "/containers/create?"+containerValues.Encode(), mergedConfig, nil)
<add> serverResp, err := cli.call("POST", "/containers/create?"+containerValues.Encode(), mergedConfig, nil)
<ide> //if image not found try to pull it
<del> if statusCode == 404 && strings.Contains(err.Error(), config.Image) {
<add> if serverResp.statusCode == 404 && strings.Contains(err.Error(), config.Image) {
<ide> repo, tag := parsers.ParseRepositoryTag(config.Image)
<ide> if tag == "" {
<ide> tag = tags.DEFAULTTAG
<ide> func (cli *DockerCli) createContainer(config *runconfig.Config, hostConfig *runc
<ide> return nil, err
<ide> }
<ide> // Retry
<del> if stream, _, _, err = cli.call("POST", "/containers/create?"+containerValues.Encode(), mergedConfig, nil); err != nil {
<add> if serverResp, err = cli.call("POST", "/containers/create?"+containerValues.Encode(), mergedConfig, nil); err != nil {
<ide> return nil, err
<ide> }
<ide> } else if err != nil {
<ide> return nil, err
<ide> }
<ide>
<del> defer stream.Close()
<add> defer serverResp.body.Close()
<ide>
<ide> var response types.ContainerCreateResponse
<del> if err := json.NewDecoder(stream).Decode(&response); err != nil {
<add> if err := json.NewDecoder(serverResp.body).Decode(&response); err != nil {
<ide> return nil, err
<ide> }
<ide> for _, warning := range response.Warnings {
<ide><path>api/client/diff.go
<ide> func (cli *DockerCli) CmdDiff(args ...string) error {
<ide> return fmt.Errorf("Container name cannot be empty")
<ide> }
<ide>
<del> rdr, _, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil, nil)
<add> serverResp, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil, nil)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> defer rdr.Close()
<add> defer serverResp.body.Close()
<ide>
<ide> changes := []types.ContainerChange{}
<del> if err := json.NewDecoder(rdr).Decode(&changes); err != nil {
<add> if err := json.NewDecoder(serverResp.body).Decode(&changes); err != nil {
<ide> return err
<ide> }
<ide>
<ide><path>api/client/exec.go
<ide> func (cli *DockerCli) CmdExec(args ...string) error {
<ide> return StatusError{StatusCode: 1}
<ide> }
<ide>
<del> stream, _, _, err := cli.call("POST", "/containers/"+execConfig.Container+"/exec", execConfig, nil)
<add> serverResp, err := cli.call("POST", "/containers/"+execConfig.Container+"/exec", execConfig, nil)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> defer stream.Close()
<add> defer serverResp.body.Close()
<ide>
<ide> var response types.ContainerExecCreateResponse
<del> if err := json.NewDecoder(stream).Decode(&response); err != nil {
<add> if err := json.NewDecoder(serverResp.body).Decode(&response); err != nil {
<ide> return err
<ide> }
<ide>
<ide><path>api/client/history.go
<ide> func (cli *DockerCli) CmdHistory(args ...string) error {
<ide>
<ide> cmd.ParseFlags(args, true)
<ide>
<del> rdr, _, _, err := cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil, nil)
<add> serverResp, err := cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil, nil)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> defer rdr.Close()
<add> defer serverResp.body.Close()
<ide>
<ide> history := []types.ImageHistory{}
<del> if err := json.NewDecoder(rdr).Decode(&history); err != nil {
<add> if err := json.NewDecoder(serverResp.body).Decode(&history); err != nil {
<ide> return err
<ide> }
<ide>
<ide><path>api/client/images.go
<ide> func (cli *DockerCli) CmdImages(args ...string) error {
<ide> v.Set("all", "1")
<ide> }
<ide>
<del> rdr, _, _, err := cli.call("GET", "/images/json?"+v.Encode(), nil, nil)
<add> serverResp, err := cli.call("GET", "/images/json?"+v.Encode(), nil, nil)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> defer rdr.Close()
<add> defer serverResp.body.Close()
<ide>
<ide> images := []types.Image{}
<del> if err := json.NewDecoder(rdr).Decode(&images); err != nil {
<add> if err := json.NewDecoder(serverResp.body).Decode(&images); err != nil {
<ide> return err
<ide> }
<ide>
<ide><path>api/client/info.go
<ide> import (
<ide> "fmt"
<ide>
<ide> "github.com/docker/docker/api/types"
<add> "github.com/docker/docker/pkg/httputils"
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> "github.com/docker/docker/pkg/units"
<ide> func (cli *DockerCli) CmdInfo(args ...string) error {
<ide>
<ide> cmd.ParseFlags(args, true)
<ide>
<del> rdr, _, _, err := cli.call("GET", "/info", nil, nil)
<add> serverResp, err := cli.call("GET", "/info", nil, nil)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> defer rdr.Close()
<add> defer serverResp.body.Close()
<ide>
<ide> info := &types.Info{}
<del> if err := json.NewDecoder(rdr).Decode(info); err != nil {
<add> if err := json.NewDecoder(serverResp.body).Decode(info); err != nil {
<ide> return fmt.Errorf("Error reading remote info: %v", err)
<ide> }
<ide>
<ide> func (cli *DockerCli) CmdInfo(args ...string) error {
<ide> fmt.Fprintf(cli.out, "Registry: %v\n", info.IndexServerAddress)
<ide> }
<ide> }
<del> if !info.MemoryLimit {
<del> fmt.Fprintf(cli.err, "WARNING: No memory limit support\n")
<del> }
<del> if !info.SwapLimit {
<del> fmt.Fprintf(cli.err, "WARNING: No swap limit support\n")
<del> }
<del> if !info.IPv4Forwarding {
<del> fmt.Fprintf(cli.err, "WARNING: IPv4 forwarding is disabled.\n")
<del> }
<del> if !info.BridgeNfIptables {
<del> fmt.Fprintf(cli.err, "WARNING: bridge-nf-call-iptables is disabled\n")
<del> }
<del> if !info.BridgeNfIp6tables {
<del> fmt.Fprintf(cli.err, "WARNING: bridge-nf-call-ip6tables is disabled\n")
<add> // Only output these warnings if the server supports these features
<add> if h, err := httputils.ParseServerHeader(serverResp.header.Get("Server")); err == nil {
<add> if h.OS != "windows" {
<add> if !info.MemoryLimit {
<add> fmt.Fprintf(cli.err, "WARNING: No memory limit support\n")
<add> }
<add> if !info.SwapLimit {
<add> fmt.Fprintf(cli.err, "WARNING: No swap limit support\n")
<add> }
<add> if !info.IPv4Forwarding {
<add> fmt.Fprintf(cli.err, "WARNING: IPv4 forwarding is disabled.\n")
<add> }
<add> if !info.BridgeNfIptables {
<add> fmt.Fprintf(cli.err, "WARNING: bridge-nf-call-iptables is disabled\n")
<add> }
<add> if !info.BridgeNfIp6tables {
<add> fmt.Fprintf(cli.err, "WARNING: bridge-nf-call-ip6tables is disabled\n")
<add> }
<add> }
<ide> }
<add>
<ide> if info.Labels != nil {
<ide> fmt.Fprintln(cli.out, "Labels:")
<ide> for _, attribute := range info.Labels {
<ide><path>api/client/login.go
<ide> func (cli *DockerCli) CmdLogin(args ...string) error {
<ide> authconfig.ServerAddress = serverAddress
<ide> cli.configFile.AuthConfigs[serverAddress] = authconfig
<ide>
<del> stream, _, statusCode, err := cli.call("POST", "/auth", cli.configFile.AuthConfigs[serverAddress], nil)
<del> if statusCode == 401 {
<add> serverResp, err := cli.call("POST", "/auth", cli.configFile.AuthConfigs[serverAddress], nil)
<add> if serverResp.statusCode == 401 {
<ide> delete(cli.configFile.AuthConfigs, serverAddress)
<ide> if err2 := cli.configFile.Save(); err2 != nil {
<ide> fmt.Fprintf(cli.out, "WARNING: could not save config file: %v\n", err2)
<ide> func (cli *DockerCli) CmdLogin(args ...string) error {
<ide> return err
<ide> }
<ide>
<del> defer stream.Close()
<add> defer serverResp.body.Close()
<ide>
<ide> var response types.AuthResponse
<del> if err := json.NewDecoder(stream).Decode(&response); err != nil {
<add> if err := json.NewDecoder(serverResp.body).Decode(&response); err != nil {
<ide> // Upon error, remove entry
<ide> delete(cli.configFile.AuthConfigs, serverAddress)
<ide> return err
<ide><path>api/client/logs.go
<ide> func (cli *DockerCli) CmdLogs(args ...string) error {
<ide>
<ide> name := cmd.Arg(0)
<ide>
<del> stream, _, _, err := cli.call("GET", "/containers/"+name+"/json", nil, nil)
<add> serverResp, err := cli.call("GET", "/containers/"+name+"/json", nil, nil)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<ide> var c types.ContainerJSON
<del> if err := json.NewDecoder(stream).Decode(&c); err != nil {
<add> if err := json.NewDecoder(serverResp.body).Decode(&c); err != nil {
<ide> return err
<ide> }
<ide>
<ide><path>api/client/network.go
<ide> import (
<ide> )
<ide>
<ide> func (cli *DockerCli) CmdNetwork(args ...string) error {
<del> nCli := nwclient.NewNetworkCli(cli.out, cli.err, nwclient.CallFunc(cli.call))
<add> nCli := nwclient.NewNetworkCli(cli.out, cli.err, nwclient.CallFunc(cli.callWrapper))
<ide> args = append([]string{"network"}, args...)
<ide> return nCli.Cmd(os.Args[0], args...)
<ide> }
<ide><path>api/client/port.go
<ide> func (cli *DockerCli) CmdPort(args ...string) error {
<ide>
<ide> cmd.ParseFlags(args, true)
<ide>
<del> stream, _, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, nil)
<add> serverResp, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, nil)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> defer stream.Close()
<add> defer serverResp.body.Close()
<ide>
<ide> var c struct {
<ide> NetworkSettings struct {
<ide> Ports nat.PortMap
<ide> }
<ide> }
<ide>
<del> if err := json.NewDecoder(stream).Decode(&c); err != nil {
<add> if err := json.NewDecoder(serverResp.body).Decode(&c); err != nil {
<ide> return err
<ide> }
<ide>
<ide><path>api/client/ps.go
<ide> func (cli *DockerCli) CmdPs(args ...string) error {
<ide> v.Set("filters", filterJSON)
<ide> }
<ide>
<del> rdr, _, _, err := cli.call("GET", "/containers/json?"+v.Encode(), nil, nil)
<add> serverResp, err := cli.call("GET", "/containers/json?"+v.Encode(), nil, nil)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> defer rdr.Close()
<add> defer serverResp.body.Close()
<ide>
<ide> containers := []types.Container{}
<del> if err := json.NewDecoder(rdr).Decode(&containers); err != nil {
<add> if err := json.NewDecoder(serverResp.body).Decode(&containers); err != nil {
<ide> return err
<ide> }
<ide>
<ide><path>api/client/rmi.go
<ide> func (cli *DockerCli) CmdRmi(args ...string) error {
<ide>
<ide> var errNames []string
<ide> for _, name := range cmd.Args() {
<del> rdr, _, _, err := cli.call("DELETE", "/images/"+name+"?"+v.Encode(), nil, nil)
<add> serverResp, err := cli.call("DELETE", "/images/"+name+"?"+v.Encode(), nil, nil)
<ide> if err != nil {
<ide> fmt.Fprintf(cli.err, "%s\n", err)
<ide> errNames = append(errNames, name)
<ide> } else {
<del> defer rdr.Close()
<add> defer serverResp.body.Close()
<ide>
<ide> dels := []types.ImageDelete{}
<del> if err := json.NewDecoder(rdr).Decode(&dels); err != nil {
<add> if err := json.NewDecoder(serverResp.body).Decode(&dels); err != nil {
<ide> fmt.Fprintf(cli.err, "%s\n", err)
<ide> errNames = append(errNames, name)
<ide> continue
<ide><path>api/client/service.go
<ide> import (
<ide> )
<ide>
<ide> func (cli *DockerCli) CmdService(args ...string) error {
<del> nCli := nwclient.NewNetworkCli(cli.out, cli.err, nwclient.CallFunc(cli.call))
<add> nCli := nwclient.NewNetworkCli(cli.out, cli.err, nwclient.CallFunc(cli.callWrapper))
<ide> args = append([]string{"service"}, args...)
<ide> return nCli.Cmd(os.Args[0], args...)
<ide> }
<ide><path>api/client/start.go
<ide> func (cli *DockerCli) CmdStart(args ...string) error {
<ide> return fmt.Errorf("You cannot start and attach multiple containers at once.")
<ide> }
<ide>
<del> stream, _, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, nil)
<add> serverResp, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, nil)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> defer stream.Close()
<add> defer serverResp.body.Close()
<ide>
<ide> var c types.ContainerJSON
<del> if err := json.NewDecoder(stream).Decode(&c); err != nil {
<add> if err := json.NewDecoder(serverResp.body).Decode(&c); err != nil {
<ide> return err
<ide> }
<ide>
<ide><path>api/client/stats.go
<ide> func (s *containerStats) Collect(cli *DockerCli, streamStats bool) {
<ide> } else {
<ide> v.Set("stream", "0")
<ide> }
<del> stream, _, _, err := cli.call("GET", "/containers/"+s.Name+"/stats?"+v.Encode(), nil, nil)
<add> serverResp, err := cli.call("GET", "/containers/"+s.Name+"/stats?"+v.Encode(), nil, nil)
<ide> if err != nil {
<ide> s.mu.Lock()
<ide> s.err = err
<ide> s.mu.Unlock()
<ide> return
<ide> }
<ide>
<del> defer stream.Close()
<add> defer serverResp.body.Close()
<ide>
<ide> var (
<ide> previousCPU uint64
<ide> previousSystem uint64
<del> dec = json.NewDecoder(stream)
<add> dec = json.NewDecoder(serverResp.body)
<ide> u = make(chan error, 1)
<ide> )
<ide> go func() {
<ide><path>api/client/top.go
<ide> func (cli *DockerCli) CmdTop(args ...string) error {
<ide> val.Set("ps_args", strings.Join(cmd.Args()[1:], " "))
<ide> }
<ide>
<del> stream, _, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/top?"+val.Encode(), nil, nil)
<add> serverResp, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/top?"+val.Encode(), nil, nil)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> defer stream.Close()
<add> defer serverResp.body.Close()
<ide>
<ide> procList := types.ContainerProcessList{}
<del> if err := json.NewDecoder(stream).Decode(&procList); err != nil {
<add> if err := json.NewDecoder(serverResp.body).Decode(&procList); err != nil {
<ide> return err
<ide> }
<ide>
<ide><path>api/client/utils.go
<ide> func (cli *DockerCli) clientRequestAttemptLogin(method, path string, in io.Reade
<ide> return body, statusCode, err
<ide> }
<ide>
<del>func (cli *DockerCli) call(method, path string, data interface{}, headers map[string][]string) (io.ReadCloser, http.Header, int, error) {
<add>func (cli *DockerCli) callWrapper(method, path string, data interface{}, headers map[string][]string) (io.ReadCloser, http.Header, int, error) {
<add> sr, err := cli.call(method, path, data, headers)
<add> return sr.body, sr.header, sr.statusCode, err
<add>}
<add>
<add>func (cli *DockerCli) call(method, path string, data interface{}, headers map[string][]string) (*serverResponse, error) {
<ide> params, err := cli.encodeData(data)
<ide> if err != nil {
<del> return nil, nil, -1, err
<add> sr := &serverResponse{
<add> body: nil,
<add> header: nil,
<add> statusCode: -1,
<add> }
<add> return sr, nil
<ide> }
<ide>
<ide> if data != nil {
<ide> func (cli *DockerCli) call(method, path string, data interface{}, headers map[st
<ide> }
<ide>
<ide> serverResp, err := cli.clientRequest(method, path, params, headers)
<del> return serverResp.body, serverResp.header, serverResp.statusCode, err
<add> return serverResp, err
<ide> }
<ide>
<ide> type streamOpts struct {
<ide> func (cli *DockerCli) resizeTty(id string, isExec bool) {
<ide> }
<ide>
<ide> func waitForExit(cli *DockerCli, containerID string) (int, error) {
<del> stream, _, _, err := cli.call("POST", "/containers/"+containerID+"/wait", nil, nil)
<add> serverResp, err := cli.call("POST", "/containers/"+containerID+"/wait", nil, nil)
<ide> if err != nil {
<ide> return -1, err
<ide> }
<ide>
<del> defer stream.Close()
<add> defer serverResp.body.Close()
<ide>
<ide> var res types.ContainerWaitResponse
<del> if err := json.NewDecoder(stream).Decode(&res); err != nil {
<add> if err := json.NewDecoder(serverResp.body).Decode(&res); err != nil {
<ide> return -1, err
<ide> }
<ide>
<ide> func waitForExit(cli *DockerCli, containerID string) (int, error) {
<ide> // getExitCode perform an inspect on the container. It returns
<ide> // the running state and the exit code.
<ide> func getExitCode(cli *DockerCli, containerID string) (bool, int, error) {
<del> stream, _, _, err := cli.call("GET", "/containers/"+containerID+"/json", nil, nil)
<add> serverResp, err := cli.call("GET", "/containers/"+containerID+"/json", nil, nil)
<ide> if err != nil {
<ide> // If we can't connect, then the daemon probably died.
<ide> if err != errConnectionRefused {
<ide> func getExitCode(cli *DockerCli, containerID string) (bool, int, error) {
<ide> return false, -1, nil
<ide> }
<ide>
<del> defer stream.Close()
<add> defer serverResp.body.Close()
<ide>
<ide> var c types.ContainerJSON
<del> if err := json.NewDecoder(stream).Decode(&c); err != nil {
<add> if err := json.NewDecoder(serverResp.body).Decode(&c); err != nil {
<ide> return false, -1, err
<ide> }
<ide>
<ide> func getExitCode(cli *DockerCli, containerID string) (bool, int, error) {
<ide> // getExecExitCode perform an inspect on the exec command. It returns
<ide> // the running state and the exit code.
<ide> func getExecExitCode(cli *DockerCli, execID string) (bool, int, error) {
<del> stream, _, _, err := cli.call("GET", "/exec/"+execID+"/json", nil, nil)
<add> serverResp, err := cli.call("GET", "/exec/"+execID+"/json", nil, nil)
<ide> if err != nil {
<ide> // If we can't connect, then the daemon probably died.
<ide> if err != errConnectionRefused {
<ide> func getExecExitCode(cli *DockerCli, execID string) (bool, int, error) {
<ide> return false, -1, nil
<ide> }
<ide>
<del> defer stream.Close()
<add> defer serverResp.body.Close()
<ide>
<ide> //TODO: Should we reconsider having a type in api/types?
<ide> //this is a response to exex/id/json not container
<ide> func getExecExitCode(cli *DockerCli, execID string) (bool, int, error) {
<ide> ExitCode int
<ide> }
<ide>
<del> if err := json.NewDecoder(stream).Decode(&c); err != nil {
<add> if err := json.NewDecoder(serverResp.body).Decode(&c); err != nil {
<ide> return false, -1, err
<ide> }
<ide>
<ide> func (cli *DockerCli) getTtySize() (int, int) {
<ide> return int(ws.Height), int(ws.Width)
<ide> }
<ide>
<del>func readBody(stream io.ReadCloser, hdr http.Header, statusCode int, err error) ([]byte, int, error) {
<del> if stream != nil {
<del> defer stream.Close()
<add>func readBody(serverResp *serverResponse, err error) ([]byte, int, error) {
<add> if serverResp.body != nil {
<add> defer serverResp.body.Close()
<ide> }
<ide> if err != nil {
<del> return nil, statusCode, err
<add> return nil, serverResp.statusCode, err
<ide> }
<del> body, err := ioutil.ReadAll(stream)
<add> body, err := ioutil.ReadAll(serverResp.body)
<ide> if err != nil {
<ide> return nil, -1, err
<ide> }
<del> return body, statusCode, nil
<add> return body, serverResp.statusCode, nil
<ide> }
<ide><path>api/client/version.go
<ide> func (cli *DockerCli) CmdVersion(args ...string) error {
<ide> fmt.Fprintf(cli.out, " Experimental: true\n")
<ide> }
<ide>
<del> stream, _, _, err := cli.call("GET", "/version", nil, nil)
<add> serverResp, err := cli.call("GET", "/version", nil, nil)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> defer stream.Close()
<add> defer serverResp.body.Close()
<ide>
<ide> var v types.Version
<del> if err := json.NewDecoder(stream).Decode(&v); err != nil {
<add> if err := json.NewDecoder(serverResp.body).Decode(&v); err != nil {
<ide> fmt.Fprintf(cli.err, "Error reading remote version: %s\n", err)
<ide> return err
<ide> } | 21 |
Text | Text | add article for javascript string.valueof() | cc1ebb718d1d10a5eca4f16828ca173bcea3d259 | <ide><path>guide/english/javascript/standard-objects/string/string-prototype-valueof/index.md
<ide> title: String.prototype.valueOf
<ide> ---
<ide> ## String.prototype.valueOf
<ide>
<del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/javascript/standard-objects/string/string-prototype-valueof/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add>The `valueOf()` method returns the primitive string value of the given `String` object.
<ide>
<del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>**Usage**
<add>```js
<add>var x = new String("hi");
<add>console.log(x); // String {"hi"}
<add>console.log(typeof x); // object
<add>console.log(x.valueOf()); // hi
<add>console.log(typeof x.valueOf()); // string
<add>```
<ide>
<del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>*Note*: For `String` objects, `valueOf()` and `toString()` return the same thing.
<ide>
<ide> #### More Information:
<del><!-- Please add any articles you think might be helpful to read before writing the article -->
<del>
<del>
<add>- [String.prototype.valueOf() on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/valueOf) | 1 |
PHP | PHP | add addtional options array for memcached | 86c7d1ff5ec3d13c6a8f57b331ca363b0f56b6a9 | <ide><path>lib/Cake/Cache/Engine/MemcachedEngine.php
<ide> class MemcachedEngine extends CacheEngine {
<ide> * - serialize = string, default => php. The serializer engine used to serialize data.
<ide> * Available engines are php, igbinary and json. Beside php, the memcached extension
<ide> * must be compiled with the appropriate serializer support.
<add> * - options - Additional options for the memcached client. Should be an array of option => value.
<add> * Use the Memcached::OPT_* constants as keys.
<ide> *
<ide> * @var array
<ide> */
<ide> public function init($settings = array()) {
<ide> 'persistent' => false,
<ide> 'login' => null,
<ide> 'password' => null,
<del> 'serialize' => 'php'
<add> 'serialize' => 'php',
<add> 'options' => array()
<ide> );
<ide> parent::init($settings);
<ide>
<ide> public function init($settings = array()) {
<ide> }
<ide> $this->_Memcached->setSaslAuthData($this->settings['login'], $this->settings['password']);
<ide> }
<add> if (is_array($this->settings['options'])) {
<add> foreach ($this->settings['options'] as $opt => $value) {
<add> $this->_Memcached->setOption($opt, $value);
<add> }
<add> }
<ide>
<ide> return true;
<ide> }
<ide><path>lib/Cake/Test/Case/Cache/Engine/MemcachedEngineTest.php
<ide> public function testSettings() {
<ide> 'login' => null,
<ide> 'password' => null,
<ide> 'groups' => array(),
<del> 'serialize' => 'php'
<add> 'serialize' => 'php',
<add> 'options' => array()
<ide> );
<ide> $this->assertEquals($expecting, $settings);
<ide> }
<ide> public function testCompressionSetting() {
<ide> $this->assertTrue($MemcachedCompressed->getMemcached()->getOption(Memcached::OPT_COMPRESSION));
<ide> }
<ide>
<add>/**
<add> * test setting options
<add> *
<add> * @return void
<add> */
<add> public function testOptionsSetting() {
<add> $memcached = new TestMemcachedEngine();
<add> $memcached->init(array(
<add> 'engine' => 'Memcached',
<add> 'servers' => array('127.0.0.1:11211'),
<add> 'options' => array(
<add> Memcached::OPT_BINARY_PROTOCOL => true
<add> )
<add> ));
<add> $this->assertEquals(1, $memcached->getMemcached()->getOption(Memcached::OPT_BINARY_PROTOCOL));
<add> }
<add>
<ide> /**
<ide> * test accepts only valid serializer engine
<ide> * | 2 |
Javascript | Javascript | remove unnecessary export to make usage clearer. | f3e6545bf5e407262a3b1c062a8761c7da1631d6 | <ide><path>examples/with-mobx/store.js
<ide> class Store {
<ide> }
<ide> }
<ide>
<del>export function initializeStore(initialData = null) {
<add>function initializeStore(initialData = null) {
<ide> const _store = store ?? new Store()
<ide>
<ide> // If your page has Next.js data fetching methods that use a Mobx store, it will | 1 |
Javascript | Javascript | use sortablesets for chunk.parents/blocks | b316bee0a669d2161e5cdcd63460ced2ba2d426c | <ide><path>lib/Chunk.js
<ide> class Chunk {
<ide> this._modules = new SortableSet(undefined, sortByIdentifier);
<ide> this.entrypoints = [];
<ide> this._chunks = new SortableSet(undefined, sortById);
<del> this.parents = [];
<del> this.blocks = [];
<add> this._parents = new SortableSet(undefined, sortById);
<add> this._blocks = new SortableSet();
<ide> this.origins = [];
<ide> this.files = [];
<ide> this.rendered = false;
<ide> class Chunk {
<ide> return this._chunks;
<ide> }
<ide>
<add> /**
<add> * @return {Array} - an array containing the parents
<add> */
<add> getParents() {
<add> return Array.from(this._parents);
<add> }
<add>
<add> setParents(newParents) {
<add> this._parents.clear();
<add> for(const p of newParents)
<add> this._parents.add(p);
<add> }
<add>
<add> mapParents(fn) {
<add> return Array.from(this._parents, fn);
<add> }
<add>
<add> getNumberOfParents() {
<add> return this._parents.size;
<add> }
<add>
<add> hasParent(parent) {
<add> return this._parents.has(parent);
<add> }
<add>
<add> get parentsIterable() {
<add> return this._parents;
<add> }
<add>
<add> /**
<add> * @return {Array} - an array containing the blocks
<add> */
<add> getBlocks() {
<add> return Array.from(this._blocks);
<add> }
<add>
<add> setBlocks(newBlocks) {
<add> this._blocks.clear();
<add> for(const p of newBlocks)
<add> this._blocks.add(p);
<add> }
<add>
<add> mapBlocks(fn) {
<add> return Array.from(this._blocks, fn);
<add> }
<add>
<add> getNumberOfBlocks() {
<add> return this._blocks.size;
<add> }
<add>
<add> hasBlock(block) {
<add> return this._blocks.has(block);
<add> }
<add>
<add> get blocksIterable() {
<add> return this._blocks;
<add> }
<add>
<ide> hasRuntime() {
<ide> if(this.entrypoints.length === 0) return false;
<ide> return this.entrypoints[0].getRuntimeChunk() === this;
<ide> class Chunk {
<ide> }
<ide>
<ide> addParent(parentChunk) {
<del> return this.addToCollection(this.parents, parentChunk);
<add> if(!this._parents.has(parentChunk)) {
<add> this._parents.add(parentChunk);
<add> return true;
<add> }
<add> return false;
<ide> }
<ide>
<ide> addModule(module) {
<ide> class Chunk {
<ide> }
<ide>
<ide> addBlock(block) {
<del> return this.addToCollection(this.blocks, block);
<add> if(!this._blocks.has(block)) {
<add> this._blocks.add(block);
<add> return true;
<add> }
<add> return false;
<ide> }
<ide>
<ide> removeModule(module) {
<ide> class Chunk {
<ide> }
<ide>
<ide> removeParent(chunk) {
<del> const idx = this.parents.indexOf(chunk);
<del> if(idx >= 0) {
<del> this.parents.splice(idx, 1);
<add> if(this._parents.delete(chunk)) {
<ide> chunk.removeChunk(this);
<ide> return true;
<ide> }
<ide> class Chunk {
<ide> remove(reason) {
<ide> // cleanup modules
<ide> // Array.from is used here to create a clone, because removeChunk modifies this._modules
<del> Array.from(this._modules).forEach(module => {
<add> for(const module of Array.from(this._modules)) {
<ide> module.removeChunk(this);
<del> });
<add> }
<ide>
<ide> // cleanup parents
<del> this.parents.forEach(parentChunk => {
<add> for(const parentChunk of this._parents) {
<ide> // remove this chunk from its parents
<ide> parentChunk._chunks.delete(this);
<ide>
<ide> class Chunk {
<ide> // add "sub chunk" to parent
<ide> parentChunk.addChunk(chunk);
<ide> });
<del> });
<add> }
<ide>
<ide> /**
<ide> * we need to iterate again over the chunks
<ide> * to remove this from the chunks parents.
<ide> * This can not be done in the above loop
<del> * as it is not garuanteed that `this.parents` contains anything.
<add> * as it is not garuanteed that `this._parents` contains anything.
<ide> */
<del> this._chunks.forEach(chunk => {
<add> for(const chunk of this._chunks) {
<ide> // remove this as parent of every "sub chunk"
<del> const idx = chunk.parents.indexOf(this);
<del> if(idx >= 0) {
<del> chunk.parents.splice(idx, 1);
<del> }
<del> });
<add> chunk._parents.delete(this);
<add> }
<ide>
<ide> // cleanup blocks
<del> this.blocks.forEach(block => {
<add> for(const block of this._blocks) {
<ide> const idx = block.chunks.indexOf(this);
<ide> if(idx >= 0) {
<ide> block.chunks.splice(idx, 1);
<ide> class Chunk {
<ide> block.chunkReason = reason;
<ide> }
<ide> }
<del> });
<add> }
<ide> }
<ide>
<ide> moveModule(module, otherChunk) {
<ide> class Chunk {
<ide> }
<ide>
<ide> replaceParentChunk(oldParentChunk, newParentChunk) {
<del> const idx = this.parents.indexOf(oldParentChunk);
<del> if(idx >= 0) {
<del> this.parents.splice(idx, 1);
<del> }
<add> this._parents.delete(oldParentChunk);
<ide> if(this !== newParentChunk && newParentChunk.addChunk(this)) {
<ide> this.addParent(newParentChunk);
<ide> }
<ide> class Chunk {
<ide> }
<ide>
<ide> // Array.from is used here to create a clone, because moveModule modifies otherChunk._modules
<del> const otherChunkModules = Array.from(otherChunk._modules);
<del> otherChunkModules.forEach(module => otherChunk.moveModule(module, this));
<add> for(const module of Array.from(otherChunk._modules)) {
<add> otherChunk.moveModule(module, this);
<add> }
<ide> otherChunk._modules.clear();
<ide>
<del> otherChunk.parents.forEach(parentChunk => parentChunk.replaceChunk(otherChunk, this));
<del> otherChunk.parents.length = 0;
<add> for(const parentChunk of otherChunk._parents) {
<add> parentChunk.replaceChunk(otherChunk, this);
<add> }
<add> otherChunk._parents.clear();
<ide>
<del> otherChunk._chunks.forEach(chunk => chunk.replaceParentChunk(otherChunk, this));
<add> for(const chunk of otherChunk._chunks) {
<add> chunk.replaceParentChunk(otherChunk, this);
<add> }
<ide> otherChunk._chunks.clear();
<ide>
<del> otherChunk.blocks.forEach(b => {
<add> for(const b of otherChunk._blocks) {
<ide> b.chunks = b.chunks ? b.chunks.map(c => {
<ide> return c === otherChunk ? this : c;
<ide> }) : [this];
<ide> b.chunkReason = reason;
<ide> this.addBlock(b);
<del> });
<del> otherChunk.blocks.length = 0;
<add> }
<add> otherChunk._blocks.clear();
<ide>
<ide> otherChunk.origins.forEach(origin => {
<ide> this.origins.push(origin);
<ide> class Chunk {
<ide> });
<ide> this._chunks.delete(otherChunk);
<ide> this._chunks.delete(this);
<del> this.parents = this.parents.filter(parentChunk => {
<del> return parentChunk !== otherChunk && parentChunk !== this;
<del> });
<add> for(const parentChunk of this._parents) {
<add> if(parentChunk === otherChunk || parentChunk === this)
<add> this._parents.delete(parentChunk);
<add> }
<ide> return true;
<ide> }
<ide>
<ide> split(newChunk) {
<del> this.blocks.forEach(block => {
<del> newChunk.blocks.push(block);
<add> for(const block of this._blocks) {
<add> newChunk._blocks.add(block);
<ide> block.chunks.push(newChunk);
<del> });
<del> this._chunks.forEach(chunk => {
<add> }
<add> for(const chunk of this._chunks) {
<ide> newChunk.addChunk(chunk);
<del> chunk.parents.push(newChunk);
<del> });
<del> this.parents.forEach(parentChunk => {
<add> chunk._parents.add(newChunk);
<add> }
<add> for(const parentChunk of this._parents) {
<ide> parentChunk.addChunk(newChunk);
<del> newChunk.parents.push(parentChunk);
<del> });
<del> this.entrypoints.forEach(entrypoint => {
<add> newChunk._parents.add(parentChunk);
<add> }
<add> for(const entrypoint of this.entrypoints) {
<ide> entrypoint.insertChunk(newChunk, this);
<del> });
<add> }
<ide> }
<ide>
<ide> isEmpty() {
<ide> class Chunk {
<ide> return false;
<ide> }
<ide> if(this.isInitial()) {
<del> if(otherChunk.parents.length !== 1 || otherChunk.parents[0] !== this) {
<add> if(otherChunk.getNumberOfParents() !== 1 || otherChunk.getParents()[0] !== this) {
<ide> return false;
<ide> }
<ide> }
<ide> class Chunk {
<ide> if(origin.reasons)
<ide> origin.reasons.sort();
<ide> });
<del> this.parents.sort(sortById);
<add> this._parents.sort();
<ide> this._chunks.sort();
<ide> }
<ide>
<ide> class Chunk {
<ide>
<ide> checkConstraints() {
<ide> const chunk = this;
<del> const chunks = Array.from(chunk._chunks);
<del> chunks.forEach((child, idx) => {
<del> if(chunks.indexOf(child) !== idx)
<del> throw new Error(`checkConstraints: duplicate child in chunk ${chunk.debugId} ${child.debugId}`);
<del> if(child.parents.indexOf(chunk) < 0)
<add> for(const child of chunk._chunks) {
<add> if(!child._parents.has(chunk))
<ide> throw new Error(`checkConstraints: child missing parent ${chunk.debugId} -> ${child.debugId}`);
<del> });
<del> chunk.parents.forEach((parentChunk, idx) => {
<del> if(chunk.parents.indexOf(parentChunk) !== idx)
<del> throw new Error(`checkConstraints: duplicate parent in chunk ${chunk.debugId} ${parentChunk.debugId}`);
<del>
<del> const chunks = Array.from(parentChunk._chunks);
<del> if(chunks.indexOf(chunk) < 0)
<add> }
<add> for(const parentChunk of chunk._parents) {
<add> if(!parentChunk._chunks.has(chunk))
<ide> throw new Error(`checkConstraints: parent missing child ${parentChunk.debugId} <- ${chunk.debugId}`);
<del> });
<add> }
<ide> }
<ide> }
<ide>
<ide> Object.defineProperty(Chunk.prototype, "chunks", {
<ide> }
<ide> });
<ide>
<add>Object.defineProperty(Chunk.prototype, "parents", {
<add> configurable: false,
<add> get: util.deprecate(function() {
<add> return this._parents.getFrozenArray();
<add> }, "Chunk.parents: Use Chunk.getParents() instead"),
<add> set: util.deprecate(function(value) {
<add> this.setParents(value);
<add> }, "Chunk.parents: Use Chunk.addParent/removeParent/setParents to modify parents.")
<add>});
<add>
<add>Object.defineProperty(Chunk.prototype, "blocks", {
<add> configurable: false,
<add> get: util.deprecate(function() {
<add> return this._blocks.getFrozenArray();
<add> }, "Chunk.blocks: Use Chunk.getBlocks() instead"),
<add> set: util.deprecate(function(value) {
<add> this.setBlocks(value);
<add> }, "Chunk.blocks: Use Chunk.addBlock/removeBlock/setBlocks to modify blocks.")
<add>});
<add>
<ide> module.exports = Chunk;
<ide><path>lib/RecordIdsPlugin.js
<ide> class RecordIdsPlugin {
<ide> records.chunks.usedIds = {};
<ide> chunks.forEach(chunk => {
<ide> const name = chunk.name;
<del> const blockIdents = chunk.blocks.map(getDepBlockIdent.bind(null, chunk)).filter(Boolean);
<add> const blockIdents = chunk.mapBlocks(getDepBlockIdent.bind(null, chunk)).filter(Boolean);
<ide> if(name) records.chunks.byName[name] = chunk.id;
<ide> blockIdents.forEach((blockIdent) => {
<ide> records.chunks.byBlocks[blockIdent] = chunk.id;
<ide> class RecordIdsPlugin {
<ide> if(records.chunks.byBlocks) {
<ide> const argumentedChunks = chunks.filter(chunk => chunk.id === null).map(chunk => ({
<ide> chunk,
<del> blockIdents: chunk.blocks.map(getDepBlockIdent.bind(null, chunk)).filter(Boolean)
<add> blockIdents: chunk.mapBlocks(getDepBlockIdent.bind(null, chunk)).filter(Boolean)
<ide> })).filter(arg => arg.blockIdents.length > 0);
<ide> let blockIdentsCount = {};
<ide> argumentedChunks.forEach((arg, idx) => {
<ide><path>lib/Stats.js
<ide> class Stats {
<ide> names: chunk.name ? [chunk.name] : [],
<ide> files: chunk.files.slice(),
<ide> hash: chunk.renderedHash,
<del> parents: chunk.parents.map(c => c.id)
<add> parents: chunk.mapParents(c => c.id)
<ide> };
<ide> if(showChunkModules) {
<ide> obj.modules = chunk
<ide><path>lib/optimize/AggressiveMergingPlugin.js
<ide> class AggressiveMergingPlugin {
<ide> const minSizeReduce = options.minSizeReduce || 1.5;
<ide>
<ide> function getParentsWeight(chunk) {
<del> return chunk.parents.map((p) => {
<add> return chunk.mapParents((p) => {
<ide> return p.isInitial() ? options.entryChunkMultiplicator || 10 : 1;
<ide> }).reduce((a, b) => {
<ide> return a + b;
<ide> class AggressiveMergingPlugin {
<ide> aOnlyModules.forEach((m) => {
<ide> pair.b.removeModule(m);
<ide> m.removeChunk(pair.b);
<del> pair.b.parents.forEach((c) => {
<add> for(const c of pair.b.parentsIterable) {
<ide> c.addModule(m);
<ide> m.addChunk(c);
<del> });
<add> }
<ide> });
<ide> bOnlyModules.forEach((m) => {
<ide> pair.a.removeModule(m);
<ide> m.removeChunk(pair.a);
<del> pair.a.parents.forEach((c) => {
<add> for(const c of pair.a.parentsIterable) {
<ide> c.addModule(m);
<ide> m.addChunk(c);
<del> });
<add> }
<ide> });
<ide> }
<ide> if(pair.b.integrate(pair.a, "aggressive-merge")) {
<ide><path>lib/optimize/CommonsChunkPlugin.js
<ide> Take a look at the "name"/"names" or async/children option.`);
<ide>
<ide> // we can only move modules from this chunk if the "commonChunk" is the only parent
<ide> if(!asyncOption)
<del> return chunk.parents.length === 1;
<add> return chunk.getNumberOfParents() === 1;
<ide>
<ide> return true;
<ide> });
<ide> Take a look at the "name"/"names" or async/children option.`);
<ide> /**
<ide> * past this point only entry chunks are allowed to become commonChunks
<ide> */
<del> if(targetChunk.parents.length > 0) {
<add> if(targetChunk.getNumberOfParents() > 0) {
<ide> compilation.errors.push(new Error("CommonsChunkPlugin: While running in normal mode it's not allowed to use a non-entry chunk (" + targetChunk.name + ")"));
<ide> return;
<ide> }
<ide> Take a look at the "name"/"names" or async/children option.`);
<ide> makeTargetChunkParentOfAffectedChunks(usedChunks, commonChunk) {
<ide> for(const chunk of usedChunks) {
<ide> // set commonChunk as new sole parent
<del> chunk.parents = [commonChunk];
<add> chunk.setParents([commonChunk]);
<ide> // add chunk to commonChunk
<ide> commonChunk.addChunk(chunk);
<ide>
<ide> Take a look at the "name"/"names" or async/children option.`);
<ide> moveExtractedChunkBlocksToTargetChunk(chunks, targetChunk) {
<ide> for(const chunk of chunks) {
<ide> if(chunk === targetChunk) continue;
<del> for(const block of chunk.blocks) {
<add> for(const block of chunk.blocksIterable) {
<ide> if(block.chunks.indexOf(targetChunk) === -1) {
<ide> block.chunks.unshift(targetChunk);
<ide> }
<ide><path>lib/optimize/EnsureChunkConditionsPlugin.js
<ide> class EnsureChunkConditionsPlugin {
<ide> if(!usedChunks) triesMap.set(module, usedChunks = new Set());
<ide> usedChunks.add(chunk);
<ide> const newChunks = [];
<del> chunk.parents.forEach((parent) => {
<add> for(const parent of chunk.parentsIterable) {
<ide> if(!usedChunks.has(parent)) {
<ide> parent.addModule(module);
<ide> module.addChunk(parent);
<ide> newChunks.push(parent);
<ide> }
<del> });
<add> }
<ide> module.rewriteChunkInReasons(chunk, newChunks);
<ide> chunk.removeModule(module);
<ide> changed = true;
<ide><path>lib/optimize/OccurrenceOrderPlugin.js
<ide> class OccurrenceOrderPlugin {
<ide> const occursInInitialChunksMap = new Map();
<ide>
<ide> chunks.forEach(c => {
<del> const result = c.parents.reduce((sum, p) => {
<add> const result = c.getParents().reduce((sum, p) => {
<ide> if(p.isInitial()) return sum + 1;
<ide> return sum;
<ide> }, 0);
<ide> return occursInInitialChunksMap.set(c, result);
<ide> });
<ide>
<ide> function occurs(c) {
<del> return c.blocks.length;
<add> return c.getNumberOfBlocks();
<ide> }
<ide>
<ide> chunks.sort((a, b) => {
<ide><path>lib/optimize/RemoveParentModulesPlugin.js
<ide>
<ide> function hasModule(chunk, module, checkedChunks) {
<ide> if(chunk.containsModule(module)) return [chunk];
<del> if(chunk.parents.length === 0) return false;
<del> return allHaveModule(chunk.parents.filter((c) => {
<add> if(chunk.getNumberOfParents() === 0) return false;
<add> return allHaveModule(chunk.getParents().filter((c) => {
<ide> return !checkedChunks.has(c);
<ide> }), module, checkedChunks);
<ide> }
<ide> class RemoveParentModulesPlugin {
<ide> compilation.plugin(["optimize-chunks-basic", "optimize-extracted-chunks-basic"], (chunks) => {
<ide> for(var index = 0; index < chunks.length; index++) {
<ide> var chunk = chunks[index];
<del> if(chunk.parents.length === 0) continue;
<add> if(chunk.getNumberOfParents() === 0) continue;
<ide>
<ide> // TODO consider Map when performance has improved https://gist.github.com/sokra/b36098368da7b8f6792fd7c85fca6311
<ide> var cache = Object.create(null);
<ide> class RemoveParentModulesPlugin {
<ide> var dId = module.getChunkIdsIdent();
<ide> var parentChunksWithModule;
<ide> if(dId === null) {
<del> parentChunksWithModule = allHaveModule(chunk.parents, module);
<add> parentChunksWithModule = allHaveModule(chunk.getParents(), module);
<ide> } else if(dId in cache) {
<ide> parentChunksWithModule = cache[dId];
<ide> } else {
<del> parentChunksWithModule = cache[dId] = allHaveModule(chunk.parents, module);
<add> parentChunksWithModule = cache[dId] = allHaveModule(chunk.getParents(), module);
<ide> }
<ide> if(parentChunksWithModule) {
<ide> module.rewriteChunkInReasons(chunk, Array.from(parentChunksWithModule)); | 8 |
Ruby | Ruby | select correct python | 23a38e0ff6beb26f86eca0c56b25d6100375b60d | <ide><path>Library/Homebrew/exceptions.rb
<ide> def message
<ide> end
<ide> end
<ide>
<add>class FormulaAmbiguousPythonError < RuntimeError
<add> def initialize(formula)
<add> super <<-EOS.undent
<add> The version of python to use with the virtualenv in the `#{formula.full_name}` formula
<add> cannot be guessed automatically. If the simultaneous use of python and python3
<add> is intentional, please add `:using => "python"` or `:using => "python3"` to
<add> `virtualenv_install_with_resources` to resolve the ambiguity manually.
<add> EOS
<add> end
<add>end
<add>
<ide> class BuildError < RuntimeError
<ide> attr_reader :formula, :env
<ide>
<ide><path>Library/Homebrew/language/python.rb
<ide> def virtualenv_create(venv_root, python = "python", formula = self)
<ide> venv
<ide> end
<ide>
<add> # Returns true if a formula option for the specified python is currently
<add> # active or if the specified python is required by the formula. Valid
<add> # inputs are "python", "python3", :python, and :python3. Note that
<add> # "with-python", "without-python", "with-python3", and "without-python3"
<add> # formula options are handled correctly even if not associated with any
<add> # corresponding depends_on statement.
<add> # @api private
<add> def needs_python?(python)
<add> return true if build.with?(python)
<add> (requirements.to_a | deps).any? { |r| r.name == python && r.required? }
<add> end
<add>
<ide> # Helper method for the common case of installing a Python application.
<ide> # Creates a virtualenv in `libexec`, installs all `resource`s defined
<del> # on the formula, and then installs the formula.
<del> def virtualenv_install_with_resources
<del> venv = virtualenv_create(libexec)
<add> # on the formula, and then installs the formula. An options hash may be
<add> # passed (e.g., :using => "python3") to override the default, guessed
<add> # formula preference for python or python3, or to resolve an ambiguous
<add> # case where it's not clear whether python or python3 should be the
<add> # default guess.
<add> def virtualenv_install_with_resources(options = {})
<add> python = options[:using]
<add> if python.nil?
<add> wanted = %w[python python3].select { |py| needs_python?(py) }
<add> raise FormulaAmbiguousPythonError, self if wanted.size > 1
<add> python = wanted.first || "python"
<add> end
<add> venv = virtualenv_create(libexec, python)
<ide> venv.pip_install resources
<ide> venv.pip_install_and_link buildpath
<ide> venv | 2 |
PHP | PHP | add a test for testvalidatemimetypes | b5accc88525e592aea50c717ded962bec2938314 | <ide><path>tests/Validation/ValidationValidatorTest.php
<ide> public function testValidateImage()
<ide> $this->assertTrue($v->passes());
<ide> }
<ide>
<add> public function testValidateMimetypes()
<add> {
<add> $trans = $this->getRealTranslator();
<add> $uploadedFile = [__FILE__, '', null, null, null, true];
<add>
<add> $file = $this->getMock('Symfony\Component\HttpFoundation\File\UploadedFile', ['guessExtension'], $uploadedFile);
<add> $file->expects($this->any())->method('validateMimetypes')->will($this->returnValue('php'));
<add> $v = new Validator($trans, [], ['x' => 'mimetypes:text/x-php']);
<add> $v->setFiles(['x' => $file]);
<add> $this->assertTrue($v->passes());
<add> }
<add>
<ide> public function testValidateMime()
<ide> {
<ide> $trans = $this->getRealTranslator(); | 1 |
Ruby | Ruby | convert exceptions test to spec | 279831fc0e3241eda17b6007aef02299b3c82c9e | <ide><path>Library/Homebrew/test/exceptions_spec.rb
<add>require "exceptions"
<add>
<add>describe MultipleVersionsInstalledError do
<add> subject { described_class.new("foo") }
<add> its(:to_s) { is_expected.to eq("foo has multiple installed versions") }
<add>end
<add>
<add>describe NoSuchKegError do
<add> subject { described_class.new("foo") }
<add> its(:to_s) { is_expected.to eq("No such keg: #{HOMEBREW_CELLAR}/foo") }
<add>end
<add>
<add>describe FormulaValidationError do
<add> subject { described_class.new("foo", "sha257", "magic") }
<add> its(:to_s) {
<add> is_expected.to eq(%q(invalid attribute for formula 'foo': sha257 ("magic")))
<add> }
<add>end
<add>
<add>describe FormulaUnavailableError do
<add> subject { described_class.new("foo") }
<add>
<add> describe "#dependent_s" do
<add> it "returns nil if there is no dependent" do
<add> expect(subject.dependent_s).to be nil
<add> end
<add>
<add> it "returns nil if it depended on by itself" do
<add> subject.dependent = "foo"
<add> expect(subject.dependent_s).to be nil
<add> end
<add>
<add> it "returns a string if there is a dependent" do
<add> subject.dependent = "foobar"
<add> expect(subject.dependent_s).to eq("(dependency of foobar)")
<add> end
<add> end
<add>
<add> context "without a dependent" do
<add> its(:to_s) { is_expected.to eq('No available formula with the name "foo" ') }
<add> end
<add>
<add> context "with a dependent" do
<add> before(:each) do
<add> subject.dependent = "foobar"
<add> end
<add>
<add> its(:to_s) {
<add> is_expected.to eq('No available formula with the name "foo" (dependency of foobar)')
<add> }
<add> end
<add>end
<add>
<add>describe TapFormulaUnavailableError do
<add> subject { described_class.new(tap, "foo") }
<add> let(:tap) { double(Tap, user: "u", repo: "r", to_s: "u/r", installed?: false) }
<add> its(:to_s) { is_expected.to match(%r{Please tap it and then try again: brew tap u/r}) }
<add>end
<add>
<add>describe FormulaClassUnavailableError do
<add> subject { described_class.new("foo", "foo.rb", "Foo", list) }
<add> let(:mod) do
<add> Module.new do
<add> class Bar < Requirement; end
<add> class Baz < Formula; end
<add> end
<add> end
<add>
<add> context "no classes" do
<add> let(:list) { [] }
<add> its(:to_s) {
<add> is_expected.to match(/Expected to find class Foo, but found no classes\./)
<add> }
<add> end
<add>
<add> context "class not derived from Formula" do
<add> let(:list) { [mod.const_get(:Bar)] }
<add> its(:to_s) {
<add> is_expected.to match(/Expected to find class Foo, but only found: Bar \(not derived from Formula!\)\./)
<add> }
<add> end
<add>
<add> context "class derived from Formula" do
<add> let(:list) { [mod.const_get(:Baz)] }
<add> its(:to_s) { is_expected.to match(/Expected to find class Foo, but only found: Baz\./) }
<add> end
<add>end
<add>
<add>describe FormulaUnreadableError do
<add> subject { described_class.new("foo", formula_error) }
<add> let(:formula_error) { LoadError.new("bar") }
<add> its(:to_s) { is_expected.to eq("foo: bar") }
<add>end
<add>
<add>describe TapUnavailableError do
<add> subject { described_class.new("foo") }
<add> its(:to_s) { is_expected.to eq("No available tap foo.\n") }
<add>end
<add>
<add>describe TapAlreadyTappedError do
<add> subject { described_class.new("foo") }
<add> its(:to_s) { is_expected.to eq("Tap foo already tapped.\n") }
<add>end
<add>
<add>describe TapPinStatusError do
<add> context "pinned" do
<add> subject { described_class.new("foo", true) }
<add> its(:to_s) { is_expected.to eq("foo is already pinned.") }
<add> end
<add>
<add> context "unpinned" do
<add> subject { described_class.new("foo", false) }
<add> its(:to_s) { is_expected.to eq("foo is already unpinned.") }
<add> end
<add>end
<add>
<add>describe BuildError do
<add> subject { described_class.new(formula, "badprg", %w[arg1 arg2], {}) }
<add> let(:formula) { double(Formula, name: "foo") }
<add> its(:to_s) { is_expected.to eq("Failed executing: badprg arg1 arg2") }
<add>end
<add>
<add>describe OperationInProgressError do
<add> subject { described_class.new("foo") }
<add> its(:to_s) { is_expected.to match(/Operation already in progress for foo/) }
<add>end
<add>
<add>describe FormulaInstallationAlreadyAttemptedError do
<add> subject { described_class.new(formula) }
<add> let(:formula) { double(Formula, full_name: "foo/bar") }
<add> its(:to_s) { is_expected.to eq("Formula installation already attempted: foo/bar") }
<add>end
<add>
<add>describe FormulaConflictError do
<add> subject { described_class.new(formula, [conflict]) }
<add> let(:formula) { double(Formula, full_name: "foo/qux") }
<add> let(:conflict) { double(name: "bar", reason: "I decided to") }
<add> its(:to_s) { is_expected.to match(/Please `brew unlink bar` before continuing\./) }
<add>end
<add>
<add>describe CompilerSelectionError do
<add> subject { described_class.new(formula) }
<add> let(:formula) { double(Formula, full_name: "foo") }
<add> its(:to_s) { is_expected.to match(/foo cannot be built with any available compilers\./) }
<add>end
<add>
<add>describe CurlDownloadStrategyError do
<add> context "file does not exist" do
<add> subject { described_class.new("file:///tmp/foo") }
<add> its(:to_s) { is_expected.to eq("File does not exist: /tmp/foo") }
<add> end
<add>
<add> context "download failed" do
<add> subject { described_class.new("http://brew.sh") }
<add> its(:to_s) { is_expected.to eq("Download failed: http://brew.sh") }
<add> end
<add>end
<add>
<add>describe ErrorDuringExecution do
<add> subject { described_class.new("badprg", %w[arg1 arg2]) }
<add> its(:to_s) { is_expected.to eq("Failure while executing: badprg arg1 arg2") }
<add>end
<add>
<add>describe ChecksumMismatchError do
<add> subject { described_class.new("/file.tar.gz", hash1, hash2) }
<add> let(:hash1) { double(hash_type: "sha256", to_s: "deadbeef") }
<add> let(:hash2) { double(hash_type: "sha256", to_s: "deadcafe") }
<add> its(:to_s) { is_expected.to match(/SHA256 mismatch/) }
<add>end
<add>
<add>describe ResourceMissingError do
<add> subject { described_class.new(formula, resource) }
<add> let(:formula) { double(Formula, full_name: "bar") }
<add> let(:resource) { double(inspect: "<resource foo>") }
<add> its(:to_s) { is_expected.to eq("bar does not define resource <resource foo>") }
<add>end
<add>
<add>describe DuplicateResourceError do
<add> subject { described_class.new(resource) }
<add> let(:resource) { double(inspect: "<resource foo>") }
<add> its(:to_s) { is_expected.to eq("Resource <resource foo> is defined more than once") }
<add>end
<add>
<add>describe BottleVersionMismatchError do
<add> subject { described_class.new("/foo.bottle.tar.gz", "1.0", formula, "1.1") }
<add> let(:formula) { double(Formula, full_name: "foo") }
<add> its(:to_s) { is_expected.to match(/Bottle version mismatch/) }
<add>end
<ide><path>Library/Homebrew/test/exceptions_test.rb
<del>require "testing_env"
<del>require "exceptions"
<del>
<del>class ExceptionsTest < Homebrew::TestCase
<del> def test_multiple_versions_installed_error
<del> assert_equal "foo has multiple installed versions",
<del> MultipleVersionsInstalledError.new("foo").to_s
<del> end
<del>
<del> def test_no_such_keg_error
<del> assert_equal "No such keg: #{HOMEBREW_CELLAR}/foo",
<del> NoSuchKegError.new("foo").to_s
<del> end
<del>
<del> def test_formula_validation_error
<del> assert_equal %q(invalid attribute for formula 'foo': sha257 ("magic")),
<del> FormulaValidationError.new("foo", "sha257", "magic").to_s
<del> end
<del>
<del> def test_formula_unavailable_error
<del> e = FormulaUnavailableError.new "foo"
<del> assert_nil e.dependent_s
<del>
<del> e.dependent = "foo"
<del> assert_nil e.dependent_s
<del>
<del> e.dependent = "foobar"
<del> assert_equal "(dependency of foobar)", e.dependent_s
<del>
<del> assert_equal "No available formula with the name \"foo\" (dependency of foobar)",
<del> e.to_s
<del> end
<del>
<del> def test_tap_formula_unavailable_error
<del> t = stub(user: "u", repo: "r", to_s: "u/r", installed?: false)
<del> assert_match "Please tap it and then try again: brew tap u/r",
<del> TapFormulaUnavailableError.new(t, "foo").to_s
<del> end
<del>
<del> def test_formula_class_unavailable_error
<del> mod = Module.new
<del> mod.module_eval <<-EOS.undent
<del> class Bar < Requirement; end
<del> class Baz < Formula; end
<del> EOS
<del>
<del> assert_match "Expected to find class Foo, but found no classes.",
<del> FormulaClassUnavailableError.new("foo", "foo.rb", "Foo", []).to_s
<del>
<del> list = [mod.const_get(:Bar)]
<del> assert_match "Expected to find class Foo, but only found: Bar (not derived from Formula!).",
<del> FormulaClassUnavailableError.new("foo", "foo.rb", "Foo", list).to_s
<del>
<del> list = [mod.const_get(:Baz)]
<del> assert_match "Expected to find class Foo, but only found: Baz.",
<del> FormulaClassUnavailableError.new("foo", "foo.rb", "Foo", list).to_s
<del> end
<del>
<del> def test_formula_unreadable_error
<del> formula_error = LoadError.new("bar")
<del> assert_equal "foo: bar", FormulaUnreadableError.new("foo", formula_error).to_s
<del> end
<del>
<del> def test_tap_unavailable_error
<del> assert_equal "No available tap foo.\n", TapUnavailableError.new("foo").to_s
<del> end
<del>
<del> def test_tap_already_tapped_error
<del> assert_equal "Tap foo already tapped.\n",
<del> TapAlreadyTappedError.new("foo").to_s
<del> end
<del>
<del> def test_pin_status_error
<del> assert_equal "foo is already pinned.",
<del> TapPinStatusError.new("foo", true).to_s
<del> assert_equal "foo is already unpinned.",
<del> TapPinStatusError.new("foo", false).to_s
<del> end
<del>
<del> def test_build_error
<del> f = stub(name: "foo")
<del> assert_equal "Failed executing: badprg arg1 arg2",
<del> BuildError.new(f, "badprg", %w[arg1 arg2], {}).to_s
<del> end
<del>
<del> def test_operation_in_progress_error
<del> assert_match "Operation already in progress for bar",
<del> OperationInProgressError.new("bar").to_s
<del> end
<del>
<del> def test_formula_installation_already_attempted_error
<del> f = stub(full_name: "foo/bar")
<del> assert_equal "Formula installation already attempted: foo/bar",
<del> FormulaInstallationAlreadyAttemptedError.new(f).to_s
<del> end
<del>
<del> def test_formula_conflict_error
<del> f = stub(full_name: "foo/qux")
<del> c = stub(name: "bar", reason: "I decided to")
<del> assert_match "Please `brew unlink bar` before continuing.",
<del> FormulaConflictError.new(f, [c]).to_s
<del> end
<del>
<del> def test_compiler_selection_error
<del> f = stub(full_name: "foo")
<del> assert_match "foo cannot be built with any available compilers.",
<del> CompilerSelectionError.new(f).to_s
<del> end
<del>
<del> def test_curl_download_strategy_error
<del> assert_equal "File does not exist: /tmp/foo",
<del> CurlDownloadStrategyError.new("file:///tmp/foo").to_s
<del> assert_equal "Download failed: http://brew.sh",
<del> CurlDownloadStrategyError.new("http://brew.sh").to_s
<del> end
<del>
<del> def test_error_during_execution
<del> assert_equal "Failure while executing: badprg arg1 arg2",
<del> ErrorDuringExecution.new("badprg", %w[arg1 arg2]).to_s
<del> end
<del>
<del> def test_checksum_mismatch_error
<del> h1 = stub(hash_type: "sha256", to_s: "deadbeef")
<del> h2 = stub(hash_type: "sha256", to_s: "deadcafe")
<del> assert_match "SHA256 mismatch",
<del> ChecksumMismatchError.new("/file.tar.gz", h1, h2).to_s
<del> end
<del>
<del> def test_resource_missing_error
<del> f = stub(full_name: "bar")
<del> r = stub(inspect: "<resource foo>")
<del> assert_match "bar does not define resource <resource foo>",
<del> ResourceMissingError.new(f, r).to_s
<del> end
<del>
<del> def test_duplicate_resource_error
<del> r = stub(inspect: "<resource foo>")
<del> assert_equal "Resource <resource foo> is defined more than once",
<del> DuplicateResourceError.new(r).to_s
<del> end
<del>
<del> def test_bottle_version_mismatch_error
<del> f = stub(full_name: "foo")
<del> assert_match "Bottle version mismatch",
<del> BottleVersionMismatchError.new("/foo.bottle.tar.gz", "1.0", f, "1.1").to_s
<del> end
<del>end | 2 |
Javascript | Javascript | add cli bundle url params | 6357931b61f955af5d72f235ad6b43fb897128b8 | <ide><path>local-cli/bundle.js
<ide> var blacklist = require('../packager/blacklist.js');
<ide> var ReactPackager = require('../packager/react-packager');
<ide>
<ide> var OUT_PATH = 'iOS/main.jsbundle';
<add>var URL_PATH = '/index.ios.bundle?dev=';
<ide>
<ide> function getBundle(flags) {
<ide>
<ide> function getBundle(flags) {
<ide> blacklistRE: blacklist('ios'),
<ide> };
<ide>
<del> var url = '/index.ios.bundle?dev=' + flags.dev;
<add> var url = flags.url ? flags.url.replace(/\.js$/i, '.bundle?dev=') : URL_PATH;
<add> url = url.match(/^\//) ? url : '/' + url;
<add> url += flags.dev;
<ide>
<ide> console.log('Building package...');
<ide> ReactPackager.buildPackageFromUrl(options, url)
<ide> function showHelp() {
<ide> ' --root\t\tadd another root(s) to be used in bundling in this project',
<ide> ' --assetRoots\t\tspecify the root directories of app assets',
<ide> ' --out\t\tspecify the output file',
<add> ' --url\t\tspecify the bundle file url',
<ide> ].join('\n'));
<ide> process.exit(1);
<ide> }
<ide> module.exports = {
<ide> root: args.indexOf('--root') !== -1 ? args[args.indexOf('--root') + 1] : false,
<ide> assetRoots: args.indexOf('--assetRoots') !== -1 ? args[args.indexOf('--assetRoots') + 1] : false,
<ide> out: args.indexOf('--out') !== -1 ? args[args.indexOf('--out') + 1] : false,
<add> url: args.indexOf('--url') !== -1 ? args[args.indexOf('--url') + 1] : false,
<ide> }
<ide>
<ide> if (flags.help) { | 1 |
Ruby | Ruby | add missing require | f9872207564c9c9dd5b4c7ecf02f2387cbceed9a | <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> require 'active_support/core_ext/hash/except'
<ide> require 'active_support/core_ext/object/blank'
<add>require 'active_support/core_ext/enumerable'
<ide> require 'active_support/inflector'
<ide> require 'action_dispatch/routing/redirection'
<ide> | 1 |
Ruby | Ruby | fix meaningless test case | 24889666c7eee345f88a588108f38e6d5fe25482 | <ide><path>actionpack/test/template/form_helper_test.rb
<ide> def test_fields_for_object_with_bracketed_name_and_index
<ide> end
<ide>
<ide> def test_form_builder_does_not_have_form_for_method
<del> assert ! ActionView::Helpers::FormBuilder.instance_methods.include?('form_for')
<add> assert !ActionView::Helpers::FormBuilder.instance_methods.include?(:form_for)
<ide> end
<ide>
<ide> def test_form_for_and_fields_for | 1 |
Ruby | Ruby | remove calls to deprecated methods | 9a3e29e126d9daf6175b4d2be50112d1c8771d17 | <ide><path>activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb
<ide> def delete_records(records)
<ide> records.each { |record| @owner.connection.delete(interpolate_sql(sql, record)) }
<ide> else
<ide> relation = Arel::Table.new(@reflection.options[:join_table])
<del> relation.where(relation[@reflection.primary_key_name].eq(@owner.id).
<add> stmt = relation.where(relation[@reflection.primary_key_name].eq(@owner.id).
<ide> and(relation[@reflection.association_foreign_key].in(records.map { |x| x.id }.compact))
<del> ).delete
<add> ).compile_delete
<add> @owner.connection.delete stmt.to_sql
<ide> end
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/migration.rb
<ide> def record_version_state_after_migrating(version)
<ide> @migrated_versions ||= []
<ide> if down?
<ide> @migrated_versions.delete(version)
<del> table.where(table["version"].eq(version.to_s)).delete
<add> stmt = table.where(table["version"].eq(version.to_s)).compile_delete
<add> Base.connection.delete stmt.to_sql
<ide> else
<ide> @migrated_versions.push(version).sort!
<ide> stmt = table.compile_insert table["version"] => version.to_s | 2 |
Python | Python | remove billiard c extension maxtasks warning | 00405074652222c8ac181c45c1ac5357935cf665 | <ide><path>celery/concurrency/prefork.py
<ide> from __future__ import absolute_import
<ide>
<ide> import os
<del>import sys
<ide>
<ide> from billiard import forking_enable
<ide> from billiard.pool import RUN, CLOSE, Pool as BlockingPool
<ide> #: List of signals to ignore when a child process starts.
<ide> WORKER_SIGIGNORE = frozenset(['SIGINT'])
<ide>
<del>MAXTASKS_NO_BILLIARD = """\
<del> maxtasksperchild enabled but billiard C extension not installed!
<del> This may lead to a deadlock, so please install the billiard C extension.
<del>"""
<del>
<ide> logger = get_logger(__name__)
<ide> warning, debug = logger.warning, logger.debug
<ide>
<ide> def on_start(self):
<ide> Will pre-fork all workers so they're ready to accept tasks.
<ide>
<ide> """
<del> if self.options.get('maxtasksperchild') and sys.platform != 'win32':
<del> try:
<del> from billiard.connection import Connection
<del> Connection.send_offset
<del> except (ImportError, AttributeError):
<del> # billiard C extension not installed
<del> warning(MAXTASKS_NO_BILLIARD)
<del>
<ide> forking_enable(self.forking_enable)
<ide> Pool = (self.BlockingPool if self.options.get('threads', True)
<ide> else self.Pool) | 1 |
Text | Text | fix some typos in nativecomponentsios.md | 0e3d627ff0764508e69b832fbcb5b36d8b0b6fd5 | <ide><path>docs/NativeComponentsIOS.md
<ide> class MapView extends React.Component {
<ide> }
<ide> }
<ide>
<del>var RCTMap= requireNativeComponent('RCTMap', MapView);
<add>var RCTMap = requireNativeComponent('RCTMap', MapView);
<ide>
<ide> MapView.propTypes = {
<ide> /**
<ide> MapView.propTypes = {
<ide> * angle is ignored and the map is always displayed as if the user
<ide> * is looking straight down onto it.
<ide> */
<del> pitchEnabled = React.PropTypes.bool,
<add> pitchEnabled: React.PropTypes.bool,
<ide> };
<ide>
<ide> module.exports = MapView;
<ide> MapView.propTypes = {
<ide> * angle is ignored and the map is always displayed as if the user
<ide> * is looking straight down onto it.
<ide> */
<del> pitchEnabled = React.PropTypes.bool,
<add> pitchEnabled: React.PropTypes.bool,
<ide>
<ide> /**
<ide> * The region to be displayed by the map.
<ide> RCT_EXPORT_MODULE()
<ide> {
<ide> MKCoordinateRegion region = mapView.region;
<ide> NSDictionary *event = @{
<del> @"target": [mapView reactTag],
<add> @"target": mapView.reactTag,
<ide> @"region": @{
<ide> @"latitude": @(region.center.latitude),
<ide> @"longitude": @(region.center.longitude), | 1 |
Ruby | Ruby | remove dummy object#try before aliasing it | 95dfcc4f3c4bda74efe220e6dd5a11f58f29a501 | <ide><path>activesupport/lib/active_support/core_ext/try.rb
<ide> class Object
<ide> def try(method, *args, &block)
<ide> send(method, *args, &block)
<ide> end
<add> remove_method :try
<ide> alias_method :try, :__send__
<ide> end
<ide> | 1 |
Javascript | Javascript | add hyperlinks to github prs for release notes | abb8e44a8efd5c7ea50765d87572eed405b74dad | <ide><path>docs/apache-airflow/static/gh-jira-links.js
<ide> */
<ide>
<ide> document.addEventListener('DOMContentLoaded', function() {
<del> var el = document.getElementById('changelog');
<add> var el = document.getElementById('release-notes');
<ide> if (el !== null ) {
<ide> // [AIRFLOW-...]
<ide> el.innerHTML = el.innerHTML.replace(
<ide><path>docs/helm-chart/static/gh-jira-links.js
<ide> */
<ide>
<ide> document.addEventListener('DOMContentLoaded', function() {
<del> var el = document.getElementById('changelog');
<add> var el = document.getElementById('release-notes');
<ide> if (el !== null ) {
<ide> // [AIRFLOW-...]
<ide> el.innerHTML = el.innerHTML.replace( | 2 |
Text | Text | fix typo in contributing guides | 5a61ca63b9ef33cd814c703051bc777a6771f205 | <ide><path>doc/contributing/releases.md
<ide> reflect the newly used value. Ensure that the release commit removes the
<ide> `-pre` suffix for the major version being prepared.
<ide>
<ide> It is current TSC policy to bump major version when ABI changes. If you
<del>see a need to bump `NODE_MODULE_VERSION` outside of a majore release then
<add>see a need to bump `NODE_MODULE_VERSION` outside of a major release then
<ide> you should consult the TSC. Commits may need to be reverted or a major
<ide> version bump may need to happen.
<ide>
<ide><path>doc/contributing/static-analysis.md
<ide> Any collaborator can ask to be added to the Node.js coverity project
<ide> by opening an issue in the [build](https://github.com/nodejs/build) repository
<ide> titled `Please add me to coverity`. A member of the build WG with admin
<ide> access will verify that the requestor is an existing collaborator as listed in
<del>the [colloborators section](https://github.com/nodejs/node#collaborators)
<add>the [collaborators section](https://github.com/nodejs/node#collaborators)
<ide> on the nodejs/node project repo. Once validated the requestor will added
<ide> to to the coverity project. | 2 |
Ruby | Ruby | upload bottles to archive.org | c11692ba780d7a5663aa693107d98d99a83d1050 | <ide><path>Library/Homebrew/dev-cmd/pr-pull.rb
<ide> def pr_pull_args
<ide> description: "Message to include when autosquashing revision bumps, deletions, and rebuilds."
<ide> flag "--artifact=",
<ide> description: "Download artifacts with the specified name (default: `bottles`)."
<add> flag "--archive-item=",
<add> description: "Upload to the specified Archive item (default: `homebrew`)."
<ide> flag "--bintray-org=",
<ide> description: "Upload to the specified Bintray organisation (default: `homebrew`)."
<ide> flag "--tap=",
<ide> def pr_pull_args
<ide> description: "Comma-separated list of workflows which can be ignored if they have not been run."
<ide>
<ide> conflicts "--clean", "--autosquash"
<add> conflicts "--archive-item", "--bintray-org"
<ide>
<ide> named_args :pull_request, min: 1
<ide> end
<ide> def pr_pull
<ide>
<ide> workflows = args.workflows.presence || ["tests.yml"]
<ide> artifact = args.artifact || "bottles"
<add> archive_item = args.archive_item
<ide> bintray_org = args.bintray_org || "homebrew"
<ide> mirror_repo = args.bintray_mirror || "mirror"
<ide> tap = Tap.fetch(args.tap || CoreTap.instance.name)
<ide> def pr_pull
<ide> upload_args << "--keep-old" if args.keep_old?
<ide> upload_args << "--warn-on-upload-failure" if args.warn_on_upload_failure?
<ide> upload_args << "--root-url=#{args.root_url}" if args.root_url
<del> upload_args << "--bintray-org=#{bintray_org}"
<add> upload_args << if archive_item.present?
<add> "--archive-item=#{archive_item}"
<add> else
<add> "--bintray-org=#{bintray_org}"
<add> end
<ide> safe_system HOMEBREW_BREW_FILE, *upload_args
<ide> end
<ide> end | 1 |
Javascript | Javascript | fix syntheticevent constructor comments | fa7461e25bb63188bc2a3d2eb5ea085dfc7c5f1a | <ide><path>src/renderers/dom/shared/syntheticEvents/SyntheticClipboardEvent.js
<ide> var ClipboardEventInterface = {
<ide> * @param {object} dispatchConfig Configuration used to dispatch this event.
<ide> * @param {string} dispatchMarker Marker identifying the event target.
<ide> * @param {object} nativeEvent Native browser event.
<del> * @extends {SyntheticUIEvent}
<add> * @extends {SyntheticEvent}
<ide> */
<ide> function SyntheticClipboardEvent(
<ide> dispatchConfig,
<ide><path>src/renderers/dom/shared/syntheticEvents/SyntheticCompositionEvent.js
<ide> var CompositionEventInterface = {
<ide> * @param {object} dispatchConfig Configuration used to dispatch this event.
<ide> * @param {string} dispatchMarker Marker identifying the event target.
<ide> * @param {object} nativeEvent Native browser event.
<del> * @extends {SyntheticUIEvent}
<add> * @extends {SyntheticEvent}
<ide> */
<ide> function SyntheticCompositionEvent(
<ide> dispatchConfig,
<ide><path>src/renderers/dom/shared/syntheticEvents/SyntheticDragEvent.js
<ide> var DragEventInterface = {
<ide> * @param {object} dispatchConfig Configuration used to dispatch this event.
<ide> * @param {string} dispatchMarker Marker identifying the event target.
<ide> * @param {object} nativeEvent Native browser event.
<del> * @extends {SyntheticUIEvent}
<add> * @extends {SyntheticMouseEvent}
<ide> */
<ide> function SyntheticDragEvent(
<ide> dispatchConfig,
<ide><path>src/renderers/dom/shared/syntheticEvents/SyntheticInputEvent.js
<ide> var InputEventInterface = {
<ide> * @param {object} dispatchConfig Configuration used to dispatch this event.
<ide> * @param {string} dispatchMarker Marker identifying the event target.
<ide> * @param {object} nativeEvent Native browser event.
<del> * @extends {SyntheticUIEvent}
<add> * @extends {SyntheticEvent}
<ide> */
<ide> function SyntheticInputEvent(
<ide> dispatchConfig, | 4 |
Javascript | Javascript | deprecate the 'ini' module | c82d64649c93325392dd0f2d94cdb0de95c90680 | <ide><path>lib/ini.js
<add>var sys = require('sys');
<add>
<add>sys.error('The "ini" module will be removed in future versions of Node, please extract it into your own code.');
<add>
<ide> // TODO:
<ide> // 1. Handle quoted strings, including line breaks, so that this:
<ide> // foo = "bar | 1 |
Python | Python | fix failing tests for azure batch | b609c119f43818f22256d0a43e274ba0ce35b51c | <ide><path>tests/providers/microsoft/azure/operators/test_azure_batch.py
<ide> def setUp(self, mock_batch, mock_hook):
<ide> batch_pool_vm_size=BATCH_VM_SIZE,
<ide> batch_job_id=BATCH_JOB_ID,
<ide> batch_task_id=BATCH_TASK_ID,
<add> vm_node_agent_sku_id=self.test_node_agent_sku,
<ide> os_family="4",
<ide> batch_task_command_line="echo hello",
<ide> azure_batch_conn_id=self.test_vm_conn_id,
<ide> def setUp(self, mock_batch, mock_hook):
<ide> batch_pool_vm_size=BATCH_VM_SIZE,
<ide> batch_job_id=BATCH_JOB_ID,
<ide> batch_task_id=BATCH_TASK_ID,
<add> vm_node_agent_sku_id=self.test_node_agent_sku,
<ide> os_family="4",
<ide> batch_task_command_line="echo hello",
<ide> azure_batch_conn_id=self.test_vm_conn_id,
<ide> def setUp(self, mock_batch, mock_hook):
<ide> batch_pool_vm_size=BATCH_VM_SIZE,
<ide> batch_job_id=BATCH_JOB_ID,
<ide> batch_task_id=BATCH_TASK_ID,
<add> vm_node_agent_sku_id=self.test_node_agent_sku,
<ide> os_family="4",
<ide> batch_task_command_line="echo hello",
<ide> azure_batch_conn_id=self.test_vm_conn_id,
<ide> def setUp(self, mock_batch, mock_hook):
<ide> batch_pool_vm_size=BATCH_VM_SIZE,
<ide> batch_job_id=BATCH_JOB_ID,
<ide> batch_task_id=BATCH_TASK_ID,
<add> vm_node_agent_sku_id=self.test_node_agent_sku,
<ide> batch_task_command_line="echo hello",
<ide> azure_batch_conn_id=self.test_vm_conn_id,
<ide> target_dedicated_nodes=1, | 1 |
Text | Text | fix formatting of changelog | b151a81a1a9219a66170340736992d54ad45274e | <ide><path>CHANGELOG.md
<ide> Plus es-do locale and locale bugfixes
<ide>
<ide> ### 2.13.0 [See full changelog](https://gist.github.com/ichernev/0132fcf5b61f7fc140b0bb0090480d49)
<ide> - Release April 18, 2016
<add>
<ide> ## Enhancements:
<ide> * [#2982](https://github.com/moment/moment/pull/2982) Add 'date' as alias to 'day' for startOf() and endOf().
<ide> * [#2955](https://github.com/moment/moment/pull/2955) Add parsing negative components in durations when ISO 8601 | 1 |
PHP | PHP | add deferred interface for service providers | 36f7df7d589d095cea44d856a597e44d8eeccdf6 | <ide><path>src/Illuminate/Contracts/Support/Deferred.php
<add><?php
<add>
<add>namespace Illuminate\Contracts\Support;
<add>
<add>interface Deferred
<add>{
<add> /**
<add> * Get the services provided by the provider.
<add> *
<add> * @return array
<add> */
<add> public function provides();
<add>}
<ide><path>src/Illuminate/Support/ServiceProvider.php
<ide> namespace Illuminate\Support;
<ide>
<ide> use Illuminate\Console\Application as Artisan;
<add>use Illuminate\Contracts\Support\Deferred;
<ide>
<ide> abstract class ServiceProvider
<ide> {
<ide> public function when()
<ide> */
<ide> public function isDeferred()
<ide> {
<del> return $this->defer;
<add> return $this->defer || $this instanceof Deferred;
<ide> }
<ide> } | 2 |
Text | Text | update changelog [ci skip] | 2d061c2c4fbd7ed4df9bd3368d94aba736663dab | <ide><path>actionpack/CHANGELOG.md
<ide> We often want to render different html/json/xml templates for phones,
<ide> tablets, and desktop browsers. Variants make it easy.
<ide>
<del> The request variant is a specialization of the request format, like :tablet,
<del> :phone, or :desktop.
<add> The request variant is a specialization of the request format, like `:tablet`,
<add> `:phone`, or `:desktop`.
<ide>
<ide> You can set the variant in a before_action:
<ide> | 1 |
Go | Go | add simple tool to test the deviceset commands | 7fb3bfed03d4d2a88f0e76fd6b8425cc753f4547 | <ide><path>devmapper/docker-device-tool/device_tool.go
<add>package main
<add>
<add>import (
<add> "fmt"
<add> "github.com/dotcloud/docker/devmapper"
<add> "os"
<add>)
<add>
<add>func usage() {
<add> fmt.Printf("Usage: %s [snap new-id base-id] | [remove id] | [mount id mountpoint]\n", os.Args[0])
<add> os.Exit(1)
<add>}
<add>
<add>func main() {
<add> devices := devmapper.NewDeviceSetDM("/var/lib/docker")
<add>
<add> if len(os.Args) < 2 {
<add> usage()
<add> }
<add>
<add> cmd := os.Args[1]
<add> if cmd == "snap" {
<add> if len(os.Args) < 4 {
<add> usage()
<add> }
<add>
<add> err := devices.AddDevice(os.Args[2], os.Args[3])
<add> if err != nil {
<add> fmt.Println("Can't create snap device: ", err)
<add> os.Exit(1)
<add> }
<add> } else if cmd == "remove" {
<add> if len(os.Args) < 3 {
<add> usage()
<add> }
<add>
<add> err := devices.RemoveDevice(os.Args[2])
<add> if err != nil {
<add> fmt.Println("Can't remove device: ", err)
<add> os.Exit(1)
<add> }
<add> } else if cmd == "mount" {
<add> if len(os.Args) < 4 {
<add> usage()
<add> }
<add>
<add> err := devices.MountDevice(os.Args[2], os.Args[3])
<add> if err != nil {
<add> fmt.Println("Can't create snap device: ", err)
<add> os.Exit(1)
<add> }
<add> } else {
<add> fmt.Printf("Unknown command %s\n", cmd)
<add> if len(os.Args) < 4 {
<add> usage()
<add> }
<add>
<add> os.Exit(1)
<add> }
<add>
<add> return
<add>} | 1 |
Text | Text | change http links to https in windows.md | 98121f325ef03857fa24d9c9a315dd903dab63a3 | <ide><path>docs/build-instructions/windows.md
<del>See the [Hacking on Atom Core](http://flight-manual.atom.io/hacking-atom/sections/hacking-on-atom-core/#platform-windows) section in the [Atom Flight Manual](http://flight-manual.atom.io).
<add>See the [Hacking on Atom Core](https://flight-manual.atom.io/hacking-atom/sections/hacking-on-atom-core/#platform-windows) section in the [Atom Flight Manual](https://flight-manual.atom.io). | 1 |
Mixed | Ruby | serialize classes and modules with activejob | fbebeabd6d59280c3a8173b58657f755904b02db | <ide><path>activejob/CHANGELOG.md
<add>* Allow `Class` and `Module` instances to be serialized.
<add>
<add> *Kevin Deisz*
<add>
<ide> * Log potential matches in `assert_enqueued_with` and `assert_performed_with`
<ide>
<ide> *Gareth du Plooy*
<ide><path>activejob/lib/active_job/serializers.rb
<ide> module Serializers # :nodoc:
<ide> autoload :DateSerializer
<ide> autoload :TimeWithZoneSerializer
<ide> autoload :TimeSerializer
<add> autoload :ModuleSerializer
<ide>
<ide> mattr_accessor :_additional_serializers
<ide> self._additional_serializers = Set.new
<ide> def add_serializers(*new_serializers)
<ide> DateTimeSerializer,
<ide> DateSerializer,
<ide> TimeWithZoneSerializer,
<del> TimeSerializer
<add> TimeSerializer,
<add> ModuleSerializer
<ide> end
<ide> end
<ide><path>activejob/lib/active_job/serializers/module_serializer.rb
<add># frozen_string_literal: true
<add>
<add>module ActiveJob
<add> module Serializers
<add> class ModuleSerializer < ObjectSerializer # :nodoc:
<add> def serialize(constant)
<add> super("value" => constant.name)
<add> end
<add>
<add> def deserialize(hash)
<add> hash["value"].constantize
<add> end
<add>
<add> private
<add> def klass
<add> Module
<add> end
<add> end
<add> end
<add>end
<ide><path>activejob/test/cases/argument_serialization_test.rb
<ide> require "support/stubs/strong_parameters"
<ide>
<ide> class ArgumentSerializationTest < ActiveSupport::TestCase
<add> module ModuleArgument
<add> class ClassArgument; end
<add> end
<add>
<add> class ClassArgument; end
<add>
<ide> setup do
<ide> @person = Person.find("5")
<ide> end
<ide> class ArgumentSerializationTest < ActiveSupport::TestCase
<ide> DateTime.new(2001, 2, 3, 4, 5, 6, "+03:00"),
<ide> ActiveSupport::TimeWithZone.new(Time.utc(1999, 12, 31, 23, 59, 59), ActiveSupport::TimeZone["UTC"]),
<ide> [ 1, "a" ],
<del> { "a" => 1 }
<add> { "a" => 1 },
<add> ModuleArgument,
<add> ModuleArgument::ClassArgument,
<add> ClassArgument
<ide> ].each do |arg|
<ide> test "serializes #{arg.class} - #{arg} verbatim" do
<ide> assert_arguments_unchanged arg
<ide> end
<ide> end
<ide>
<del> [ Object.new, self, Person.find("5").to_gid ].each do |arg|
<add> [ Object.new, Person.find("5").to_gid ].each do |arg|
<ide> test "does not serialize #{arg.class}" do
<ide> assert_raises ActiveJob::SerializationError do
<ide> ActiveJob::Arguments.serialize [ arg ]
<ide><path>guides/source/active_job_basics.md
<ide> ActiveJob supports the following types of arguments by default:
<ide> - `Hash` (Keys should be of `String` or `Symbol` type)
<ide> - `ActiveSupport::HashWithIndifferentAccess`
<ide> - `Array`
<add> - `Module`
<add> - `Class`
<ide>
<ide> ### GlobalID
<ide> | 5 |
Python | Python | update optimizers for tf2. | 544625545afe2e9c2b358e356c11bb8be53ceb51 | <ide><path>keras/optimizers.py
<ide>
<ide> import six
<ide> import copy
<add>import numpy as np
<ide> from six.moves import zip
<ide>
<ide> from . import backend as K
<ide> class SGD(Optimizer):
<ide> learning_rate: float >= 0. Learning rate.
<ide> momentum: float >= 0. Parameter that accelerates SGD
<ide> in the relevant direction and dampens oscillations.
<del> decay: float >= 0. Learning rate decay over each update.
<ide> nesterov: boolean. Whether to apply Nesterov momentum.
<ide> """
<ide>
<del> def __init__(self, learning_rate=0.01, momentum=0., decay=0.,
<add> def __init__(self, learning_rate=0.01, momentum=0.,
<ide> nesterov=False, **kwargs):
<del> learning_rate = kwargs.pop('lr', None) or learning_rate
<add> learning_rate = kwargs.pop('lr', learning_rate)
<add> self.initial_decay = kwargs.pop('decay', 0.0)
<ide> super(SGD, self).__init__(**kwargs)
<ide> with K.name_scope(self.__class__.__name__):
<ide> self.iterations = K.variable(0, dtype='int64', name='iterations')
<ide> self.learning_rate = K.variable(learning_rate, name='learning_rate')
<ide> self.momentum = K.variable(momentum, name='momentum')
<del> self.decay = K.variable(decay, name='decay')
<del> self.initial_decay = decay
<add> self.decay = K.variable(self.initial_decay, name='decay')
<ide> self.nesterov = nesterov
<ide>
<ide> @interfaces.legacy_get_updates_support
<ide> class RMSprop(Optimizer):
<ide> # Arguments
<ide> learning_rate: float >= 0. Learning rate.
<ide> rho: float >= 0.
<del> epsilon: float >= 0. Fuzz factor. If `None`, defaults to `K.epsilon()`.
<del> decay: float >= 0. Learning rate decay over each update.
<ide>
<ide> # References
<ide> - [rmsprop: Divide the gradient by a running average of its recent magnitude
<ide> ](http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)
<ide> """
<ide>
<del> def __init__(self, learning_rate=0.001, rho=0.9, epsilon=None, decay=0.,
<del> **kwargs):
<del> learning_rate = kwargs.pop('lr', None) or learning_rate
<add> def __init__(self, learning_rate=0.001, rho=0.9, **kwargs):
<add> self.initial_decay = kwargs.pop('decay', 0.0)
<add> self.epsilon = kwargs.pop('epsilon', K.epsilon())
<add> learning_rate = kwargs.pop('lr', learning_rate)
<ide> super(RMSprop, self).__init__(**kwargs)
<ide> with K.name_scope(self.__class__.__name__):
<ide> self.learning_rate = K.variable(learning_rate, name='learning_rate')
<ide> self.rho = K.variable(rho, name='rho')
<del> self.decay = K.variable(decay, name='decay')
<add> self.decay = K.variable(self.initial_decay, name='decay')
<ide> self.iterations = K.variable(0, dtype='int64', name='iterations')
<del> if epsilon is None:
<del> epsilon = K.epsilon()
<del> self.epsilon = epsilon
<del> self.initial_decay = decay
<ide>
<ide> @interfaces.legacy_get_updates_support
<ide> @K.symbolic
<ide> def get_updates(self, loss, params):
<ide> dtype=K.dtype(p),
<ide> name='accumulator_' + str(i))
<ide> for (i, p) in enumerate(params)]
<del> self.weights = accumulators
<add> self.weights = [self.iterations] + accumulators
<ide> self.updates = [K.update_add(self.iterations, 1)]
<ide>
<ide> lr = self.learning_rate
<ide> def get_updates(self, loss, params):
<ide> self.updates.append(K.update(p, new_p))
<ide> return self.updates
<ide>
<add> def set_weights(self, weights):
<add> params = self.weights
<add> # Override set_weights for backward compatibility of Keras 2.2.4 optimizer
<add> # since it does not include iteration at head of the weight list. Set
<add> # iteration to 0.
<add> if len(params) == len(weights) + 1:
<add> weights = [np.array(0)] + weights
<add> super(RMSprop, self).set_weights(weights)
<add>
<ide> def get_config(self):
<ide> config = {'learning_rate': float(K.get_value(self.learning_rate)),
<ide> 'rho': float(K.get_value(self.rho)),
<ide> class Adagrad(Optimizer):
<ide>
<ide> # Arguments
<ide> learning_rate: float >= 0. Initial learning rate.
<del> epsilon: float >= 0. If `None`, defaults to `K.epsilon()`.
<del> decay: float >= 0. Learning rate decay over each update.
<ide>
<ide> # References
<ide> - [Adaptive Subgradient Methods for Online Learning and Stochastic
<ide> Optimization](http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf)
<ide> """
<ide>
<del> def __init__(self, learning_rate=0.01, epsilon=None, decay=0., **kwargs):
<del> learning_rate = kwargs.pop('lr', None) or learning_rate
<add> def __init__(self, learning_rate=0.01, **kwargs):
<add> self.initial_decay = kwargs.pop('decay', 0.0)
<add> self.epsilon = kwargs.pop('epsilon', K.epsilon())
<add> learning_rate = kwargs.pop('lr', learning_rate)
<ide> super(Adagrad, self).__init__(**kwargs)
<ide> with K.name_scope(self.__class__.__name__):
<ide> self.learning_rate = K.variable(learning_rate, name='learning_rate')
<del> self.decay = K.variable(decay, name='decay')
<add> self.decay = K.variable(self.initial_decay, name='decay')
<ide> self.iterations = K.variable(0, dtype='int64', name='iterations')
<del> if epsilon is None:
<del> epsilon = K.epsilon()
<del> self.epsilon = epsilon
<del> self.initial_decay = decay
<ide>
<ide> @interfaces.legacy_get_updates_support
<ide> @K.symbolic
<ide> def get_updates(self, loss, params):
<ide> shapes = [K.int_shape(p) for p in params]
<ide> accumulators = [K.zeros(shape, name='accumulator_' + str(i))
<ide> for (i, shape) in enumerate(shapes)]
<del> self.weights = accumulators
<add> self.weights = [self.iterations] + accumulators
<ide> self.updates = [K.update_add(self.iterations, 1)]
<ide>
<ide> lr = self.learning_rate
<ide> def get_updates(self, loss, params):
<ide> self.updates.append(K.update(p, new_p))
<ide> return self.updates
<ide>
<add> def set_weights(self, weights):
<add> params = self.weights
<add> # Override set_weights for backward compatibility of Keras 2.2.4 optimizer
<add> # since it does not include iteration at head of the weight list. Set
<add> # iteration to 0.
<add> if len(params) == len(weights) + 1:
<add> weights = [np.array(0)] + weights
<add> super(Adagrad, self).set_weights(weights)
<add>
<ide> def get_config(self):
<ide> config = {'learning_rate': float(K.get_value(self.learning_rate)),
<ide> 'decay': float(K.get_value(self.decay)),
<ide> class Adadelta(Optimizer):
<ide> It is recommended to leave it at the default value.
<ide> rho: float >= 0. Adadelta decay factor, corresponding to fraction of
<ide> gradient to keep at each time step.
<del> epsilon: float >= 0. Fuzz factor. If `None`, defaults to `K.epsilon()`.
<del> decay: float >= 0. Initial learning rate decay.
<ide>
<ide> # References
<ide> - [Adadelta - an adaptive learning rate method](
<ide> https://arxiv.org/abs/1212.5701)
<ide> """
<ide>
<del> def __init__(self, learning_rate=1.0, rho=0.95, epsilon=None, decay=0.,
<del> **kwargs):
<del> learning_rate = kwargs.pop('lr', None) or learning_rate
<add> def __init__(self, learning_rate=1.0, rho=0.95, **kwargs):
<add> self.initial_decay = kwargs.pop('decay', 0.0)
<add> self.epsilon = kwargs.pop('epsilon', K.epsilon())
<add> learning_rate = kwargs.pop('lr', learning_rate)
<ide> super(Adadelta, self).__init__(**kwargs)
<ide> with K.name_scope(self.__class__.__name__):
<ide> self.learning_rate = K.variable(learning_rate, name='learning_rate')
<del> self.decay = K.variable(decay, name='decay')
<add> self.decay = K.variable(self.initial_decay, name='decay')
<ide> self.iterations = K.variable(0, dtype='int64', name='iterations')
<del> if epsilon is None:
<del> epsilon = K.epsilon()
<ide> self.rho = rho
<del> self.epsilon = epsilon
<del> self.initial_decay = decay
<ide>
<ide> @interfaces.legacy_get_updates_support
<ide> @K.symbolic
<ide> def get_updates(self, loss, params):
<ide> for (i, shape) in enumerate(shapes)]
<ide> delta_accumulators = [K.zeros(shape, name='delta_accumulator_' + str(i))
<ide> for (i, shape) in enumerate(shapes)]
<del> self.weights = accumulators + delta_accumulators
<add> self.weights = [self.iterations] + accumulators + delta_accumulators
<ide> self.updates = [K.update_add(self.iterations, 1)]
<ide>
<ide> lr = self.learning_rate
<ide> def get_updates(self, loss, params):
<ide> self.updates.append(K.update(d_a, new_d_a))
<ide> return self.updates
<ide>
<add> def set_weights(self, weights):
<add> params = self.weights
<add> # Override set_weights for backward compatibility of Keras 2.2.4 optimizer
<add> # since it does not include iteration at head of the weight list. Set
<add> # iteration to 0.
<add> if len(params) == len(weights) + 1:
<add> weights = [np.array(0)] + weights
<add> super(Adadelta, self).set_weights(weights)
<add>
<ide> def get_config(self):
<ide> config = {'learning_rate': float(K.get_value(self.learning_rate)),
<ide> 'rho': self.rho,
<ide> class Adam(Optimizer):
<ide> learning_rate: float >= 0. Learning rate.
<ide> beta_1: float, 0 < beta < 1. Generally close to 1.
<ide> beta_2: float, 0 < beta < 1. Generally close to 1.
<del> epsilon: float >= 0. Fuzz factor. If `None`, defaults to `K.epsilon()`.
<del> decay: float >= 0. Learning rate decay over each update.
<ide> amsgrad: boolean. Whether to apply the AMSGrad variant of this
<ide> algorithm from the paper "On the Convergence of Adam and
<ide> Beyond".
<ide> class Adam(Optimizer):
<ide> """
<ide>
<ide> def __init__(self, learning_rate=0.001, beta_1=0.9, beta_2=0.999,
<del> epsilon=None, decay=0., amsgrad=False, **kwargs):
<del> learning_rate = kwargs.pop('lr', None) or learning_rate
<add> amsgrad=False, **kwargs):
<add> self.initial_decay = kwargs.pop('decay', 0.0)
<add> self.epsilon = kwargs.pop('epsilon', K.epsilon())
<add> learning_rate = kwargs.pop('lr', learning_rate)
<ide> super(Adam, self).__init__(**kwargs)
<ide> with K.name_scope(self.__class__.__name__):
<ide> self.iterations = K.variable(0, dtype='int64', name='iterations')
<ide> self.learning_rate = K.variable(learning_rate, name='learning_rate')
<ide> self.beta_1 = K.variable(beta_1, name='beta_1')
<ide> self.beta_2 = K.variable(beta_2, name='beta_2')
<del> self.decay = K.variable(decay, name='decay')
<del> if epsilon is None:
<del> epsilon = K.epsilon()
<del> self.epsilon = epsilon
<del> self.initial_decay = decay
<add> self.decay = K.variable(self.initial_decay, name='decay')
<ide> self.amsgrad = amsgrad
<ide>
<ide> @interfaces.legacy_get_updates_support
<ide> class Adamax(Optimizer):
<ide> learning_rate: float >= 0. Learning rate.
<ide> beta_1: float, 0 < beta < 1. Generally close to 1.
<ide> beta_2: float, 0 < beta < 1. Generally close to 1.
<del> epsilon: float >= 0. Fuzz factor. If `None`, defaults to `K.epsilon()`.
<del> decay: float >= 0. Learning rate decay over each update.
<ide>
<ide> # References
<ide> - [Adam - A Method for Stochastic Optimization](
<ide> https://arxiv.org/abs/1412.6980v8)
<ide> """
<ide>
<del> def __init__(self, learning_rate=0.002, beta_1=0.9, beta_2=0.999,
<del> epsilon=None, decay=0., **kwargs):
<del> learning_rate = kwargs.pop('lr', None) or learning_rate
<add> def __init__(self, learning_rate=0.002, beta_1=0.9, beta_2=0.999, **kwargs):
<add> self.initial_decay = kwargs.pop('decay', 0.0)
<add> self.epsilon = kwargs.pop('epsilon', K.epsilon())
<add> learning_rate = kwargs.pop('lr', learning_rate)
<ide> super(Adamax, self).__init__(**kwargs)
<ide> with K.name_scope(self.__class__.__name__):
<ide> self.iterations = K.variable(0, dtype='int64', name='iterations')
<ide> self.learning_rate = K.variable(learning_rate, name='learning_rate')
<ide> self.beta_1 = K.variable(beta_1, name='beta_1')
<ide> self.beta_2 = K.variable(beta_2, name='beta_2')
<del> self.decay = K.variable(decay, name='decay')
<del> if epsilon is None:
<del> epsilon = K.epsilon()
<del> self.epsilon = epsilon
<del> self.initial_decay = decay
<add> self.decay = K.variable(self.initial_decay, name='decay')
<ide>
<ide> @interfaces.legacy_get_updates_support
<ide> @K.symbolic
<ide> class Nadam(Optimizer):
<ide> learning_rate: float >= 0. Learning rate.
<ide> beta_1: float, 0 < beta < 1. Generally close to 1.
<ide> beta_2: float, 0 < beta < 1. Generally close to 1.
<del> epsilon: float >= 0. Fuzz factor. If `None`, defaults to `K.epsilon()`.
<del> schedule_decay: float, 0 < schedule_decay < 1.
<ide>
<ide> # References
<ide> - [Nadam report](http://cs229.stanford.edu/proj2015/054_report.pdf)
<ide> - [On the importance of initialization and momentum in deep learning](
<ide> http://www.cs.toronto.edu/~fritz/absps/momentum.pdf)
<ide> """
<ide>
<del> def __init__(self, learning_rate=0.002, beta_1=0.9, beta_2=0.999,
<del> epsilon=None, schedule_decay=0.004, **kwargs):
<del> learning_rate = kwargs.pop('lr', None) or learning_rate
<add> def __init__(self, learning_rate=0.002, beta_1=0.9, beta_2=0.999, **kwargs):
<add> self.schedule_decay = kwargs.pop('schedule_decay', 0.004)
<add> self.epsilon = kwargs.pop('epsilon', K.epsilon())
<add> learning_rate = kwargs.pop('lr', learning_rate)
<ide> super(Nadam, self).__init__(**kwargs)
<ide> with K.name_scope(self.__class__.__name__):
<ide> self.iterations = K.variable(0, dtype='int64', name='iterations')
<ide> self.m_schedule = K.variable(1., name='m_schedule')
<ide> self.learning_rate = K.variable(learning_rate, name='learning_rate')
<ide> self.beta_1 = K.variable(beta_1, name='beta_1')
<ide> self.beta_2 = K.variable(beta_2, name='beta_2')
<del> if epsilon is None:
<del> epsilon = K.epsilon()
<del> self.epsilon = epsilon
<del> self.schedule_decay = schedule_decay
<ide>
<ide> @interfaces.legacy_get_updates_support
<ide> @K.symbolic
<ide> def get_updates(self, loss, params):
<ide> vs = [K.zeros(shape, name='v_' + str(i))
<ide> for (i, shape) in enumerate(shapes)]
<ide>
<del> self.weights = [self.iterations] + ms + vs
<add> self.weights = [self.iterations, self.m_schedule] + ms + vs
<ide>
<ide> for p, g, m, v in zip(params, grads, ms, vs):
<ide> # the following equations given in [1]
<ide> def get_updates(self, loss, params):
<ide> self.updates.append(K.update(p, new_p))
<ide> return self.updates
<ide>
<add> def set_weights(self, weights):
<add> params = self.weights
<add> # Override set_weights for backward compatibility of Keras 2.2.4 optimizer
<add> # since it does not include m_schedule at head of the weight list. Set
<add> # m_schedule to 1.
<add> if len(params) == len(weights) + 1:
<add> weights = [weights[0]] + [np.array(1.)] + weights[1:]
<add> super(Nadam, self).set_weights(weights)
<add>
<ide> def get_config(self):
<ide> config = {'learning_rate': float(K.get_value(self.learning_rate)),
<ide> 'beta_1': float(K.get_value(self.beta_1)), | 1 |
Ruby | Ruby | use params default | b8df3a9197252ec62f390ef1f8cd0e0e827c6252 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
<ide> def current_savepoint_name
<ide>
<ide> protected
<ide>
<del> def log(sql, name)
<del> name ||= "SQL"
<add> def log(sql, name = "SQL")
<ide> @instrumenter.instrument("sql.active_record",
<ide> :sql => sql, :name => name, :connection_id => object_id) do
<ide> yield | 1 |
Python | Python | fix incorrect use of stringio to handle bytes | 01e63f270a39f3b52f6c4c6fa4b72bf46d0c8349 | <ide><path>numpy/linalg/lapack_lite/clapack_scrub.py
<ide> from __future__ import division, absolute_import, print_function
<ide>
<ide> import sys, os
<del>from io import StringIO
<add>from io import BytesIO
<ide> import re
<ide> from plex import Scanner, Str, Lexicon, Opt, Bol, State, AnyChar, TEXT, IGNORE
<ide> from plex.traditional import re as Re
<ide> def sep_seq(sequence, sep):
<ide> return pat
<ide>
<ide> def runScanner(data, scanner_class, lexicon=None):
<del> info = StringIO(data)
<del> outfo = StringIO()
<add> info = BytesIO(data)
<add> outfo = BytesIO()
<ide> if lexicon is not None:
<ide> scanner = scanner_class(lexicon, info)
<ide> else:
<ide> def HaveBlankLines(line):
<ide> return SourceLines
<ide>
<ide> state = SourceLines
<del> for line in StringIO(source):
<add> for line in BytesIO(source):
<ide> state = state(line)
<ide> comments.flushTo(lines)
<ide> return lines.getValue()
<ide> def OutOfHeader(line):
<ide> return OutOfHeader
<ide>
<ide> state = LookingForHeader
<del> for line in StringIO(source):
<add> for line in BytesIO(source):
<ide> state = state(line)
<ide> return lines.getValue()
<ide> | 1 |
PHP | PHP | improve error message when route filters fail | 0c8ffd001436615916f4b823dabbc0a03c01cc65 | <ide><path>src/Routing/Router.php
<ide> use Cake\Http\ServerRequest;
<ide> use Cake\Routing\Exception\MissingRouteException;
<ide> use Cake\Utility\Inflector;
<add>use Exception;
<ide> use Psr\Http\Message\ServerRequestInterface;
<add>use RuntimeException;
<add>use Throwable;
<ide>
<ide> /**
<ide> * Parses the request URL into controller, action, and parameters. Uses the connected routes
<ide> public static function addUrlFilter(callable $function)
<ide> protected static function _applyUrlFilters($url)
<ide> {
<ide> $request = static::getRequest(true);
<del> foreach (static::$_urlFilters as $filter) {
<del> $url = $filter($url, $request);
<add> $e = null;
<add> foreach (static::$_urlFilters as $index => $filter) {
<add> try {
<add> $url = $filter($url, $request);
<add> } catch (Exception $e) {
<add> // fall through
<add> } catch (Throwable $e) {
<add> // fall through
<add> }
<add> if ($e !== null) {
<add> $message = 'URL filter at index %s could not be applied. The filter failed with: %s';
<add> throw new RuntimeException(sprintf($message, $index, $e->getMessage()), $e->getCode(), $e);
<add> }
<ide> }
<ide>
<ide> return $url;
<ide><path>tests/TestCase/Routing/RouterTest.php
<ide> use Cake\Routing\Router;
<ide> use Cake\Routing\Route\Route;
<ide> use Cake\TestSuite\TestCase;
<add>use RuntimeException;
<ide>
<ide> /**
<ide> * RouterTest class
<ide> public function testUrlGenerationWithUrlFilter()
<ide> $this->assertEquals(2, $calledCount);
<ide> }
<ide>
<add> /**
<add> * Test that url filter failure gives better errors
<add> *
<add> * @return void
<add> */
<add> public function testUrlGenerationWithUrlFilterFailure()
<add> {
<add> $this->expectException(RuntimeException::class);
<add> $this->expectExceptionMessage('URL filter at index 0 could not be applied. The filter failed with: nope');
<add> Router::connect('/:lang/:controller/:action/*');
<add> $request = new ServerRequest([
<add> 'params' => [
<add> 'plugin' => null,
<add> 'lang' => 'en',
<add> 'controller' => 'posts',
<add> 'action' => 'index'
<add> ]
<add> ]);
<add> Router::pushRequest($request);
<add>
<add> Router::addUrlFilter(function ($url, $request) {
<add> throw new RuntimeException('nope');
<add> });
<add> Router::url(['controller' => 'posts', 'action' => 'index', 'lang' => 'en']);
<add> }
<add>
<ide> /**
<ide> * Test url param persistence.
<ide> * | 2 |
PHP | PHP | fix a few request bugs | 04f1c04afea8a7fc733e305e33e05411dc316399 | <ide><path>src/Illuminate/Foundation/Application.php
<ide> public function booted($callback)
<ide> * @param \Symfony\Component\HttpFoundation\Request $request
<ide> * @return void
<ide> */
<del> public function run(SymfonyRequest $request)
<add> public function run(SymfonyRequest $request = null)
<ide> {
<add> $request = $request ?: $this['request'];
<add>
<ide> $response = with(new \Stack\Builder)
<ide> ->push('Illuminate\Cookie\Guard', $this['encrypter'])
<ide> ->push('Illuminate\Cookie\Queue', $this['cookie'])
<ide> ->push('Illuminate\Session\Middleware', $this['session'])
<ide> ->resolve($this)
<del> ->handle($this['request']);
<add> ->handle($request);
<ide>
<ide> $this->callCloseCallbacks($request, $response);
<ide> | 1 |
Go | Go | remove job from export | 6b737752e342e30dd20417b18c92c9b4e1c4f8da | <ide><path>api/server/server.go
<ide> func getContainersExport(eng *engine.Engine, version version.Version, w http.Res
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<del> job := eng.Job("export", vars["name"])
<del> job.Stdout.Add(w)
<del> if err := job.Run(); err != nil {
<del> return err
<del> }
<del> return nil
<add>
<add> d := getDaemon(eng)
<add>
<add> return d.ContainerExport(vars["name"], w)
<ide> }
<ide>
<ide> func getImagesJSON(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) Install(eng *engine.Engine) error {
<ide> "container_inspect": daemon.ContainerInspect,
<ide> "container_stats": daemon.ContainerStats,
<ide> "create": daemon.ContainerCreate,
<del> "export": daemon.ContainerExport,
<ide> "info": daemon.CmdInfo,
<ide> "logs": daemon.ContainerLogs,
<ide> "restart": daemon.ContainerRestart,
<ide><path>daemon/export.go
<ide> package daemon
<ide> import (
<ide> "fmt"
<ide> "io"
<del>
<del> "github.com/docker/docker/engine"
<ide> )
<ide>
<del>func (daemon *Daemon) ContainerExport(job *engine.Job) error {
<del> if len(job.Args) != 1 {
<del> return fmt.Errorf("Usage: %s container_id", job.Name)
<del> }
<del> name := job.Args[0]
<del>
<add>func (daemon *Daemon) ContainerExport(name string, out io.Writer) error {
<ide> container, err := daemon.Get(name)
<ide> if err != nil {
<ide> return err
<ide> func (daemon *Daemon) ContainerExport(job *engine.Job) error {
<ide> defer data.Close()
<ide>
<ide> // Stream the entire contents of the container (basically a volatile snapshot)
<del> if _, err := io.Copy(job.Stdout, data); err != nil {
<add> if _, err := io.Copy(out, data); err != nil {
<ide> return fmt.Errorf("%s: %s", name, err)
<ide> }
<ide> // FIXME: factor job-specific LogEvent to engine.Job.Run() | 3 |
Go | Go | add zero padding for rfc5424 syslog format | fa6dabf8762da42ce02bf7f484bd6b2621e479d9 | <ide><path>daemon/logger/syslog/syslog.go
<ide> func rfc5424formatterWithAppNameAsTag(p syslog.Priority, hostname, tag, content
<ide> // for multiple syntaxes, there are further restrictions in rfc5424, i.e., the maximum
<ide> // resolution is limited to "TIME-SECFRAC" which is 6 (microsecond resolution)
<ide> func rfc5424microformatterWithAppNameAsTag(p syslog.Priority, hostname, tag, content string) string {
<del> timestamp := time.Now().Format("2006-01-02T15:04:05.999999Z07:00")
<add> timestamp := time.Now().Format("2006-01-02T15:04:05.000000Z07:00")
<ide> pid := os.Getpid()
<ide> msg := fmt.Sprintf("<%d>%d %s %s %s %d %s - %s",
<ide> p, 1, timestamp, hostname, tag, pid, tag, content) | 1 |
Ruby | Ruby | use a case statement in pathname#compression_type | 607605dd8fef262b5c382a78eedef43edbdba27e | <ide><path>Library/Homebrew/extend/pathname.rb
<ide> def version
<ide> end
<ide>
<ide> def compression_type
<del> # Don't treat jars or wars as compressed
<del> return nil if self.extname == '.jar'
<del> return nil if self.extname == '.war'
<del>
<del> # OS X installer package
<del> return :pkg if self.extname == '.pkg'
<del>
<del> # If the filename ends with .gz not preceded by .tar
<del> # then we want to gunzip but not tar
<del> return :gzip_only if self.extname == '.gz'
<add> case extname
<add> when ".jar", ".war"
<add> # Don't treat jars or wars as compressed
<add> return
<add> when ".pkg"
<add> # OS X installer package
<add> return :pkg
<add> when ".gz"
<add> # If the filename ends with .gz not preceded by .tar
<add> # then we want to gunzip but not tar
<add> return :gzip_only
<add> end
<ide>
<ide> # Get enough of the file to detect common file types
<ide> # POSIX tar magic has a 257 byte offset | 1 |
Text | Text | fix url for jawshooah | ebe50703cad152d73150d3f7701a43f26c7839e1 | <ide><path>README.md
<ide> This is our PGP key which is valid until May 24, 2017.
<ide> ## Who Are You?
<ide> Homebrew's lead maintainer is [Mike McQuaid](https://github.com/mikemcquaid).
<ide>
<del>Homebrew's current maintainers are [Misty De Meo](https://github.com/mistydemeo), [Andrew Janke](https://github.com/apjanke), [Xu Cheng](https://github.com/xu-cheng), [Tomasz Pajor](https://github.com/nijikon), [Josh Hagins](https://github.com/vladshablinsky), [Baptiste Fontaine](https://github.com/bfontaine), [Zhiming Wang](https://github.com/zmwangx), [Markus Reiter](https://github.com/reitermarkus), [ilovezfs](https://github.com/ilovezfs), [Martin Afanasjew](https://github.com/UniqMartin), [Tom Schoonjans](https://github.com/tschoonj), [Uladzislau Shablinski](https://github.com/vladshablinsky), [Tim Smith](https://github.com/tdsmith) and [Alex Dunn](https://github.com/dunn).
<add>Homebrew's current maintainers are [Misty De Meo](https://github.com/mistydemeo), [Andrew Janke](https://github.com/apjanke), [Xu Cheng](https://github.com/xu-cheng), [Tomasz Pajor](https://github.com/nijikon), [Josh Hagins](https://github.com/jawshooah), [Baptiste Fontaine](https://github.com/bfontaine), [Zhiming Wang](https://github.com/zmwangx), [Markus Reiter](https://github.com/reitermarkus), [ilovezfs](https://github.com/ilovezfs), [Martin Afanasjew](https://github.com/UniqMartin), [Tom Schoonjans](https://github.com/tschoonj), [Uladzislau Shablinski](https://github.com/vladshablinsky), [Tim Smith](https://github.com/tdsmith) and [Alex Dunn](https://github.com/dunn).
<ide>
<ide> Former maintainers with significant contributions include [Dominyk Tiller](https://github.com/DomT4), [Brett Koonce](https://github.com/asparagui), [Jack Nagel](https://github.com/jacknagel), [Adam Vandenberg](https://github.com/adamv) and Homebrew's creator: [Max Howell](https://github.com/mxcl).
<ide> | 1 |
Javascript | Javascript | fix apollo example | a81913f1ba019c767da0d876a0b18f2922bd9d5e | <ide><path>examples/with-apollo/lib/apollo.js
<ide> import React from 'react'
<ide> import App from 'next/app'
<add>import Head from 'next/head'
<ide> import { ApolloProvider } from '@apollo/react-hooks'
<ide> import createApolloClient from '../apolloClient'
<ide>
<ide> export const withApollo = ({ ssr = false } = {}) => PageComponent => {
<ide> // https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-error
<ide> console.error('Error while running `getDataFromTree`', error)
<ide> }
<add>
<add> // getDataFromTree does not call componentWillUnmount
<add> // head side effect therefore need to be cleared manually
<add> Head.rewind()
<ide> }
<ide> }
<ide> | 1 |
Ruby | Ruby | improve error message for invalid regex to search | 148da475710b882a17e044153102961919c48477 | <ide><path>Library/Homebrew/cmd/search.rb
<ide> def query_regexp(query)
<ide> when %r{^/(.*)/$} then Regexp.new($1)
<ide> else /.*#{Regexp.escape(query)}.*/i
<ide> end
<add> rescue RegexpError
<add> odie "#{query} is not a valid regex"
<ide> end
<ide>
<ide> def search_taps(rx) | 1 |
Python | Python | update absmax.py (#602) | 301493094ef1638fae09c24a2fc4880812839e87 | <ide><path>Maths/absMax.py
<del>from Maths.abs import absVal
<del>
<ide> def absMax(x):
<ide> """
<ide> #>>>absMax([0,5,1,11])
<ide> def absMax(x):
<ide> """
<ide> j =x[0]
<ide> for i in x:
<del> if absVal(i) > absVal(j):
<add> if abs(i) > abs(j):
<ide> j = i
<ide> return j
<del> #BUG: i is apparently a list, TypeError: '<' not supported between instances of 'list' and 'int' in absVal
<del> #BUG fix
<add>
<ide>
<ide> def main():
<del> a = [-13, 2, -11, -12]
<del> print(absMax(a)) # = -13
<add> a = [1,2,-11]
<add> print(absMax(a)) # = -11
<add>
<ide>
<ide> if __name__ == '__main__':
<ide> main() | 1 |
Text | Text | remove wrong usage in usingdocker.md | f46cf7329507351e107e3a84132f14ed02dc163b | <ide><path>docs/sources/userguide/usingdocker.md
<ide> language powering Docker).
<ide>
<ide> Last stable version: 0.8.0
<ide>
<del>### Seeing what the Docker client can do
<add>## Get Docker command help
<ide>
<del>We can see all of the commands available to us with the Docker client by
<del>running the `docker` binary without any options.
<add>You can display the help for specific Docker commands. The help details the
<add>options and their usage. To see a list of all the possible commands, use the
<add>following:
<ide>
<del> $ docker
<add> $ docker --help
<ide>
<del>You will see a list of all currently available commands.
<del>
<del> Commands:
<del> attach Attach to a running container
<del> build Build an image from a Dockerfile
<del> commit Create a new image from a container's changes
<del> . . .
<del>
<del>### Seeing Docker command usage
<del>
<del>You can also zoom in and review the usage for specific Docker commands.
<del>
<del>Try typing Docker followed with a `[command]` to see the usage for that
<del>command:
<del>
<del> $ docker attach
<del> Help output . . .
<del>
<del>Or you can also pass the `--help` flag to the `docker` binary.
<add>To see usage for a specific command, specify the command with the `--help` flag:
<ide>
<ide> $ docker attach --help
<ide>
<del>This will display the help text and all available flags:
<del>
<ide> Usage: docker attach [OPTIONS] CONTAINER
<ide>
<ide> Attach to a running container
<ide>
<del> --no-stdin=false: Do not attach stdin
<del> --sig-proxy=true: Proxify all received signal to the process (non-TTY mode only)
<add> --help=false Print usage
<add> --no-stdin=false Do not attach stdin
<add> --sig-proxy=true Proxy all received signals to the process
<ide>
<ide> > **Note:**
<del>> You can see a full list of Docker's commands
<del>> [here](/reference/commandline/cli/).
<add>> For further details and examples of each command, see the
<add>> [command reference](/reference/commandline/cli/) in this guide.
<ide>
<ide> ## Running a web application in Docker
<ide> | 1 |
Java | Java | fix flaky tests | 9807aae38ce5efdd5a953d297a2ba8da071123fd | <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java
<ide> public void subscribe(Subscriber<? super String> s) {
<ide> ts.assertValues("hello", "hello");
<ide> }
<ide>
<del> @Test(timeout = 10000)
<add> @Test(timeout = 30000)
<ide> public void testIssue2890NoStackoverflow() throws InterruptedException {
<ide> final ExecutorService executor = Executors.newFixedThreadPool(2);
<ide> final Scheduler sch = Schedulers.from(executor);
<ide> public void onError(Throwable e) {
<ide> }
<ide> });
<ide>
<del> executor.awaitTermination(12000, TimeUnit.MILLISECONDS);
<add> executor.awaitTermination(20000, TimeUnit.MILLISECONDS);
<ide>
<ide> assertEquals(n, counter.get());
<ide> }
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java
<ide> public void testAsyncComeAndGo() {
<ide> .subscribeOn(Schedulers.io());
<ide> Flowable<Long> cached = source.replay().autoConnect();
<ide>
<del> Flowable<Long> output = cached.observeOn(Schedulers.computation());
<add> Flowable<Long> output = cached.observeOn(Schedulers.computation(), false, 1024);
<ide>
<ide> List<TestSubscriber<Long>> list = new ArrayList<TestSubscriber<Long>>(100);
<ide> for (int i = 0; i < 100; i++) {
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithSizeTest.java
<ide> public void accept(Integer t1) {
<ide> ts.assertTerminated();
<ide> ts.assertValues(1, 2, 3, 4, 5, 5, 6, 7, 8, 9);
<ide> // make sure we don't emit all values ... the unsubscribe should propagate
<del> assertTrue(count.get() < 100000);
<add> // assertTrue(count.get() < 100000); // disabled: a small hiccup in the consumption may allow the source to run to completion
<ide> }
<ide>
<ide> private List<String> list(String... args) {
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java
<ide> public void subscribe(Observer<? super String> s) {
<ide> ts.assertValues("hello", "hello");
<ide> }
<ide>
<del> @Test(timeout = 10000)
<add> @Test(timeout = 30000)
<ide> public void testIssue2890NoStackoverflow() throws InterruptedException {
<ide> final ExecutorService executor = Executors.newFixedThreadPool(2);
<ide> final Scheduler sch = Schedulers.from(executor);
<ide> public void onError(Throwable e) {
<ide> }
<ide> });
<ide>
<del> executor.awaitTermination(12000, TimeUnit.MILLISECONDS);
<add> executor.awaitTermination(20000, TimeUnit.MILLISECONDS);
<ide>
<ide> assertEquals(n, counter.get());
<ide> }
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithSizeTest.java
<ide> public void accept(Integer t1) {
<ide> ts.assertTerminated();
<ide> ts.assertValues(1, 2, 3, 4, 5, 5, 6, 7, 8, 9);
<ide> // make sure we don't emit all values ... the unsubscribe should propagate
<del> assertTrue(count.get() < 100000);
<add> // assertTrue(count.get() < 100000); // disabled: a small hiccup in the consumption may allow the source to run to completion
<ide> }
<ide>
<ide> private List<String> list(String... args) { | 5 |
Javascript | Javascript | pass opts to `eventemitter.init` | 22792c8632fd17b151aa374c555b66bfc7c2022b | <ide><path>lib/domain.js
<ide> Domain.prototype.bind = function(cb) {
<ide> EventEmitter.usingDomains = true;
<ide>
<ide> const eventInit = EventEmitter.init;
<del>EventEmitter.init = function() {
<add>EventEmitter.init = function(opts) {
<ide> ObjectDefineProperty(this, 'domain', {
<ide> configurable: true,
<ide> enumerable: false,
<ide> EventEmitter.init = function() {
<ide> this.domain = exports.active;
<ide> }
<ide>
<del> return FunctionPrototypeCall(eventInit, this);
<add> return FunctionPrototypeCall(eventInit, this, opts);
<ide> };
<ide>
<ide> const eventEmit = EventEmitter.prototype.emit;
<ide><path>lib/events.js
<ide> EventEmitter.setMaxListeners =
<ide> }
<ide> };
<ide>
<add>// If you're updating this function definition, please also update any
<add>// re-definitions, such as the one in the Domain module (lib/domain.js).
<ide> EventEmitter.init = function(opts) {
<ide>
<ide> if (this._events === undefined ||
<ide><path>test/parallel/test-domain-ee.js
<ide> d.on('error', common.mustCall((err) => {
<ide>
<ide> d.add(e);
<ide> e.emit('error', new Error('foobar'));
<add>
<add>{
<add> // Ensure initial params pass to origin `EventEmitter.init` function
<add> const e = new EventEmitter({ captureRejections: true });
<add> const kCapture = Object.getOwnPropertySymbols(e)
<add> .find((it) => it.description === 'kCapture');
<add> assert.strictEqual(e[kCapture], true);
<add>} | 3 |
Javascript | Javascript | eliminate cached placeholdertextvnode | d92e0fc0a10acfaf53e3dd6cd9b88fd35a35acf0 | <ide><path>src/text-editor-component.js
<ide> class TextEditorComponent {
<ide> this.pendingScrollLeftColumn = this.props.initialScrollLeftColumn
<ide>
<ide> this.measuredContent = false
<del> this.placeholderTextVnode = null
<del>
<ide> this.queryGuttersToRender()
<ide> this.queryMaxLineNumberDigits()
<ide> this.observeBlockDecorations()
<ide> class TextEditorComponent {
<ide> }
<ide>
<ide> renderPlaceholderText () {
<del> if (!this.measuredContent) {
<del> this.placeholderTextVnode = null
<del> const {model} = this.props
<del> if (model.isEmpty()) {
<del> const placeholderText = model.getPlaceholderText()
<del> if (placeholderText != null) {
<del> this.placeholderTextVnode = $.div({className: 'placeholder-text'}, placeholderText)
<del> }
<add> const {model} = this.props
<add> if (model.isEmpty()) {
<add> const placeholderText = model.getPlaceholderText()
<add> if (placeholderText != null) {
<add> return $.div({className: 'placeholder-text'}, placeholderText)
<ide> }
<ide> }
<del> return this.placeholderTextVnode
<add> return null
<ide> }
<ide>
<ide> renderCharacterMeasurementLine () { | 1 |
Ruby | Ruby | use hasandbelongstomany instead of habtm | 34c77bcf2dea31decc3a0fe78874ab598d7e8651 | <ide><path>activerecord/lib/active_record/associations.rb
<ide> def has_and_belongs_to_many(name, scope = nil, options = {}, &extension)
<ide> scope = nil
<ide> end
<ide>
<del> habtm_reflection = ActiveRecord::Reflection::HABTMReflection.new(:has_and_belongs_to_many, name, scope, options, self)
<add> habtm_reflection = ActiveRecord::Reflection::HasAndBelongsToManyReflection.new(:has_and_belongs_to_many, name, scope, options, self)
<ide>
<ide> builder = Builder::HasAndBelongsToMany.new name, self, options
<ide>
<ide><path>activerecord/lib/active_record/reflection.rb
<ide> def primary_key(klass)
<ide> end
<ide> end
<ide>
<del> class HABTMReflection < AssociationReflection #:nodoc:
<add> class HasAndBelongsToManyReflection < AssociationReflection #:nodoc:
<ide> def initialize(macro, name, scope, options, active_record)
<ide> super
<ide> @collection = true | 2 |
Text | Text | clarify dockerignore semantics | 899ecc11c521d536f26b2e2f062382930dd6ff99 | <ide><path>docs/reference/builder.md
<ide> that set `abc` to `bye`.
<ide>
<ide> ### .dockerignore file
<ide>
<del>If a file named `.dockerignore` exists in the root of `PATH`, then Docker
<del>interprets it as a newline-separated list of exclusion patterns. Docker excludes
<del>files or directories relative to `PATH` that match these exclusion patterns. If
<del>there are any `.dockerignore` files in `PATH` subdirectories, Docker treats
<del>them as normal files.
<del>
<del>Filepaths in `.dockerignore` are absolute with the current directory as the
<del>root. Wildcards are allowed but the search is not recursive. Globbing (file name
<del>expansion) is done using Go's
<del>[filepath.Match](http://golang.org/pkg/path/filepath#Match) rules.
<del>
<del>You can specify exceptions to exclusion rules. To do this, simply prefix a
<del>pattern with an `!` (exclamation mark) in the same way you would in a
<del>`.gitignore` file. Currently there is no support for regular expressions.
<del>Formats like `[^temp*]` are ignored.
<del>
<del>The following is an example `.dockerignore` file:
<add>Before the docker CLI sends the context to the docker daemon, it looks
<add>for a file named `.dockerignore` in the root directory of the context.
<add>If this file exists, the CLI modifies the context to exclude files and
<add>directories that match patterns in it. This helps to avoid
<add>unnecessarily sending large or sensitive files and directories to the
<add>daemon and potentially adding them to images using `ADD` or `COPY`.
<add>
<add>The CLI interprets the `.dockerignore` file as a newline-separated
<add>list of patterns similar to the file globs of Unix shells. For the
<add>purposes of matching, the root of the context is considered to be both
<add>the working and the root directory. For example, the patterns
<add>`/foo/bar` and `foo/bar` both exclude a file or directory named `bar`
<add>in the `foo` subdirectory of `PATH` or in the root of the git
<add>repository located at `URL`. Neither excludes anything else.
<add>
<add>Here is an example `.dockerignore` file:
<ide>
<ide> ```
<ide> */temp*
<ide> */*/temp*
<ide> temp?
<del> *.md
<del> !LICENSE.md
<ide> ```
<ide>
<ide> This file causes the following build behavior:
<ide>
<ide> | Rule | Behavior |
<ide> |----------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
<del>| `*/temp*` | Exclude all files with names starting with`temp` in any subdirectory below the root directory. For example, a file named`/somedir/temporary.txt` is ignored. |
<del>| `*/*/temp*` | Exclude files starting with name `temp` from any subdirectory that is two levels below the root directory. For example, the file `/somedir/subdir/temporary.txt` is ignored. |
<del>| `temp?` | Exclude the files that match the pattern in the root directory. For example, the files `tempa`, `tempb` in the root directory are ignored. |
<del>| `*.md ` | Exclude all markdown files in the root directory. |
<del>| `!LICENSE.md` | Exception to the Markdown files exclusion. `LICENSE.md`is included in the build. |
<del>
<del>The placement of `!` exception rules influences the matching algorithm; the
<del>last line of the `.dockerignore` that matches a particular file determines
<del>whether it is included or excluded. In the above example, the `LICENSE.md` file
<del>matches both the `*.md` and `!LICENSE.md` rule. If you reverse the lines in the
<del>example:
<add>| `*/temp*` | Exclude files and directories whose names start with `temp` in any immediate subdirectory of the root. For example, the plain file `/somedir/temporary.txt` is excluded, as is the directory `/somedir/temp`. |
<add>| `*/*/temp*` | Exclude files and directories starting with `temp` from any subdirectory that is two levels below the root. For example, `/somedir/subdir/temporary.txt` is excluded. |
<add>| `temp?` | Exclude files and directories in the root directory whose names are a one-character extension of `temp`. For example, `/tempa` and `/tempb` are excluded.
<add>
<add>
<add>Matching is done using Go's
<add>[filepath.Match](http://golang.org/pkg/path/filepath#Match) rules. A
<add>preprocessing step removes leading and trailing whitespace and
<add>eliminates `.` and `..` elements using Go's
<add>[filepath.Clean](http://golang.org/pkg/path/filepath/#Clean). Lines
<add>that are blank after preprocessing are ignored.
<add>
<add>Lines starting with `!` (exclamation mark) can be used to make exceptions
<add>to exclusions. The following is an example `.dockerignore` file that
<add>uses this mechanism:
<ide>
<ide> ```
<del> */temp*
<del> */*/temp*
<del> temp?
<del> !LICENSE.md
<ide> *.md
<add> !README.md
<ide> ```
<ide>
<del>The build would exclude `LICENSE.md` because the last `*.md` rule adds all
<del>Markdown files in the root directory back onto the ignore list. The
<del>`!LICENSE.md` rule has no effect because the subsequent `*.md` rule overrides
<del>it.
<add>All markdown files *except* `README.md` are excluded from the context.
<add>
<add>The placement of `!` exception rules influences the behavior: the last
<add>line of the `.dockerignore` that matches a particular file determines
<add>whether it is included or excluded. Consider the following example:
<add>
<add>```
<add> *.md
<add> !README*.md
<add> README-secret.md
<add>```
<add>
<add>No markdown files are included in the context except README files other than
<add>`README-secret.md`.
<add>
<add>Now consider this example:
<add>
<add>```
<add> *.md
<add> README-secret.md
<add> !README*.md
<add>```
<add>
<add>All of the README files are included. The middle line has no effect because
<add>`!README*.md` matches `README-secret.md` and comes last.
<add>
<add>You can even use the `.dockerignore` file to exclude the `Dockerfile`
<add>and `.dockerignore` files. These files are still sent to the daemon
<add>because it needs them to do its job. But the `ADD` and `COPY` commands
<add>do not copy them to the the image.
<ide>
<del>You can even use the `.dockerignore` file to ignore the `Dockerfile` and
<del>`.dockerignore` files. This is useful if you are copying files from the root of
<del>the build context into your new container but do not want to include the
<del>`Dockerfile` or `.dockerignore` files (e.g. `ADD . /someDir/`).
<add>Finally, you may want to specify which files to include in the
<add>context, rather than which to exclude. To achieve this, specify `*` as
<add>the first pattern, followed by one or more `!` exception patterns.
<ide>
<add>**Note**: For historical reasons, the pattern `.` is ignored.
<ide>
<ide> ## FROM
<ide> | 1 |
PHP | PHP | send an event when the user's email is verified | 045cbfd95c611928aef1b877d1a3dc60d5f19580 | <ide><path>src/Illuminate/Auth/Events/Verified.php
<add><?php
<add>
<add>namespace Illuminate\Auth\Events;
<add>
<add>use Illuminate\Queue\SerializesModels;
<add>
<add>class Verified
<add>{
<add> use SerializesModels;
<add>
<add> /**
<add> * The verified user.
<add> *
<add> * @var \Illuminate\Contracts\Auth\MustVerifyEmail
<add> */
<add> public $user;
<add>
<add> /**
<add> * Create a new event instance.
<add> *
<add> * @param \Illuminate\Contracts\Auth\MustVerifyEmail $user
<add> * @return void
<add> */
<add> public function __construct($user)
<add> {
<add> $this->user = $user;
<add> }
<add>}
<ide><path>src/Illuminate/Auth/MustVerifyEmail.php
<ide> public function hasVerifiedEmail()
<ide> /**
<ide> * Mark the given user's email as verified.
<ide> *
<del> * @return void
<add> * @return bool
<ide> */
<ide> public function markEmailAsVerified()
<ide> {
<del> $this->forceFill(['email_verified_at' => $this->freshTimestamp()])->save();
<add> return $this->forceFill(['email_verified_at' => $this->freshTimestamp()])->save();
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Foundation/Auth/VerifiesEmails.php
<ide>
<ide> namespace Illuminate\Foundation\Auth;
<ide>
<add>use Illuminate\Auth\Events\Verified;
<ide> use Illuminate\Http\Request;
<ide>
<ide> trait VerifiesEmails
<ide> public function show(Request $request)
<ide> public function verify(Request $request)
<ide> {
<ide> if ($request->route('id') == $request->user()->getKey()) {
<del> $request->user()->markEmailAsVerified();
<add> if ($request->user()->markEmailAsVerified()) {
<add> event(new Verified($request->user()));
<add> }
<ide> }
<ide>
<ide> return redirect($this->redirectPath()); | 3 |
Java | Java | fix code style | dde2c0e7b0435b4195d02699ef4c8f8d666480e2 | <ide><path>src/main/java/io/reactivex/rxjava3/core/Flowable.java
<ide> public final Flowable<T> onBackpressureLatest() {
<ide> * <dd>{@code onBackpressureReduce} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<ide> * @param reducer the bi-function to call when there is more than one non-emitted value to downstream,
<del> * the first argument of the bi-function is previous item and the second one is currently emitting from upstream
<add> * the first argument of the bi-function is previous item and the second one is currently
<add> * emitting from upstream
<ide> * @return the new {@code Flowable} instance
<ide> * @throws NullPointerException if {@code reducer} is {@code null}
<ide> * @since 3.0.9 - experimental
<add> * @see #onBackpressureReduce(Supplier, BiFunction)
<ide> */
<ide> @Experimental
<ide> @CheckReturnValue
<ide> public final Flowable<T> onBackpressureReduce(@NonNull BiFunction<T, T, T> reduc
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code onBackpressureReduce} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<add> * @param <R> the aggregate type emitted when the downstream requests more items
<ide> * @param supplier the factory to call to create new item of type R to pass it as the first argument to {@code reducer}.
<del> * It is called when previous returned value by {@code reducer} already sent to downstream or the very first update from upstream received.
<add> * It is called when previous returned value by {@code reducer} already sent to
<add> * downstream or the very first update from upstream received.
<ide> * @param reducer the bi-function to call to reduce excessive updates which downstream is not ready to receive.
<del> * The first argument of type R is the object returned by {@code supplier} or result of previous {@code reducer} invocation.
<del> * The second argument of type T is the current update from upstream.
<add> * The first argument of type R is the object returned by {@code supplier} or result of previous
<add> * {@code reducer} invocation. The second argument of type T is the current update from upstream.
<ide> * @return the new {@code Flowable} instance
<ide> * @throws NullPointerException if {@code supplier} or {@code reducer} is {@code null}
<ide> * @see #onBackpressureReduce(BiFunction)
<ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/flowable/AbstractBackpressureThrottlingSubscriber.java
<ide> import io.reactivex.rxjava3.core.FlowableSubscriber;
<ide> import io.reactivex.rxjava3.internal.subscriptions.SubscriptionHelper;
<ide> import io.reactivex.rxjava3.internal.util.BackpressureHelper;
<del>import org.reactivestreams.Publisher;
<ide> import org.reactivestreams.Subscriber;
<ide> import org.reactivestreams.Subscription;
<ide>
<ide>
<ide> /**
<ide> * Abstract base class for operators that throttle excessive updates from upstream in case if
<del> * downstream {@link Subscriber} is not ready to receive updates
<add> * downstream {@link Subscriber} is not ready to receive updates.
<ide> *
<ide> * @param <T> the upstream value type
<ide> * @param <R> the downstream value type
<ide> */
<ide> abstract class AbstractBackpressureThrottlingSubscriber<T, R> extends AtomicInteger implements FlowableSubscriber<T>, Subscription {
<ide>
<add> private static final long serialVersionUID = -5050301752721603566L;
<add>
<ide> final Subscriber<? super R> downstream;
<ide>
<ide> Subscription upstream;
<ide> public void onSubscribe(Subscription s) {
<ide> }
<ide>
<ide> @Override
<del> abstract public void onNext(T t);
<add> public abstract void onNext(T t);
<ide>
<ide> @Override
<ide> public void onError(Throwable t) {
<ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableOnBackpressureReduceTest.java
<ide> public void synchronousDrop() {
<ide> ts.assertValues(1, 2);
<ide>
<ide> source.onNext(3);
<del> source.onNext(4);//3 + 4 + 50 == 57
<del> source.onNext(5);//57 + 5 + 50 == 112
<del> source.onNext(6);//112 + 6 + 50 == 168
<add> source.onNext(4); //3 + 4 + 50 == 57
<add> source.onNext(5); //57 + 5 + 50 == 112
<add> source.onNext(6); //112 + 6 + 50 == 168
<ide>
<ide> ts.request(2);
<ide>
<ide> public void synchronousDrop() {
<ide> ts.assertValues(1, 2, 168, 7);
<ide>
<ide> source.onNext(8);
<del> source.onNext(9);//8 + 9 + 50 == 67
<add> source.onNext(9); //8 + 9 + 50 == 67
<ide> source.onComplete();
<ide>
<ide> ts.request(1); | 3 |
Text | Text | remove unecessary comments [ci skip] | df17f7e374eb9cd4052deef23c67fb68997e53b3 | <ide><path>guides/source/getting_started.md
<ide> Rails.application.routes.draw do
<ide> get 'welcome/index'
<ide>
<ide> # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
<del>
<del> # Serve websocket cable requests in-process
<del> # mount ActionCable.server => '/cable'
<ide> end
<ide> ```
<ide>
<ide> Rails.application.routes.draw do
<ide>
<ide> # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
<ide>
<del> # Serve websocket cable requests in-process
<del> # mount ActionCable.server => '/cable'
<ide> root 'welcome#index'
<ide> end
<ide> ``` | 1 |
PHP | PHP | add test for using automock and multiple redirects | 61d6a720d6e7b761f210fac1186e2fe5891dc625 | <ide><path>lib/Cake/Test/Case/TestSuite/ControllerTestCaseTest.php
<ide> public function testNoMocking() {
<ide> * @return void
<ide> */
<ide> public function testNoControllerReuse() {
<add> $this->Case->autoMock = true;
<ide> $result = $this->Case->testAction('/tests_apps/index', array(
<ide> 'data' => array('var' => 'first call'),
<ide> 'method' => 'get',
<ide> public function testNoControllerReuse() {
<ide> $this->assertContains('third call', $result);
<ide> }
<ide>
<add>/**
<add> * Test that multiple calls to redirect in the same test method don't cause issues.
<add> *
<add> * @return void
<add> */
<add> public function testTestActionWithMultipleRedirect() {
<add> $this->Case->autoMock = true;
<add> $Controller = $this->Case->generate('TestsApps');
<add>
<add> $options = array('method' => 'get');
<add> $this->Case->testAction('/tests_apps/redirect_to', $options);
<add> $this->Case->testAction('/tests_apps/redirect_to', $options);
<add> }
<add>
<ide> } | 1 |
Javascript | Javascript | rework the propagation system for event components | 784ebd8fa919bbca41c2a2f5a3eda5be6961f32c | <ide><path>packages/react-dom/src/events/DOMEventResponderSystem.js
<ide> import {
<ide> HostComponent,
<ide> } from 'shared/ReactWorkTags';
<ide> import type {
<add> ReactEventResponder,
<ide> ReactEventResponderEventType,
<ide> ReactEventComponentInstance,
<ide> ReactResponderContext,
<ide> type ResponderTimeout = {|
<ide>
<ide> type ResponderTimer = {|
<ide> instance: ReactEventComponentInstance,
<del> func: () => boolean,
<add> func: () => void,
<ide> id: Symbol,
<ide> |};
<ide>
<del>const ROOT_PHASE = 0;
<del>const BUBBLE_PHASE = 1;
<del>const CAPTURE_PHASE = 2;
<ide> const activeTimeouts: Map<Symbol, ResponderTimeout> = new Map();
<ide> const rootEventTypesToEventComponentInstances: Map<
<ide> DOMTopLevelEventType | string,
<ide> const eventResponderContext: ReactResponderContext = {
<ide> triggerOwnershipListeners();
<ide> return false;
<ide> },
<del> setTimeout(func: () => boolean, delay): Symbol {
<add> setTimeout(func: () => void, delay): Symbol {
<ide> validateResponderContext();
<ide> if (currentTimers === null) {
<ide> currentTimers = new Map();
<ide> const eventResponderContext: ReactResponderContext = {
<ide>
<ide> function processTimers(timers: Map<Symbol, ResponderTimer>): void {
<ide> const timersArr = Array.from(timers.values());
<del> let shouldStopPropagation = false;
<ide> currentEventQueue = createEventQueue();
<ide> try {
<ide> for (let i = 0; i < timersArr.length; i++) {
<ide> const {instance, func, id} = timersArr[i];
<ide> currentInstance = instance;
<ide> try {
<del> if (!shouldStopPropagation) {
<del> shouldStopPropagation = func();
<del> }
<add> func();
<ide> } finally {
<ide> activeTimeouts.delete(id);
<ide> }
<ide> function createResponderEvent(
<ide> nativeEvent: AnyNativeEvent,
<ide> nativeEventTarget: Element | Document,
<ide> eventSystemFlags: EventSystemFlags,
<del> phase: 0 | 1 | 2,
<ide> ): ReactResponderEvent {
<ide> const responderEvent = {
<ide> nativeEvent: nativeEvent,
<ide> target: nativeEventTarget,
<ide> type: topLevelType,
<ide> passive: (eventSystemFlags & IS_PASSIVE) !== 0,
<ide> passiveSupported: (eventSystemFlags & PASSIVE_NOT_SUPPORTED) === 0,
<del> phase,
<ide> };
<ide> if (__DEV__) {
<ide> Object.freeze(responderEvent);
<ide> function getRootEventResponderInstances(
<ide> return eventResponderInstances;
<ide> }
<ide>
<del>function triggerEventResponderEventListener(
<del> responderEvent: ReactResponderEvent,
<del> eventComponentInstance: ReactEventComponentInstance,
<del>): boolean {
<del> const {responder, props, state} = eventComponentInstance;
<del> currentInstance = eventComponentInstance;
<del> return responder.onEvent(responderEvent, eventResponderContext, props, state);
<del>}
<del>
<del>function traverseAndTriggerEventResponderInstances(
<add>function traverseAndHandleEventResponderInstances(
<ide> topLevelType: DOMTopLevelEventType,
<ide> targetFiber: null | Fiber,
<ide> nativeEvent: AnyNativeEvent,
<ide> function traverseAndTriggerEventResponderInstances(
<ide> topLevelType,
<ide> targetFiber,
<ide> );
<add> const responderEvent = createResponderEvent(
<add> ((topLevelType: any): string),
<add> nativeEvent,
<add> ((nativeEventTarget: any): Element | Document),
<add> eventSystemFlags,
<add> );
<add> const propagatedEventResponders: Set<ReactEventResponder> = new Set();
<ide> let length = targetEventResponderInstances.length;
<ide> let i;
<del> let shouldStopPropagation = false;
<del> let responderEvent;
<ide>
<add> // Captured and bubbled event phases have the notion of local propagation.
<add> // This means that the propgation chain can be stopped part of the the way
<add> // through processing event component instances. The major difference to other
<add> // events systems is that the stopping of propgation is localized to a single
<add> // phase, rather than both phases.
<ide> if (length > 0) {
<ide> // Capture target phase
<del> responderEvent = createResponderEvent(
<del> ((topLevelType: any): string),
<del> nativeEvent,
<del> ((nativeEventTarget: any): Element | Document),
<del> eventSystemFlags,
<del> CAPTURE_PHASE,
<del> );
<ide> for (i = length; i-- > 0; ) {
<ide> const targetEventResponderInstance = targetEventResponderInstances[i];
<del> shouldStopPropagation = triggerEventResponderEventListener(
<del> responderEvent,
<del> targetEventResponderInstance,
<del> );
<del> if (shouldStopPropagation) {
<del> return;
<add> const {responder, props, state} = targetEventResponderInstance;
<add> if (responder.stopLocalPropagation) {
<add> if (propagatedEventResponders.has(responder)) {
<add> continue;
<add> }
<add> propagatedEventResponders.add(responder);
<add> }
<add> const eventListener = responder.onEventCapture;
<add> if (eventListener !== undefined) {
<add> currentInstance = targetEventResponderInstance;
<add> eventListener(responderEvent, eventResponderContext, props, state);
<ide> }
<ide> }
<add> // We clean propagated event responders between phases.
<add> propagatedEventResponders.clear();
<ide> // Bubble target phase
<del> responderEvent = createResponderEvent(
<del> ((topLevelType: any): string),
<del> nativeEvent,
<del> ((nativeEventTarget: any): Element | Document),
<del> eventSystemFlags,
<del> BUBBLE_PHASE,
<del> );
<ide> for (i = 0; i < length; i++) {
<ide> const targetEventResponderInstance = targetEventResponderInstances[i];
<del> shouldStopPropagation = triggerEventResponderEventListener(
<del> responderEvent,
<del> targetEventResponderInstance,
<del> );
<del> if (shouldStopPropagation) {
<del> return;
<add> const {responder, props, state} = targetEventResponderInstance;
<add> if (responder.stopLocalPropagation) {
<add> if (propagatedEventResponders.has(responder)) {
<add> continue;
<add> }
<add> propagatedEventResponders.add(responder);
<add> }
<add> const eventListener = responder.onEvent;
<add> if (eventListener !== undefined) {
<add> currentInstance = targetEventResponderInstance;
<add> eventListener(responderEvent, eventResponderContext, props, state);
<ide> }
<ide> }
<ide> }
<ide> function traverseAndTriggerEventResponderInstances(
<ide> );
<ide> length = rootEventResponderInstances.length;
<ide> if (length > 0) {
<del> responderEvent = createResponderEvent(
<del> ((topLevelType: any): string),
<del> nativeEvent,
<del> ((nativeEventTarget: any): Element | Document),
<del> eventSystemFlags,
<del> ROOT_PHASE,
<del> );
<ide> for (i = 0; i < length; i++) {
<del> const targetEventResponderInstance = rootEventResponderInstances[i];
<del> shouldStopPropagation = triggerEventResponderEventListener(
<del> responderEvent,
<del> targetEventResponderInstance,
<del> );
<del> if (shouldStopPropagation) {
<del> return;
<add> const rootEventResponderInstance = rootEventResponderInstances[i];
<add> const {responder, props, state} = rootEventResponderInstance;
<add> const eventListener = responder.onRootEvent;
<add> if (eventListener !== undefined) {
<add> currentInstance = rootEventResponderInstance;
<add> eventListener(responderEvent, eventResponderContext, props, state);
<ide> }
<ide> }
<ide> }
<ide> export function dispatchEventForResponderEventSystem(
<ide> if (enableEventAPI) {
<ide> currentEventQueue = createEventQueue();
<ide> try {
<del> traverseAndTriggerEventResponderInstances(
<add> traverseAndHandleEventResponderInstances(
<ide> topLevelType,
<ide> targetFiber,
<ide> nativeEvent,
<ide><path>packages/react-dom/src/events/__tests__/DOMEventResponderSystem-test.internal.js
<ide> function createReactEventComponent(
<ide> targetEventTypes,
<ide> createInitialState,
<ide> onEvent,
<add> onEventCapture,
<add> onRootEvent,
<ide> onUnmount,
<ide> onOwnershipChange,
<add> stopLocalPropagation,
<ide> ) {
<ide> const testEventResponder = {
<ide> targetEventTypes,
<ide> createInitialState,
<ide> onEvent,
<add> onEventCapture,
<add> onRootEvent,
<ide> onUnmount,
<ide> onOwnershipChange,
<add> stopLocalPropagation: stopLocalPropagation || false,
<ide> };
<ide>
<ide> return {
<ide> function createReactEventComponent(
<ide> };
<ide> }
<ide>
<del>const ROOT_PHASE = 0;
<del>const BUBBLE_PHASE = 1;
<del>const CAPTURE_PHASE = 2;
<del>
<del>function phaseToString(phase) {
<del> return phase === ROOT_PHASE
<del> ? 'root'
<del> : phase === BUBBLE_PHASE
<del> ? 'bubble'
<del> : 'capture';
<del>}
<del>
<ide> function dispatchEvent(element, type) {
<ide> const event = document.createEvent('Event');
<ide> event.initEvent(type, true, true);
<ide> describe('DOMEventResponderSystem', () => {
<ide> container = null;
<ide> });
<ide>
<del> it('the event responder onEvent() function should fire on click event', () => {
<add> it('the event responder event listeners should fire on click event', () => {
<ide> let eventResponderFiredCount = 0;
<ide> let eventLog = [];
<ide> const buttonRef = React.createRef();
<ide> describe('DOMEventResponderSystem', () => {
<ide> name: event.type,
<ide> passive: event.passive,
<ide> passiveSupported: event.passiveSupported,
<del> phase: event.phase,
<add> phase: 'bubble',
<add> });
<add> },
<add> (event, context, props) => {
<add> eventResponderFiredCount++;
<add> eventLog.push({
<add> name: event.type,
<add> passive: event.passive,
<add> passiveSupported: event.passiveSupported,
<add> phase: 'capture',
<ide> });
<ide> },
<ide> );
<ide> describe('DOMEventResponderSystem', () => {
<ide> name: 'click',
<ide> passive: false,
<ide> passiveSupported: false,
<del> phase: CAPTURE_PHASE,
<add> phase: 'capture',
<ide> },
<ide> {
<ide> name: 'click',
<ide> passive: false,
<ide> passiveSupported: false,
<del> phase: BUBBLE_PHASE,
<add> phase: 'bubble',
<ide> },
<ide> ]);
<ide>
<ide> describe('DOMEventResponderSystem', () => {
<ide> expect(eventResponderFiredCount).toBe(4);
<ide> });
<ide>
<del> it('the event responder onEvent() function should fire on click event (passive events forced)', () => {
<add> it('the event responder event listeners should fire on click event (passive events forced)', () => {
<ide> // JSDOM does not support passive events, so this manually overrides the value to be true
<ide> const checkPassiveEvents = require('react-dom/src/events/checkPassiveEvents');
<ide> checkPassiveEvents.passiveBrowserEventsSupported = true;
<ide> describe('DOMEventResponderSystem', () => {
<ide> name: event.type,
<ide> passive: event.passive,
<ide> passiveSupported: event.passiveSupported,
<del> phase: event.phase,
<add> phase: 'bubble',
<add> });
<add> },
<add> (event, context, props) => {
<add> eventLog.push({
<add> name: event.type,
<add> passive: event.passive,
<add> passiveSupported: event.passiveSupported,
<add> phase: 'capture',
<ide> });
<ide> },
<ide> );
<ide> describe('DOMEventResponderSystem', () => {
<ide> name: 'click',
<ide> passive: true,
<ide> passiveSupported: true,
<del> phase: CAPTURE_PHASE,
<add> phase: 'capture',
<ide> },
<ide> {
<ide> name: 'click',
<ide> passive: true,
<ide> passiveSupported: true,
<del> phase: BUBBLE_PHASE,
<add> phase: 'bubble',
<ide> },
<ide> ]);
<ide> });
<ide>
<del> it('nested event responders and their onEvent() function should fire multiple times', () => {
<add> it('nested event responders and their event listeners should fire multiple times', () => {
<ide> let eventResponderFiredCount = 0;
<ide> let eventLog = [];
<ide> const buttonRef = React.createRef();
<ide> describe('DOMEventResponderSystem', () => {
<ide> name: event.type,
<ide> passive: event.passive,
<ide> passiveSupported: event.passiveSupported,
<del> phase: event.phase,
<add> phase: 'bubble',
<add> });
<add> },
<add> (event, context, props) => {
<add> eventResponderFiredCount++;
<add> eventLog.push({
<add> name: event.type,
<add> passive: event.passive,
<add> passiveSupported: event.passiveSupported,
<add> phase: 'capture',
<ide> });
<ide> },
<ide> );
<ide> describe('DOMEventResponderSystem', () => {
<ide> name: 'click',
<ide> passive: false,
<ide> passiveSupported: false,
<del> phase: CAPTURE_PHASE,
<add> phase: 'capture',
<ide> },
<ide> {
<ide> name: 'click',
<ide> passive: false,
<ide> passiveSupported: false,
<del> phase: CAPTURE_PHASE,
<add> phase: 'capture',
<ide> },
<ide> {
<ide> name: 'click',
<ide> passive: false,
<ide> passiveSupported: false,
<del> phase: BUBBLE_PHASE,
<add> phase: 'bubble',
<ide> },
<ide> {
<ide> name: 'click',
<ide> passive: false,
<ide> passiveSupported: false,
<del> phase: BUBBLE_PHASE,
<add> phase: 'bubble',
<ide> },
<ide> ]);
<ide> });
<ide>
<del> it('nested event responders and their onEvent() should fire in the correct order', () => {
<add> it('nested event responders and their event listeners should fire in the correct order', () => {
<ide> let eventLog = [];
<ide> const buttonRef = React.createRef();
<ide>
<ide> const ClickEventComponentA = createReactEventComponent(
<ide> ['click'],
<ide> undefined,
<ide> (event, context, props) => {
<del> eventLog.push(`A [${phaseToString(event.phase)}]`);
<add> eventLog.push(`A [bubble]`);
<add> },
<add> (event, context, props) => {
<add> eventLog.push(`A [capture]`);
<ide> },
<ide> );
<ide>
<ide> const ClickEventComponentB = createReactEventComponent(
<ide> ['click'],
<ide> undefined,
<ide> (event, context, props) => {
<del> eventLog.push(`B [${phaseToString(event.phase)}]`);
<add> eventLog.push(`B [bubble]`);
<add> },
<add> (event, context, props) => {
<add> eventLog.push(`B [capture]`);
<ide> },
<ide> );
<ide>
<ide> describe('DOMEventResponderSystem', () => {
<ide> ]);
<ide> });
<ide>
<del> it('nested event responders and their onEvent() should fire in the correct order with stopPropagation', () => {
<del> let eventLog;
<del> let stopPropagationOnPhase;
<add> it('nested event responders should fire in the correct order without stopLocalPropagation', () => {
<add> let eventLog = [];
<ide> const buttonRef = React.createRef();
<ide>
<del> const ClickEventComponentA = createReactEventComponent(
<add> const ClickEventComponent = createReactEventComponent(
<ide> ['click'],
<ide> undefined,
<ide> (event, context, props) => {
<del> context.addRootEventTypes(event.target.ownerDocument, [
<del> 'click',
<del> 'pointermove',
<del> ]);
<del> eventLog.push(`A [${event.type}, ${phaseToString(event.phase)}]`);
<add> eventLog.push(`${props.name} [bubble]`);
<ide> },
<del> );
<del>
<del> const ClickEventComponentB = createReactEventComponent(
<del> ['click'],
<del> undefined,
<ide> (event, context, props) => {
<del> context.addRootEventTypes(event.target.ownerDocument, [
<del> 'click',
<del> 'pointermove',
<del> ]);
<del> eventLog.push(`B [${event.type}, ${phaseToString(event.phase)}]`);
<del> if (event.phase === stopPropagationOnPhase) {
<del> return true;
<del> }
<add> eventLog.push(`${props.name} [capture]`);
<ide> },
<add> undefined,
<add> undefined,
<add> undefined,
<add> false,
<ide> );
<ide>
<ide> const Test = () => (
<del> <ClickEventComponentA>
<del> <ClickEventComponentB>
<add> <ClickEventComponent name="A">
<add> <ClickEventComponent name="B">
<ide> <button ref={buttonRef}>Click me!</button>
<del> </ClickEventComponentB>
<del> </ClickEventComponentA>
<add> </ClickEventComponent>
<add> </ClickEventComponent>
<ide> );
<ide>
<del> function runTestWithPhase(phase) {
<del> eventLog = [];
<del> stopPropagationOnPhase = phase;
<del> ReactDOM.render(<Test />, container);
<del> let buttonElement = buttonRef.current;
<del> dispatchClickEvent(buttonElement);
<del> dispatchEvent(buttonElement, 'pointermove');
<del> }
<add> ReactDOM.render(<Test />, container);
<add>
<add> // Clicking the button should trigger the event responder onEvent()
<add> let buttonElement = buttonRef.current;
<add> dispatchClickEvent(buttonElement);
<ide>
<del> runTestWithPhase(BUBBLE_PHASE);
<del> // Root phase should not be skipped for different event type
<del> expect(eventLog).toEqual([
<del> 'A [click, capture]',
<del> 'B [click, capture]',
<del> 'B [click, bubble]',
<del> 'A [pointermove, root]',
<del> 'B [pointermove, root]',
<del> ]);
<del> runTestWithPhase(CAPTURE_PHASE);
<del> // Root phase should not be skipped for different event type
<ide> expect(eventLog).toEqual([
<del> 'A [click, capture]',
<del> 'B [click, capture]',
<del> 'A [pointermove, root]',
<del> 'B [pointermove, root]',
<add> 'A [capture]',
<add> 'B [capture]',
<add> 'B [bubble]',
<add> 'A [bubble]',
<ide> ]);
<ide> });
<ide>
<del> it('nested event responders and their onEvent() should fire in the correct order with stopPropagation #2', () => {
<del> let eventLog;
<del> let stopPropagationOnPhase;
<add> it('nested event responders should fire in the correct order with stopLocalPropagation', () => {
<add> let eventLog = [];
<ide> const buttonRef = React.createRef();
<ide>
<del> const ClickEventComponentA = createReactEventComponent(
<add> const ClickEventComponent = createReactEventComponent(
<ide> ['click'],
<ide> undefined,
<ide> (event, context, props) => {
<del> context.addRootEventTypes(event.target.ownerDocument, [
<del> 'click',
<del> 'pointermove',
<del> ]);
<del> eventLog.push(`A [${event.type}, ${phaseToString(event.phase)}]`);
<del> if (event.phase === stopPropagationOnPhase) {
<del> return true;
<del> }
<add> eventLog.push(`${props.name} [bubble]`);
<ide> },
<del> );
<del>
<del> const ClickEventComponentB = createReactEventComponent(
<del> ['click'],
<del> undefined,
<ide> (event, context, props) => {
<del> context.addRootEventTypes(event.target.ownerDocument, [
<del> 'click',
<del> 'pointermove',
<del> ]);
<del> eventLog.push(`B [${event.type}, ${phaseToString(event.phase)}]`);
<add> eventLog.push(`${props.name} [capture]`);
<ide> },
<add> undefined,
<add> undefined,
<add> undefined,
<add> true,
<ide> );
<ide>
<ide> const Test = () => (
<del> <ClickEventComponentA>
<del> <ClickEventComponentB>
<add> <ClickEventComponent name="A">
<add> <ClickEventComponent name="B">
<ide> <button ref={buttonRef}>Click me!</button>
<del> </ClickEventComponentB>
<del> </ClickEventComponentA>
<add> </ClickEventComponent>
<add> </ClickEventComponent>
<ide> );
<ide>
<del> function runTestWithPhase(phase) {
<del> eventLog = [];
<del> stopPropagationOnPhase = phase;
<del> ReactDOM.render(<Test />, container);
<del> let buttonElement = buttonRef.current;
<del> dispatchClickEvent(buttonElement);
<del> dispatchEvent(buttonElement, 'pointermove');
<del> }
<add> ReactDOM.render(<Test />, container);
<ide>
<del> runTestWithPhase(BUBBLE_PHASE);
<del> // Root phase should not be skipped for different event type
<del> expect(eventLog).toEqual([
<del> 'A [click, capture]',
<del> 'B [click, capture]',
<del> 'B [click, bubble]',
<del> 'A [click, bubble]',
<del> 'A [pointermove, root]',
<del> 'B [pointermove, root]',
<del> ]);
<del> runTestWithPhase(CAPTURE_PHASE);
<del> // Root phase should not be skipped for different event type
<del> expect(eventLog).toEqual([
<del> 'A [click, capture]',
<del> 'A [pointermove, root]',
<del> 'B [pointermove, root]',
<del> ]);
<add> // Clicking the button should trigger the event responder onEvent()
<add> let buttonElement = buttonRef.current;
<add> dispatchClickEvent(buttonElement);
<add>
<add> expect(eventLog).toEqual(['A [capture]', 'B [bubble]']);
<ide> });
<ide>
<ide> it('custom event dispatching for click -> magicClick works', () => {
<ide> describe('DOMEventResponderSystem', () => {
<ide> const syntheticEvent = {
<ide> target: event.target,
<ide> type: 'magicclick',
<del> phase: phaseToString(event.phase),
<add> phase: 'bubble',
<add> };
<add> context.dispatchEvent(syntheticEvent, props.onMagicClick, {
<add> discrete: true,
<add> });
<add> }
<add> },
<add> (event, context, props) => {
<add> if (props.onMagicClick) {
<add> const syntheticEvent = {
<add> target: event.target,
<add> type: 'magicclick',
<add> phase: 'capture',
<ide> };
<ide> context.dispatchEvent(syntheticEvent, props.onMagicClick, {
<ide> discrete: true,
<ide> describe('DOMEventResponderSystem', () => {
<ide> let eventLog = [];
<ide> const buttonRef = React.createRef();
<ide>
<add> function handleEvent(event, context, props, phase) {
<add> const pressEvent = {
<add> target: event.target,
<add> type: 'press',
<add> phase,
<add> };
<add> context.dispatchEvent(pressEvent, props.onPress, {discrete: true});
<add>
<add> context.setTimeout(() => {
<add> if (props.onLongPress) {
<add> const longPressEvent = {
<add> target: event.target,
<add> type: 'longpress',
<add> phase,
<add> };
<add> context.dispatchEvent(longPressEvent, props.onLongPress, {
<add> discrete: true,
<add> });
<add> }
<add>
<add> if (props.onLongPressChange) {
<add> const longPressChangeEvent = {
<add> target: event.target,
<add> type: 'longpresschange',
<add> phase,
<add> };
<add> context.dispatchEvent(longPressChangeEvent, props.onLongPressChange, {
<add> discrete: true,
<add> });
<add> }
<add> }, 500);
<add> }
<add>
<ide> const LongPressEventComponent = createReactEventComponent(
<ide> ['click'],
<ide> undefined,
<ide> (event, context, props) => {
<del> const pressEvent = {
<del> target: event.target,
<del> type: 'press',
<del> phase: phaseToString(event.phase),
<del> };
<del> context.dispatchEvent(pressEvent, props.onPress, {discrete: true});
<del>
<del> context.setTimeout(() => {
<del> if (props.onLongPress) {
<del> const longPressEvent = {
<del> target: event.target,
<del> type: 'longpress',
<del> phase: phaseToString(event.phase),
<del> };
<del> context.dispatchEvent(longPressEvent, props.onLongPress, {
<del> discrete: true,
<del> });
<del> }
<del>
<del> if (props.onLongPressChange) {
<del> const longPressChangeEvent = {
<del> target: event.target,
<del> type: 'longpresschange',
<del> phase: phaseToString(event.phase),
<del> };
<del> context.dispatchEvent(
<del> longPressChangeEvent,
<del> props.onLongPressChange,
<del> {discrete: true},
<del> );
<del> }
<del> }, 500);
<add> handleEvent(event, context, props, 'bubble');
<add> },
<add> (event, context, props) => {
<add> handleEvent(event, context, props, 'capture');
<ide> },
<ide> );
<ide>
<ide> describe('DOMEventResponderSystem', () => {
<ide> const EventComponent = createReactEventComponent(
<ide> [],
<ide> undefined,
<add> undefined,
<add> undefined,
<ide> (event, context, props, state) => {},
<ide> () => {
<ide> onUnmountFired++;
<ide> describe('DOMEventResponderSystem', () => {
<ide> () => ({
<ide> incrementAmount: 5,
<ide> }),
<del> (event, context, props, state) => {},
<add> undefined,
<add> undefined,
<add> undefined,
<ide> (context, props, state) => {
<ide> counter += state.incrementAmount;
<ide> },
<ide> describe('DOMEventResponderSystem', () => {
<ide> ['click'],
<ide> undefined,
<ide> (event, context, props, state) => {
<del> if (event.phase === BUBBLE_PHASE) {
<del> ownershipGained = context.requestOwnership();
<del> }
<add> ownershipGained = context.requestOwnership();
<ide> },
<ide> undefined,
<add> undefined,
<add> undefined,
<ide> () => {
<ide> onOwnershipChangeFired++;
<ide> },
<ide><path>packages/react-events/src/Drag.js
<ide> import type {
<ide> } from 'shared/ReactTypes';
<ide> import {REACT_EVENT_COMPONENT_TYPE} from 'shared/ReactSymbols';
<ide>
<del>const CAPTURE_PHASE = 2;
<del>const targetEventTypes = ['pointerdown', 'pointercancel'];
<del>const rootEventTypes = ['pointerup', {name: 'pointermove', passive: false}];
<add>const targetEventTypes = ['pointerdown'];
<add>const rootEventTypes = [
<add> 'pointerup',
<add> 'pointercancel',
<add> {name: 'pointermove', passive: false},
<add>];
<ide>
<ide> type DragState = {
<ide> dragTarget: null | Element | Document,
<ide> type DragState = {
<ide> // In the case we don't have PointerEvents (Safari), we listen to touch events
<ide> // too
<ide> if (typeof window !== 'undefined' && window.PointerEvent === undefined) {
<del> targetEventTypes.push('touchstart', 'touchend', 'mousedown', 'touchcancel');
<del> rootEventTypes.push('mouseup', 'mousemove', {
<add> targetEventTypes.push('touchstart', 'mousedown');
<add> rootEventTypes.push('mouseup', 'mousemove', 'touchend', 'touchcancel', {
<ide> name: 'touchmove',
<ide> passive: false,
<ide> });
<ide> const DragResponder = {
<ide> y: 0,
<ide> };
<ide> },
<add> stopLocalPropagation: true,
<ide> onEvent(
<ide> event: ReactResponderEvent,
<ide> context: ReactResponderContext,
<ide> props: Object,
<ide> state: DragState,
<del> ): boolean {
<del> const {target, phase, type, nativeEvent} = event;
<add> ): void {
<add> const {target, type, nativeEvent} = event;
<ide>
<del> // Drag doesn't handle capture target events at this point
<del> if (phase === CAPTURE_PHASE) {
<del> return false;
<del> }
<ide> switch (type) {
<ide> case 'touchstart':
<ide> case 'mousedown':
<ide> const DragResponder = {
<ide> }
<ide> break;
<ide> }
<add> }
<add> },
<add> onRootEvent(
<add> event: ReactResponderEvent,
<add> context: ReactResponderContext,
<add> props: Object,
<add> state: DragState,
<add> ): void {
<add> const {type, nativeEvent} = event;
<add>
<add> switch (type) {
<ide> case 'touchmove':
<ide> case 'mousemove':
<ide> case 'pointermove': {
<ide> if (event.passive) {
<del> return false;
<add> return;
<ide> }
<ide> if (state.isPointerDown) {
<ide> const obj =
<ide> const DragResponder = {
<ide> break;
<ide> }
<ide> }
<del> return false;
<ide> },
<ide> };
<ide>
<ide><path>packages/react-events/src/Focus.js
<ide> import type {
<ide> import {REACT_EVENT_COMPONENT_TYPE} from 'shared/ReactSymbols';
<ide> import {getEventCurrentTarget} from './utils.js';
<ide>
<del>const CAPTURE_PHASE = 2;
<del>
<ide> type FocusProps = {
<ide> disabled: boolean,
<ide> onBlur: (e: FocusEvent) => void,
<ide> const FocusResponder = {
<ide> context: ReactResponderContext,
<ide> props: Object,
<ide> state: FocusState,
<del> ): boolean {
<del> const {type, phase, target} = event;
<del> const shouldStopPropagation =
<del> props.stopPropagation === undefined ? true : props.stopPropagation;
<add> ): void {
<add> const {type, target} = event;
<ide>
<ide> if (props.disabled) {
<ide> if (state.isFocused) {
<ide> dispatchFocusOutEvents(context, props, state);
<ide> state.isFocused = false;
<ide> state.focusTarget = null;
<ide> }
<del> return false;
<del> }
<del>
<del> // Focus doesn't handle capture target events at this point
<del> if (phase === CAPTURE_PHASE) {
<del> return false;
<add> return;
<ide> }
<ide>
<ide> switch (type) {
<ide> const FocusResponder = {
<ide> break;
<ide> }
<ide> }
<del> return shouldStopPropagation;
<ide> },
<ide> onUnmount(
<ide> context: ReactResponderContext,
<ide><path>packages/react-events/src/Hover.js
<ide> import {
<ide> isEventPositionWithinTouchHitTarget,
<ide> } from './utils';
<ide>
<del>const CAPTURE_PHASE = 2;
<del>
<ide> type HoverProps = {
<ide> disabled: boolean,
<ide> delayHoverEnd: number,
<ide> function dispatchHoverStartEvents(
<ide> state.hoverStartTimeout = context.setTimeout(() => {
<ide> state.hoverStartTimeout = null;
<ide> activate();
<del> return false;
<ide> }, delayHoverStart);
<ide> } else {
<ide> activate();
<ide> function dispatchHoverEndEvents(
<ide> if (delayHoverEnd > 0) {
<ide> state.hoverEndTimeout = context.setTimeout(() => {
<ide> deactivate();
<del> return false;
<ide> }, delayHoverEnd);
<ide> } else {
<ide> deactivate();
<ide> const HoverResponder = {
<ide> ignoreEmulatedMouseEvents: false,
<ide> };
<ide> },
<add> stopLocalPropagation: true,
<ide> onEvent(
<ide> event: ReactResponderEvent,
<ide> context: ReactResponderContext,
<ide> props: HoverProps,
<ide> state: HoverState,
<del> ): boolean {
<add> ): void {
<ide> const {type} = event;
<ide>
<ide> if (props.disabled) {
<ide> const HoverResponder = {
<ide> if (state.isTouched) {
<ide> state.isTouched = false;
<ide> }
<del> return false;
<del> }
<del>
<del> // Hover doesn't handle capture target events at this point
<del> if (event.phase === CAPTURE_PHASE) {
<del> return false;
<add> return;
<ide> }
<del>
<ide> const pointerType = getEventPointerType(event);
<ide>
<ide> switch (type) {
<ide> const HoverResponder = {
<ide> // Prevent hover events for touch
<ide> if (state.isTouched || pointerType === 'touch') {
<ide> state.isTouched = true;
<del> return false;
<add> return;
<ide> }
<ide>
<ide> // Prevent hover events for emulated events
<ide> if (isEmulatedMouseEvent(event, state)) {
<del> return false;
<add> return;
<ide> }
<ide>
<ide> if (isEventPositionWithinTouchHitTarget(event, context)) {
<ide> state.isOverTouchHitTarget = true;
<del> return false;
<add> return;
<ide> }
<ide> state.hoverTarget = getEventCurrentTarget(event, context);
<ide> state.ignoreEmulatedMouseEvents = true;
<ide> dispatchHoverStartEvents(event, context, props, state);
<ide> }
<del> return false;
<add> return;
<ide> }
<ide>
<ide> // MOVE
<ide> const HoverResponder = {
<ide> }
<ide> }
<ide> }
<del> return false;
<add> return;
<ide> }
<ide>
<ide> // END
<ide> const HoverResponder = {
<ide> if (state.isTouched) {
<ide> state.isTouched = false;
<ide> }
<del> return false;
<add> return;
<ide> }
<ide> }
<del> return false;
<ide> },
<ide> onUnmount(
<ide> context: ReactResponderContext,
<ide><path>packages/react-events/src/Press.js
<ide> import {
<ide> isEventPositionWithinTouchHitTarget,
<ide> } from './utils';
<ide>
<del>const CAPTURE_PHASE = 2;
<del>
<ide> type PressProps = {
<ide> disabled: boolean,
<ide> delayLongPress: number,
<ide> const rootEventTypes = ['keyup', 'pointerup', 'pointermove', 'scroll'];
<ide>
<ide> // If PointerEvents is not supported (e.g., Safari), also listen to touch and mouse events.
<ide> if (typeof window !== 'undefined' && window.PointerEvent === undefined) {
<del> targetEventTypes.push('touchstart', 'touchend', 'touchcancel', 'mousedown');
<add> targetEventTypes.push('touchstart', 'touchcancel', 'mousedown');
<ide> rootEventTypes.push(
<ide> {name: 'mouseup', passive: false},
<ide> 'touchmove',
<add> 'touchend',
<ide> 'mousemove',
<ide> );
<ide> }
<ide> function dispatchPressStartEvents(
<ide> props: PressProps,
<ide> state: PressState,
<ide> ): void {
<del> const shouldStopPropagation =
<del> props.stopPropagation === undefined ? true : props.stopPropagation;
<ide> state.isPressed = true;
<ide>
<ide> if (state.pressEndTimeout !== null) {
<ide> function dispatchPressStartEvents(
<ide> if (props.onLongPressChange) {
<ide> dispatchLongPressChangeEvent(context, props, state);
<ide> }
<del> return shouldStopPropagation;
<ide> }, delayLongPress);
<ide> }
<ide> };
<ide> function dispatchPressStartEvents(
<ide> state.pressStartTimeout = context.setTimeout(() => {
<ide> state.pressStartTimeout = null;
<ide> dispatch();
<del> return shouldStopPropagation;
<ide> }, delayPressStart);
<ide> } else {
<ide> dispatch();
<ide> function dispatchPressEndEvents(
<ide> props: PressProps,
<ide> state: PressState,
<ide> ): void {
<del> const shouldStopPropagation =
<del> props.stopPropagation === undefined ? true : props.stopPropagation;
<ide> const wasActivePressStart = state.isActivePressStart;
<ide> let activationWasForced = false;
<ide>
<ide> function dispatchPressEndEvents(
<ide> state.pressEndTimeout = context.setTimeout(() => {
<ide> state.pressEndTimeout = null;
<ide> deactivate(context, props, state);
<del> return shouldStopPropagation;
<ide> }, delayPressEnd);
<ide> } else {
<ide> deactivate(context, props, state);
<ide> function unmountResponder(
<ide> }
<ide> }
<ide>
<add>function dispatchCancel(
<add> type: string,
<add> nativeEvent: $PropertyType<ReactResponderEvent, 'nativeEvent'>,
<add> context: ReactResponderContext,
<add> props: PressProps,
<add> state: PressState,
<add>): void {
<add> if (state.isPressed) {
<add> if (type === 'contextmenu' && props.preventDefault !== false) {
<add> (nativeEvent: any).preventDefault();
<add> } else {
<add> state.ignoreEmulatedMouseEvents = false;
<add> dispatchPressEndEvents(context, props, state);
<add> context.removeRootEventTypes(rootEventTypes);
<add> }
<add> }
<add>}
<add>
<ide> const PressResponder = {
<ide> targetEventTypes,
<ide> createInitialState(): PressState {
<ide> const PressResponder = {
<ide> ignoreEmulatedMouseEvents: false,
<ide> };
<ide> },
<add> stopLocalPropagation: true,
<ide> onEvent(
<ide> event: ReactResponderEvent,
<ide> context: ReactResponderContext,
<ide> props: PressProps,
<ide> state: PressState,
<del> ): boolean {
<del> const {phase, target, type} = event;
<add> ): void {
<add> const {target, type} = event;
<ide>
<ide> if (props.disabled) {
<ide> dispatchPressEndEvents(context, props, state);
<ide> context.removeRootEventTypes(rootEventTypes);
<ide> state.ignoreEmulatedMouseEvents = false;
<del> return false;
<add> return;
<ide> }
<del>
<del> // Press doesn't handle capture target events at this point
<del> if (phase === CAPTURE_PHASE) {
<del> return false;
<del> }
<del>
<ide> const nativeEvent: any = event.nativeEvent;
<ide> const pointerType = getEventPointerType(event);
<del> const shouldStopPropagation =
<del> props.stopPropagation === undefined ? true : props.stopPropagation;
<ide>
<ide> switch (type) {
<ide> // START
<ide> const PressResponder = {
<ide> // Ignore unrelated key events
<ide> if (pointerType === 'keyboard') {
<ide> if (!isValidKeyPress(nativeEvent.key)) {
<del> return shouldStopPropagation;
<add> return;
<ide> }
<ide> }
<ide>
<ide> const PressResponder = {
<ide> state.ignoreEmulatedMouseEvents ||
<ide> isEventPositionWithinTouchHitTarget(event, context)
<ide> ) {
<del> return shouldStopPropagation;
<add> return;
<ide> }
<ide> }
<ide>
<ide> // Ignore any device buttons except left-mouse and touch/pen contact
<ide> if (nativeEvent.button > 0) {
<del> return shouldStopPropagation;
<add> return;
<ide> }
<ide>
<ide> state.pointerType = pointerType;
<ide> state.pressTarget = target;
<ide> state.isPressWithinResponderRegion = true;
<ide> dispatchPressStartEvents(context, props, state);
<ide> context.addRootEventTypes(target.ownerDocument, rootEventTypes);
<del> return shouldStopPropagation;
<ide> } else {
<ide> // Prevent spacebar press from scrolling the window
<ide> if (isValidKeyPress(nativeEvent.key) && nativeEvent.key === ' ') {
<ide> nativeEvent.preventDefault();
<del> return shouldStopPropagation;
<ide> }
<ide> }
<del> return shouldStopPropagation;
<add> break;
<add> }
<add>
<add> // CANCEL
<add> case 'contextmenu': {
<add> dispatchCancel(type, nativeEvent, context, props, state);
<add> break;
<ide> }
<ide>
<add> case 'click': {
<add> if (isAnchorTagElement(target)) {
<add> const {ctrlKey, metaKey, shiftKey} = (nativeEvent: MouseEvent);
<add> // Check "open in new window/tab" and "open context menu" key modifiers
<add> const preventDefault = props.preventDefault;
<add> if (preventDefault !== false && !shiftKey && !metaKey && !ctrlKey) {
<add> nativeEvent.preventDefault();
<add> }
<add> }
<add> break;
<add> }
<add> }
<add> },
<add> onRootEvent(
<add> event: ReactResponderEvent,
<add> context: ReactResponderContext,
<add> props: PressProps,
<add> state: PressState,
<add> ): void {
<add> const {target, type} = event;
<add>
<add> const nativeEvent: any = event.nativeEvent;
<add> const pointerType = getEventPointerType(event);
<add>
<add> switch (type) {
<ide> // MOVE
<ide> case 'pointermove':
<ide> case 'mousemove':
<ide> const PressResponder = {
<ide> // Ignore emulated events (pointermove will dispatch touch and mouse events)
<ide> // Ignore pointermove events during a keyboard press
<ide> if (state.pointerType !== pointerType) {
<del> return shouldStopPropagation;
<add> return;
<ide> }
<ide>
<ide> if (state.responderRegion == null) {
<ide> const PressResponder = {
<ide> state.isPressWithinResponderRegion = false;
<ide> dispatchPressEndEvents(context, props, state);
<ide> }
<del> return shouldStopPropagation;
<ide> }
<del> return false;
<add> break;
<ide> }
<ide>
<ide> // END
<ide> const PressResponder = {
<ide> // Ignore unrelated keyboard events
<ide> if (pointerType === 'keyboard') {
<ide> if (!isValidKeyPress(nativeEvent.key)) {
<del> return false;
<add> return;
<ide> }
<ide> }
<ide>
<ide> const PressResponder = {
<ide> }
<ide> }
<ide> context.removeRootEventTypes(rootEventTypes);
<del> return shouldStopPropagation;
<ide> } else if (type === 'mouseup' && state.ignoreEmulatedMouseEvents) {
<ide> state.ignoreEmulatedMouseEvents = false;
<ide> }
<del> return false;
<add> break;
<ide> }
<ide>
<ide> // CANCEL
<del> case 'contextmenu':
<ide> case 'pointercancel':
<ide> case 'scroll':
<ide> case 'touchcancel': {
<del> if (state.isPressed) {
<del> if (type === 'contextmenu' && props.preventDefault !== false) {
<del> nativeEvent.preventDefault();
<del> } else {
<del> state.ignoreEmulatedMouseEvents = false;
<del> dispatchPressEndEvents(context, props, state);
<del> context.removeRootEventTypes(rootEventTypes);
<del> }
<del> return shouldStopPropagation;
<del> }
<del> return false;
<del> }
<del>
<del> case 'click': {
<del> if (isAnchorTagElement(target)) {
<del> const {ctrlKey, metaKey, shiftKey} = (nativeEvent: MouseEvent);
<del> // Check "open in new window/tab" and "open context menu" key modifiers
<del> const preventDefault = props.preventDefault;
<del> if (preventDefault !== false && !shiftKey && !metaKey && !ctrlKey) {
<del> nativeEvent.preventDefault();
<del> }
<del> return shouldStopPropagation;
<del> }
<del> return false;
<add> dispatchCancel(type, nativeEvent, context, props, state);
<ide> }
<ide> }
<del> return false;
<ide> },
<ide> onUnmount(
<ide> context: ReactResponderContext,
<ide><path>packages/react-events/src/Swipe.js
<ide> import type {
<ide> } from 'shared/ReactTypes';
<ide> import {REACT_EVENT_COMPONENT_TYPE} from 'shared/ReactSymbols';
<ide>
<del>const CAPTURE_PHASE = 2;
<del>const targetEventTypes = ['pointerdown', 'pointercancel'];
<del>const rootEventTypes = ['pointerup', {name: 'pointermove', passive: false}];
<add>const targetEventTypes = ['pointerdown'];
<add>const rootEventTypes = [
<add> 'pointerup',
<add> 'pointercancel',
<add> {name: 'pointermove', passive: false},
<add>];
<ide>
<ide> // In the case we don't have PointerEvents (Safari), we listen to touch events
<ide> // too
<ide> if (typeof window !== 'undefined' && window.PointerEvent === undefined) {
<del> targetEventTypes.push('touchstart', 'touchend', 'mousedown', 'touchcancel');
<del> rootEventTypes.push('mouseup', 'mousemove', {
<add> targetEventTypes.push('touchstart', 'mousedown');
<add> rootEventTypes.push('mouseup', 'mousemove', 'touchend', 'touchcancel', {
<ide> name: 'touchmove',
<ide> passive: false,
<ide> });
<ide> const SwipeResponder = {
<ide> y: 0,
<ide> };
<ide> },
<add> stopLocalPropagation: true,
<ide> onEvent(
<ide> event: ReactResponderEvent,
<ide> context: ReactResponderContext,
<ide> props: Object,
<ide> state: SwipeState,
<del> ): boolean {
<del> const {target, phase, type, nativeEvent} = event;
<add> ): void {
<add> const {target, type, nativeEvent} = event;
<ide>
<del> // Swipe doesn't handle capture target events at this point
<del> if (phase === CAPTURE_PHASE) {
<del> return false;
<del> }
<ide> switch (type) {
<ide> case 'touchstart':
<ide> case 'mousedown':
<ide> const SwipeResponder = {
<ide> }
<ide> break;
<ide> }
<add> }
<add> },
<add> onRootEvent(
<add> event: ReactResponderEvent,
<add> context: ReactResponderContext,
<add> props: Object,
<add> state: SwipeState,
<add> ): void {
<add> const {type, nativeEvent} = event;
<add>
<add> switch (type) {
<ide> case 'touchmove':
<ide> case 'mousemove':
<ide> case 'pointermove': {
<ide> if (event.passive) {
<del> return false;
<add> return;
<ide> }
<ide> if (state.isSwiping) {
<ide> let obj = null;
<ide> const SwipeResponder = {
<ide> state.swipeTarget = null;
<ide> state.touchId = null;
<ide> context.removeRootEventTypes(rootEventTypes);
<del> return false;
<add> return;
<ide> }
<ide> const x = (obj: any).screenX;
<ide> const y = (obj: any).screenY;
<ide> const SwipeResponder = {
<ide> case 'pointerup': {
<ide> if (state.isSwiping) {
<ide> if (state.x === state.startX && state.y === state.startY) {
<del> return false;
<add> return;
<ide> }
<ide> if (props.onShouldClaimOwnership) {
<ide> context.releaseOwnership();
<ide> const SwipeResponder = {
<ide> break;
<ide> }
<ide> }
<del> return false;
<ide> },
<ide> };
<ide>
<ide><path>packages/react-events/src/__tests__/Press-test.internal.js
<ide> describe('Event responder: Press', () => {
<ide> 'pointerdown',
<ide> 'inner: onPressStart',
<ide> 'inner: onPressChange',
<del> 'outer: onPressStart',
<del> 'outer: onPressChange',
<ide> 'pointerup',
<ide> 'inner: onPressEnd',
<ide> 'inner: onPressChange',
<ide> 'inner: onPress',
<del> 'outer: onPressEnd',
<del> 'outer: onPressChange',
<del> 'outer: onPress',
<ide> ]);
<ide> });
<ide>
<ide> describe('Event responder: Press', () => {
<ide> expect(fn).toHaveBeenCalledTimes(2);
<ide> });
<ide> });
<del>
<del> describe('correctly bubble to other event responders when stopPropagation is set to false', () => {
<del> it('for onPress', () => {
<del> const ref = React.createRef();
<del> const fn = jest.fn();
<del> const element = (
<del> <Press onPress={fn}>
<del> <Press onPress={fn} stopPropagation={false}>
<del> <div ref={ref} />
<del> </Press>
<del> </Press>
<del> );
<del> ReactDOM.render(element, container);
<del>
<del> ref.current.dispatchEvent(createPointerEvent('pointerdown'));
<del> ref.current.dispatchEvent(createPointerEvent('pointerup'));
<del> expect(fn).toHaveBeenCalledTimes(2);
<del> });
<del>
<del> it('for onLongPress', () => {
<del> const ref = React.createRef();
<del> const fn = jest.fn();
<del> const element = (
<del> <Press onLongPress={fn}>
<del> <Press onLongPress={fn} stopPropagation={false}>
<del> <div ref={ref} />
<del> </Press>
<del> </Press>
<del> );
<del> ReactDOM.render(element, container);
<del>
<del> ref.current.dispatchEvent(createPointerEvent('pointerdown'));
<del> jest.advanceTimersByTime(DEFAULT_LONG_PRESS_DELAY);
<del> ref.current.dispatchEvent(createPointerEvent('pointerup'));
<del> expect(fn).toHaveBeenCalledTimes(2);
<del> });
<del>
<del> it('for onPressStart/onPressEnd', () => {
<del> const ref = React.createRef();
<del> const fn = jest.fn();
<del> const fn2 = jest.fn();
<del> const element = (
<del> <Press onPressStart={fn} onPressEnd={fn2}>
<del> <Press onPressStart={fn} onPressEnd={fn2} stopPropagation={false}>
<del> <div ref={ref} />
<del> </Press>
<del> </Press>
<del> );
<del> ReactDOM.render(element, container);
<del>
<del> ref.current.dispatchEvent(createPointerEvent('pointerdown'));
<del> expect(fn).toHaveBeenCalledTimes(2);
<del> expect(fn2).toHaveBeenCalledTimes(0);
<del> ref.current.dispatchEvent(createPointerEvent('pointerup'));
<del> expect(fn).toHaveBeenCalledTimes(2);
<del> expect(fn2).toHaveBeenCalledTimes(2);
<del> });
<del>
<del> it('for onPressChange', () => {
<del> const ref = React.createRef();
<del> const fn = jest.fn();
<del> const element = (
<del> <Press onPressChange={fn}>
<del> <Press onPressChange={fn} stopPropagation={false}>
<del> <div ref={ref} />
<del> </Press>
<del> </Press>
<del> );
<del> ReactDOM.render(element, container);
<del>
<del> ref.current.dispatchEvent(createPointerEvent('pointerdown'));
<del> expect(fn).toHaveBeenCalledTimes(2);
<del> ref.current.dispatchEvent(createPointerEvent('pointerup'));
<del> expect(fn).toHaveBeenCalledTimes(4);
<del> });
<del> });
<ide> });
<ide>
<ide> describe('link components', () => {
<ide><path>packages/shared/ReactTypes.js
<ide> export type ReactEventResponderEventType =
<ide> export type ReactEventResponder = {
<ide> targetEventTypes: Array<ReactEventResponderEventType>,
<ide> createInitialState?: (props: null | Object) => Object,
<del> onEvent: (
<add> stopLocalPropagation: boolean,
<add> onEvent?: (
<ide> event: ReactResponderEvent,
<ide> context: ReactResponderContext,
<ide> props: null | Object,
<ide> state: null | Object,
<del> ) => boolean,
<add> ) => void,
<add> onEventCapture?: (
<add> event: ReactResponderEvent,
<add> context: ReactResponderContext,
<add> props: null | Object,
<add> state: null | Object,
<add> ) => void,
<add> onRootEvent?: (
<add> event: ReactResponderEvent,
<add> context: ReactResponderContext,
<add> props: null | Object,
<add> state: null | Object,
<add> ) => void,
<ide> onUnmount: (
<ide> context: ReactResponderContext,
<ide> props: null | Object,
<ide> export type ReactResponderEvent = {
<ide> type: string,
<ide> passive: boolean,
<ide> passiveSupported: boolean,
<del> phase: 0 | 1 | 2,
<ide> };
<ide>
<ide> export type ReactResponderDispatchEventOptions = {
<ide> export type ReactResponderContext = {
<ide> hasOwnership: () => boolean,
<ide> requestOwnership: () => boolean,
<ide> releaseOwnership: () => boolean,
<del> setTimeout: (func: () => boolean, timeout: number) => Symbol,
<add> setTimeout: (func: () => void, timeout: number) => Symbol,
<ide> clearTimeout: (timerId: Symbol) => void,
<ide> getEventTargetsFromTarget: (
<ide> target: Element | Document, | 9 |
Go | Go | remove jobs from daemon/networkdriver/bridge | 53582321ee502335a9c3be4789bef984e09f77c4 | <ide><path>api/client/port.go
<ide> package client
<ide>
<ide> import (
<add> "encoding/json"
<ide> "fmt"
<ide> "strings"
<ide>
<del> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/nat"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> )
<ide> func (cli *DockerCli) CmdPort(args ...string) error {
<ide> return err
<ide> }
<ide>
<del> env := engine.Env{}
<del> if err := env.Decode(stream); err != nil {
<del> return err
<add> var c struct {
<add> NetworkSettings struct {
<add> Ports nat.PortMap
<add> }
<ide> }
<del> ports := nat.PortMap{}
<del> if err := env.GetSubEnv("NetworkSettings").GetJson("Ports", &ports); err != nil {
<add>
<add> if err := json.NewDecoder(stream).Decode(&c); err != nil {
<ide> return err
<ide> }
<ide>
<ide> func (cli *DockerCli) CmdPort(args ...string) error {
<ide> proto = parts[1]
<ide> }
<ide> natPort := port + "/" + proto
<del> if frontends, exists := ports[nat.Port(port+"/"+proto)]; exists && frontends != nil {
<add> if frontends, exists := c.NetworkSettings.Ports[nat.Port(port+"/"+proto)]; exists && frontends != nil {
<ide> for _, frontend := range frontends {
<ide> fmt.Fprintf(cli.out, "%s:%s\n", frontend.HostIp, frontend.HostPort)
<ide> }
<ide> func (cli *DockerCli) CmdPort(args ...string) error {
<ide> return fmt.Errorf("Error: No public port '%s' published for %s", natPort, cmd.Arg(0))
<ide> }
<ide>
<del> for from, frontends := range ports {
<add> for from, frontends := range c.NetworkSettings.Ports {
<ide> for _, frontend := range frontends {
<ide> fmt.Fprintf(cli.out, "%s -> %s:%s\n", from, frontend.HostIp, frontend.HostPort)
<ide> }
<ide><path>builtins/builtins.go
<ide> import (
<ide> "github.com/docker/docker/api"
<ide> apiserver "github.com/docker/docker/api/server"
<ide> "github.com/docker/docker/autogen/dockerversion"
<del> "github.com/docker/docker/daemon/networkdriver/bridge"
<ide> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/pkg/parsers/kernel"
<ide> )
<ide>
<ide> func Register(eng *engine.Engine) error {
<del> if err := daemon(eng); err != nil {
<del> return err
<del> }
<ide> if err := remote(eng); err != nil {
<ide> return err
<ide> }
<ide> func remote(eng *engine.Engine) error {
<ide> return eng.Register("acceptconnections", apiserver.AcceptConnections)
<ide> }
<ide>
<del>// daemon: a default execution and storage backend for Docker on Linux,
<del>// with the following underlying components:
<del>//
<del>// * Pluggable storage drivers including aufs, vfs, lvm and btrfs.
<del>// * Pluggable execution drivers including lxc and chroot.
<del>//
<del>// In practice `daemon` still includes most core Docker components, including:
<del>//
<del>// * The reference registry client implementation
<del>// * Image management
<del>// * The build facility
<del>// * Logging
<del>//
<del>// These components should be broken off into plugins of their own.
<del>//
<del>func daemon(eng *engine.Engine) error {
<del> return eng.Register("init_networkdriver", bridge.InitDriver)
<del>}
<del>
<ide> // builtins jobs independent of any subsystem
<ide> func dockerVersion(job *engine.Job) error {
<ide> v := &engine.Env{}
<ide><path>daemon/config.go
<ide> package daemon
<ide>
<ide> import (
<del> "net"
<del>
<ide> "github.com/docker/docker/daemon/networkdriver"
<add> "github.com/docker/docker/daemon/networkdriver/bridge"
<ide> "github.com/docker/docker/opts"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> "github.com/docker/docker/pkg/ulimit"
<ide> const (
<ide> // to the docker daemon when you launch it with say: `docker -d -e lxc`
<ide> // FIXME: separate runtime configuration from http api configuration
<ide> type Config struct {
<del> Pidfile string
<del> Root string
<del> AutoRestart bool
<del> Dns []string
<del> DnsSearch []string
<del> EnableIPv6 bool
<del> EnableIptables bool
<del> EnableIpForward bool
<del> EnableIpMasq bool
<del> DefaultIp net.IP
<del> BridgeIface string
<del> BridgeIP string
<del> FixedCIDR string
<del> FixedCIDRv6 string
<del> InterContainerCommunication bool
<del> GraphDriver string
<del> GraphOptions []string
<del> ExecDriver string
<del> Mtu int
<del> SocketGroup string
<del> EnableCors bool
<del> CorsHeaders string
<del> DisableNetwork bool
<del> EnableSelinuxSupport bool
<del> Context map[string][]string
<del> TrustKeyPath string
<del> Labels []string
<del> Ulimits map[string]*ulimit.Ulimit
<del> LogConfig runconfig.LogConfig
<add> Bridge bridge.Config
<add>
<add> Pidfile string
<add> Root string
<add> AutoRestart bool
<add> Dns []string
<add> DnsSearch []string
<add> GraphDriver string
<add> GraphOptions []string
<add> ExecDriver string
<add> Mtu int
<add> SocketGroup string
<add> EnableCors bool
<add> CorsHeaders string
<add> DisableNetwork bool
<add> EnableSelinuxSupport bool
<add> Context map[string][]string
<add> TrustKeyPath string
<add> Labels []string
<add> Ulimits map[string]*ulimit.Ulimit
<add> LogConfig runconfig.LogConfig
<ide> }
<ide>
<ide> // InstallFlags adds command-line options to the top-level flag parser for
<ide> func (config *Config) InstallFlags() {
<ide> flag.StringVar(&config.Pidfile, []string{"p", "-pidfile"}, "/var/run/docker.pid", "Path to use for daemon PID file")
<ide> flag.StringVar(&config.Root, []string{"g", "-graph"}, "/var/lib/docker", "Root of the Docker runtime")
<ide> flag.BoolVar(&config.AutoRestart, []string{"#r", "#-restart"}, true, "--restart on the daemon has been deprecated in favor of --restart policies on docker run")
<del> flag.BoolVar(&config.EnableIptables, []string{"#iptables", "-iptables"}, true, "Enable addition of iptables rules")
<del> flag.BoolVar(&config.EnableIpForward, []string{"#ip-forward", "-ip-forward"}, true, "Enable net.ipv4.ip_forward")
<del> flag.BoolVar(&config.EnableIpMasq, []string{"-ip-masq"}, true, "Enable IP masquerading")
<del> flag.BoolVar(&config.EnableIPv6, []string{"-ipv6"}, false, "Enable IPv6 networking")
<del> flag.StringVar(&config.BridgeIP, []string{"#bip", "-bip"}, "", "Specify network bridge IP")
<del> flag.StringVar(&config.BridgeIface, []string{"b", "-bridge"}, "", "Attach containers to a network bridge")
<del> flag.StringVar(&config.FixedCIDR, []string{"-fixed-cidr"}, "", "IPv4 subnet for fixed IPs")
<del> flag.StringVar(&config.FixedCIDRv6, []string{"-fixed-cidr-v6"}, "", "IPv6 subnet for fixed IPs")
<del> flag.BoolVar(&config.InterContainerCommunication, []string{"#icc", "-icc"}, true, "Enable inter-container communication")
<add> flag.BoolVar(&config.Bridge.EnableIptables, []string{"#iptables", "-iptables"}, true, "Enable addition of iptables rules")
<add> flag.BoolVar(&config.Bridge.EnableIpForward, []string{"#ip-forward", "-ip-forward"}, true, "Enable net.ipv4.ip_forward")
<add> flag.BoolVar(&config.Bridge.EnableIpMasq, []string{"-ip-masq"}, true, "Enable IP masquerading")
<add> flag.BoolVar(&config.Bridge.EnableIPv6, []string{"-ipv6"}, false, "Enable IPv6 networking")
<add> flag.StringVar(&config.Bridge.IP, []string{"#bip", "-bip"}, "", "Specify network bridge IP")
<add> flag.StringVar(&config.Bridge.Iface, []string{"b", "-bridge"}, "", "Attach containers to a network bridge")
<add> flag.StringVar(&config.Bridge.FixedCIDR, []string{"-fixed-cidr"}, "", "IPv4 subnet for fixed IPs")
<add> flag.StringVar(&config.Bridge.FixedCIDRv6, []string{"-fixed-cidr-v6"}, "", "IPv6 subnet for fixed IPs")
<add> flag.BoolVar(&config.Bridge.InterContainerCommunication, []string{"#icc", "-icc"}, true, "Enable inter-container communication")
<ide> flag.StringVar(&config.GraphDriver, []string{"s", "-storage-driver"}, "", "Storage driver to use")
<ide> flag.StringVar(&config.ExecDriver, []string{"e", "-exec-driver"}, "native", "Exec driver to use")
<ide> flag.BoolVar(&config.EnableSelinuxSupport, []string{"-selinux-enabled"}, false, "Enable selinux support")
<ide> flag.IntVar(&config.Mtu, []string{"#mtu", "-mtu"}, 0, "Set the containers network MTU")
<ide> flag.StringVar(&config.SocketGroup, []string{"G", "-group"}, "docker", "Group for the unix socket")
<ide> flag.BoolVar(&config.EnableCors, []string{"#api-enable-cors", "#-api-enable-cors"}, false, "Enable CORS headers in the remote API, this is deprecated by --api-cors-header")
<ide> flag.StringVar(&config.CorsHeaders, []string{"-api-cors-header"}, "", "Set CORS headers in the remote API")
<del> opts.IPVar(&config.DefaultIp, []string{"#ip", "-ip"}, "0.0.0.0", "Default IP when binding container ports")
<add> opts.IPVar(&config.Bridge.DefaultIp, []string{"#ip", "-ip"}, "0.0.0.0", "Default IP when binding container ports")
<ide> opts.ListVar(&config.GraphOptions, []string{"-storage-opt"}, "Set storage driver options")
<ide> // FIXME: why the inconsistency between "hosts" and "sockets"?
<ide> opts.IPListVar(&config.Dns, []string{"#dns", "-dns"}, "DNS server to use")
<ide><path>daemon/container.go
<ide> import (
<ide> "github.com/docker/docker/daemon/logger"
<ide> "github.com/docker/docker/daemon/logger/jsonfilelog"
<ide> "github.com/docker/docker/daemon/logger/syslog"
<add> "github.com/docker/docker/daemon/network"
<add> "github.com/docker/docker/daemon/networkdriver/bridge"
<ide> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/links"
<ide> type Container struct {
<ide> Config *runconfig.Config
<ide> ImageID string `json:"Image"`
<ide>
<del> NetworkSettings *NetworkSettings
<add> NetworkSettings *network.Settings
<ide>
<ide> ResolvConfPath string
<ide> HostnamePath string
<ide> func (container *Container) AllocateNetwork() error {
<ide> }
<ide>
<ide> var (
<del> env *engine.Env
<ide> err error
<ide> eng = container.daemon.eng
<ide> )
<ide>
<del> job := eng.Job("allocate_interface", container.ID)
<del> job.Setenv("RequestedMac", container.Config.MacAddress)
<del> if env, err = job.Stdout.AddEnv(); err != nil {
<del> return err
<del> }
<del> if err = job.Run(); err != nil {
<add> networkSettings, err := bridge.Allocate(container.ID, container.Config.MacAddress, "", "")
<add> if err != nil {
<ide> return err
<ide> }
<ide>
<ide> func (container *Container) AllocateNetwork() error {
<ide>
<ide> if container.Config.PortSpecs != nil {
<ide> if err = migratePortMappings(container.Config, container.hostConfig); err != nil {
<del> eng.Job("release_interface", container.ID).Run()
<add> bridge.Release(container.ID)
<ide> return err
<ide> }
<ide> container.Config.PortSpecs = nil
<ide> if err = container.WriteHostConfig(); err != nil {
<del> eng.Job("release_interface", container.ID).Run()
<add> bridge.Release(container.ID)
<ide> return err
<ide> }
<ide> }
<ide> func (container *Container) AllocateNetwork() error {
<ide>
<ide> for port := range portSpecs {
<ide> if err = container.allocatePort(eng, port, bindings); err != nil {
<del> eng.Job("release_interface", container.ID).Run()
<add> bridge.Release(container.ID)
<ide> return err
<ide> }
<ide> }
<ide> container.WriteHostConfig()
<ide>
<del> container.NetworkSettings.Ports = bindings
<del> container.NetworkSettings.Bridge = env.Get("Bridge")
<del> container.NetworkSettings.IPAddress = env.Get("IP")
<del> container.NetworkSettings.IPPrefixLen = env.GetInt("IPPrefixLen")
<del> container.NetworkSettings.MacAddress = env.Get("MacAddress")
<del> container.NetworkSettings.Gateway = env.Get("Gateway")
<del> container.NetworkSettings.LinkLocalIPv6Address = env.Get("LinkLocalIPv6")
<del> container.NetworkSettings.LinkLocalIPv6PrefixLen = 64
<del> container.NetworkSettings.GlobalIPv6Address = env.Get("GlobalIPv6")
<del> container.NetworkSettings.GlobalIPv6PrefixLen = env.GetInt("GlobalIPv6PrefixLen")
<del> container.NetworkSettings.IPv6Gateway = env.Get("IPv6Gateway")
<add> networkSettings.Ports = bindings
<add> container.NetworkSettings = networkSettings
<ide>
<ide> return nil
<ide> }
<ide> func (container *Container) ReleaseNetwork() {
<ide> if container.Config.NetworkDisabled || !container.hostConfig.NetworkMode.IsPrivate() {
<ide> return
<ide> }
<del> eng := container.daemon.eng
<ide>
<del> job := eng.Job("release_interface", container.ID)
<del> job.SetenvBool("overrideShutdown", true)
<del> job.Run()
<del> container.NetworkSettings = &NetworkSettings{}
<add> bridge.Release(container.ID)
<add>
<add> container.NetworkSettings = &network.Settings{}
<ide> }
<ide>
<ide> func (container *Container) isNetworkAllocated() bool {
<ide> func (container *Container) RestoreNetwork() error {
<ide> eng := container.daemon.eng
<ide>
<ide> // Re-allocate the interface with the same IP and MAC address.
<del> job := eng.Job("allocate_interface", container.ID)
<del> job.Setenv("RequestedIP", container.NetworkSettings.IPAddress)
<del> job.Setenv("RequestedMac", container.NetworkSettings.MacAddress)
<del> if err := job.Run(); err != nil {
<add> if _, err := bridge.Allocate(container.ID, container.NetworkSettings.MacAddress, container.NetworkSettings.IPAddress, ""); err != nil {
<ide> return err
<ide> }
<ide>
<ide> func (container *Container) setupContainerDns() error {
<ide> latestResolvConf, latestHash := resolvconf.GetLastModified()
<ide>
<ide> // clean container resolv.conf re: localhost nameservers and IPv6 NS (if IPv6 disabled)
<del> updatedResolvConf, modified := resolvconf.FilterResolvDns(latestResolvConf, container.daemon.config.EnableIPv6)
<add> updatedResolvConf, modified := resolvconf.FilterResolvDns(latestResolvConf, container.daemon.config.Bridge.EnableIPv6)
<ide> if modified {
<ide> // changes have occurred during resolv.conf localhost cleanup: generate an updated hash
<ide> newHash, err := utils.HashData(bytes.NewReader(updatedResolvConf))
<ide> func (container *Container) setupContainerDns() error {
<ide> }
<ide>
<ide> // replace any localhost/127.*, and remove IPv6 nameservers if IPv6 disabled in daemon
<del> resolvConf, _ = resolvconf.FilterResolvDns(resolvConf, daemon.config.EnableIPv6)
<add> resolvConf, _ = resolvconf.FilterResolvDns(resolvConf, daemon.config.Bridge.EnableIPv6)
<ide> }
<ide> //get a sha256 hash of the resolv conf at this point so we can check
<ide> //for changes when the host resolv.conf changes (e.g. network update)
<ide> func (container *Container) allocatePort(eng *engine.Engine, port nat.Port, bind
<ide> }
<ide>
<ide> for i := 0; i < len(binding); i++ {
<del> b := binding[i]
<del>
<del> job := eng.Job("allocate_port", container.ID)
<del> job.Setenv("HostIP", b.HostIp)
<del> job.Setenv("HostPort", b.HostPort)
<del> job.Setenv("Proto", port.Proto())
<del> job.Setenv("ContainerPort", port.Port())
<del>
<del> portEnv, err := job.Stdout.AddEnv()
<add> b, err := bridge.AllocatePort(container.ID, port, binding[i])
<ide> if err != nil {
<ide> return err
<ide> }
<del> if err := job.Run(); err != nil {
<del> return err
<del> }
<del> b.HostIp = portEnv.Get("HostIP")
<del> b.HostPort = portEnv.Get("HostPort")
<del>
<ide> binding[i] = b
<ide> }
<ide> bindings[port] = binding
<ide><path>daemon/daemon.go
<ide> import (
<ide> "github.com/docker/docker/daemon/execdriver/lxc"
<ide> "github.com/docker/docker/daemon/graphdriver"
<ide> _ "github.com/docker/docker/daemon/graphdriver/vfs"
<del> _ "github.com/docker/docker/daemon/networkdriver/bridge"
<add> "github.com/docker/docker/daemon/network"
<add> "github.com/docker/docker/daemon/networkdriver/bridge"
<ide> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/graph"
<ide> "github.com/docker/docker/image"
<ide> func (daemon *Daemon) setupResolvconfWatcher() error {
<ide> logrus.Debugf("Error retrieving updated host resolv.conf: %v", err)
<ide> } else if updatedResolvConf != nil {
<ide> // because the new host resolv.conf might have localhost nameservers..
<del> updatedResolvConf, modified := resolvconf.FilterResolvDns(updatedResolvConf, daemon.config.EnableIPv6)
<add> updatedResolvConf, modified := resolvconf.FilterResolvDns(updatedResolvConf, daemon.config.Bridge.EnableIPv6)
<ide> if modified {
<ide> // changes have occurred during localhost cleanup: generate an updated hash
<ide> newHash, err := utils.HashData(bytes.NewReader(updatedResolvConf))
<ide> func (daemon *Daemon) newContainer(name string, config *runconfig.Config, imgID
<ide> Config: config,
<ide> hostConfig: &runconfig.HostConfig{},
<ide> ImageID: imgID,
<del> NetworkSettings: &NetworkSettings{},
<add> NetworkSettings: &network.Settings{},
<ide> Name: name,
<ide> Driver: daemon.driver.String(),
<ide> ExecDriver: daemon.execDriver.Name(),
<ide> func NewDaemonFromDirectory(config *Config, eng *engine.Engine, registryService
<ide> config.Mtu = getDefaultNetworkMtu()
<ide> }
<ide> // Check for mutually incompatible config options
<del> if config.BridgeIface != "" && config.BridgeIP != "" {
<add> if config.Bridge.Iface != "" && config.Bridge.IP != "" {
<ide> return nil, fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one.")
<ide> }
<del> if !config.EnableIptables && !config.InterContainerCommunication {
<add> if !config.Bridge.EnableIptables && !config.Bridge.InterContainerCommunication {
<ide> return nil, fmt.Errorf("You specified --iptables=false with --icc=false. ICC uses iptables to function. Please set --icc or --iptables to true.")
<ide> }
<del> if !config.EnableIptables && config.EnableIpMasq {
<del> config.EnableIpMasq = false
<add> if !config.Bridge.EnableIptables && config.Bridge.EnableIpMasq {
<add> config.Bridge.EnableIpMasq = false
<ide> }
<del> config.DisableNetwork = config.BridgeIface == disableNetworkBridge
<add> config.DisableNetwork = config.Bridge.Iface == disableNetworkBridge
<ide>
<ide> // Claim the pidfile first, to avoid any and all unexpected race conditions.
<ide> // Some of the init doesn't need a pidfile lock - but let's not try to be smart.
<ide> func NewDaemonFromDirectory(config *Config, eng *engine.Engine, registryService
<ide> }
<ide>
<ide> if !config.DisableNetwork {
<del> job := eng.Job("init_networkdriver")
<del>
<del> job.SetenvBool("EnableIptables", config.EnableIptables)
<del> job.SetenvBool("InterContainerCommunication", config.InterContainerCommunication)
<del> job.SetenvBool("EnableIpForward", config.EnableIpForward)
<del> job.SetenvBool("EnableIpMasq", config.EnableIpMasq)
<del> job.SetenvBool("EnableIPv6", config.EnableIPv6)
<del> job.Setenv("BridgeIface", config.BridgeIface)
<del> job.Setenv("BridgeIP", config.BridgeIP)
<del> job.Setenv("FixedCIDR", config.FixedCIDR)
<del> job.Setenv("FixedCIDRv6", config.FixedCIDRv6)
<del> job.Setenv("DefaultBindingIP", config.DefaultIp.String())
<del>
<del> if err := job.Run(); err != nil {
<add> if err := bridge.InitDriver(&config.Bridge); err != nil {
<ide> return nil, err
<ide> }
<ide> }
<add><path>daemon/network/settings.go
<del><path>daemon/network_settings.go
<del>package daemon
<add>package network
<ide>
<del>import (
<del> "github.com/docker/docker/nat"
<del>)
<add>import "github.com/docker/docker/nat"
<ide>
<del>// FIXME: move deprecated port stuff to nat to clean up the core.
<del>type PortMapping map[string]string // Deprecated
<del>
<del>type NetworkSettings struct {
<add>type Settings struct {
<ide> IPAddress string
<ide> IPPrefixLen int
<ide> MacAddress string
<ide> type NetworkSettings struct {
<ide> Gateway string
<ide> IPv6Gateway string
<ide> Bridge string
<del> PortMapping map[string]PortMapping // Deprecated
<add> PortMapping map[string]map[string]string // Deprecated
<ide> Ports nat.PortMap
<ide> }
<ide><path>daemon/networkdriver/bridge/driver.go
<ide> import (
<ide> "io/ioutil"
<ide> "net"
<ide> "os"
<add> "strconv"
<ide> "strings"
<ide> "sync"
<ide>
<ide> "github.com/Sirupsen/logrus"
<add> "github.com/docker/docker/daemon/network"
<ide> "github.com/docker/docker/daemon/networkdriver"
<ide> "github.com/docker/docker/daemon/networkdriver/ipallocator"
<ide> "github.com/docker/docker/daemon/networkdriver/portmapper"
<del> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/nat"
<ide> "github.com/docker/docker/pkg/iptables"
<ide> "github.com/docker/docker/pkg/parsers/kernel"
<ide> func initPortMapper() {
<ide> })
<ide> }
<ide>
<del>func InitDriver(job *engine.Job) error {
<add>type Config struct {
<add> EnableIPv6 bool
<add> EnableIptables bool
<add> EnableIpForward bool
<add> EnableIpMasq bool
<add> DefaultIp net.IP
<add> Iface string
<add> IP string
<add> FixedCIDR string
<add> FixedCIDRv6 string
<add> InterContainerCommunication bool
<add>}
<add>
<add>func InitDriver(config *Config) error {
<ide> var (
<del> networkv4 *net.IPNet
<del> networkv6 *net.IPNet
<del> addrv4 net.Addr
<del> addrsv6 []net.Addr
<del> enableIPTables = job.GetenvBool("EnableIptables")
<del> enableIPv6 = job.GetenvBool("EnableIPv6")
<del> icc = job.GetenvBool("InterContainerCommunication")
<del> ipMasq = job.GetenvBool("EnableIpMasq")
<del> ipForward = job.GetenvBool("EnableIpForward")
<del> bridgeIP = job.Getenv("BridgeIP")
<del> bridgeIPv6 = "fe80::1/64"
<del> fixedCIDR = job.Getenv("FixedCIDR")
<del> fixedCIDRv6 = job.Getenv("FixedCIDRv6")
<add> networkv4 *net.IPNet
<add> networkv6 *net.IPNet
<add> addrv4 net.Addr
<add> addrsv6 []net.Addr
<add> bridgeIPv6 = "fe80::1/64"
<ide> )
<ide> initPortMapper()
<ide>
<del> if defaultIP := job.Getenv("DefaultBindingIP"); defaultIP != "" {
<del> defaultBindingIP = net.ParseIP(defaultIP)
<add> if config.DefaultIp != nil {
<add> defaultBindingIP = config.DefaultIp
<ide> }
<ide>
<del> bridgeIface = job.Getenv("BridgeIface")
<add> bridgeIface = config.Iface
<ide> usingDefaultBridge := false
<ide> if bridgeIface == "" {
<ide> usingDefaultBridge = true
<ide> func InitDriver(job *engine.Job) error {
<ide> }
<ide>
<ide> // If the iface is not found, try to create it
<del> if err := configureBridge(bridgeIP, bridgeIPv6, enableIPv6); err != nil {
<add> if err := configureBridge(config.IP, bridgeIPv6, config.EnableIPv6); err != nil {
<ide> return err
<ide> }
<ide>
<ide> func InitDriver(job *engine.Job) error {
<ide> return err
<ide> }
<ide>
<del> if fixedCIDRv6 != "" {
<add> if config.FixedCIDRv6 != "" {
<ide> // Setting route to global IPv6 subnet
<del> logrus.Infof("Adding route to IPv6 network %q via device %q", fixedCIDRv6, bridgeIface)
<del> if err := netlink.AddRoute(fixedCIDRv6, "", "", bridgeIface); err != nil {
<del> logrus.Fatalf("Could not add route to IPv6 network %q via device %q", fixedCIDRv6, bridgeIface)
<add> logrus.Infof("Adding route to IPv6 network %q via device %q", config.FixedCIDRv6, bridgeIface)
<add> if err := netlink.AddRoute(config.FixedCIDRv6, "", "", bridgeIface); err != nil {
<add> logrus.Fatalf("Could not add route to IPv6 network %q via device %q", config.FixedCIDRv6, bridgeIface)
<ide> }
<ide> }
<ide> } else {
<ide> // Bridge exists already, getting info...
<ide> // Validate that the bridge ip matches the ip specified by BridgeIP
<del> if bridgeIP != "" {
<add> if config.IP != "" {
<ide> networkv4 = addrv4.(*net.IPNet)
<del> bip, _, err := net.ParseCIDR(bridgeIP)
<add> bip, _, err := net.ParseCIDR(config.IP)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func InitDriver(job *engine.Job) error {
<ide> // (for example, an existing Docker installation that has only been used
<ide> // with IPv4 and docker0 already is set up) In that case, we can perform
<ide> // the bridge init for IPv6 here, else we will error out below if --ipv6=true
<del> if len(addrsv6) == 0 && enableIPv6 {
<add> if len(addrsv6) == 0 && config.EnableIPv6 {
<ide> if err := setupIPv6Bridge(bridgeIPv6); err != nil {
<ide> return err
<ide> }
<ide> func InitDriver(job *engine.Job) error {
<ide> }
<ide> }
<ide>
<del> // TODO: Check if route to fixedCIDRv6 is set
<add> // TODO: Check if route to config.FixedCIDRv6 is set
<ide> }
<ide>
<del> if enableIPv6 {
<add> if config.EnableIPv6 {
<ide> bip6, _, err := net.ParseCIDR(bridgeIPv6)
<ide> if err != nil {
<ide> return err
<ide> func InitDriver(job *engine.Job) error {
<ide>
<ide> networkv4 = addrv4.(*net.IPNet)
<ide>
<del> if enableIPv6 {
<add> if config.EnableIPv6 {
<ide> if len(addrsv6) == 0 {
<ide> return errors.New("IPv6 enabled but no IPv6 detected")
<ide> }
<ide> bridgeIPv6Addr = networkv6.IP
<ide> }
<ide>
<ide> // Configure iptables for link support
<del> if enableIPTables {
<del> if err := setupIPTables(addrv4, icc, ipMasq); err != nil {
<add> if config.EnableIptables {
<add> if err := setupIPTables(addrv4, config.InterContainerCommunication, config.EnableIpMasq); err != nil {
<ide> return err
<ide> }
<ide>
<ide> }
<ide>
<del> if ipForward {
<add> if config.EnableIpForward {
<ide> // Enable IPv4 forwarding
<ide> if err := ioutil.WriteFile("/proc/sys/net/ipv4/ip_forward", []byte{'1', '\n'}, 0644); err != nil {
<ide> logrus.Warnf("WARNING: unable to enable IPv4 forwarding: %s\n", err)
<ide> }
<ide>
<del> if fixedCIDRv6 != "" {
<add> if config.FixedCIDRv6 != "" {
<ide> // Enable IPv6 forwarding
<ide> if err := ioutil.WriteFile("/proc/sys/net/ipv6/conf/default/forwarding", []byte{'1', '\n'}, 0644); err != nil {
<ide> logrus.Warnf("WARNING: unable to enable IPv6 default forwarding: %s\n", err)
<ide> func InitDriver(job *engine.Job) error {
<ide> return err
<ide> }
<ide>
<del> if enableIPTables {
<add> if config.EnableIptables {
<ide> _, err := iptables.NewChain("DOCKER", bridgeIface, iptables.Nat)
<ide> if err != nil {
<ide> return err
<ide> func InitDriver(job *engine.Job) error {
<ide> }
<ide>
<ide> bridgeIPv4Network = networkv4
<del> if fixedCIDR != "" {
<del> _, subnet, err := net.ParseCIDR(fixedCIDR)
<add> if config.FixedCIDR != "" {
<add> _, subnet, err := net.ParseCIDR(config.FixedCIDR)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func InitDriver(job *engine.Job) error {
<ide> }
<ide> }
<ide>
<del> if fixedCIDRv6 != "" {
<del> _, subnet, err := net.ParseCIDR(fixedCIDRv6)
<add> if config.FixedCIDRv6 != "" {
<add> _, subnet, err := net.ParseCIDR(config.FixedCIDRv6)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func InitDriver(job *engine.Job) error {
<ide> // Block BridgeIP in IP allocator
<ide> ipAllocator.RequestIP(bridgeIPv4Network, bridgeIPv4Network.IP)
<ide>
<del> // https://github.com/docker/docker/issues/2768
<del> job.Eng.HackSetGlobalVar("httpapi.bridgeIP", bridgeIPv4Network.IP)
<del>
<del> for name, f := range map[string]engine.Handler{
<del> "allocate_interface": Allocate,
<del> "release_interface": Release,
<del> "allocate_port": AllocatePort,
<del> "link": LinkContainers,
<del> } {
<del> if err := job.Eng.Register(name, f); err != nil {
<del> return err
<del> }
<del> }
<ide> return nil
<ide> }
<ide>
<ide> func linkLocalIPv6FromMac(mac string) (string, error) {
<ide> }
<ide>
<ide> // Allocate a network interface
<del>func Allocate(job *engine.Job) error {
<add>func Allocate(id, requestedMac, requestedIP, requestedIPv6 string) (*network.Settings, error) {
<ide> var (
<del> ip net.IP
<del> mac net.HardwareAddr
<del> err error
<del> id = job.Args[0]
<del> requestedIP = net.ParseIP(job.Getenv("RequestedIP"))
<del> requestedIPv6 = net.ParseIP(job.Getenv("RequestedIPv6"))
<del> globalIPv6 net.IP
<add> ip net.IP
<add> mac net.HardwareAddr
<add> err error
<add> globalIPv6 net.IP
<ide> )
<ide>
<del> ip, err = ipAllocator.RequestIP(bridgeIPv4Network, requestedIP)
<add> ip, err = ipAllocator.RequestIP(bridgeIPv4Network, net.ParseIP(requestedIP))
<ide> if err != nil {
<del> return err
<add> return nil, err
<ide> }
<ide>
<ide> // If no explicit mac address was given, generate a random one.
<del> if mac, err = net.ParseMAC(job.Getenv("RequestedMac")); err != nil {
<add> if mac, err = net.ParseMAC(requestedMac); err != nil {
<ide> mac = generateMacAddr(ip)
<ide> }
<ide>
<ide> if globalIPv6Network != nil {
<ide> // If globalIPv6Network Size is at least a /80 subnet generate IPv6 address from MAC address
<ide> netmaskOnes, _ := globalIPv6Network.Mask.Size()
<del> if requestedIPv6 == nil && netmaskOnes <= 80 {
<del> requestedIPv6 = make(net.IP, len(globalIPv6Network.IP))
<del> copy(requestedIPv6, globalIPv6Network.IP)
<add> ipv6 := net.ParseIP(requestedIPv6)
<add> if ipv6 == nil && netmaskOnes <= 80 {
<add> ipv6 = make(net.IP, len(globalIPv6Network.IP))
<add> copy(ipv6, globalIPv6Network.IP)
<ide> for i, h := range mac {
<del> requestedIPv6[i+10] = h
<add> ipv6[i+10] = h
<ide> }
<ide> }
<ide>
<del> globalIPv6, err = ipAllocator.RequestIP(globalIPv6Network, requestedIPv6)
<add> globalIPv6, err = ipAllocator.RequestIP(globalIPv6Network, ipv6)
<ide> if err != nil {
<ide> logrus.Errorf("Allocator: RequestIP v6: %v", err)
<del> return err
<add> return nil, err
<ide> }
<ide> logrus.Infof("Allocated IPv6 %s", globalIPv6)
<ide> }
<ide>
<del> out := engine.Env{}
<del> out.Set("IP", ip.String())
<del> out.Set("Mask", bridgeIPv4Network.Mask.String())
<del> out.Set("Gateway", bridgeIPv4Network.IP.String())
<del> out.Set("MacAddress", mac.String())
<del> out.Set("Bridge", bridgeIface)
<del>
<del> size, _ := bridgeIPv4Network.Mask.Size()
<del> out.SetInt("IPPrefixLen", size)
<add> maskSize, _ := bridgeIPv4Network.Mask.Size()
<ide>
<ide> // If linklocal IPv6
<ide> localIPv6Net, err := linkLocalIPv6FromMac(mac.String())
<ide> if err != nil {
<del> return err
<add> return nil, err
<ide> }
<ide> localIPv6, _, _ := net.ParseCIDR(localIPv6Net)
<del> out.Set("LinkLocalIPv6", localIPv6.String())
<del> out.Set("MacAddress", mac.String())
<add>
<add> networkSettings := &network.Settings{
<add> IPAddress: ip.String(),
<add> Gateway: bridgeIPv4Network.IP.String(),
<add> MacAddress: mac.String(),
<add> Bridge: bridgeIface,
<add> IPPrefixLen: maskSize,
<add> LinkLocalIPv6Address: localIPv6.String(),
<add> }
<ide>
<ide> if globalIPv6Network != nil {
<del> out.Set("GlobalIPv6", globalIPv6.String())
<del> sizev6, _ := globalIPv6Network.Mask.Size()
<del> out.SetInt("GlobalIPv6PrefixLen", sizev6)
<del> out.Set("IPv6Gateway", bridgeIPv6Addr.String())
<add> networkSettings.GlobalIPv6Address = globalIPv6.String()
<add> maskV6Size, _ := globalIPv6Network.Mask.Size()
<add> networkSettings.GlobalIPv6PrefixLen = maskV6Size
<add> networkSettings.IPv6Gateway = bridgeIPv6Addr.String()
<ide> }
<ide>
<ide> currentInterfaces.Set(id, &networkInterface{
<ide> IP: ip,
<ide> IPv6: globalIPv6,
<ide> })
<ide>
<del> out.WriteTo(job.Stdout)
<del>
<del> return nil
<add> return networkSettings, nil
<ide> }
<ide>
<ide> // Release an interface for a select ip
<del>func Release(job *engine.Job) error {
<del> var (
<del> id = job.Args[0]
<del> containerInterface = currentInterfaces.Get(id)
<del> )
<add>func Release(id string) {
<add> var containerInterface = currentInterfaces.Get(id)
<ide>
<ide> if containerInterface == nil {
<del> return fmt.Errorf("No network information to release for %s", id)
<add> logrus.Warnf("No network information to release for %s", id)
<ide> }
<ide>
<ide> for _, nat := range containerInterface.PortMappings {
<ide> func Release(job *engine.Job) error {
<ide> logrus.Infof("Unable to release IPv6 %s", err)
<ide> }
<ide> }
<del> return nil
<ide> }
<ide>
<ide> // Allocate an external port and map it to the interface
<del>func AllocatePort(job *engine.Job) error {
<add>func AllocatePort(id string, port nat.Port, binding nat.PortBinding) (nat.PortBinding, error) {
<ide> var (
<del> err error
<del>
<ide> ip = defaultBindingIP
<del> id = job.Args[0]
<del> hostIP = job.Getenv("HostIP")
<del> hostPort = job.GetenvInt("HostPort")
<del> containerPort = job.GetenvInt("ContainerPort")
<del> proto = job.Getenv("Proto")
<add> proto = port.Proto()
<add> containerPort = port.Int()
<ide> network = currentInterfaces.Get(id)
<ide> )
<ide>
<del> if hostIP != "" {
<del> ip = net.ParseIP(hostIP)
<add> if binding.HostIp != "" {
<add> ip = net.ParseIP(binding.HostIp)
<ide> if ip == nil {
<del> return fmt.Errorf("Bad parameter: invalid host ip %s", hostIP)
<add> return nat.PortBinding{}, fmt.Errorf("Bad parameter: invalid host ip %s", binding.HostIp)
<ide> }
<ide> }
<ide>
<ide> func AllocatePort(job *engine.Job) error {
<ide> case "udp":
<ide> container = &net.UDPAddr{IP: network.IP, Port: containerPort}
<ide> default:
<del> return fmt.Errorf("unsupported address type %s", proto)
<add> return nat.PortBinding{}, fmt.Errorf("unsupported address type %s", proto)
<ide> }
<ide>
<ide> //
<ide> func AllocatePort(job *engine.Job) error {
<ide> // yields.
<ide> //
<ide>
<del> var host net.Addr
<add> var (
<add> host net.Addr
<add> err error
<add> )
<add> hostPort, err := nat.ParsePort(binding.HostPort)
<add> if err != nil {
<add> return nat.PortBinding{}, err
<add> }
<ide> for i := 0; i < MaxAllocatedPortAttempts; i++ {
<ide> if host, err = portMapper.Map(container, ip, hostPort); err == nil {
<ide> break
<ide> func AllocatePort(job *engine.Job) error {
<ide> }
<ide>
<ide> if err != nil {
<del> return err
<add> return nat.PortBinding{}, err
<ide> }
<ide>
<ide> network.PortMappings = append(network.PortMappings, host)
<ide>
<del> out := engine.Env{}
<ide> switch netAddr := host.(type) {
<ide> case *net.TCPAddr:
<del> out.Set("HostIP", netAddr.IP.String())
<del> out.SetInt("HostPort", netAddr.Port)
<add> return nat.PortBinding{HostIp: netAddr.IP.String(), HostPort: strconv.Itoa(netAddr.Port)}, nil
<ide> case *net.UDPAddr:
<del> out.Set("HostIP", netAddr.IP.String())
<del> out.SetInt("HostPort", netAddr.Port)
<del> }
<del> if _, err := out.WriteTo(job.Stdout); err != nil {
<del> return err
<add> return nat.PortBinding{HostIp: netAddr.IP.String(), HostPort: strconv.Itoa(netAddr.Port)}, nil
<add> default:
<add> return nat.PortBinding{}, fmt.Errorf("unsupported address type %T", netAddr)
<ide> }
<del>
<del> return nil
<ide> }
<ide>
<del>func LinkContainers(job *engine.Job) error {
<del> var (
<del> action = job.Args[0]
<del> nfAction iptables.Action
<del> childIP = job.Getenv("ChildIP")
<del> parentIP = job.Getenv("ParentIP")
<del> ignoreErrors = job.GetenvBool("IgnoreErrors")
<del> ports = job.GetenvList("Ports")
<del> )
<add>//TODO: should it return something more than just an error?
<add>func LinkContainers(action, parentIP, childIP string, ports []nat.Port, ignoreErrors bool) error {
<add> var nfAction iptables.Action
<ide>
<ide> switch action {
<ide> case "-A":
<ide> func LinkContainers(job *engine.Job) error {
<ide> }
<ide>
<ide> chain := iptables.Chain{Name: "DOCKER", Bridge: bridgeIface}
<del> for _, p := range ports {
<del> port := nat.Port(p)
<add> for _, port := range ports {
<ide> if err := chain.Link(nfAction, ip1, ip2, port.Int(), port.Proto()); !ignoreErrors && err != nil {
<ide> return err
<ide> }
<ide><path>daemon/networkdriver/bridge/driver_test.go
<ide> import (
<ide> "strconv"
<ide> "testing"
<ide>
<add> "github.com/docker/docker/daemon/network"
<ide> "github.com/docker/docker/daemon/networkdriver/portmapper"
<del> "github.com/docker/docker/engine"
<add> "github.com/docker/docker/nat"
<ide> "github.com/docker/docker/pkg/iptables"
<ide> )
<ide>
<ide> func init() {
<ide> portmapper.NewProxy = portmapper.NewMockProxyCommand
<ide> }
<ide>
<del>func findFreePort(t *testing.T) int {
<add>func findFreePort(t *testing.T) string {
<ide> l, err := net.Listen("tcp", ":0")
<ide> if err != nil {
<ide> t.Fatal("Failed to find a free port")
<ide> func findFreePort(t *testing.T) int {
<ide> if err != nil {
<ide> t.Fatal("Failed to resolve address to identify free port")
<ide> }
<del> return result.Port
<del>}
<del>
<del>func newPortAllocationJob(eng *engine.Engine, port int) (job *engine.Job) {
<del> strPort := strconv.Itoa(port)
<del>
<del> job = eng.Job("allocate_port", "container_id")
<del> job.Setenv("HostIP", "127.0.0.1")
<del> job.Setenv("HostPort", strPort)
<del> job.Setenv("Proto", "tcp")
<del> job.Setenv("ContainerPort", strPort)
<del> return
<del>}
<del>
<del>func newPortAllocationJobWithInvalidHostIP(eng *engine.Engine, port int) (job *engine.Job) {
<del> strPort := strconv.Itoa(port)
<del>
<del> job = eng.Job("allocate_port", "container_id")
<del> job.Setenv("HostIP", "localhost")
<del> job.Setenv("HostPort", strPort)
<del> job.Setenv("Proto", "tcp")
<del> job.Setenv("ContainerPort", strPort)
<del> return
<add> return strconv.Itoa(result.Port)
<ide> }
<ide>
<ide> func TestAllocatePortDetection(t *testing.T) {
<del> eng := engine.New()
<del> eng.Logging = false
<del>
<ide> freePort := findFreePort(t)
<ide>
<del> // Init driver
<del> job := eng.Job("initdriver")
<del> if res := InitDriver(job); res != nil {
<add> if err := InitDriver(new(Config)); err != nil {
<ide> t.Fatal("Failed to initialize network driver")
<ide> }
<ide>
<ide> // Allocate interface
<del> job = eng.Job("allocate_interface", "container_id")
<del> if res := Allocate(job); res != nil {
<add> if _, err := Allocate("container_id", "", "", ""); err != nil {
<ide> t.Fatal("Failed to allocate network interface")
<ide> }
<ide>
<add> port := nat.Port(freePort + "/tcp")
<add> binding := nat.PortBinding{HostIp: "127.0.0.1", HostPort: freePort}
<add>
<ide> // Allocate same port twice, expect failure on second call
<del> job = newPortAllocationJob(eng, freePort)
<del> if res := AllocatePort(job); res != nil {
<add> if _, err := AllocatePort("container_id", port, binding); err != nil {
<ide> t.Fatal("Failed to find a free port to allocate")
<ide> }
<del> if res := AllocatePort(job); res == nil {
<add> if _, err := AllocatePort("container_id", port, binding); err == nil {
<ide> t.Fatal("Duplicate port allocation granted by AllocatePort")
<ide> }
<ide> }
<ide>
<ide> func TestHostnameFormatChecking(t *testing.T) {
<del> eng := engine.New()
<del> eng.Logging = false
<del>
<ide> freePort := findFreePort(t)
<ide>
<del> // Init driver
<del> job := eng.Job("initdriver")
<del> if res := InitDriver(job); res != nil {
<add> if err := InitDriver(new(Config)); err != nil {
<ide> t.Fatal("Failed to initialize network driver")
<ide> }
<ide>
<ide> // Allocate interface
<del> job = eng.Job("allocate_interface", "container_id")
<del> if res := Allocate(job); res != nil {
<add> if _, err := Allocate("container_id", "", "", ""); err != nil {
<ide> t.Fatal("Failed to allocate network interface")
<ide> }
<ide>
<del> // Allocate port with invalid HostIP, expect failure with Bad Request http status
<del> job = newPortAllocationJobWithInvalidHostIP(eng, freePort)
<del> if res := AllocatePort(job); res == nil {
<add> port := nat.Port(freePort + "/tcp")
<add> binding := nat.PortBinding{HostIp: "localhost", HostPort: freePort}
<add>
<add> if _, err := AllocatePort("container_id", port, binding); err == nil {
<ide> t.Fatal("Failed to check invalid HostIP")
<ide> }
<ide> }
<ide>
<del>func newInterfaceAllocation(t *testing.T, input engine.Env) (output engine.Env) {
<del> eng := engine.New()
<del> eng.Logging = false
<del>
<del> done := make(chan bool)
<del>
<add>func newInterfaceAllocation(t *testing.T, globalIPv6 *net.IPNet, requestedMac, requestedIP, requestedIPv6 string, expectFail bool) *network.Settings {
<ide> // set IPv6 global if given
<del> if input.Exists("globalIPv6Network") {
<del> _, globalIPv6Network, _ = net.ParseCIDR(input.Get("globalIPv6Network"))
<add> if globalIPv6 != nil {
<add> globalIPv6Network = globalIPv6
<ide> }
<ide>
<del> job := eng.Job("allocate_interface", "container_id")
<del> job.Env().Init(&input)
<del> reader, _ := job.Stdout.AddPipe()
<del> go func() {
<del> output.Decode(reader)
<del> done <- true
<del> }()
<del>
<del> res := Allocate(job)
<del> job.Stdout.Close()
<del> <-done
<del>
<del> if input.Exists("expectFail") && input.GetBool("expectFail") {
<del> if res == nil {
<del> t.Fatal("Doesn't fail to allocate network interface")
<del> }
<del> } else {
<del> if res != nil {
<del> t.Fatal("Failed to allocate network interface")
<del> }
<add> networkSettings, err := Allocate("container_id", requestedMac, requestedIP, requestedIPv6)
<add> if err == nil && expectFail {
<add> t.Fatal("Doesn't fail to allocate network interface")
<add> } else if err != nil && !expectFail {
<add> t.Fatal("Failed to allocate network interface")
<add>
<ide> }
<ide>
<del> if input.Exists("globalIPv6Network") {
<add> if globalIPv6 != nil {
<ide> // check for bug #11427
<del> _, subnet, _ := net.ParseCIDR(input.Get("globalIPv6Network"))
<del> if globalIPv6Network.IP.String() != subnet.IP.String() {
<add> if globalIPv6Network.IP.String() != globalIPv6.IP.String() {
<ide> t.Fatal("globalIPv6Network was modified during allocation")
<ide> }
<ide> // clean up IPv6 global
<ide> globalIPv6Network = nil
<ide> }
<ide>
<del> return
<add> return networkSettings
<ide> }
<ide>
<ide> func TestIPv6InterfaceAllocationAutoNetmaskGt80(t *testing.T) {
<del>
<del> input := engine.Env{}
<del>
<ide> _, subnet, _ := net.ParseCIDR("2001:db8:1234:1234:1234::/81")
<del>
<del> // set global ipv6
<del> input.Set("globalIPv6Network", subnet.String())
<del>
<del> output := newInterfaceAllocation(t, input)
<add> networkSettings := newInterfaceAllocation(t, subnet, "", "", "", false)
<ide>
<ide> // ensure low manually assigend global ip
<del> ip := net.ParseIP(output.Get("GlobalIPv6"))
<add> ip := net.ParseIP(networkSettings.GlobalIPv6Address)
<ide> _, subnet, _ = net.ParseCIDR(fmt.Sprintf("%s/%d", subnet.IP.String(), 120))
<ide> if !subnet.Contains(ip) {
<ide> t.Fatalf("Error ip %s not in subnet %s", ip.String(), subnet.String())
<ide> }
<ide> }
<ide>
<ide> func TestIPv6InterfaceAllocationAutoNetmaskLe80(t *testing.T) {
<del>
<del> input := engine.Env{}
<del>
<ide> _, subnet, _ := net.ParseCIDR("2001:db8:1234:1234:1234::/80")
<del>
<del> // set global ipv6
<del> input.Set("globalIPv6Network", subnet.String())
<del> input.Set("RequestedMac", "ab:cd:ab:cd:ab:cd")
<del>
<del> output := newInterfaceAllocation(t, input)
<add> networkSettings := newInterfaceAllocation(t, subnet, "ab:cd:ab:cd:ab:cd", "", "", false)
<ide>
<ide> // ensure global ip with mac
<del> ip := net.ParseIP(output.Get("GlobalIPv6"))
<add> ip := net.ParseIP(networkSettings.GlobalIPv6Address)
<ide> expectedIP := net.ParseIP("2001:db8:1234:1234:1234:abcd:abcd:abcd")
<ide> if ip.String() != expectedIP.String() {
<ide> t.Fatalf("Error ip %s should be %s", ip.String(), expectedIP.String())
<ide> }
<ide>
<ide> // ensure link local format
<del> ip = net.ParseIP(output.Get("LinkLocalIPv6"))
<add> ip = net.ParseIP(networkSettings.LinkLocalIPv6Address)
<ide> expectedIP = net.ParseIP("fe80::a9cd:abff:fecd:abcd")
<ide> if ip.String() != expectedIP.String() {
<ide> t.Fatalf("Error ip %s should be %s", ip.String(), expectedIP.String())
<ide> func TestIPv6InterfaceAllocationAutoNetmaskLe80(t *testing.T) {
<ide> }
<ide>
<ide> func TestIPv6InterfaceAllocationRequest(t *testing.T) {
<del>
<del> input := engine.Env{}
<del>
<ide> _, subnet, _ := net.ParseCIDR("2001:db8:1234:1234:1234::/80")
<del> expectedIP := net.ParseIP("2001:db8:1234:1234:1234::1328")
<del>
<del> // set global ipv6
<del> input.Set("globalIPv6Network", subnet.String())
<del> input.Set("RequestedIPv6", expectedIP.String())
<add> expectedIP := "2001:db8:1234:1234:1234::1328"
<ide>
<del> output := newInterfaceAllocation(t, input)
<add> networkSettings := newInterfaceAllocation(t, subnet, "", "", expectedIP, false)
<ide>
<ide> // ensure global ip with mac
<del> ip := net.ParseIP(output.Get("GlobalIPv6"))
<del> if ip.String() != expectedIP.String() {
<del> t.Fatalf("Error ip %s should be %s", ip.String(), expectedIP.String())
<add> ip := net.ParseIP(networkSettings.GlobalIPv6Address)
<add> if ip.String() != expectedIP {
<add> t.Fatalf("Error ip %s should be %s", ip.String(), expectedIP)
<ide> }
<ide>
<ide> // retry -> fails for duplicated address
<del> input.SetBool("expectFail", true)
<del> output = newInterfaceAllocation(t, input)
<add> _ = newInterfaceAllocation(t, subnet, "", "", expectedIP, true)
<ide> }
<ide>
<ide> func TestMacAddrGeneration(t *testing.T) {
<ide> func TestMacAddrGeneration(t *testing.T) {
<ide> }
<ide>
<ide> func TestLinkContainers(t *testing.T) {
<del> eng := engine.New()
<del> eng.Logging = false
<del>
<ide> // Init driver
<del> job := eng.Job("initdriver")
<del> if res := InitDriver(job); res != nil {
<add> if err := InitDriver(new(Config)); err != nil {
<ide> t.Fatal("Failed to initialize network driver")
<ide> }
<ide>
<ide> // Allocate interface
<del> job = eng.Job("allocate_interface", "container_id")
<del> if res := Allocate(job); res != nil {
<add> if _, err := Allocate("container_id", "", "", ""); err != nil {
<ide> t.Fatal("Failed to allocate network interface")
<ide> }
<ide>
<del> job.Args[0] = "-I"
<del>
<del> job.Setenv("ChildIP", "172.17.0.2")
<del> job.Setenv("ParentIP", "172.17.0.1")
<del> job.SetenvBool("IgnoreErrors", false)
<del> job.SetenvList("Ports", []string{"1234"})
<del>
<ide> bridgeIface = "lo"
<del> _, err := iptables.NewChain("DOCKER", bridgeIface, iptables.Filter)
<del> if err != nil {
<add> if _, err := iptables.NewChain("DOCKER", bridgeIface, iptables.Filter); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> if res := LinkContainers(job); res != nil {
<del> t.Fatalf("LinkContainers failed")
<add> if err := LinkContainers("-I", "172.17.0.1", "172.17.0.2", []nat.Port{nat.Port("1234")}, false); err != nil {
<add> t.Fatal("LinkContainers failed")
<ide> }
<ide>
<ide> // flush rules
<del> if _, err = iptables.Raw([]string{"-F", "DOCKER"}...); err != nil {
<add> if _, err := iptables.Raw([]string{"-F", "DOCKER"}...); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide><path>integration/utils_test.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/builtins"
<ide> "github.com/docker/docker/daemon"
<add> "github.com/docker/docker/daemon/networkdriver/bridge"
<ide> "github.com/docker/docker/engine"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> "github.com/docker/docker/registry"
<ide> func newTestEngine(t Fataler, autorestart bool, root string) *engine.Engine {
<ide> ExecDriver: "native",
<ide> // Either InterContainerCommunication or EnableIptables must be set,
<ide> // otherwise NewDaemon will fail because of conflicting settings.
<del> InterContainerCommunication: true,
<del> TrustKeyPath: filepath.Join(root, "key.json"),
<del> LogConfig: runconfig.LogConfig{Type: "json-file"},
<add> Bridge: bridge.Config{
<add> InterContainerCommunication: true,
<add> },
<add> TrustKeyPath: filepath.Join(root, "key.json"),
<add> LogConfig: runconfig.LogConfig{Type: "json-file"},
<ide> }
<ide> d, err := daemon.NewDaemon(cfg, eng, registry.NewService(nil))
<ide> if err != nil {
<ide><path>links/links.go
<ide> package links
<ide>
<ide> import (
<ide> "fmt"
<del> "github.com/docker/docker/engine"
<del> "github.com/docker/docker/nat"
<ide> "path"
<ide> "strings"
<add>
<add> "github.com/docker/docker/daemon/networkdriver/bridge"
<add> "github.com/docker/docker/engine"
<add> "github.com/docker/docker/nat"
<ide> )
<ide>
<ide> type Link struct {
<ide> func (l *Link) Disable() {
<ide> }
<ide>
<ide> func (l *Link) toggle(action string, ignoreErrors bool) error {
<del> job := l.eng.Job("link", action)
<del>
<del> job.Setenv("ParentIP", l.ParentIP)
<del> job.Setenv("ChildIP", l.ChildIP)
<del> job.SetenvBool("IgnoreErrors", ignoreErrors)
<del>
<del> out := make([]string, len(l.Ports))
<del> for i, p := range l.Ports {
<del> out[i] = string(p)
<del> }
<del> job.SetenvList("Ports", out)
<del>
<del> if err := job.Run(); err != nil {
<del> // TODO: get ouput from job
<del> return err
<del> }
<del> return nil
<add> return bridge.LinkContainers(action, l.ParentIP, l.ChildIP, l.Ports, ignoreErrors)
<ide> }
<ide><path>nat/nat.go
<ide> func NewPort(proto, port string) Port {
<ide> }
<ide>
<ide> func ParsePort(rawPort string) (int, error) {
<add> if len(rawPort) == 0 {
<add> return 0, nil
<add> }
<ide> port, err := strconv.ParseUint(rawPort, 10, 16)
<ide> if err != nil {
<ide> return 0, err | 11 |
PHP | PHP | add tests for operating on collections | 8ccd63d46086e2f61786b4030030c7b0524c0ca4 | <ide><path>tests/TestCase/View/Form/EntityContextTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\View\Form;
<ide>
<add>use Cake\Collection\Collection;
<ide> use Cake\Network\Request;
<ide> use Cake\ORM\Entity;
<ide> use Cake\ORM\Table;
<ide> use Cake\ORM\TableRegistry;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\Validation\Validator;
<ide> use Cake\View\Form\EntityContext;
<add>use ArrayObject;
<ide>
<ide> /**
<ide> * Test stub.
<ide> public function testOperationsNoTableArg() {
<ide> $this->assertEquals($row->errors('title'), $result);
<ide> }
<ide>
<add>/**
<add> * Data provider for testing collections.
<add> *
<add> * @return array
<add> */
<add> public static function collectionProvider() {
<add> $one = new Entity([
<add> 'title' => 'First post',
<add> 'body' => 'Stuff',
<add> 'user' => new Entity(['username' => 'mark'])
<add> ]);
<add> $one->errors('title', 'Required field');
<add>
<add> $two = new Entity([
<add> 'title' => 'Second post',
<add> 'body' => 'Some text',
<add> 'user' => new Entity(['username' => 'jose'])
<add> ]);
<add> $two->errors('body', 'Not long enough');
<add>
<add> return [
<add> 'array' => [[$one, $two]],
<add> 'basic iterator' => [new ArrayObject([$one, $two])],
<add> 'collection' => [new Collection([$one, $two])],
<add> ];
<add> }
<add>
<add>/**
<add> * Test operations on a collection of entities.
<add> *
<add> * @dataProvider collectionProvider
<add> * @return void
<add> */
<add> public function testValOnCollections($collection) {
<add> $context = new EntityContext($this->request, [
<add> 'entity' => $collection,
<add> 'table' => 'Articles',
<add> ]);
<add>
<add> $result = $context->val('0.title');
<add> $this->assertEquals('First post', $result);
<add>
<add> $result = $context->val('0.user.username');
<add> $this->assertEquals('mark', $result);
<add>
<add> $result = $context->val('1.title');
<add> $this->assertEquals('Second post', $result);
<add>
<add> $result = $context->val('1.user.username');
<add> $this->assertEquals('jose', $result);
<add> }
<add>
<add>/**
<add> * Test error operations on a collection of entities.
<add> *
<add> * @dataProvider collectionProvider
<add> * @return void
<add> */
<add> public function testErrorsOnCollections($collection) {
<add> $context = new EntityContext($this->request, [
<add> 'entity' => $collection,
<add> 'table' => 'Articles',
<add> ]);
<add>
<add> $this->assertTrue($context->hasError('0.title'));
<add> $this->assertEquals(['Required field'], $context->error('0.title'));
<add> $this->assertFalse($context->hasError('0.body'));
<add>
<add> $this->assertFalse($context->hasError('1.title'));
<add> $this->assertEquals(['Not long enough'], $context->error('1.body'));
<add> $this->assertTrue($context->hasError('1.body'));
<add> }
<add>
<add>/**
<add> * Test schema operations on a collection of entities.
<add> *
<add> * @dataProvider collectionProvider
<add> * @return void
<add> */
<add> public function testSchemaOnCollections($collection) {
<add> $this->_setupTables();
<add> $context = new EntityContext($this->request, [
<add> 'entity' => $collection,
<add> 'table' => 'Articles',
<add> ]);
<add>
<add> $this->assertEquals('string', $context->type('0.title'));
<add> $this->assertEquals('text', $context->type('1.body'));
<add> $this->assertEquals('string', $context->type('0.user.username'));
<add> $this->assertEquals('string', $context->type('1.user.username'));
<add> $this->assertNull($context->type('0.nope'));
<add>
<add> $expected = ['length' => 255, 'precision' => null];
<add> $this->assertEquals($expected, $context->attributes('0.user.username'));
<add> }
<add>
<add>/**
<add> * Test validation operations on a collection of entities.
<add> *
<add> * @dataProvider collectionProvider
<add> * @return void
<add> */
<add> public function testValidatorsOnCollections($collection) {
<add> $this->_setupTables();
<add>
<add> $context = new EntityContext($this->request, [
<add> 'entity' => $collection,
<add> 'table' => 'Articles',
<add> 'validator' => [
<add> 'Articles' => 'create',
<add> 'Users' => 'custom',
<add> ]
<add> ]);
<add>
<add> $this->assertTrue($context->isRequired('0.title'));
<add> $this->assertFalse($context->isRequired('1.body'));
<add> $this->assertTrue($context->isRequired('0.user.username'));
<add> }
<add>
<ide> /**
<ide> * Test reading data.
<ide> * | 1 |
Text | Text | fix a typo | 8d138eb7fa69ec0ca8d47220d56635d8acea2eba | <ide><path>project/RELEASE-CHECKLIST.md
<ide> We recommend announcing the release candidate on:
<ide> - In a comment on the pull request to notify subscribed people on GitHub
<ide> - The [docker-dev](https://groups.google.com/forum/#!forum/docker-dev) group
<ide> - The [docker-maintainers](https://groups.google.com/a/dockerproject.org/forum/#!forum/maintainers) group
<del>- Any social media that can get bring some attention to the release cabdidate
<add>- Any social media that can bring some attention to the release candidate
<ide>
<ide> ### 7. Iterate on successive release candidates
<ide> | 1 |
PHP | PHP | fix property type | dc0d384752e9508bacd8941509ef18fc70bbf8fd | <ide><path>src/Database/Statement/StatementDecorator.php
<ide> class StatementDecorator implements StatementInterface, Countable, IteratorAggre
<ide> * Statement instance implementation, such as PDOStatement
<ide> * or any other custom implementation.
<ide> *
<del> * @var \Cake\Database\StatementInterface
<add> * @var \PDOStatement
<ide> */
<ide> protected $_statement;
<ide>
<ide><path>src/Database/StatementInterface.php
<ide> /**
<ide> * Represents a database statement. Concrete implementations
<ide> * can either use PDOStatement or a native driver
<del> *
<del> * @property string $queryString
<ide> */
<ide> interface StatementInterface
<ide> { | 2 |
Javascript | Javascript | fix lazy methods on valuesseq | 7fbd8fb6cc850110b43323c3c64bcbec7763eecf | <ide><path>dist/Immutable.js
<ide> var ValuesSequence = function ValuesSequence(seq) {
<ide> this.length = seq.length;
<ide> };
<ide> ($traceurRuntime.createClass)(ValuesSequence, {
<del> get: function(key, notSetValue) {
<del> return this._seq.get(key, notSetValue);
<del> },
<del> has: function(key) {
<del> return this._seq.has(key);
<add> contains: function(value) {
<add> return this._seq.contains(value);
<ide> },
<ide> cacheResult: function() {
<ide> this._seq.cacheResult();
<ide><path>dist/Immutable.min.js
<ide> return V(this,t,!0)},contains:function(t){return this.find(function(e){return Q(
<ide> })&&e.next().done},entrySeq:function(){var t=this;if(t._cache)return nr(t._cache);var e=t.toKeyedSeq().map(x).valueSeq();return e.fromEntries=function(){return t},e},findKey:function(t,e){var r;return this.__iterate(function(n,i,u){return t.call(e,n,i,u)?(r=i,!1):void 0}),r},findLast:function(t,e,r){return this.toKeyedSeq().reverse().find(t,e,r)},findLastKey:function(t,e){return this.toKeyedSeq().reverse().findKey(t,e)},first:function(){return this.find(k)},flatMap:function(t,e){return this.map(t,e).flatten()},flatten:function(){return N(this,!0)},flip:function(){return R(this)},get:function(t,e){return this.find(function(e,r){return Q(r,t)},null,e)},getIn:function(t,e){var r=this;if(t)for(var n=0;t.length>n;n++)if(r=r&&r.get?r.get(t[n],We):We,r===We)return e;return r},groupBy:function(t,e){return K(this,t,e,!0)},has:function(t){return this.get(t,We)!==We},keySeq:function(){return this.flip().valueSeq()},last:function(){return this.findLast(k)},mapEntries:function(t,e){var r=this;return this.entrySeq().map(function(n,i){return t.call(e,n,i,r)}).fromEntrySeq()},mapKeys:function(t,e){var r=this;return this.flip().map(function(n,i){return t.call(e,n,i,r)}).flip()},rest:function(){return this.slice(1)},skip:function(t){return B(this,t,!0)},skipLast:function(t){return this.reverse().skip(t).reverse()},skipWhile:function(t,e){return L(this,t,e,!0)},skipUntil:function(t,e){return this.skipWhile(D(t),e)},sortBy:function(t,e){e=e||O;var r=this;return nr(this.entrySeq().entrySeq().toArray().sort(function(n,i){return e(t(n[1][1],n[1][0],r),t(i[1][1],i[1][0],r))||n[0]-i[0]})).fromEntrySeq().valueSeq().fromEntrySeq()},take:function(t){return z(this,t)},takeLast:function(t){return this.reverse().take(t).reverse()},takeWhile:function(t,e){return J(this,t,e)},takeUntil:function(t,e){return this.takeWhile(D(t),e)},toKeyedSeq:function(){return this},valueSeq:function(){return new _r(this)},cacheResult:function(){return!this._cache&&this.__iterateUncached&&(A(this.length),this._cache=this.entrySeq().toArray(),null==this.length&&(this.length=this._cache.length)),this
<ide> },hashCode:function(){return this.__hash||(this.__hash=1/0===this.length?0:this.reduce(function(t,e,r){return t+(o(e)^(e===r?0:o(r)))&Le},0))},__makeSequence:function(){return Object.create(ir)},__iterate:function(t,e){return E(this,t,e,!0)},__iterator:function(t,e){return j(this,t,e,!0)}},{from:function(t){if(t instanceof nr)return t;if(!Array.isArray(t)){if(p(t))return new or(t);if(g(t))return new hr(t);if(t&&t.constructor===Object)return new cr(t);t=[t]}return new fr(t)}});var ir=rr.prototype;ir[$e]=ir.entries,ir.toJSON=ir.toJS,ir.__toJS=ir.toObject,ir.inspect=ir.toSource=function(){return""+this},ir.chain=ir.flatMap;var ur=function(){Ee.defaultSuperCall(this,ar.prototype,arguments)},ar=ur;Ee.createClass(ur,{toString:function(){return this.__toString("Seq [","]")},concat:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return V(this,t,!1)},filter:function(t,e){return W(this,t,e,!1)},findIndex:function(t,e){var r=this.findKey(t,e);return null==r?-1:r},indexOf:function(t){return this.findIndex(function(e){return Q(e,t)})},lastIndexOf:function(t){return this.toKeyedSeq().reverse().indexOf(t)},splice:function(t,e){var r=arguments.length;if(e=Math.max(0|e,0),0===r||2===r&&!e)return this;t=S(t,this.length);var n=this.slice(0,t);return 1===r?n:n.concat(a(arguments,2),this.slice(t+e))},findLastIndex:function(t,e){return this.toKeyedSeq().reverse().findIndex(t,e)},first:function(){return this.get(0)},flatten:function(){return N(this,!1)},flip:function(){return R(this.toKeyedSeq())},fromEntrySeq:function(){return new vr(this)},get:function(t,e){return t=C(this,t),0>t||1/0===this.length||null!=this.length&&t>this.length?e:this.find(function(e,r){return r===t},null,e)},groupBy:function(t,e){return K(this,t,e,!1)},has:function(t){return t=C(this,t),t>=0&&(null!=this.length?1/0===this.length||this.length>t:-1!==this.indexOf(t))},interpose:function(t){return T(this,t)},last:function(){return this.get(this.length?this.length-1:0)},skip:function(t){var e=this,r=B(e,t,!1);return r!==e&&(r.get=function(r,n){return r=C(this,r),r>=0?e.get(r+t,n):n
<ide> }),r},skipWhile:function(t,e){return L(this,t,e,!1)},sortBy:function(t,e){e=e||O;var r=this;return rr(this.entrySeq().toArray().sort(function(n,i){return e(t(n[1],n[0],r),t(i[1],i[0],r))||n[0]-i[0]})).fromEntrySeq().valueSeq()},take:function(t){var e=this,r=z(e,t);return r!==e&&(r.get=function(r,n){return r=C(this,r),r>=0&&t>r?e.get(r,n):n}),r},toKeyedSeq:function(){return new lr(this)},valueSeq:function(){return this},__makeSequence:function(){return Object.create(sr)},__iterate:function(t,e){return E(this,t,e,!1)},__iterator:function(t,e){return j(this,t,e,!1)}},{},rr);var sr=ur.prototype;sr[$e]=sr.values,sr.__toJS=sr.toArray,sr.__toStringMapper=M;var or=function(t){this._iterator=t,this._iteratorCache=[]};Ee.createClass(or,{__iterateUncached:function(t,e){if(e)return this.cacheResult().__iterate(t,e);for(var r=this._iterator,n=this._iteratorCache,i=0;n.length>i;)if(t(n[i],i++,this)===!1)return i;for(var u;!(u=r.next()).done;){var a=u.value;if(n[i]=a,t(a,i++,this)===!1)break}return i},__iteratorUncached:function(t,e){if(e)return this.cacheResult().__iterator(t,e);var r=this._iterator,n=this._iteratorCache,i=0;return new tr(function(){if(i>=n.length){var e=r.next();if(e.done)return e;n[i]=e.value}return l(t,i,n[i++])})}},{},ur);var hr=function(t){this._iterable=t,this.length=t.length||t.size};Ee.createClass(hr,{__iterateUncached:function(t,e){if(e)return this.cacheResult().__iterate(t,e);var r=this._iterable,n=m(r),i=0;if(p(n))for(var u;!(u=n.next()).done&&t(u.value,i++,this)!==!1;);return i},__iteratorUncached:function(t,e){if(e)return this.cacheResult().__iterator(t,e);var r=this._iterable,n=m(r);if(!p(n))return new tr(function(){return v()});var i=0;return new tr(function(){var e=n.next();return e.done?e:l(t,i++,e.value)})}},{},ur);var cr=function(t){var e=Object.keys(t);this._object=t,this._keys=e,this.length=e.length};Ee.createClass(cr,{toObject:function(){return this._object},get:function(t,e){return void 0===e||this.has(t)?this._object[t]:e},has:function(t){return this._object.hasOwnProperty(t)},__iterate:function(t,e){for(var r=this._object,n=this._keys,i=n.length-1,u=0;i>=u;u++){var a=n[e?i-u:u];
<del>if(t(r[a],a,this)===!1)return u+1}return u},__iterator:function(t,e){var r=this._object,n=this._keys,i=n.length-1,u=0;return new tr(function(){var a=n[e?i-u:u];return u++>i?v():l(t,a,r[a])})}},{},rr);var fr=function(t){this._array=t,this.length=t.length};Ee.createClass(fr,{toArray:function(){return this._array},get:function(t,e){return this.has(t)?this._array[C(this,t)]:e},__iterate:function(t,e){for(var r=this._array,n=r.length-1,i=0;n>=i;i++)if(t(r[e?n-i:i],i,this)===!1)return i+1;return i},__iterator:function(t,e){var r=this._array,n=r.length-1,i=0;return new tr(function(){return i>n?v():l(t,i,r[e?n-i++:i++])})}},{},ur);var _r=function(t){this._seq=t,this.length=t.length};Ee.createClass(_r,{get:function(t,e){return this._seq.get(t,e)},has:function(t){return this._seq.has(t)},cacheResult:function(){return this._seq.cacheResult(),this.length=this._seq.length,this},__iterate:function(t,e){var r=this,n=0;return this._seq.__iterate(function(e){return t(e,n++,r)},e)},__iterator:function(t,e){var r=this._seq.__iterator(Xe,e),n=0;return new tr(function(){var e=r.next();return e.done?e:l(t,n++,e.value,e)})}},{},ur);var lr=function(t){this._seq=t,this.length=t.length};Ee.createClass(lr,{get:function(t,e){return this._seq.get(t,e)},has:function(t){return this._seq.has(t)},valueSeq:function(){return this._seq},reverse:function(){var t=this,e=P(this);return e.valueSeq=function(){return t._seq.reverse()},e},map:function(t,e){var r=this,n=U(this,t,e);return n.valueSeq=function(){return r._seq.map(t,e)},n},cacheResult:function(){return this._seq.cacheResult(),this.length=this._seq.length,this},__iterate:function(t,e){var r=this,n=e?y(this):0;return this._seq.__iterate(function(i){return t(i,e?--n:n++,r)},e)},__iterator:function(t,e){var r=this._seq.__iterator(Xe,e),n=e?y(this):0;return new tr(function(){var i=r.next();return i.done?i:l(t,e?--n:n++,i.value,i)})}},{},rr);var vr=function(t){this._seq=t,this.length=t.length};Ee.createClass(vr,{entrySeq:function(){return this._seq},cacheResult:function(){return this._seq.cacheResult(),this.length=this._seq.length,this
<add>if(t(r[a],a,this)===!1)return u+1}return u},__iterator:function(t,e){var r=this._object,n=this._keys,i=n.length-1,u=0;return new tr(function(){var a=n[e?i-u:u];return u++>i?v():l(t,a,r[a])})}},{},rr);var fr=function(t){this._array=t,this.length=t.length};Ee.createClass(fr,{toArray:function(){return this._array},get:function(t,e){return this.has(t)?this._array[C(this,t)]:e},__iterate:function(t,e){for(var r=this._array,n=r.length-1,i=0;n>=i;i++)if(t(r[e?n-i:i],i,this)===!1)return i+1;return i},__iterator:function(t,e){var r=this._array,n=r.length-1,i=0;return new tr(function(){return i>n?v():l(t,i,r[e?n-i++:i++])})}},{},ur);var _r=function(t){this._seq=t,this.length=t.length};Ee.createClass(_r,{contains:function(t){return this._seq.contains(t)},cacheResult:function(){return this._seq.cacheResult(),this.length=this._seq.length,this},__iterate:function(t,e){var r=this,n=0;return this._seq.__iterate(function(e){return t(e,n++,r)},e)},__iterator:function(t,e){var r=this._seq.__iterator(Xe,e),n=0;return new tr(function(){var e=r.next();return e.done?e:l(t,n++,e.value,e)})}},{},ur);var lr=function(t){this._seq=t,this.length=t.length};Ee.createClass(lr,{get:function(t,e){return this._seq.get(t,e)},has:function(t){return this._seq.has(t)},valueSeq:function(){return this._seq},reverse:function(){var t=this,e=P(this);return e.valueSeq=function(){return t._seq.reverse()},e},map:function(t,e){var r=this,n=U(this,t,e);return n.valueSeq=function(){return r._seq.map(t,e)},n},cacheResult:function(){return this._seq.cacheResult(),this.length=this._seq.length,this},__iterate:function(t,e){var r=this,n=e?y(this):0;return this._seq.__iterate(function(i){return t(i,e?--n:n++,r)},e)},__iterator:function(t,e){var r=this._seq.__iterator(Xe,e),n=e?y(this):0;return new tr(function(){var i=r.next();return i.done?i:l(t,e?--n:n++,i.value,i)})}},{},rr);var vr=function(t){this._seq=t,this.length=t.length};Ee.createClass(vr,{entrySeq:function(){return this._seq},cacheResult:function(){return this._seq.cacheResult(),this.length=this._seq.length,this
<ide> },__iterate:function(t,e){var r=this;return this._seq.__iterate(function(e){return e&&t(e[1],e[0],r)},e)},__iterator:function(t,e){var r=this._seq.__iterator(Xe,e);return new tr(function(){for(;;){var e=r.next();if(e.done)return e;var n=e.value;if(n)return t===Ye?e:l(t,n[0],n[1],e)}})}},{},rr);var gr=function(t,e,r,n){n=n?n:t.getIn(e),this.length=n instanceof rr?n.length:null,this._rootData=t,this._keyPath=e,this._onChange=r};Ee.createClass(gr,{deref:function(t){return this._rootData.getIn(this._keyPath,t)},get:function(t,e){if(Array.isArray(t)&&0===t.length)return this;var r=this._rootData.getIn(this._keyPath.concat(t),We);return r===We?e:F(this,t,r)},set:function(t,e){return H(this,function(r){return r.set(t,e)},t)},remove:function(t){return H(this,function(e){return e.remove(t)},t)},clear:function(){return H(this,function(t){return t.clear()})},update:function(t,e,r){return 1===arguments.length?H(this,t):H(this,function(n){return n.update(t,e,r)},t)},withMutations:function(t){return H(this,function(e){return(e||pr.empty()).withMutations(t)})},cursor:function(t){return Array.isArray(t)&&0===t.length?this:G(this,t)},__iterate:function(t,e){var r=this,n=this.deref();return n&&n.__iterate?n.__iterate(function(e,n){return t(F(r,n,e),n,r)},e):0},__iterator:function(t,e){var r=this,n=this.deref(),i=n&&n.__iterator&&n.__iterator(Ye,e);return new tr(function(){if(!i)return v();var e=i.next();if(e.done)return e;var n=e.value,u=n[0],a=n[1];return l(t,u,F(r,u,a),e)})}},{},rr),gr.prototype[je]=gr.prototype.remove,gr.prototype.getIn=gr.prototype.get;var pr=function(t){var e=mr.empty();return t?t.constructor===mr?t:e.merge(t):e},mr=pr;Ee.createClass(pr,{toString:function(){return this.__toString("Map {","}")},get:function(t,e){return this._root?this._root.get(0,o(t),t,e):e},set:function(t,e){return $(this,t,e)},remove:function(t){return $(this,t,We)},update:function(t,e,r){return 1===arguments.length?this.updateIn([],null,t):this.updateIn([t],e,r)},updateIn:function(t,e,r){var n;return r||(n=[e,r],r=n[0],e=n[1],n),oe(this,t,e,r,0)
<ide> },clear:function(){return 0===this.length?this:this.__ownerID?(this.length=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):mr.empty()},merge:function(){return ue(this,null,arguments)},mergeWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return ue(this,t,e)},mergeDeep:function(){return ue(this,ae(null),arguments)},mergeDeepWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return ue(this,ae(t),e)},cursor:function(t,e){return e||"function"!=typeof t?0===arguments.length?t=[]:Array.isArray(t)||(t=[t]):(e=t,t=[]),new gr(this,t,e)},withMutations:function(t){var e=this.asMutable();return t(e),e.wasAltered()?e.__ensureOwner(this.__ownerID):this},asMutable:function(){return this.__ownerID?this:this.__ensureOwner(new u)},asImmutable:function(){return this.__ensureOwner()},wasAltered:function(){return this.__altered},__iterator:function(t,e){return new Dr(this,t,e)},__iterate:function(t,e){var r=this,n=0;return this._root&&this._root.iterate(function(e){return n++,t(e[1],e[0],r)},e),n},__ensureOwner:function(t){return t===this.__ownerID?this:t?Z(this.length,this._root,t,this.__hash):(this.__ownerID=t,this.__altered=!1,this)}},{empty:function(){return Mr||(Mr=Z(0))}},rr);var dr=pr.prototype;dr[je]=dr.remove,pr.from=pr;var yr=function(t,e,r){this.ownerID=t,this.bitmap=e,this.nodes=r},wr=yr;Ee.createClass(yr,{get:function(t,e,r,n){var i=1<<((0===t?e:e>>>t)&Pe),u=this.bitmap;return 0===(u&i)?n:this.nodes[he(u&i-1)].get(t+Re,e,r,n)},update:function(t,e,r,n,i,u,a){var s=(0===e?r:r>>>e)&Pe,o=1<<s,h=this.bitmap,c=0!==(h&o);if(!c&&i===We)return this;var f=he(h&o-1),_=this.nodes,l=c?_[f]:null,v=te(l,t,e+Re,r,n,i,u,a);if(v===l)return this;if(!c&&v&&_.length>=Or)return ie(t,_,h,s,v);if(c&&!v&&2===_.length&&ee(_[1^f]))return _[1^f];if(c&&v&&1===_.length&&ee(v))return v;var g=t&&t===this.ownerID,p=c?v?h:h^o:h|o,m=c?v?ce(_,f,v,g):_e(_,f,g):fe(_,f,v,g);return g?(this.bitmap=p,this.nodes=m,this):new wr(t,p,m)},iterate:function(t,e){for(var r=this.nodes,n=0,i=r.length-1;i>=n;n++)if(r[e?i-n:n].iterate(t,e)===!1)return!1
<ide> }},{});var Sr=function(t,e,r){this.ownerID=t,this.count=e,this.nodes=r},Ir=Sr;Ee.createClass(Sr,{get:function(t,e,r,n){var i=(0===t?e:e>>>t)&Pe,u=this.nodes[i];return u?u.get(t+Re,e,r,n):n},update:function(t,e,r,n,i,u,a){var s=(0===e?r:r>>>e)&Pe,o=i===We,h=this.nodes,c=h[s];if(o&&!c)return this;var f=te(c,t,e+Re,r,n,i,u,a);if(f===c)return this;var _=this.count;if(c){if(!f&&(_--,Cr>_))return ne(t,h,_,s)}else _++;var l=t&&t===this.ownerID,v=ce(h,s,f,l);return l?(this.count=_,this.nodes=v,this):new Ir(t,_,v)},iterate:function(t,e){for(var r=this.nodes,n=0,i=r.length-1;i>=n;n++){var u=r[e?i-n:n];if(u&&u.iterate(t,e)===!1)return!1}}},{});var br=function(t,e,r){this.ownerID=t,this.hash=e,this.entries=r},qr=br;Ee.createClass(br,{get:function(t,e,r,n){for(var i=this.entries,u=0,a=i.length;a>u;u++)if(Q(r,i[u][0]))return i[u][1];return n},update:function(t,e,r,n,u,s,o){var h=u===We;if(r!==this.hash)return h?this:(i(o),i(s),re(this,t,e,r,[n,u]));for(var c=this.entries,f=0,_=c.length;_>f&&!Q(n,c[f][0]);f++);var l=_>f;if(h&&!l)return this;if(i(o),(h||!l)&&i(s),h&&2===_)return new xr(t,this.hash,c[1^f]);var v=t&&t===this.ownerID,g=v?c:a(c);return l?h?f===_-1?g.pop():g[f]=g.pop():g[f]=[n,u]:g.push([n,u]),v?(this.entries=g,this):new qr(t,this.hash,g)},iterate:function(t,e){for(var r=this.entries,n=0,i=r.length-1;i>=n;n++)if(t(r[e?i-n:n])===!1)return!1}},{});var xr=function(t,e,r){this.ownerID=t,this.hash=e,this.entry=r},kr=xr;Ee.createClass(xr,{get:function(t,e,r,n){return Q(r,this.entry[0])?this.entry[1]:n},update:function(t,e,r,n,u,a,s){var o=u===We,h=Q(n,this.entry[0]);return(h?u===this.entry[1]:o)?this:(i(s),o?(i(a),null):h?t&&t===this.ownerID?(this.entry[1]=u,this):new kr(t,r,[n,u]):(i(a),re(this,t,e,r,[n,u])))},iterate:function(t){return t(this.entry)}},{});var Dr=function(t,e,r){this._type=e,this._reverse=r,this._stack=t._root&&Y(t._root)};Ee.createClass(Dr,{next:function(){for(var t=this._type,e=this._stack;e;){var r,n=e.node,i=e.index++;if(n.entry){if(0===i)return X(t,n.entry)}else if(n.entries){if(r=n.entries.length-1,r>=i)return X(t,n.entries[this._reverse?r-i:i])
<ide><path>src/Sequence.js
<ide> class ValuesSequence extends IndexedSequence {
<ide> this.length = seq.length;
<ide> }
<ide>
<del> get(key, notSetValue) {
<del> return this._seq.get(key, notSetValue);
<del> }
<del>
<del> has(key) {
<del> return this._seq.has(key);
<add> contains(value) {
<add> return this._seq.contains(value);
<ide> }
<ide>
<ide> cacheResult() { | 3 |
Java | Java | fix broken links in javadoc | 93efb20a53365fea87cf3ef422f06959fcf9c313 | <ide><path>spring-context/src/main/java/org/springframework/cache/concurrent/ConcurrentMapCacheManager.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 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> * <p>Note: This is by no means a sophisticated CacheManager; it comes with no
<ide> * cache configuration options. However, it may be useful for testing or simple
<ide> * caching scenarios. For advanced local caching needs, consider
<del> * {@link org.springframework.cache.jcache.JCacheCacheManager},
<del> * {@link org.springframework.cache.ehcache.EhCacheCacheManager},
<add> * {@link org.springframework.cache.jcache.JCacheCacheManager} or
<ide> * {@link org.springframework.cache.caffeine.CaffeineCacheManager}.
<ide> *
<ide> * @author Juergen Hoeller
<ide><path>spring-context/src/main/java/org/springframework/scheduling/SchedulingAwareRunnable.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2021 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> package org.springframework.scheduling;
<ide>
<ide> /**
<del> * Extension of the Runnable interface, adding special callbacks
<add> * Extension of the {@link Runnable} interface, adding special callbacks
<ide> * for long-running operations.
<ide> *
<del> * <p>This interface closely corresponds to the CommonJ Work interface,
<del> * but is kept separate to avoid a required CommonJ dependency.
<del> *
<ide> * <p>Scheduling-capable TaskExecutors are encouraged to check a submitted
<ide> * Runnable, detecting whether this interface is implemented and reacting
<ide> * as appropriately as they are able to.
<ide> *
<ide> * @author Juergen Hoeller
<ide> * @since 2.0
<del> * @see commonj.work.Work
<ide> * @see org.springframework.core.task.TaskExecutor
<ide> * @see SchedulingTaskExecutor
<del> * @see org.springframework.scheduling.commonj.WorkManagerTaskExecutor
<ide> */
<ide> public interface SchedulingAwareRunnable extends Runnable {
<ide>
<ide><path>spring-context/src/main/java/org/springframework/scheduling/SchedulingTaskExecutor.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2021 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> *
<ide> * <p>Note: {@link SchedulingTaskExecutor} implementations are encouraged to also
<ide> * implement the {@link org.springframework.core.task.AsyncListenableTaskExecutor}
<del> * interface. This is not required due to the dependency on Spring 4.0's new
<add> * interface. This is not required due to the dependency on Spring 4.0's
<ide> * {@link org.springframework.util.concurrent.ListenableFuture} interface,
<ide> * which would make it impossible for third-party executor implementations
<ide> * to remain compatible with both Spring 4.0 and Spring 3.x.
<ide> * @since 2.0
<ide> * @see SchedulingAwareRunnable
<ide> * @see org.springframework.core.task.TaskExecutor
<del> * @see org.springframework.scheduling.commonj.WorkManagerTaskExecutor
<ide> */
<ide> public interface SchedulingTaskExecutor extends AsyncTaskExecutor {
<ide>
<ide><path>spring-core/src/main/java/org/springframework/core/ConfigurableObjectInputStream.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.springframework.util.ClassUtils;
<ide>
<ide> /**
<del> * Special ObjectInputStream subclass that resolves class names
<del> * against a specific ClassLoader. Serves as base class for
<del> * {@link org.springframework.remoting.rmi.CodebaseAwareObjectInputStream}.
<add> * Special {@link ObjectInputStream} subclass that resolves class names
<add> * against a specific {@link ClassLoader}.
<ide> *
<ide> * @author Juergen Hoeller
<ide> * @since 2.5.5
<add> * @see org.springframework.core.serializer.DefaultDeserializer
<ide> */
<ide> public class ConfigurableObjectInputStream extends ObjectInputStream {
<ide>
<ide><path>spring-core/src/main/java/org/springframework/core/io/VfsResource.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2021 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> * @author Costin Leau
<ide> * @author Sam Brannen
<ide> * @since 3.0
<del> * @see org.jboss.vfs.VirtualFile
<ide> */
<ide> public class VfsResource extends AbstractResource {
<ide>
<ide><path>spring-core/src/main/java/org/springframework/core/io/VfsUtils.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2021 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> * (package {@code org.jboss.vfs}) and is in particular compatible with
<ide> * JBoss AS 7 and WildFly 8+.
<ide> *
<del> * <p>Thanks go to Marius Bogoevici for the initial patch.
<del> * <b>Note:</b> This is an internal class and should not be used outside the framework.
<add> * <p>Thanks go to Marius Bogoevici for the initial implementation.
<add> *
<add> * <p><b>Note:</b> This is an internal class and should not be used outside the framework.
<ide> *
<ide> * @author Costin Leau
<ide> * @author Juergen Hoeller
<ide><path>spring-core/src/main/java/org/springframework/core/task/SimpleAsyncTaskExecutor.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 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> * @see #setConcurrencyLimit
<ide> * @see SyncTaskExecutor
<ide> * @see org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
<del> * @see org.springframework.scheduling.commonj.WorkManagerTaskExecutor
<ide> */
<ide> @SuppressWarnings("serial")
<ide> public class SimpleAsyncTaskExecutor extends CustomizableThreadCreator
<ide><path>spring-jms/src/main/java/org/springframework/jms/listener/DefaultMessageListenerContainer.java
<ide> * abstraction. By default, the specified number of invoker tasks will be created
<ide> * on startup, according to the {@link #setConcurrentConsumers "concurrentConsumers"}
<ide> * setting. Specify an alternative {@code TaskExecutor} to integrate with an existing
<del> * thread pool facility (such as a Jakarta EE server's), for example using a
<del> * {@link org.springframework.scheduling.commonj.WorkManagerTaskExecutor CommonJ WorkManager}.
<del> * With a native JMS setup, each of those listener threads is going to use a
<del> * cached JMS {@code Session} and {@code MessageConsumer} (only refreshed in case
<del> * of failure), using the JMS provider's resources as efficiently as possible.
<add> * thread pool facility (such as a Jakarta EE server's). With a native JMS setup,
<add> * each of those listener threads is going to use a cached JMS {@code Session} and
<add> * {@code MessageConsumer} (only refreshed in case of failure), using the JMS provider's
<add> * resources as efficiently as possible.
<ide> *
<ide> * <p>Message reception and listener execution can automatically be wrapped
<ide> * in transactions by passing a Spring
<ide> public class DefaultMessageListenerContainer extends AbstractPollingMessageListe
<ide> * will occupy a number of threads for its entire lifetime.
<ide> * @see #setConcurrentConsumers
<ide> * @see org.springframework.core.task.SimpleAsyncTaskExecutor
<del> * @see org.springframework.scheduling.commonj.WorkManagerTaskExecutor
<ide> */
<ide> public void setTaskExecutor(Executor taskExecutor) {
<ide> this.taskExecutor = taskExecutor;
<ide><path>spring-jms/src/main/java/org/springframework/jms/listener/SimpleMessageListenerContainer.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 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 void setConcurrentConsumers(int concurrentConsumers) {
<ide> * {@link jakarta.jms.MessageListener} will work fine, in general.
<ide> * @see #setConcurrentConsumers
<ide> * @see org.springframework.core.task.SimpleAsyncTaskExecutor
<del> * @see org.springframework.scheduling.commonj.WorkManagerTaskExecutor
<ide> */
<ide> public void setTaskExecutor(Executor taskExecutor) {
<ide> this.taskExecutor = taskExecutor;
<ide><path>spring-jms/src/main/java/org/springframework/jms/support/converter/MessageConverter.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2021 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> * @since 1.1
<ide> * @see org.springframework.jms.core.JmsTemplate#setMessageConverter
<ide> * @see org.springframework.jms.listener.adapter.MessageListenerAdapter#setMessageConverter
<del> * @see org.springframework.jms.remoting.JmsInvokerClientInterceptor#setMessageConverter
<del> * @see org.springframework.jms.remoting.JmsInvokerServiceExporter#setMessageConverter
<ide> */
<ide> public interface MessageConverter {
<ide>
<ide><path>spring-tx/src/main/java/org/springframework/jca/endpoint/GenericMessageEndpointManager.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 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> *
<ide> * <pre class="code">
<ide> * <bean class="org.springframework.jca.endpoint.GenericMessageEndpointManager">
<del> * <property name="resourceAdapter" ref="resourceAdapter"/>
<del> * <property name="messageEndpointFactory">
<del> * <bean class="org.springframework.jca.endpoint.GenericMessageEndpointFactory">
<del> * <property name="messageListener" ref="messageListener"/>
<del> * </bean>
<del> * </property>
<del> * <property name="activationSpec">
<del> * <bean class="org.apache.activemq.ra.ActiveMQActivationSpec">
<del> * <property name="destination" value="myQueue"/>
<del> * <property name="destinationType" value="jakarta.jms.Queue"/>
<del> * </bean>
<del> * </property>
<del> * </bean></pre>
<add> * <property name="resourceAdapter" ref="resourceAdapter"/>
<add> * <property name="messageEndpointFactory">
<add> * <bean class="org.springframework.jca.endpoint.GenericMessageEndpointFactory">
<add> * <property name="messageListener" ref="messageListener"/>
<add> * </bean>
<add> * </property>
<add> * <property name="activationSpec">
<add> * <bean class="org.apache.activemq.ra.ActiveMQActivationSpec">
<add> * <property name="destination" value="myQueue"/>
<add> * <property name="destinationType" value="jakarta.jms.Queue"/>
<add> * </bean>
<add> * </property>
<add> * </bean>
<add> * </pre>
<ide> *
<del> * In this example, Spring's own {@link GenericMessageEndpointFactory} is used
<add> * <p>In this example, Spring's own {@link GenericMessageEndpointFactory} is used
<ide> * to point to a standard message listener object that happens to be supported
<ide> * by the specified target ResourceAdapter: in this case, a JMS
<ide> * {@link jakarta.jms.MessageListener} object as supported by the ActiveMQ
<ide> * message broker, defined as a Spring bean:
<ide> *
<ide> * <pre class="code">
<ide> * <bean id="messageListener" class="com.myorg.messaging.myMessageListener">
<del> * ...
<del> * </bean></pre>
<add> * <!-- ... -->
<add> * </bean>
<add> * </pre>
<ide> *
<del> * The target ResourceAdapter may be configured as a local Spring bean as well
<add> * <p>The target ResourceAdapter may be configured as a local Spring bean as well
<ide> * (the typical case) or obtained from JNDI (e.g. on WebLogic). For the
<ide> * example above, a local ResourceAdapter bean could be defined as follows
<ide> * (matching the "resourceAdapter" bean reference above):
<ide> *
<ide> * <pre class="code">
<ide> * <bean id="resourceAdapter" class="org.springframework.jca.support.ResourceAdapterFactoryBean">
<del> * <property name="resourceAdapter">
<del> * <bean class="org.apache.activemq.ra.ActiveMQResourceAdapter">
<del> * <property name="serverUrl" value="tcp://localhost:61616"/>
<del> * </bean>
<del> * </property>
<del> * <property name="workManager">
<del> * <bean class="org.springframework.jca.work.SimpleTaskWorkManager"/>
<del> * </property>
<del> * </bean></pre>
<add> * <property name="resourceAdapter">
<add> * <bean class="org.apache.activemq.ra.ActiveMQResourceAdapter">
<add> * <property name="serverUrl" value="tcp://localhost:61616"/>
<add> * </bean>
<add> * </property>
<add> * <property name="workManager">
<add> * <bean class="..."/>
<add> * </property>
<add> * </bean>
<add> * </pre>
<ide> *
<del> * For a different target resource, the configuration would simply point to a
<add> * <p>For a different target resource, the configuration would simply point to a
<ide> * different ResourceAdapter and a different ActivationSpec object (which are
<ide> * both specific to the resource provider), and possibly a different message
<ide> * listener (e.g. a CCI {@link jakarta.resource.cci.MessageListener} for a
<ide> * resource adapter which is based on the JCA Common Client Interface).
<ide> *
<ide> * <p>The asynchronous execution strategy can be customized through the
<del> * "workManager" property on the ResourceAdapterFactoryBean (as shown above).
<del> * Check out {@link org.springframework.jca.work.SimpleTaskWorkManager}'s
<del> * javadoc for its configuration options; alternatively, any other
<del> * JCA-compliant WorkManager can be used (e.g. Geronimo's).
<add> * "workManager" property on the ResourceAdapterFactoryBean as shown above,
<add> * where {@code <bean class="..."/>} should be replaced with configuration for
<add> * any JCA-compliant {@code WorkManager}.
<ide> *
<ide> * <p>Transactional execution is a responsibility of the concrete message endpoint,
<ide> * as built by the specified MessageEndpointFactory. {@link GenericMessageEndpointFactory}
<ide> *
<ide> * <pre class="code">
<ide> * <bean class="org.springframework.jca.endpoint.GenericMessageEndpointManager">
<del> * <property name="resourceAdapter" ref="resourceAdapter"/>
<del> * <property name="messageEndpointFactory">
<del> * <bean class="org.springframework.jca.endpoint.GenericMessageEndpointFactory">
<del> * <property name="messageListener" ref="messageListener"/>
<del> * <property name="transactionManager" ref="transactionManager"/>
<del> * </bean>
<del> * </property>
<del> * <property name="activationSpec">
<del> * <bean class="org.apache.activemq.ra.ActiveMQActivationSpec">
<del> * <property name="destination" value="myQueue"/>
<del> * <property name="destinationType" value="jakarta.jms.Queue"/>
<del> * </bean>
<del> * </property>
<add> * <property name="resourceAdapter" ref="resourceAdapter"/>
<add> * <property name="messageEndpointFactory">
<add> * <bean class="org.springframework.jca.endpoint.GenericMessageEndpointFactory">
<add> * <property name="messageListener" ref="messageListener"/>
<add> * <property name="transactionManager" ref="transactionManager"/>
<add> * </bean>
<add> * </property>
<add> * <property name="activationSpec">
<add> * <bean class="org.apache.activemq.ra.ActiveMQActivationSpec">
<add> * <property name="destination" value="myQueue"/>
<add> * <property name="destinationType" value="jakarta.jms.Queue"/>
<add> * </bean>
<add> * </property>
<ide> * </bean>
<ide> *
<del> * <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"/></pre>
<add> * <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"/>
<add> * </pre>
<ide> *
<del> * Alternatively, check out your resource provider's ActivationSpec object,
<add> * <p>Alternatively, check out your resource provider's ActivationSpec object,
<ide> * which should support local transactions through a provider-specific config flag,
<ide> * e.g. ActiveMQActivationSpec's "useRAManagedTransaction" bean property.
<ide> *
<ide> * <pre class="code">
<ide> * <bean class="org.springframework.jca.endpoint.GenericMessageEndpointManager">
<del> * <property name="resourceAdapter" ref="resourceAdapter"/>
<del> * <property name="messageEndpointFactory">
<del> * <bean class="org.springframework.jca.endpoint.GenericMessageEndpointFactory">
<del> * <property name="messageListener" ref="messageListener"/>
<del> * </bean>
<del> * </property>
<del> * <property name="activationSpec">
<del> * <bean class="org.apache.activemq.ra.ActiveMQActivationSpec">
<del> * <property name="destination" value="myQueue"/>
<del> * <property name="destinationType" value="jakarta.jms.Queue"/>
<del> * <property name="useRAManagedTransaction" value="true"/>
<del> * </bean>
<del> * </property>
<del> * </bean></pre>
<add> * <property name="resourceAdapter" ref="resourceAdapter"/>
<add> * <property name="messageEndpointFactory">
<add> * <bean class="org.springframework.jca.endpoint.GenericMessageEndpointFactory">
<add> * <property name="messageListener" ref="messageListener"/>
<add> * </bean>
<add> * </property>
<add> * <property name="activationSpec">
<add> * <bean class="org.apache.activemq.ra.ActiveMQActivationSpec">
<add> * <property name="destination" value="myQueue"/>
<add> * <property name="destinationType" value="jakarta.jms.Queue"/>
<add> * <property name="useRAManagedTransaction" value="true"/>
<add> * </bean>
<add> * </property>
<add> * </bean>
<add> * </pre>
<ide> *
<ide> * @author Juergen Hoeller
<ide> * @since 2.5
<ide><path>spring-tx/src/main/java/org/springframework/jca/support/LocalConnectionFactoryBean.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2021 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> * order to make the connector interact with an XA transaction coordinator.
<ide> * Alternatively, simply use the native local transaction facilities of the
<ide> * exposed API (e.g. CCI local transactions), or use a corresponding
<del> * implementation of Spring's PlatformTransactionManager SPI
<del> * (e.g. {@link org.springframework.jca.cci.connection.CciLocalTransactionManager})
<del> * to drive local transactions.
<add> * implementation of Spring's PlatformTransactionManager SPI to drive local
<add> * transactions.
<ide> *
<ide> * @author Juergen Hoeller
<ide> * @since 1.2
<ide> * @see #setManagedConnectionFactory
<ide> * @see #setConnectionManager
<ide> * @see jakarta.resource.cci.ConnectionFactory
<ide> * @see jakarta.resource.cci.Connection#getLocalTransaction
<del> * @see org.springframework.jca.cci.connection.CciLocalTransactionManager
<ide> */
<ide> public class LocalConnectionFactoryBean implements FactoryBean<Object>, InitializingBean {
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperFactoryBean.java
<ide> * <p>Example usage with
<ide> * {@link MappingJackson2HttpMessageConverter}:
<ide> *
<del> * <pre class="code">{@code
<del> * <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<del> * <property name="objectMapper">
<del> * <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
<add> * <pre class="code">
<add> * <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<add> * <property name="objectMapper">
<add> * <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
<ide> * p:autoDetectFields="false"
<ide> * p:autoDetectGettersSetters="false"
<del> * p:annotationIntrospector-ref="jaxbAnnotationIntrospector" />
<del> * </property>
<del> * </bean>
<del> * }</pre>
<add> * p:annotationIntrospector-ref="jaxbAnnotationIntrospector" />
<add> * </property>
<add> * </bean></pre>
<ide> *
<ide> * <p>Example usage with MappingJackson2JsonView:
<ide> *
<del> * <pre class="code">{@code
<del> * <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
<del> * <property name="objectMapper">
<del> * <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
<add> * <pre class="code">
<add> * <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
<add> * <property name="objectMapper">
<add> * <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
<ide> * p:failOnEmptyBeans="false"
<del> * p:indentOutput="true">
<del> * <property name="serializers">
<del> * <array>
<del> * <bean class="org.mycompany.MyCustomSerializer" />
<del> * </array>
<del> * </property>
<del> * </bean>
<del> * </property>
<del> * </bean>
<del> * }</pre>
<add> * p:indentOutput="true">
<add> * <property name="serializers">
<add> * <array>
<add> * <bean class="org.mycompany.MyCustomSerializer" />
<add> * </array>
<add> * </property>
<add> * </bean>
<add> * </property>
<add> * </bean></pre>
<ide> *
<ide> * <p>In case there are no specific setters provided (for some rarely used options),
<ide> * you can still use the more general methods {@link #setFeaturesToEnable} and
<ide> * {@link #setFeaturesToDisable}.
<ide> *
<del> * <pre class="code">{@code
<del> * <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<del> * <property name="featuresToEnable">
<del> * <array>
<del> * <util:constant static-field="com.fasterxml.jackson.databind.SerializationFeature.WRAP_ROOT_VALUE"/>
<del> * <util:constant static-field="com.fasterxml.jackson.databind.SerializationFeature.CLOSE_CLOSEABLE"/>
<del> * </array>
<del> * </property>
<del> * <property name="featuresToDisable">
<del> * <array>
<del> * <util:constant static-field="com.fasterxml.jackson.databind.MapperFeature.USE_ANNOTATIONS"/>
<del> * </array>
<del> * </property>
<del> * </bean>
<del> * }</pre>
<add> * <pre class="code">
<add> * <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<add> * <property name="featuresToEnable">
<add> * <array>
<add> * <util:constant static-field="com.fasterxml.jackson.databind.SerializationFeature.WRAP_ROOT_VALUE"/>
<add> * <util:constant static-field="com.fasterxml.jackson.databind.SerializationFeature.CLOSE_CLOSEABLE"/>
<add> * </array>
<add> * </property>
<add> * <property name="featuresToDisable">
<add> * <array>
<add> * <util:constant static-field="com.fasterxml.jackson.databind.MapperFeature.USE_ANNOTATIONS"/>
<add> * </array>
<add> * </property>
<add> * </bean></pre>
<ide> *
<ide> * <p>It also automatically registers the following well-known modules if they are
<ide> * detected on the classpath:
<ide> * <p>In case you want to configure Jackson's {@link ObjectMapper} with a custom {@link Module},
<ide> * you can register one or more such Modules by class name via {@link #setModulesToInstall}:
<ide> *
<del> * <pre class="code">{@code
<del> * <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<del> * <property name="modulesToInstall" value="myapp.jackson.MySampleModule,myapp.jackson.MyOtherModule"/>
<del> * </bean
<del> * }</pre>
<add> * <pre class="code">
<add> * <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<add> * <property name="modulesToInstall" value="myapp.jackson.MySampleModule,myapp.jackson.MyOtherModule"/>
<add> * </bean></pre>
<ide> *
<ide> * <p>Compatible with Jackson 2.9 to 2.12, as of Spring 5.3.
<ide> *
<ide><path>spring-web/src/main/java/org/springframework/web/HttpRequestHandler.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2021 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> * return value gives a clearer signature to callers other than the
<ide> * DispatcherServlet, indicating that there will never be a view to render.
<ide> *
<del> * <p>As of Spring 2.0, Spring's HTTP-based remote exporters, such as
<del> * {@link org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter}
<del> * and {@link org.springframework.remoting.caucho.HessianServiceExporter},
<del> * implement this interface rather than the more extensive Controller interface,
<del> * for minimal dependencies on Spring-specific web infrastructure.
<del> *
<ide> * <p>Note that HttpRequestHandlers may optionally implement the
<ide> * {@link org.springframework.web.servlet.mvc.LastModified} interface,
<ide> * just like Controllers can, <i>provided that they run within Spring's
<ide> * @see org.springframework.web.servlet.mvc.Controller
<ide> * @see org.springframework.web.servlet.mvc.LastModified
<ide> * @see org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter
<del> * @see org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter
<del> * @see org.springframework.remoting.caucho.HessianServiceExporter
<ide> */
<ide> @FunctionalInterface
<ide> public interface HttpRequestHandler {
<ide><path>spring-web/src/main/java/org/springframework/web/context/support/HttpRequestHandlerServlet.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2021 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> * in Spring's root web application context. The target bean name must match the
<ide> * HttpRequestHandlerServlet servlet-name as defined in {@code web.xml}.
<ide> *
<del> * <p>This can for example be used to expose a single Spring remote exporter,
<del> * such as {@link org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter}
<del> * or {@link org.springframework.remoting.caucho.HessianServiceExporter},
<del> * per HttpRequestHandlerServlet definition. This is a minimal alternative
<del> * to defining remote exporters as beans in a DispatcherServlet context
<del> * (with advanced mapping and interception facilities being available there).
<del> *
<ide> * @author Juergen Hoeller
<ide> * @since 2.0
<ide> * @see org.springframework.web.HttpRequestHandler
<ide><path>spring-web/src/main/java/org/springframework/web/multipart/MultipartFile.java
<ide> public interface MultipartFile extends InputStreamSource {
<ide> * this one one somewhere for reference, if necessary.
<ide> * @return the original filename, or the empty String if no file has been chosen
<ide> * in the multipart form, or {@code null} if not defined or not available
<del> * @see org.apache.commons.fileupload.FileItem#getName()
<del> * @see org.springframework.web.multipart.commons.CommonsMultipartFile#setPreserveFilename
<ide> * @see <a href="https://tools.ietf.org/html/rfc7578#section-4.2">RFC 7578, Section 4.2</a>
<ide> * @see <a href="https://owasp.org/www-community/vulnerabilities/Unrestricted_File_Upload">Unrestricted File Upload</a>
<ide> */
<ide> default Resource getResource() {
<ide> * @throws IOException in case of reading or writing errors
<ide> * @throws IllegalStateException if the file has already been moved
<ide> * in the filesystem and is not available anymore for another transfer
<del> * @see org.apache.commons.fileupload.FileItem#write(File)
<ide> * @see jakarta.servlet.http.Part#write(String)
<ide> */
<ide> void transferTo(File dest) throws IOException, IllegalStateException;
<ide><path>spring-web/src/main/java/org/springframework/web/multipart/MultipartHttpServletRequest.java
<ide> /**
<ide> * Provides additional methods for dealing with multipart content within a
<ide> * servlet request, allowing to access uploaded files.
<del> * Implementations also need to override the standard
<add> *
<add> * <p>Implementations also need to override the standard
<ide> * {@link jakarta.servlet.ServletRequest} methods for parameter access, making
<ide> * multipart parameters available.
<ide> *
<ide><path>spring-web/src/main/java/org/springframework/web/multipart/MultipartResolver.java
<ide> /*
<del> * Copyright 2002-2015 the original author or authors.
<add> * Copyright 2002-2021 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> * Implementations are typically usable both within an application context
<ide> * and standalone.
<ide> *
<del> * <p>There are two concrete implementations included in Spring, as of Spring 3.1:
<add> * <p>Spring provides the following concrete implementation:
<ide> * <ul>
<del> * <li>{@link org.springframework.web.multipart.commons.CommonsMultipartResolver}
<del> * for Apache Commons FileUpload
<ide> * <li>{@link org.springframework.web.multipart.support.StandardServletMultipartResolver}
<ide> * for the Servlet 3.0+ Part API
<ide> * </ul>
<ide> * @since 29.09.2003
<ide> * @see MultipartHttpServletRequest
<ide> * @see MultipartFile
<del> * @see org.springframework.web.multipart.commons.CommonsMultipartResolver
<ide> * @see org.springframework.web.multipart.support.ByteArrayMultipartFileEditor
<ide> * @see org.springframework.web.multipart.support.StringMultipartFileEditor
<ide> * @see org.springframework.web.servlet.DispatcherServlet
<ide><path>spring-web/src/main/java/org/springframework/web/multipart/support/AbstractMultipartHttpServletRequest.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.springframework.web.multipart.MultipartHttpServletRequest;
<ide>
<ide> /**
<del> * Abstract base implementation of the MultipartHttpServletRequest interface.
<del> * Provides management of pre-generated MultipartFile instances.
<add> * Abstract base implementation of the {@link MultipartHttpServletRequest} interface.
<add> * <p>Provides management of pre-generated {@link MultipartFile} instances.
<ide> *
<ide> * @author Juergen Hoeller
<ide> * @author Arjen Poutsma
<ide><path>spring-web/src/main/java/org/springframework/web/multipart/support/DefaultMultipartHttpServletRequest.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2021 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> * {@link org.springframework.web.multipart.MultipartHttpServletRequest}
<ide> * interface. Provides management of pre-generated parameter values.
<ide> *
<del> * <p>Used by {@link org.springframework.web.multipart.commons.CommonsMultipartResolver}.
<del> *
<ide> * @author Trevor D. Cook
<ide> * @author Juergen Hoeller
<ide> * @author Arjen Poutsma
<ide><path>spring-web/src/main/java/org/springframework/web/multipart/support/StandardServletMultipartResolver.java
<ide> *
<ide> * <p>This resolver variant uses your Servlet container's multipart parser as-is,
<ide> * potentially exposing the application to container implementation differences.
<del> * See {@link org.springframework.web.multipart.commons.CommonsMultipartResolver}
<del> * for an alternative implementation using a local Commons FileUpload library
<del> * within the application, providing maximum portability across Servlet containers.
<ide> * Also, see this resolver's configuration option for
<del> * {@link #setStrictServletCompliance strict Servlet compliance}, narrowing the
<add> * {@linkplain #setStrictServletCompliance strict Servlet compliance}, narrowing the
<ide> * applicability of Spring's {@link MultipartHttpServletRequest} to form data only.
<ide> *
<ide> * <p><b>Note:</b> In order to use Servlet 3.0 based multipart parsing,
<ide> *
<ide> * <pre class="code">
<ide> * public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
<del> * // ...
<del> * @Override
<del> * protected void customizeRegistration(ServletRegistration.Dynamic registration) {
<add> * // ...
<add> * @Override
<add> * protected void customizeRegistration(ServletRegistration.Dynamic registration) {
<ide> * // Optionally also set maxFileSize, maxRequestSize, fileSizeThreshold
<ide> * registration.setMultipartConfig(new MultipartConfigElement("/tmp"));
<ide> * }
<del> * }
<del> * </pre>
<add> * }</pre>
<ide> *
<ide> * @author Juergen Hoeller
<ide> * @since 3.1
<ide> * @see #setResolveLazily
<ide> * @see #setStrictServletCompliance
<ide> * @see HttpServletRequest#getParts()
<del> * @see org.springframework.web.multipart.commons.CommonsMultipartResolver
<ide> */
<ide> public class StandardServletMultipartResolver implements MultipartResolver {
<ide>
<ide> public void setResolveLazily(boolean resolveLazily) {
<ide> * switch this flag to "true": Only "multipart/form-data" requests will be
<ide> * wrapped with a {@link MultipartHttpServletRequest} then; other kinds of
<ide> * requests will be left as-is, allowing for custom processing in user code.
<del> * <p>Note that Commons FileUpload and therefore
<del> * {@link org.springframework.web.multipart.commons.CommonsMultipartResolver}
<del> * supports any "multipart/" request type. However, it restricts processing
<del> * to POST requests which standard Servlet multipart parsers might not do.
<ide> * @since 5.3.9
<ide> */
<ide> public void setStrictServletCompliance(boolean strictServletCompliance) {
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/DispatcherServlet.java
<ide> * {@link org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator}.
<ide> *
<ide> * <li>The dispatcher's strategy for resolving multipart requests is determined by a
<del> * {@link org.springframework.web.multipart.MultipartResolver} implementation.
<del> * Implementations for Apache Commons FileUpload and Servlet 3 are included; the typical
<del> * choice is {@link org.springframework.web.multipart.commons.CommonsMultipartResolver}.
<del> * The MultipartResolver bean name is "multipartResolver"; default is none.
<add> * {@link org.springframework.web.multipart.MultipartResolver} implementation. An
<add> * implementation for Servlet 3 is included. The MultipartResolver bean name is
<add> * "multipartResolver"; default is none.
<ide> *
<ide> * <li>Its locale resolution strategy is determined by a {@link LocaleResolver}.
<ide> * Out-of-the-box implementations work via HTTP accept header, cookie, or session.
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/ViewResolversBeanDefinitionParser.java
<ide> import org.springframework.web.servlet.view.script.ScriptTemplateViewResolver;
<ide>
<ide> /**
<del> * Parse the {@code view-resolvers} MVC namespace element and register
<add> * Parses the {@code view-resolvers} MVC namespace element and registers
<ide> * {@link org.springframework.web.servlet.ViewResolver} bean definitions.
<ide> *
<ide> * <p>All registered resolvers are wrapped in a single (composite) ViewResolver
<ide> * <p>When content negotiation is enabled the order property is set to highest priority
<ide> * instead with the ContentNegotiatingViewResolver encapsulating all other registered
<ide> * view resolver instances. That way the resolvers registered through the MVC namespace
<del> * form self-encapsulated resolver chain.
<add> * form a self-encapsulated resolver chain.
<ide> *
<ide> * @author Sivaprasad Valluru
<ide> * @author Sebastien Deleuze
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.1
<del> * @see TilesConfigurerBeanDefinitionParser
<ide> * @see FreeMarkerConfigurerBeanDefinitionParser
<ide> * @see GroovyMarkupConfigurerBeanDefinitionParser
<ide> * @see ScriptTemplateConfigurerBeanDefinitionParser
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/standard/WebSphereRequestUpgradeStrategy.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2021 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> /**
<ide> * WebSphere support for upgrading an {@link HttpServletRequest} during a
<ide> * WebSocket handshake. To modify properties of the underlying
<del> * {@link javax.websocket.server.ServerContainer} you can use
<add> * {@link jakarta.websocket.server.ServerContainer} you can use
<ide> * {@link ServletServerContainerFactoryBean} in XML configuration or, when using
<ide> * Java configuration, access the container instance through the
<ide> * "javax.websocket.server.ServerContainer" ServletContext attribute. | 24 |
Mixed | Javascript | fix unassigned deprecation code | 1261b94a3facbf486c58b8e8b2682f0de8b4d107 | <ide><path>doc/api/deprecations.md
<ide> function for [`util.inspect()`][] is deprecated. Use [`util.inspect.custom`][]
<ide> instead. For backwards compatibility with Node.js prior to version 6.4.0, both
<ide> may be specified.
<ide>
<del><a id="DEP00XX"></a>
<del>### DEP00XX: path.\_makeLong()
<add><a id="DEP0080"></a>
<add>### DEP0080: path.\_makeLong()
<ide>
<ide> Type: Documentation-only
<ide>
<ide><path>lib/path.js
<ide> const posix = {
<ide> posix.win32 = win32.win32 = win32;
<ide> posix.posix = win32.posix = posix;
<ide>
<del>// Legacy internal API, docs-only deprecated: DEP00XX
<add>// Legacy internal API, docs-only deprecated: DEP0080
<ide> win32._makeLong = win32.toNamespacedPath;
<ide> posix._makeLong = posix.toNamespacedPath;
<ide> | 2 |
Javascript | Javascript | relax permissionsandroid enforcement | 8db4de41e41f1983ac71f618fa29ce70e3d09eb5 | <ide><path>Libraries/PermissionsAndroid/NativePermissionsAndroid.js
<ide> export interface Spec extends TurboModule {
<ide> ) => Promise<{[permission: PermissionType]: PermissionStatus}>;
<ide> }
<ide>
<del>export default TurboModuleRegistry.getEnforcing<Spec>('PermissionsAndroid');
<add>export default TurboModuleRegistry.get<Spec>('PermissionsAndroid');
<ide><path>Libraries/PermissionsAndroid/PermissionsAndroid.js
<ide> 'use strict';
<ide>
<ide> import NativeDialogManagerAndroid from '../NativeModules/specs/NativeDialogManagerAndroid';
<del>const NativeModules = require('../BatchedBridge/NativeModules');
<ide> const Platform = require('../Utilities/Platform');
<ide> import NativePermissionsAndroid from './NativePermissionsAndroid';
<ide>
<add>import invariant from 'invariant';
<add>
<ide> import type {
<ide> PermissionStatus,
<ide> PermissionType,
<ide> class PermissionsAndroid {
<ide> return Promise.resolve(false);
<ide> }
<ide>
<add> invariant(
<add> NativePermissionsAndroid,
<add> 'PermissionsAndroid is not installed correctly.',
<add> );
<add>
<ide> return NativePermissionsAndroid.checkPermission(permission);
<ide> }
<ide>
<ide> class PermissionsAndroid {
<ide> );
<ide> return Promise.resolve(false);
<ide> }
<add>
<add> invariant(
<add> NativePermissionsAndroid,
<add> 'PermissionsAndroid is not installed correctly.',
<add> );
<add>
<ide> return NativePermissionsAndroid.checkPermission(permission);
<ide> }
<ide>
<ide> class PermissionsAndroid {
<ide> return Promise.resolve(this.RESULTS.DENIED);
<ide> }
<ide>
<add> invariant(
<add> NativePermissionsAndroid,
<add> 'PermissionsAndroid is not installed correctly.',
<add> );
<add>
<ide> if (rationale) {
<ide> const shouldShowRationale = await NativePermissionsAndroid.shouldShowRequestPermissionRationale(
<ide> permission,
<ide> class PermissionsAndroid {
<ide> return Promise.resolve({});
<ide> }
<ide>
<add> invariant(
<add> NativePermissionsAndroid,
<add> 'PermissionsAndroid is not installed correctly.',
<add> );
<add>
<ide> return NativePermissionsAndroid.requestMultiplePermissions(permissions);
<ide> }
<ide> } | 2 |
PHP | PHP | add space (formatting) | f9615859856204035f0137241602303b498acf88 | <ide><path>src/Database/Dialect/PostgresDialectTrait.php
<ide> protected function _transformFunctionExpression(FunctionExpression $expression)
<ide> ->name('')
<ide> ->type('-')
<ide> ->iterateParts(function ($p) {
<del> if( is_string($p) ) {
<add> if ( is_string($p) ) {
<ide> $p = [ 'value' => [$p => 'literal'], 'type' => null ];
<ide> } else {
<ide> $p['value'] = [$p['value']]; | 1 |
Ruby | Ruby | inline id_key variable | 9b8195b4b03e9ee70bde3072e364826f198d9fb2 | <ide><path>lib/action_cable/server.rb
<ide> def subscribe_channel(data)
<ide> end
<ide>
<ide> def process_message(message)
<del> id_key = message['identifier']
<del>
<del> if @subscriptions[id_key]
<del> @subscriptions[id_key].receive(ActiveSupport::JSON.decode message['data'])
<add> if @subscriptions[message['identifier']]
<add> @subscriptions[message['identifier']].receive(ActiveSupport::JSON.decode message['data'])
<ide> end
<ide> end
<ide>
<ide> def unsubscribe_channel(data)
<del> id_key = data['identifier']
<del> @subscriptions[id_key].unsubscribe
<del> @subscriptions.delete(id_key)
<add> @subscriptions[data['identifier']].unsubscribe
<add> @subscriptions.delete(data['identifier'])
<ide> end
<ide>
<ide> def invalid_request | 1 |
Text | Text | update ios .xcodeproj path | 365cdde1efd580977d2141e971a5e466c7699d05 | <ide><path>docs/Tutorial.md
<ide> After installing these dependencies there are two simple commands to get a React
<ide>
<ide> ## Development
<ide>
<del>For iOS, you can now open this new project (`AwesomeProject/AwesomeProject.xcodeproj`) in Xcode and simply build and run it with `⌘+R`. Doing so will also start a Node server which enables live code reloading. With this you can see your changes by pressing `⌘+R` in the simulator rather than recompiling in Xcode.
<add>For iOS, you can now open this new project (`AwesomeProject/ios/AwesomeProject.xcodeproj`) in Xcode and simply build and run it with `⌘+R`. Doing so will also start a Node server which enables live code reloading. With this you can see your changes by pressing `⌘+R` in the simulator rather than recompiling in Xcode.
<ide>
<ide> For Android, run `react-native run-android` from `AwesomeProject` to install the generated app on your emulator or device, and start the Node server which enables live code reloading. To see your changes you have to open the rage-shake-menu (either shake the device or press the menu button on devices, press F2 or Page Up for emulator, ⌘+M for Genymotion), and then press `Reload JS`.
<ide> | 1 |
Python | Python | fix relative import in top numpy.distutils | ccdfafcf58fdf3dc1d95acc090445e56267bd4ab | <ide><path>numpy/distutils/__init__.py
<add>import sys
<ide>
<del>from __version__ import version as __version__
<add>if sys.version_info[0] < 3:
<add> from __version__ import version as __version__
<add> # Must import local ccompiler ASAP in order to get
<add> # customized CCompiler.spawn effective.
<add> import ccompiler
<add> import unixccompiler
<ide>
<del># Must import local ccompiler ASAP in order to get
<del># customized CCompiler.spawn effective.
<del>import ccompiler
<del>import unixccompiler
<add> from info import __doc__
<add> from npy_pkg_config import *
<ide>
<del>from info import __doc__
<del>from npy_pkg_config import *
<add> try:
<add> import __config__
<add> _INSTALLED = True
<add> except ImportError:
<add> _INSTALLED = False
<add>else:
<add> from numpy.distutils.__version__ import version as __version__
<add> # Must import local ccompiler ASAP in order to get
<add> # customized CCompiler.spawn effective.
<add> import numpy.distutils.ccompiler
<add> import numpy.distutils.unixccompiler
<ide>
<del>try:
<del> import __config__
<del> _INSTALLED = True
<del>except ImportError:
<del> _INSTALLED = False
<add> from numpy.distutils.info import __doc__
<add> from numpy.distutils.npy_pkg_config import *
<add>
<add> try:
<add> import numpy.distutils.__config__
<add> _INSTALLED = True
<add> except ImportError:
<add> _INSTALLED = False
<ide>
<ide> if _INSTALLED:
<ide> from numpy.testing import Tester | 1 |
Python | Python | add the data/ directory as package data | 53d5bd62ee21137f9f4b271dd6b1102258aa4a70 | <ide><path>setup.py
<ide> def setup_package():
<ide> name=about['__title__'],
<ide> zip_safe=False,
<ide> packages=PACKAGES,
<del> package_data={'': ['*.pyx', '*.pxd', '*.txt', '*.tokens']},
<add> package_data={'': ['*.pyx', '*.pxd', '*.txt', '*.tokens', 'data']},
<ide> description=about['__summary__'],
<ide> long_description=readme,
<ide> author=about['__author__'], | 1 |
Go | Go | fix diffs->diff typo in aufs.go | 7a60b9063c109892f60165adb71682988d39d3d8 | <ide><path>daemon/graphdriver/aufs/aufs.go
<ide> aufs driver directory structure
<ide> │ ├── 1
<ide> │ ├── 2
<ide> │ └── 3
<del>├── diffs // Content of the layer
<add>├── diff // Content of the layer
<ide> │ ├── 1 // Contains layers that need to be mounted for the id
<ide> │ ├── 2
<ide> │ └── 3 | 1 |
PHP | PHP | fix missing line breaks | b7415525c8de61ff7261f4a5b45ab128aacb7a66 | <ide><path>lib/Cake/Console/Command/Task/ModelTask.php
<ide> public function fieldValidation($fieldName, $metaData, $primaryKey = 'id') {
<ide> for ($i = 1, $m = $defaultChoice / 2; $i < $m; $i++) {
<ide> $line = sprintf("%2d. %s", $i, $this->_validations[$i]);
<ide> $optionText .= $line . str_repeat(" ", 31 - strlen($line));
<del> $optionText .= sprintf("%2d. %s", $m + $i, $this->_validations[$m + $i]);
<add> $optionText .= sprintf("%2d. %s\n", $m + $i, $this->_validations[$m + $i]);
<ide> }
<ide> $this->out($optionText);
<ide> $this->out(__d('cake_console', "%s - Do not do any validation on this field.", $defaultChoice)); | 1 |
Mixed | Text | remove deprecated `missinghelpererror` proxy | a1ddde15ae0d612ff2973de9cf768ed701b594e8 | <ide><path>actionpack/CHANGELOG.md
<add>* Remove deprecated `AbstractController::Helpers::ClassMethods::MissingHelperError`
<add> in favor of `AbstractController::Helpers::MissingHelperError`.
<add>
<add> *Yves Senn*
<add>
<ide> * Fix `assert_template` not being able to assert that no files were rendered.
<ide>
<ide> *Guo Xiang Tan*
<ide><path>actionpack/lib/abstract_controller/helpers.rb
<ide> def initialize(error, path)
<ide> end
<ide>
<ide> module ClassMethods
<del> MissingHelperError = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('AbstractController::Helpers::ClassMethods::MissingHelperError',
<del> 'AbstractController::Helpers::MissingHelperError')
<del>
<ide> # When a class is inherited, wrap its helper module in a new module.
<ide> # This ensures that the parent class's module can be changed
<ide> # independently of the child class's.
<ide><path>guides/source/4_2_release_notes.md
<ide> Action Pack
<ide>
<ide> Please refer to the [Changelog][action-pack] for detailed changes.
<ide>
<add>### Removals
<add>
<add>* Removed deprecated `AbstractController::Helpers::ClassMethods::MissingHelperError`
<add> in favor of `AbstractController::Helpers::MissingHelperError`.
<add>
<ide> ### Deprecations
<ide>
<ide> * Deprecated support for setting the `:to` option of a router to a symbol or a | 3 |
PHP | PHP | remove all indentation | 917ee514d4bbd4162b6ddb385c643df97dcfa7d3 | <ide><path>src/Illuminate/Mail/resources/views/html/button.blade.php
<ide> <table class="action" align="center" width="100%" cellpadding="0" cellspacing="0" role="presentation">
<del> <tr>
<del> <td align="center">
<del> <table width="100%" border="0" cellpadding="0" cellspacing="0" role="presentation">
<del> <tr>
<del> <td align="center">
<del> <table border="0" cellpadding="0" cellspacing="0" role="presentation">
<del> <tr>
<del> <td>
<del> <a href="{{ $url }}" class="button button-{{ $color ?? 'primary' }}" target="_blank">{{ $slot }}</a>
<del> </td>
<del> </tr>
<del> </table>
<del> </td>
<del> </tr>
<del> </table>
<del> </td>
<del> </tr>
<add><tr>
<add><td align="center">
<add><table width="100%" border="0" cellpadding="0" cellspacing="0" role="presentation">
<add><tr>
<add><td align="center">
<add><table border="0" cellpadding="0" cellspacing="0" role="presentation">
<add><tr>
<add><td>
<add><a href="{{ $url }}" class="button button-{{ $color ?? 'primary' }}" target="_blank">{{ $slot }}</a>
<add></td>
<add></tr>
<add></table>
<add></td>
<add></tr>
<add></table>
<add></td>
<add></tr>
<ide> </table>
<ide><path>src/Illuminate/Mail/resources/views/html/header.blade.php
<ide> <tr>
<del> <td class="header">
<del> <a href="{{ $url }}">
<del> {{ $slot }}
<del> </a>
<del> </td>
<add><td class="header">
<add><a href="{{ $url }}">
<add>{{ $slot }}
<add></a>
<add></td>
<ide> </tr>
<ide><path>src/Illuminate/Mail/resources/views/html/layout.blade.php
<ide> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ide> <html xmlns="http://www.w3.org/1999/xhtml">
<ide> <head>
<del> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<del> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<add><meta name="viewport" content="width=device-width, initial-scale=1.0" />
<add><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<ide> </head>
<ide> <body>
<del> <style>
<del> @media only screen and (max-width: 600px) {
<del> .inner-body {
<del> width: 100% !important;
<del> }
<add><style>
<add>@media only screen and (max-width: 600px) {
<add>.inner-body {
<add>width: 100% !important;
<add>}
<ide>
<del> .footer {
<del> width: 100% !important;
<del> }
<del> }
<add>.footer {
<add>width: 100% !important;
<add>}
<add>}
<ide>
<del> @media only screen and (max-width: 500px) {
<del> .button {
<del> width: 100% !important;
<del> }
<del> }
<del> </style>
<add>@media only screen and (max-width: 500px) {
<add>.button {
<add>width: 100% !important;
<add>}
<add>}
<add></style>
<ide>
<del> <table class="wrapper" width="100%" cellpadding="0" cellspacing="0" role="presentation">
<del> <tr>
<del> <td align="center">
<del> <table class="content" width="100%" cellpadding="0" cellspacing="0" role="presentation">
<del> {{ $header ?? '' }}
<add><table class="wrapper" width="100%" cellpadding="0" cellspacing="0" role="presentation">
<add><tr>
<add><td align="center">
<add><table class="content" width="100%" cellpadding="0" cellspacing="0" role="presentation">
<add>{{ $header ?? '' }}
<ide>
<del> <!-- Email Body -->
<del> <tr>
<del> <td class="body" width="100%" cellpadding="0" cellspacing="0">
<del> <table class="inner-body" align="center" width="570" cellpadding="0" cellspacing="0" role="presentation">
<del> <!-- Body content -->
<del> <tr>
<del> <td class="content-cell">
<del> {{ Illuminate\Mail\Markdown::parse($slot) }}
<add><!-- Email Body -->
<add><tr>
<add><td class="body" width="100%" cellpadding="0" cellspacing="0">
<add><table class="inner-body" align="center" width="570" cellpadding="0" cellspacing="0" role="presentation">
<add><!-- Body content -->
<add><tr>
<add><td class="content-cell">
<add>{{ Illuminate\Mail\Markdown::parse($slot) }}
<ide>
<del> {{ $subcopy ?? '' }}
<del> </td>
<del> </tr>
<del> </table>
<del> </td>
<del> </tr>
<add>{{ $subcopy ?? '' }}
<add></td>
<add></tr>
<add></table>
<add></td>
<add></tr>
<ide>
<del> {{ $footer ?? '' }}
<del> </table>
<del> </td>
<del> </tr>
<del> </table>
<add>{{ $footer ?? '' }}
<add></table>
<add></td>
<add></tr>
<add></table>
<ide> </body>
<ide> </html>
<ide><path>src/Illuminate/Mail/resources/views/html/message.blade.php
<ide> @component('mail::layout')
<del> {{-- Header --}}
<del> @slot('header')
<del> @component('mail::header', ['url' => config('app.url')])
<del> {{ config('app.name') }}
<del> @endcomponent
<del> @endslot
<add>{{-- Header --}}
<add>@slot('header')
<add>@component('mail::header', ['url' => config('app.url')])
<add>{{ config('app.name') }}
<add>@endcomponent
<add>@endslot
<ide>
<del> {{-- Body --}}
<del> {{ $slot }}
<add>{{-- Body --}}
<add>{{ $slot }}
<ide>
<del> {{-- Subcopy --}}
<del> @isset($subcopy)
<del> @slot('subcopy')
<del> @component('mail::subcopy')
<del> {{ $subcopy }}
<del> @endcomponent
<del> @endslot
<del> @endisset
<add>{{-- Subcopy --}}
<add>@isset($subcopy)
<add>@slot('subcopy')
<add>@component('mail::subcopy')
<add>{{ $subcopy }}
<add>@endcomponent
<add>@endslot
<add>@endisset
<ide>
<del> {{-- Footer --}}
<del> @slot('footer')
<del> @component('mail::footer')
<del> © {{ date('Y') }} {{ config('app.name') }}. @lang('All rights reserved.')
<del> @endcomponent
<del> @endslot
<add>{{-- Footer --}}
<add>@slot('footer')
<add>@component('mail::footer')
<add>© {{ date('Y') }} {{ config('app.name') }}. @lang('All rights reserved.')
<add>@endcomponent
<add>@endslot
<ide> @endcomponent
<ide><path>src/Illuminate/Mail/resources/views/html/promotion.blade.php
<ide> <table class="promotion" align="center" width="100%" cellpadding="0" cellspacing="0" role="presentation">
<del> <tr>
<del> <td align="center">
<del> {{ Illuminate\Mail\Markdown::parse($slot) }}
<del> </td>
<del> </tr>
<add><tr>
<add><td align="center">
<add>{{ Illuminate\Mail\Markdown::parse($slot) }}
<add></td>
<add></tr>
<ide> </table> | 5 |
Text | Text | change text to title | c12c467ac960690ac3506d9998f54efb6375d2c4 | <ide><path>docs/tutorials/essentials/part-4-using-data.md
<ide> Redux action objects are required to have a `type` field, which is normally a de
<ide>
<ide> By default, the action creators generated by `createSlice` expect you to pass in one argument, and that value will be put into the action object as `action.payload`. So, we can pass an object containing those fields as the argument to the `postUpdated` action creator.
<ide>
<del>We also know that the reducer is responsible for determing how the state should actually be updated when an action is dispatched. Given that, we should have the reducer find the right post object based on the ID, and specifically update the `text` and `content` fields in that post.
<add>We also know that the reducer is responsible for determing how the state should actually be updated when an action is dispatched. Given that, we should have the reducer find the right post object based on the ID, and specifically update the `title` and `content` fields in that post.
<ide>
<ide> Finally, we'll need to export the action creator function that `createSlice` generated for us, so that the UI can dispatch the new `postUpdated` action when the user saves the post.
<ide> | 1 |
Javascript | Javascript | add optional harmony support to browser transform | e6c93f9246f2801e200864a74aec145410f13803 | <ide><path>vendor/browser-transforms.js
<ide> var headEl;
<ide>
<ide> var buffer = require('buffer');
<ide> var transform = require('jstransform').transform;
<del>var visitors = require('./fbtransform/visitors').transformVisitors;
<add>var visitors = require('./fbtransform/visitors');
<ide> var docblock = require('jstransform/src/docblock');
<ide>
<ide> // The source-map library relies on Object.defineProperty, but IE8 doesn't
<ide> var docblock = require('jstransform/src/docblock');
<ide> // the source map in that case.
<ide> var supportsAccessors = Object.prototype.hasOwnProperty('__defineGetter__');
<ide>
<del>function transformReact(source) {
<del> return transform(visitors.react, source, {
<add>function transformReact(source, options) {
<add> var visitorList;
<add> if (options && options.harmony) {
<add> visitorList = visitors.getAllVisitors();
<add> } else {
<add> visitorList = visitors.transformVisitors.react;
<add> }
<add>
<add> return transform(visitorList, source, {
<ide> sourceMap: supportsAccessors
<ide> });
<ide> }
<ide>
<ide> exports.transform = transformReact;
<ide>
<del>exports.exec = function(code) {
<del> return eval(transformReact(code).code);
<add>exports.exec = function(code, options) {
<add> return eval(transformReact(code, options).code);
<ide> };
<ide>
<ide> var inlineScriptCount = 0; | 1 |
Python | Python | add tests for ner oracle with whitespace | 3c1c0ec18ec702afbe03e24519cdb0c3a513c945 | <ide><path>spacy/tests/parser/test_ner.py
<ide> def test_doc_add_entities_set_ents_iob(en_vocab):
<ide> assert [w.ent_iob_ for w in doc] == ["", "", "", "B"]
<ide> doc.ents = [(doc.vocab.strings["WORD"], 0, 2)]
<ide> assert [w.ent_iob_ for w in doc] == ["B", "I", "", ""]
<add>
<add>
<add>def test_oracle_moves_missing_B(en_vocab):
<add> words = ["B", "52", "Bomber"]
<add> biluo_tags = [None, None, "L-PRODUCT"]
<add>
<add> doc = Doc(en_vocab, words=words)
<add> gold = GoldParse(doc, words=words, entities=biluo_tags)
<add>
<add> moves = BiluoPushDown(en_vocab.strings)
<add> move_types = ("M", "B", "I", "L", "U", "O")
<add> for tag in biluo_tags:
<add> if tag is None:
<add> continue
<add> elif tag == "O":
<add> moves.add_action(move_types.index("O"), "")
<add> else:
<add> action, label = tag.split("-")
<add> moves.add_action(move_types.index("B"), label)
<add> moves.add_action(move_types.index("I"), label)
<add> moves.add_action(move_types.index("L"), label)
<add> moves.add_action(move_types.index("U"), label)
<add> moves.preprocess_gold(gold)
<add> seq = moves.get_oracle_sequence(doc, gold)
<add> print(seq)
<add>
<add>
<add>def test_oracle_moves_whitespace(en_vocab):
<add> words = [
<add> "production",
<add> "\n",
<add> "of",
<add> "Northrop",
<add> "\n",
<add> "Corp.",
<add> "\n",
<add> "'s",
<add> "radar",
<add> ]
<add> biluo_tags = [
<add> "O",
<add> "O",
<add> "O",
<add> "B-ORG",
<add> None,
<add> "I-ORG",
<add> "L-ORG",
<add> "O",
<add> "O",
<add> ]
<add>
<add> doc = Doc(en_vocab, words=words)
<add> gold = GoldParse(doc, words=words, entities=biluo_tags)
<add>
<add> moves = BiluoPushDown(en_vocab.strings)
<add> move_types = ("M", "B", "I", "L", "U", "O")
<add> for tag in biluo_tags:
<add> if tag is None:
<add> continue
<add> elif tag == "O":
<add> moves.add_action(move_types.index("O"), "")
<add> else:
<add> action, label = tag.split("-")
<add> moves.add_action(move_types.index(action), label)
<add> moves.preprocess_gold(gold)
<add> seq = moves.get_oracle_sequence(doc, gold) | 1 |
Javascript | Javascript | implement a bunch of rng tests including k-s test | 0722f4006c2429fa389b745141ba5d0fb86f83f3 | <ide><path>test/math/random-test.js
<ide> var vows = require("vows"),
<ide>
<ide> var suite = vows.describe("d3.random");
<ide>
<add>var STDDEV = 5;
<add>var MEAN = 38;
<add>
<add>
<add>/**
<add> * Testing a random number generator is a bit more complicated than testing
<add> * deterministic code, so we use a different methodology.
<add> *
<add> * If the RNG is correct, each test in this suite will pass with probability
<add> * at least P. The tests have been designed so that P is 98%+. If the tests
<add> * fail consistently, the RNG is broken. The value of P is given above each
<add> * test case.
<add> *
<add> * More on RNG testing here:
<add> * http://www.johndcook.com/Beautiful_Testing_ch10.pdf
<add> *
<add> * @author Daniel Goldbach
<add> */
<ide> suite.addBatch({
<ide> "random": {
<ide> topic: load("math/random").expression("d3.random"),
<ide> "normal": {
<ide> "topic": function(random) {
<del> return random.normal();
<add> return random.normal(MEAN, STDDEV);
<add> },
<add>
<add> // Mean of n normals is within µ ± 3σ/√n with P=99.7%.
<add> "has expected mean" : function(normalRNG) {
<add> var normals = [];
<add> for (var i=0 ; i<2500 ; i++) {
<add> normals.push(normalRNG());
<add> }
<add> assert.inDelta(d3_test_math_random_mean(normals), MEAN, 3 * STDDEV/50);
<ide> },
<del> "returns a number": function(r) {
<del> assert.typeOf(r(), "number");
<del> }
<add>
<add> // Variance of n normals is within σ² ± 3*σ²√(2/(n-1)) with P=99.7%.
<add> "has expected variance" : function(normalRNG) {
<add> var normals = [];
<add> for (var i=0 ; i<2500 ; i++) {
<add> normals.push(normalRNG());
<add> }
<add> var sampleVar = d3_test_math_random_variance(normals);
<add> var radiusAroundMean = 3 * Math.pow(STDDEV, 2) * Math.sqrt(2 / 2499);
<add> assert.inDelta(sampleVar, Math.pow(STDDEV, 2), radiusAroundMean);
<add> },
<add>
<add> "has normal distribution" : KSTest(normalCDF(MEAN, STDDEV))
<ide> },
<ide> "logNormal": {
<ide> "topic": function(random) {
<del> return random.logNormal();
<add> return random.logNormal(MEAN, STDDEV);
<ide> },
<del> "returns a number": function(r) {
<del> assert.typeOf(r(), "number");
<del> }
<add> "has log-normal distribution" : KSTest(logNormalCDF(MEAN, STDDEV))
<ide> },
<ide> "irwinHall": {
<ide> "topic": function(random) {
<ide> return random.irwinHall(10);
<ide> },
<del> "returns a number": function(r) {
<del> assert.typeOf(r(), "number");
<del> }
<add> "has Irwin-Hall distribution" : KSTest(irwinHallCDF(10))
<ide> }
<ide> }
<ide> });
<ide>
<add>/**
<add> * A macro that that takes a RNG and asserts that the values generated by the
<add> * RNG could be generated by a random variable with cumulative distribution
<add> * function `cdf'.
<add> *
<add> * Passes with P≈98%.
<add> */
<add>function KSTest(cdf) {
<add> return function(rng) {
<add> var n = 1000, values = [];
<add> for (var i = 0; i < n; i++) {
<add> values.push(rng());
<add> }
<add> values.sort(function(a, b) { return a - b; });
<add>
<add> K_positive = -Infinity; // Identity of max() function
<add> for (var i = 0; i < n; i++) {
<add> var edf_x = i/n, x = values[i];
<add> console.log(edf_x, cdf(x));
<add> K_positive = Math.max(K_positive, edf_x - cdf(x));
<add> }
<add> K_positive *= Math.sqrt(n);
<add>
<add> // Derivation of this interval is difficult.
<add> // @see K-S test in Knuth's AoCP vol.2
<add> assert.inDelta(K_positive, 0.723255, 0.794145);
<add> }
<add>}
<add>
<add>function normalCDF(mean, stddev) {
<add> // Logistic approximation to normal CDF around N(mean, stddev).
<add> return function(x) {
<add> return 1 / (1 + Math.exp(-0.07056 * Math.pow((x-mean)/stddev, 3) - 1.5976 * (x-mean)/stddev));
<add> }
<add>}
<add>
<add>function logNormalCDF(mean, stddev) {
<add> var normal = normalCDF(1, 1);
<add> return function(x) {
<add> return normal((Math.exp(x) - mean) / stddev);
<add> }
<add>}
<add>
<add>function irwinHallCDF(n) {
<add> var multiplier = 1 / factorial(n);
<add>
<add> // Precompute binom(n, k), k=0..n for efficiency. (<3 closures)
<add> var binoms = [];
<add> for (var k = 0; k <= n; k++) {
<add> binoms.push(binom(n, k));
<add> }
<add>
<add> return function(x) {
<add> var t = 0;
<add> x *= n;
<add> for (var k = 0; k < x; k++) {
<add> t += Math.pow(-1, k % 2) * binoms[k] * Math.pow(x - k, n);
<add> }
<add> return multiplier * t;
<add> }
<add>}
<add>
<add>function factorial(n) {
<add> var t = 1;
<add> for (var i = 2; i <= n; i++) {
<add> t *= i;
<add> }
<add> return t;
<add>}
<add>
<add>function binom(n, k) {
<add> if (k > n) return undefined;
<add> return factorial(n) / (factorial(k) * factorial(n - k));
<add>}
<add>
<add>function d3_test_math_random_mean(arr) {
<add> if (arr.length === 0) {
<add> return 0;
<add> }
<add>
<add> var mean = 0;
<add> for (var i = 0; i < arr.length; i++) {
<add> mean += arr[i];
<add> }
<add> return mean / arr.length;
<add>}
<add>
<add>/**
<add> * Sample variance implementation borrowed from science.js.
<add> */
<add>function d3_test_math_random_variance(x) {
<add> var n = x.length;
<add> if (n < 1) return NaN;
<add> if (n === 1) return 0;
<add> var mean = d3_test_math_random_mean(x),
<add> i = -1,
<add> s = 0;
<add> while (++i < n) {
<add> var v = x[i] - mean;
<add> s += v * v;
<add> }
<add> return s / (n - 1);
<add>};
<ide> suite.export(module); | 1 |
Javascript | Javascript | expose a new prop `transition` for scene renderer | 55c308615ab08c45a4e4c7b274f5ce3b25bb4826 | <ide><path>Libraries/NavigationExperimental/NavigationAnimatedView.js
<ide> 'use strict';
<ide>
<ide> const Animated = require('Animated');
<add>const Easing = require('Easing');
<ide> const NavigationPropTypes = require('NavigationPropTypes');
<ide> const NavigationScenesReducer = require('NavigationScenesReducer');
<ide> const React = require('React');
<ide> import type {
<ide> NavigationParentState,
<ide> NavigationScene,
<ide> NavigationSceneRenderer,
<add> NavigationTransitionConfigurator,
<ide> } from 'NavigationTypeDefinition';
<ide>
<ide> type Props = {
<ide> type Props = {
<ide> onNavigate: NavigationActionCaller,
<ide> renderOverlay: ?NavigationSceneRenderer,
<ide> renderScene: NavigationSceneRenderer,
<add> configureTransition: NavigationTransitionConfigurator,
<ide> style: any,
<ide> };
<ide>
<ide> type State = {
<ide> layout: NavigationLayout,
<ide> position: NavigationAnimatedValue,
<ide> scenes: Array<NavigationScene>,
<add> transition: NavigationAnimatedValue,
<ide> };
<ide>
<ide> const {PropTypes} = React;
<ide>
<add>const DefaultTransitionSpec = {
<add> duration: 250,
<add> easing: Easing.inOut(Easing.ease),
<add>};
<add>
<add>function isSceneNotStale(scene: NavigationScene): boolean {
<add> return !scene.isStale;
<add>}
<add>
<ide> function applyDefaultAnimation(
<ide> position: NavigationAnimatedValue,
<ide> navigationState: NavigationParentState,
<ide> class NavigationAnimatedView
<ide> extends React.Component<any, Props, State> {
<ide>
<ide> _onLayout: (event: any) => void;
<del> _onProgressChange: (data: {value: number}) => void;
<del> _positionListener: any;
<add> _onTransitionEnd: () => void;
<ide>
<ide> props: Props;
<ide> state: State;
<ide>
<ide> static propTypes = {
<ide> applyAnimation: PropTypes.func,
<add> configureTransition: PropTypes.func,
<ide> navigationState: NavigationPropTypes.navigationState.isRequired,
<ide> onNavigate: PropTypes.func.isRequired,
<ide> renderOverlay: PropTypes.func,
<ide> class NavigationAnimatedView
<ide>
<ide> static defaultProps = {
<ide> applyAnimation: applyDefaultAnimation,
<add> configureTransition: () => DefaultTransitionSpec,
<ide> };
<ide>
<ide> constructor(props: Props, context: any) {
<ide> class NavigationAnimatedView
<ide> layout,
<ide> position: new Animated.Value(this.props.navigationState.index),
<ide> scenes: NavigationScenesReducer([], this.props.navigationState),
<add> transition: new Animated.Value(1),
<ide> };
<ide> }
<ide>
<ide> componentWillMount(): void {
<ide> this._onLayout = this._onLayout.bind(this);
<del> this._onProgressChange = this._onProgressChange.bind(this);
<del> }
<del>
<del> componentDidMount(): void {
<del> this._positionListener =
<del> this.state.position.addListener(this._onProgressChange);
<add> this._onTransitionEnd = this._onTransitionEnd.bind(this);
<ide> }
<ide>
<ide> componentWillReceiveProps(nextProps: Props): void {
<del> if (nextProps.navigationState !== this.props.navigationState) {
<del> this.setState({
<del> scenes: NavigationScenesReducer(
<del> this.state.scenes,
<del> nextProps.navigationState,
<del> this.props.navigationState
<del> ),
<del> });
<del> }
<del> }
<del>
<del> componentDidUpdate(lastProps: Props): void {
<del> if (lastProps.navigationState.index !== this.props.navigationState.index) {
<del> this.props.applyAnimation(
<del> this.state.position,
<del> this.props.navigationState,
<del> lastProps.navigationState
<del> );
<del> }
<del> }
<del>
<del> componentWillUnmount(): void {
<del> this.state.position.removeListener(this._positionListener);
<del> }
<add> const nextScenes = NavigationScenesReducer(
<add> this.state.scenes,
<add> nextProps.navigationState,
<add> this.props.navigationState
<add> );
<ide>
<del> _onProgressChange(data: Object): void {
<del> const delta = Math.abs(data.value - this.props.navigationState.index);
<del> if (delta > Number.EPSILON) {
<add> if (nextScenes === this.state.scenes) {
<ide> return;
<ide> }
<ide>
<del> const scenes = this.state.scenes.filter(scene => {
<del> return !scene.isStale;
<add> const {
<add> position,
<add> transition,
<add> } = this.state;
<add>
<add> // update scenes.
<add> this.setState({
<add> scenes: nextScenes,
<ide> });
<ide>
<del> if (scenes.length !== this.state.scenes.length) {
<del> this.setState({ scenes });
<add> // get the transition spec.
<add> const transtionSpec = nextProps.configureTransition();
<add> transition.setValue(0);
<add>
<add> const animations = [
<add> Animated.timing(
<add> transition,
<add> {
<add> ...transtionSpec,
<add> toValue: 1,
<add> },
<add> ),
<add> ];
<add>
<add> if (nextProps.navigationState.index !== this.props.navigationState.index) {
<add> animations.push(
<add> Animated.timing(
<add> position,
<add> {
<add> ...transtionSpec,
<add> toValue: nextProps.navigationState.index,
<add> },
<add> ),
<add> );
<ide> }
<add>
<add> // play the transition.
<add> Animated.parallel(animations).start(this._onTransitionEnd);
<ide> }
<ide>
<ide> render(): ReactElement {
<ide> class NavigationAnimatedView
<ide> const {
<ide> position,
<ide> scenes,
<add> transition,
<ide> } = this.state;
<ide>
<ide> return renderScene({
<ide> class NavigationAnimatedView
<ide> position,
<ide> scene,
<ide> scenes,
<add> transition,
<ide> });
<ide> }
<ide>
<ide> class NavigationAnimatedView
<ide> const {
<ide> position,
<ide> scenes,
<add> transition,
<ide> } = this.state;
<ide>
<ide> return renderOverlay({
<ide> class NavigationAnimatedView
<ide> position,
<ide> scene: scenes[navigationState.index],
<ide> scenes,
<add> transition,
<ide> });
<ide> }
<ide> return null;
<ide> class NavigationAnimatedView
<ide>
<ide> this.setState({ layout });
<ide> }
<add>
<add> _onTransitionEnd(): void {
<add> const scenes = this.state.scenes.filter(isSceneNotStale);
<add> if (scenes.length !== this.state.scenes.length) {
<add> this.setState({ scenes });
<add> }
<add> }
<ide> }
<ide>
<ide> const styles = StyleSheet.create({
<ide><path>Libraries/NavigationExperimental/NavigationPropTypes.js
<ide> const SceneRenderer = {
<ide> position: animatedValue.isRequired,
<ide> scene: scene.isRequired,
<ide> scenes: PropTypes.arrayOf(scene).isRequired,
<add> transition: animatedValue.isRequired,
<ide> };
<ide>
<ide> /* NavigationPanPanHandlers */
<ide> function extractSceneRendererProps(
<ide> position: props.position,
<ide> scene: props.scene,
<ide> scenes: props.scenes,
<add> transition: props.transition,
<ide> };
<ide> }
<ide>
<ide><path>Libraries/NavigationExperimental/NavigationTypeDefinition.js
<ide> export type NavigationLayout = {
<ide> width: NavigationAnimatedValue,
<ide> };
<ide>
<del>export type NavigationPosition = NavigationAnimatedValue;
<del>
<ide> export type NavigationScene = {
<ide> index: number,
<ide> isStale: boolean,
<ide> export type NavigationSceneRendererProps = {
<ide> onNavigate: NavigationActionCaller,
<ide>
<ide> // The progressive index of the containing view's navigation state.
<del> position: NavigationPosition,
<add> position: NavigationAnimatedValue,
<ide>
<ide> // The scene to render.
<ide> scene: NavigationScene,
<ide>
<ide> // All the scenes of the containing view's.
<ide> scenes: Array<NavigationScene>,
<add>
<add> // The value that represents the progress of the transition when navigation
<add> // state changes from one to another. Its numberic value will range from 0
<add> // to 1.
<add> // transition.__getAnimatedValue() < 1 : transtion is happening.
<add> // transition.__getAnimatedValue() == 1 : transtion completes.
<add> transition: NavigationAnimatedValue,
<ide> };
<ide>
<ide> export type NavigationPanPanHandlers = {
<ide> export type NavigationPanPanHandlers = {
<ide> onStartShouldSetResponderCapture: Function,
<ide> };
<ide>
<add>export type NavigationTransitionSpec = {
<add> duration: number,
<add> // An easing function from `Easing`.
<add> easing: () => any,
<add>};
<add>
<ide> // Functions.
<ide>
<ide> export type NavigationActionCaller = Function;
<ide> export type NavigationSceneRenderer = (
<ide> export type NavigationStyleInterpolator = (
<ide> props: NavigationSceneRendererProps,
<ide> ) => Object;
<add>
<add>export type NavigationTransitionConfigurator = () => NavigationTransitionSpec;
<ide><path>Libraries/NavigationExperimental/Reducer/NavigationScenesReducer.js
<ide> function NavigationScenesReducer(
<ide> nextState: NavigationParentState,
<ide> prevState: ?NavigationParentState,
<ide> ): Array<NavigationScene> {
<add> if (prevState === nextState) {
<add> return scenes;
<add> }
<ide>
<ide> const prevScenes = new Map();
<ide> const freshScenes = new Map(); | 4 |
PHP | PHP | use global functino | 0c3d1fabe5a9319131aa4e9d74b27f29e74a50fb | <ide><path>database/factories/UserFactory.php
<ide> class UserFactory extends Factory
<ide> public function definition()
<ide> {
<ide> return [
<del> 'name' => $this->faker->name(),
<del> 'email' => $this->faker->unique()->safeEmail(),
<add> 'name' => fake()->name(),
<add> 'email' => fake()->safeEmail(),
<ide> 'email_verified_at' => now(),
<ide> 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
<ide> 'remember_token' => Str::random(10), | 1 |
Ruby | Ruby | fix syntax warning | affae7d904e1dd91c89f8126358a2d2fbbe49eeb | <ide><path>activerecord/lib/active_record/tasks/database_tasks.rb
<ide> def load_schema_for(*args)
<ide> This method was renamed to `#load_schema` and will be removed in the future.
<ide> Use `#load_schema` instead.
<ide> MSG
<del> load_schema *args
<add> load_schema(*args)
<ide> end
<ide>
<ide> def schema_file(format = ActiveSupport::Base.schema_format) | 1 |
PHP | PHP | handle old signature and trigger warning | d7b5af7db8e16736714cdc0a77d9aab76cd9794a | <ide><path>src/Error/Middleware/ErrorHandlerMiddleware.php
<ide> class ErrorHandlerMiddleware implements MiddlewareInterface
<ide> */
<ide> public function __construct($errorHandler = [])
<ide> {
<add> if (func_num_args() > 1) {
<add> deprecationWarning(
<add> 'The signature of ErrorHandlerMiddleware::__construct() has changed. '
<add> . 'Pass the config array as 1st argument instead.'
<add> );
<add>
<add> $errorHandler = func_get_arg(1);
<add> }
<add>
<ide> if (is_array($errorHandler)) {
<ide> $this->setConfig($errorHandler);
<ide> | 1 |
Text | Text | fix inconsistency for pause and unpause | 082f4919cac55f32674874d96d82a310f6b1522d | <ide><path>docs/reference/commandline/pause.md
<ide> Options:
<ide> --help Print usage
<ide> ```
<ide>
<del>The `docker pause` command suspends all processes in a container. On Linux,
<del>this uses the cgroups freezer. Traditionally, when suspending a process the
<del>`SIGSTOP` signal is used, which is observable by the process being suspended.
<add>The `docker pause` command suspends all processes in the specified containers.
<add>On Linux, this uses the cgroups freezer. Traditionally, when suspending a process
<add>the `SIGSTOP` signal is used, which is observable by the process being suspended.
<ide> With the cgroups freezer the process is unaware, and unable to capture,
<ide> that it is being suspended, and subsequently resumed. On Windows, only Hyper-V
<ide> containers can be paused.
<ide>
<ide> See the
<ide> [cgroups freezer documentation](https://www.kernel.org/doc/Documentation/cgroup-v1/freezer-subsystem.txt)
<ide> for further details.
<add>
<add>## Related information
<add>
<add>* [unpause](unpause.md)
<ide><path>docs/reference/commandline/unpause.md
<ide> Options:
<ide> --help Print usage
<ide> ```
<ide>
<del>The `docker unpause` command un-suspends all processes in a container.
<add>The `docker unpause` command un-suspends all processes in the specified containers.
<ide> On Linux, it does this using the cgroups freezer.
<ide>
<ide> See the
<ide> [cgroups freezer documentation](https://www.kernel.org/doc/Documentation/cgroup-v1/freezer-subsystem.txt)
<ide> for further details.
<add>
<add>## Related information
<add>
<add>* [pause](pause.md)
<ide><path>man/docker-pause.1.md
<ide> % Docker Community
<ide> % JUNE 2014
<ide> # NAME
<del>docker-pause - Pause all processes within a container
<add>docker-pause - Pause all processes within one or more containers
<ide>
<ide> # SYNOPSIS
<ide> **docker pause**
<ide> CONTAINER [CONTAINER...]
<ide>
<ide> # DESCRIPTION
<ide>
<del>The `docker pause` command suspends all processes in a container. On Linux,
<del>this uses the cgroups freezer. Traditionally, when suspending a process the
<del>`SIGSTOP` signal is used, which is observable by the process being suspended.
<add>The `docker pause` command suspends all processes in the specified containers.
<add>On Linux, this uses the cgroups freezer. Traditionally, when suspending a process
<add>the `SIGSTOP` signal is used, which is observable by the process being suspended.
<ide> With the cgroups freezer the process is unaware, and unable to capture,
<ide> that it is being suspended, and subsequently resumed. On Windows, only Hyper-V
<ide> containers can be paused.
<ide> See the [cgroups freezer documentation]
<ide> further details.
<ide>
<ide> # OPTIONS
<del>There are no available options.
<add>**--help**
<add> Print usage statement
<ide>
<ide> # See also
<del>**docker-unpause(1)** to unpause all processes within a container.
<add>**docker-unpause(1)** to unpause all processes within one or more containers.
<ide>
<ide> # HISTORY
<ide> June 2014, updated by Sven Dowideit <SvenDowideit@home.org.au>
<ide><path>man/docker-unpause.1.md
<ide> % Docker Community
<ide> % JUNE 2014
<ide> # NAME
<del>docker-unpause - Unpause all processes within a container
<add>docker-unpause - Unpause all processes within one or more containers
<ide>
<ide> # SYNOPSIS
<ide> **docker unpause**
<ide> CONTAINER [CONTAINER...]
<ide>
<ide> # DESCRIPTION
<ide>
<del>The `docker unpause` command un-suspends all processes in a container.
<add>The `docker unpause` command un-suspends all processes in the specified containers.
<ide> On Linux, it does this using the cgroups freezer.
<ide>
<ide> See the [cgroups freezer documentation]
<ide> (https://www.kernel.org/doc/Documentation/cgroup-v1/freezer-subsystem.txt) for
<ide> further details.
<ide>
<ide> # OPTIONS
<del>There are no available options.
<add>**--help**
<add> Print usage statement
<ide>
<ide> # See also
<del>**docker-pause(1)** to pause all processes within a container.
<add>**docker-pause(1)** to pause all processes within one or more containers.
<ide>
<ide> # HISTORY
<ide> June 2014, updated by Sven Dowideit <SvenDowideit@home.org.au> | 4 |
PHP | PHP | add foreign key reflection to mysql driver | 5268439d59e52530e32adbdbee31504aa0519878 | <ide><path>lib/Cake/Database/Schema/MysqlSchema.php
<ide> public function convertIndexDescription(Table $table, $row) {
<ide> *
<ide> * @return array List of sql, params
<ide> */
<del> public function describeForeignKeySql($table) {
<del> return ['', []];
<add> public function describeForeignKeySql($table, $config) {
<add> $sql = 'SELECT * FROM information_schema.key_column_usage AS kcu
<add> INNER JOIN information_schema.referential_constraints AS rc
<add> ON (kcu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME)
<add> WHERE kcu.TABLE_SCHEMA = ?
<add> AND kcu.TABLE_NAME = ?';
<add> return [$sql, [$config['database'], $table]];
<ide> }
<ide>
<ide> /**
<ide> public function describeForeignKeySql($table) {
<ide> * @return void
<ide> */
<ide> public function convertForeignKey(Table $table, $row) {
<add> $data = [
<add> 'type' => Table::CONSTRAINT_FOREIGN,
<add> 'columns' => [$row['COLUMN_NAME']],
<add> 'references' => [$row['REFERENCED_TABLE_NAME'], $row['REFERENCED_COLUMN_NAME']],
<add> 'update' => $this->_convertOnClause($row['UPDATE_RULE']),
<add> 'delete' => $this->_convertOnClause($row['DELETE_RULE']),
<add> ];
<add> $name = $row['CONSTRAINT_NAME'];
<add> $table->addConstraint($name, $data);
<add> }
<add>
<add>/**
<add> * Convert MySQL on clauses to the abstract ones.
<add> *
<add> * @param string $clause
<add> * @return string|null
<add> */
<add> protected function _convertOnClause($clause) {
<add> if ($clause === 'CASCADE' || $clause === 'RESTRICT') {
<add> return strtolower($clause);
<add> }
<add> if ($clause === 'NO ACTION') {
<add> return Table::ACTION_NO_ACTION;
<add> }
<add> return Table::ACTION_SET_NULL;
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Test/TestCase/Database/Schema/MysqlSchemaTest.php
<ide> public function testConvertColumnType($input, $expected) {
<ide> */
<ide> protected function _createTables($connection) {
<ide> $this->_needsConnection();
<del> $connection->execute('DROP TABLE IF EXISTS articles');
<del> $connection->execute('DROP TABLE IF EXISTS authors');
<add> $connection->execute('DROP TABLE IF EXISTS schema_articles');
<add> $connection->execute('DROP TABLE IF EXISTS schema_authors');
<ide>
<ide> $table = <<<SQL
<del>CREATE TABLE authors (
<add>CREATE TABLE schema_authors (
<ide> id INT(11) PRIMARY KEY AUTO_INCREMENT,
<ide> name VARCHAR(50),
<ide> bio TEXT,
<ide> created DATETIME
<del>)
<add>)ENGINE=InnoDB
<ide> SQL;
<ide> $connection->execute($table);
<ide>
<ide> $table = <<<SQL
<del>CREATE TABLE articles (
<add>CREATE TABLE schema_articles (
<ide> id BIGINT PRIMARY KEY AUTO_INCREMENT,
<ide> title VARCHAR(20) COMMENT 'A title',
<ide> body TEXT,
<ide> protected function _createTables($connection) {
<ide> allow_comments TINYINT(1) DEFAULT 0,
<ide> created DATETIME,
<ide> KEY `author_idx` (`author_id`),
<del>UNIQUE KEY `length_idx` (`title`(4))
<del>) COLLATE=utf8_general_ci
<add>UNIQUE KEY `length_idx` (`title`(4)),
<add>FOREIGN KEY `author_idx` (`author_id`) REFERENCES `schema_authors`(`id`) ON UPDATE CASCADE ON DELETE RESTRICT
<add>) ENGINE=InnoDB COLLATE=utf8_general_ci
<ide> SQL;
<ide> $connection->execute($table);
<ide> }
<ide> public function testListTables() {
<ide>
<ide> $this->assertInternalType('array', $result);
<ide> $this->assertCount(2, $result);
<del> $this->assertEquals('articles', $result[0]);
<del> $this->assertEquals('authors', $result[1]);
<add> $this->assertEquals('schema_articles', $result[0]);
<add> $this->assertEquals('schema_authors', $result[1]);
<ide> }
<ide>
<ide> /**
<ide> public function testDescribeTable() {
<ide> $this->_createTables($connection);
<ide>
<ide> $schema = new SchemaCollection($connection);
<del> $result = $schema->describe('articles');
<add> $result = $schema->describe('schema_articles');
<ide> $this->assertInstanceOf('Cake\Database\Schema\Table', $result);
<ide> $expected = [
<ide> 'id' => [
<ide> public function testDescribeTableIndexes() {
<ide> $this->_createTables($connection);
<ide>
<ide> $schema = new SchemaCollection($connection);
<del> $result = $schema->describe('articles');
<add> $result = $schema->describe('schema_articles');
<ide> $this->assertInstanceOf('Cake\Database\Schema\Table', $result);
<ide>
<del> $this->assertCount(2, $result->constraints());
<add> $this->assertCount(3, $result->constraints());
<ide> $expected = [
<ide> 'primary' => [
<ide> 'type' => 'primary',
<ide> public function testDescribeTableIndexes() {
<ide> 'length' => [
<ide> 'title' => 4,
<ide> ]
<add> ],
<add> 'schema_articles_ibfk_1' => [
<add> 'type' => 'foreign',
<add> 'columns' => ['author_id'],
<add> 'references' => ['schema_authors', 'id'],
<add> 'length' => [],
<add> 'update' => 'cascade',
<add> 'delete' => 'restrict',
<ide> ]
<ide> ];
<ide> $this->assertEquals($expected['primary'], $result->constraint('primary'));
<ide> $this->assertEquals($expected['length_idx'], $result->constraint('length_idx'));
<add> $this->assertEquals($expected['schema_articles_ibfk_1'], $result->constraint('schema_articles_ibfk_1'));
<ide>
<ide> $this->assertCount(1, $result->indexes());
<ide> $expected = [ | 2 |
PHP | PHP | implement the rest of the errortrap behavior | c57ee713509f8d849ea5ddccb1d7aaa2b9b495c4 | <ide><path>src/Error/ErrorRendererInterface.php
<ide> interface ErrorRendererInterface
<ide> * @return string The output to be echoed.
<ide> */
<ide> public function render(PhpError $error): string;
<add>
<add> /**
<add> * Output to the renderers output stream
<add> *
<add> * @param string $out The content to output.
<add> * @return void
<add> */
<add> public function output(string $out): void;
<ide> }
<ide><path>src/Error/ErrorTrap.php
<ide>
<ide> use Cake\Core\InstanceConfigTrait;
<ide> use Cake\Error\ErrorRendererInterface;
<add>use Cake\Error\Renderer\ConsoleRenderer;
<ide> use Cake\Error\Renderer\HtmlRenderer;
<del>use Cake\Error\Renderer\TextRenderer;
<ide> use Closure;
<add>use Exception;
<ide> use InvalidArgumentException;
<ide> use LogicException;
<ide>
<ide> class ErrorTrap
<ide> 'trace' => false,
<ide> ];
<ide>
<add> /**
<add> * @var array<\Closure>
<add> */
<add> protected $callbacks = [];
<add>
<ide> /**
<ide> * @var bool
<ide> */
<ide> protected function chooseErrorRenderer(): string
<ide> return $config;
<ide> }
<ide>
<del> return PHP_SAPI === 'cli' ? TextRenderer::class : HtmlRenderer::class;
<add> return PHP_SAPI === 'cli' ? ConsoleRenderer::class : HtmlRenderer::class;
<ide> }
<ide>
<ide> /**
<ide> protected function chooseErrorRenderer(): string
<ide> */
<ide> public function register(): void
<ide> {
<add> $this->registered = true;
<add>
<add> $level = $this->_config['errorLevel'] ?? -1;
<add> error_reporting($level);
<add> set_error_handler([$this, 'handleError'], $level);
<add> }
<add>
<add> /**
<add> * Handle an error from PHP set_error_handler
<add> *
<add> * Will use the configured renderer to generate output
<add> * and output it.
<add> *
<add> * @param int $code Code of error
<add> * @param string $description Error description
<add> * @param string|null $file File on which error occurred
<add> * @param int|null $line Line that triggered the error
<add> * @return bool True if error was handled
<add> */
<add> public function handleError(
<add> int $code,
<add> string $description,
<add> ?string $file = null,
<add> ?int $line = null
<add> ): bool {
<add> if (!(error_reporting() & $code)) {
<add> return false;
<add> }
<add> $trace = Debugger::trace(['start' => 1, 'format' => 'points']);
<add> $error = new PhpError($code, $description, $file, $line, $trace);
<add>
<add> $renderer = $this->renderer();
<add> $logger = $this->logger();
<add>
<add> try {
<add> // Log first incase rendering or callbacks fail.
<add> $logger->logMessage($error->getLabel(), $error->getMessage());
<add>
<add> foreach ($this->callbacks as $callback) {
<add> $callback($error);
<add> }
<add> $renderer->output($renderer->render($error));
<add> } catch (Exception $e) {
<add> return false;
<add> }
<add>
<add> return true;
<ide> }
<ide>
<ide> /**
<ide> public function setLevel(int $level)
<ide> * When the logger is constructed it will be passed
<ide> * the current options array.
<ide> *
<del> * @param int $level The PHP error reporting value to use.
<add> * @param class-string<\Cake\Error\ErrorLoggerInterface> $class The logging class to use.
<ide> * @return $this
<ide> */
<ide> public function setLogger(string $class)
<ide> public function setLogger(string $class)
<ide> */
<ide> public function addCallback(Closure $closure)
<ide> {
<add> $this->callbacks[] = $closure;
<add>
<ide> return $this;
<ide> }
<ide> }
<ide><path>src/Error/Renderer/ConsoleRenderer.php
<add><?php
<add>declare(strict_types=1);
<add>
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> * @link https://cakephp.org CakePHP(tm) Project
<add> * @since 4.4.0
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Error\Renderer;
<add>
<add>use Cake\Error\ErrorRendererInterface;
<add>use Cake\Error\PhpError;
<add>
<add>/**
<add> * Plain text error rendering with a stack trace.
<add> *
<add> * Writes to STDERR for console environments
<add> */
<add>class ConsoleRenderer implements ErrorRendererInterface
<add>{
<add> /**
<add> * @inheritDoc
<add> */
<add> public function output(string $out): void
<add> {
<add> // Write to stderr which is useful in console environments.
<add> fwrite(STDERR, $out);
<add> }
<add>
<add> /**
<add> * @inheritDoc
<add> */
<add> public function render(PhpError $error): string
<add> {
<add> return sprintf(
<add> "%s: %s :: %s on line %s of %s\nTrace:\n%s",
<add> $error->getLabel(),
<add> $error->getCode(),
<add> $error->getMessage(),
<add> $error->getLine(),
<add> $error->getFile(),
<add> $error->getTraceAsString(),
<add> );
<add> }
<add>}
<ide><path>src/Error/Renderer/HtmlRenderer.php
<ide> */
<ide> class HtmlRenderer implements ErrorRendererInterface
<ide> {
<add> /**
<add> * @inheritDoc
<add> */
<add> public function output(string $out): void
<add> {
<add> // Output to stdout which is the server response.
<add> echo $out;
<add> }
<add>
<ide> /**
<ide> * @inheritDoc
<ide> */
<ide><path>src/Error/Renderer/TextRenderer.php
<ide> /**
<ide> * Plain text error rendering with a stack trace.
<ide> *
<del> * Useful in CLI and log file contexts.
<add> * Useful in CLI environments.
<ide> */
<ide> class TextRenderer implements ErrorRendererInterface
<ide> {
<add> /**
<add> * @inheritDoc
<add> */
<add> public function output(string $out): void
<add> {
<add> echo $out;
<add> }
<add>
<ide> /**
<ide> * @inheritDoc
<ide> */
<ide><path>tests/TestCase/Error/ErrorTrapTest.php
<ide>
<ide> use Cake\Error\ErrorLogger;
<ide> use Cake\Error\ErrorTrap;
<add>use Cake\Error\PhpError;
<ide> use Cake\Error\Renderer\HtmlRenderer;
<add>use Cake\Error\Renderer\TextRenderer;
<add>use Cake\Log\Log;
<ide> use Cake\TestSuite\TestCase;
<ide> use InvalidArgumentException;
<ide> use stdClass;
<ide>
<ide> class ErrorTrapTest extends TestCase
<ide> {
<add> public function setUp(): void
<add> {
<add> parent::setUp();
<add>
<add> Log::drop('test_error');
<add> }
<add>
<ide> public function testSetErrorRendererInvalid()
<ide> {
<ide> $trap = new ErrorTrap();
<ide> public function testSetLogger()
<ide> $trap->setLogger(ErrorLogger::class);
<ide> $this->assertInstanceOf(ErrorLogger::class, $trap->logger());
<ide> }
<add>
<add> public function testRegisterAndRendering()
<add> {
<add> $trap = new ErrorTrap();
<add> $trap->setErrorRenderer(TextRenderer::class);
<add> $trap->register();
<add> ob_start();
<add> trigger_error('Oh no it was bad', E_USER_NOTICE);
<add> $output = ob_get_clean();
<add> restore_error_handler();
<add>
<add> $this->assertStringContainsString('Oh no it was bad', $output);
<add> }
<add>
<add> public function testRegisterAndLogging()
<add> {
<add> Log::setConfig('test_error', [
<add> 'className' => 'Array',
<add> ]);
<add> $trap = new ErrorTrap();
<add> $trap->register();
<add> $trap->setErrorRenderer(TextRenderer::class);
<add>
<add> ob_start();
<add> trigger_error('Oh no it was bad', E_USER_NOTICE);
<add> $output = ob_get_clean();
<add> restore_error_handler();
<add>
<add> $logs = Log::engine('test_error')->read();
<add> $this->assertStringContainsString('Oh no it was bad', $logs[0]);
<add> }
<add>
<add> public function testAddCallback()
<add> {
<add> $trap = new ErrorTrap();
<add> $trap->register();
<add> $trap->setErrorRenderer(TextRenderer::class);
<add> $trap->addCallback(function (PhpError $error) {
<add> $this->assertEquals(E_USER_NOTICE, $error->getCode());
<add> $this->assertStringContainsString('Oh no it was bad', $error->getMessage());
<add> });
<add>
<add> ob_start();
<add> trigger_error('Oh no it was bad', E_USER_NOTICE);
<add> $out = ob_get_clean();
<add> restore_error_handler();
<add> $this->assertNotEmpty($out);
<add> }
<ide> } | 6 |
Javascript | Javascript | remove unnecessary tokenizedbuffer methods | 8be9375508cfdd7614d6b575894ebee350b941b7 | <ide><path>src/tokenized-buffer.js
<ide> class TokenizedBuffer {
<ide> while (this.firstInvalidRow() != null && rowsRemaining > 0) {
<ide> var endRow, filledRegion
<ide> const startRow = this.invalidRows.shift()
<del> const lastRow = this.getLastRow()
<add> const lastRow = this.buffer.getLastRow()
<ide> if (startRow > lastRow) continue
<ide>
<ide> let row = startRow
<ide> class TokenizedBuffer {
<ide>
<ide> if (line === '') {
<ide> let nextRow = bufferRow + 1
<del> const lineCount = this.getLineCount()
<add> const lineCount = this.buffer.getLineCount()
<ide> while (nextRow < lineCount) {
<ide> const nextLine = this.buffer.lineForRow(nextRow)
<ide> if (nextLine !== '') {
<ide> class TokenizedBuffer {
<ide> }
<ide> }
<ide>
<del> // Gets the row number of the last line.
<del> //
<del> // Returns a {Number}.
<del> getLastRow () {
<del> return this.buffer.getLastRow()
<del> }
<del>
<del> getLineCount () {
<del> return this.buffer.getLineCount()
<del> }
<del>
<ide> logLines (start = 0, end = this.buffer.getLastRow()) {
<ide> for (let row = start; row <= end; row++) {
<ide> const line = this.tokenizedLines[row].text | 1 |
Text | Text | add note to avoid requiring config/initializers | f976dec24b497311af7f08c8924dcff34c3f1446 | <ide><path>guides/source/configuring.md
<ide> Some parts of Rails can also be configured externally by supplying environment v
<ide> Using Initializer Files
<ide> -----------------------
<ide>
<del>After loading the framework and any gems in your application, Rails turns to loading initializers. An initializer is any Ruby file stored under `config/initializers` in your application. You can use initializers to hold configuration settings that should be made after all of the frameworks and gems are loaded, such as options to configure settings for these parts.
<del>
<del>NOTE: There is no guarantee that your initializers will run after all the gem initializers, so any initialization code that depends on a given gem having been initialized should go into a `config.after_initialize` block.
<del>
<del>NOTE: You can use subfolders to organize your initializers if you like, because Rails will look into the whole file hierarchy from the initializers folder on down.
<del>
<del>TIP: While Rails supports numbering of initializer file names for load ordering purposes, a better technique is to place any code that needs to load in a specific order within the same file. This reduces file name churn, makes dependencies more explicit, and can help surface new concepts within your application.
<add>After loading the framework and any gems in your application, Rails turns to
<add>loading initializers. An initializer is any Ruby file stored under
<add>`config/initializers` in your application. You can use initializers to hold
<add>configuration settings that should be made after all of the frameworks and gems
<add>are loaded, such as options to configure settings for these parts.
<add>
<add>The files in `config/initializers` (and any subdirectories of
<add>`config/initializers`) are sorted and loaded one by one as part of
<add>the `load_config_initializers` initializer.
<add>
<add>If an initializer has code that relies on code in another initializer, you can
<add>combine them into a single initializer instead. This makes the dependencies more
<add>explicit, and can help surface new concepts within your application. Rails also
<add>supports numbering of initializer file names, but this can lead to file name
<add>churn. Explicitly loading initializers with `require` is not recommended, since
<add>it will cause the initializer to get loaded twice.
<add>
<add>NOTE: There is no guarantee that your initializers will run after all the gem
<add>initializers, so any initialization code that depends on a given gem having been
<add>initialized should go into a `config.after_initialize` block.
<ide>
<ide> Initialization events
<ide> --------------------- | 1 |
Text | Text | add a big fat warning | 459451de8b6760034dd4bf7a782b7875441254a5 | <ide><path>pkg/tarsum/tarsum_spec.md
<ide> This document describes the algorithms used in performing the TarSum checksum
<ide> calculation on filesystem layers, the need for this method over existing
<ide> methods, and the versioning of this calculation.
<ide>
<add>## Warning
<add>
<add>This checksum algorithm is for best-effort comparison of file trees with fuzzy logic.
<add>
<add>This is _not_ a cryptographic attestation, and should not be considered secure.
<ide>
<ide> ## Introduction
<ide> | 1 |
Javascript | Javascript | add missing android dangerous permissions | 4b25a0aaa077caf9c437bcfeef8a226eda5a102e | <ide><path>Libraries/PermissionsAndroid/NativePermissionsAndroid.js
<ide> export type PermissionType =
<ide> | 'android.permission.BLUETOOTH_CONNECT'
<ide> | 'android.permission.BLUETOOTH_SCAN'
<ide> | 'android.permission.BLUETOOTH_ADVERTISE'
<del> | 'android.permission.ACCESS_MEDIA_LOCATION';
<add> | 'android.permission.ACCESS_MEDIA_LOCATION'
<add> | 'android.permission.ACCEPT_HANDOVER'
<add> | 'android.permission.ACTIVITY_RECOGNITION'
<add> | 'android.permission.ANSWER_PHONE_CALLS'
<add> | 'android.permission.READ_PHONE_NUMBERS'
<add> | 'android.permission.UWB_RANGING';
<ide> */
<ide>
<ide> export interface Spec extends TurboModule {
<ide><path>Libraries/PermissionsAndroid/PermissionsAndroid.js
<ide> const PERMISSIONS = Object.freeze({
<ide> BLUETOOTH_SCAN: 'android.permission.BLUETOOTH_SCAN',
<ide> BLUETOOTH_ADVERTISE: 'android.permission.BLUETOOTH_ADVERTISE',
<ide> ACCESS_MEDIA_LOCATION: 'android.permission.ACCESS_MEDIA_LOCATION',
<add> ACCEPT_HANDOVER: 'android.permission.ACCEPT_HANDOVER',
<add> ACTIVITY_RECOGNITION: 'android.permission.ACTIVITY_RECOGNITION',
<add> ANSWER_PHONE_CALLS: 'android.permission.ANSWER_PHONE_CALLS',
<add> READ_PHONE_NUMBERS: 'android.permission.READ_PHONE_NUMBERS',
<add> UWB_RANGING: 'android.permission.UWB_RANGING',
<ide> });
<ide>
<ide> /**
<ide> const PERMISSIONS = Object.freeze({
<ide>
<ide> class PermissionsAndroid {
<ide> PERMISSIONS: {|
<add> ACCEPT_HANDOVER: string,
<ide> ACCESS_BACKGROUND_LOCATION: string,
<ide> ACCESS_COARSE_LOCATION: string,
<ide> ACCESS_FINE_LOCATION: string,
<ide> ACCESS_MEDIA_LOCATION: string,
<add> ACTIVITY_RECOGNITION: string,
<ide> ADD_VOICEMAIL: string,
<add> ANSWER_PHONE_CALLS: string,
<ide> BLUETOOTH_ADVERTISE: string,
<ide> BLUETOOTH_CONNECT: string,
<ide> BLUETOOTH_SCAN: string,
<ide> class PermissionsAndroid {
<ide> READ_CALL_LOG: string,
<ide> READ_CONTACTS: string,
<ide> READ_EXTERNAL_STORAGE: string,
<add> READ_PHONE_NUMBERS: string,
<ide> READ_PHONE_STATE: string,
<ide> READ_SMS: string,
<ide> RECEIVE_MMS: string,
<ide> class PermissionsAndroid {
<ide> RECORD_AUDIO: string,
<ide> SEND_SMS: string,
<ide> USE_SIP: string,
<add> UWB_RANGING: string,
<ide> WRITE_CALENDAR: string,
<ide> WRITE_CALL_LOG: string,
<ide> WRITE_CONTACTS: string, | 2 |
PHP | PHP | fix array types in docblock | c57cd1fcb4ba9cc9ba9907bdffbb05e5493a38d1 | <ide><path>src/Database/Connection.php
<ide> public function getSchemaCollection(): SchemaCollectionInterface
<ide> *
<ide> * @param string $table the table to insert values in
<ide> * @param array $values values to be inserted
<del> * @param array<string, string> $types list of associative array containing the types to be used for casting
<add> * @param array<int|string, string> $types Array containing the types to be used for casting
<ide> * @return \Cake\Database\StatementInterface
<ide> */
<ide> public function insert(string $table, array $values, array $types = []): StatementInterface
<ide> public function insert(string $table, array $values, array $types = []): Stateme
<ide> * @param string $table the table to update rows from
<ide> * @param array $values values to be updated
<ide> * @param array $conditions conditions to be set for update statement
<del> * @param array $types list of associative array containing the types to be used for casting
<add> * @param array<string> $types list of associative array containing the types to be used for casting
<ide> * @return \Cake\Database\StatementInterface
<ide> */
<ide> public function update(string $table, array $values, array $conditions = [], array $types = []): StatementInterface
<ide> public function update(string $table, array $values, array $conditions = [], arr
<ide> *
<ide> * @param string $table the table to delete rows from
<ide> * @param array $conditions conditions to be set for delete statement
<del> * @param array $types list of associative array containing the types to be used for casting
<add> * @param array<string> $types list of associative array containing the types to be used for casting
<ide> * @return \Cake\Database\StatementInterface
<ide> */
<ide> public function delete(string $table, array $conditions = [], array $types = []): StatementInterface
<ide><path>src/Database/Expression/QueryExpression.php
<ide> public function getConjunction(): string
<ide> * be added. When using an array and the key is 'OR' or 'AND' a new expression
<ide> * object will be created with that conjunction and internal array value passed
<ide> * as conditions.
<del> * @param array<string, string> $types Associative array of fields pointing to the type of the
<add> * @param array<int|string, string> $types Associative array of fields pointing to the type of the
<ide> * values that are being passed. Used for correctly binding values to statements.
<ide> * @see \Cake\Database\Query::where() for examples on conditions
<ide> * @return $this
<ide> public function hasNestedExpression(): bool
<ide> * representation is wrapped around an adequate instance or of this class.
<ide> *
<ide> * @param array $conditions list of conditions to be stored in this object
<del> * @param array<string, string> $types list of types associated on fields referenced in $conditions
<add> * @param array<int|string, string> $types list of types associated on fields referenced in $conditions
<ide> * @return void
<ide> */
<ide> protected function _addConditions(array $conditions, array $types): void
<ide><path>src/Database/Query.php
<ide> public function unionAll($query, $overwrite = false)
<ide> * with Query::values().
<ide> *
<ide> * @param array $columns The columns to insert into.
<del> * @param array<string, string> $types A map between columns & their datatypes.
<add> * @param array<int|string, string> $types A map between columns & their datatypes.
<ide> * @return $this
<ide> * @throws \RuntimeException When there are 0 columns.
<ide> */
<ide><path>src/Database/TypeMap.php
<ide> class TypeMap
<ide> {
<ide> /**
<del> * Associative array with the default fields and the related types this query might contain.
<add> * Array with the default fields and the related types this query might contain.
<ide> *
<ide> * Used to avoid repetition when calling multiple functions inside this class that
<ide> * may require a custom type for a specific field.
<ide> *
<del> * @var array<string, string>
<add> * @var array<int|string, string>
<ide> */
<ide> protected $_defaults = [];
<ide>
<ide> /**
<del> * Associative array with the fields and the related types that override defaults this query might contain
<add> * Array with the fields and the related types that override defaults this query might contain
<ide> *
<ide> * Used to avoid repetition when calling multiple functions inside this class that
<ide> * may require a custom type for a specific field.
<ide> *
<del> * @var array<string, string>
<add> * @var array<int|string, string>
<ide> */
<ide> protected $_types = [];
<ide>
<ide> /**
<ide> * Creates an instance with the given defaults
<ide> *
<del> * @param array<string, string> $defaults The defaults to use.
<add> * @param array<int|string, string> $defaults The defaults to use.
<ide> */
<ide> public function __construct(array $defaults = [])
<ide> {
<ide> public function __construct(array $defaults = [])
<ide> * This method will replace all the existing default mappings with the ones provided.
<ide> * To add into the mappings use `addDefaults()`.
<ide> *
<del> * @param array<string, string> $defaults Associative array where keys are field names and values
<add> * @param array<int|string, string> $defaults Array where keys are field names / positions and values
<ide> * are the correspondent type.
<ide> * @return $this
<ide> */
<ide> public function setDefaults(array $defaults)
<ide> /**
<ide> * Returns the currently configured types.
<ide> *
<del> * @return array<string, string>
<add> * @return array<int|string, string>
<ide> */
<ide> public function getDefaults(): array
<ide> {
<ide> public function getDefaults(): array
<ide> *
<ide> * If a key already exists it will not be overwritten.
<ide> *
<del> * @param array<string, string> $types The additional types to add.
<add> * @param array<int|string, string> $types The additional types to add.
<ide> * @return void
<ide> */
<ide> public function addDefaults(array $types): void
<ide> public function addDefaults(array $types): void
<ide> *
<ide> * This method will replace all the existing type maps with the ones provided.
<ide> *
<del> * @param array<string, string> $types Associative array where keys are field names and values
<add> * @param array<int|string, string> $types Array where keys are field names / positions and values
<ide> * are the correspondent type.
<ide> * @return $this
<ide> */
<ide> public function setTypes(array $types)
<ide> /**
<ide> * Gets a map of fields and their associated types for single-use.
<ide> *
<del> * @return array<string, string>
<add> * @return array<int|string, string>
<ide> */
<ide> public function getTypes(): array
<ide> {
<ide> public function type($column): ?string
<ide> /**
<ide> * Returns an array of all types mapped types
<ide> *
<del> * @return array<string, string>
<add> * @return array<int|string, string>
<ide> */
<ide> public function toArray(): array
<ide> {
<ide><path>src/Database/TypeMapTrait.php
<ide> public function getTypeMap(): TypeMap
<ide> * To add a default without overwriting existing ones
<ide> * use `getTypeMap()->addDefaults()`
<ide> *
<del> * @param array<string, string> $types The array of types to set.
<add> * @param array<int|string, string> $types The array of types to set.
<ide> * @return $this
<ide> * @see \Cake\Database\TypeMap::setDefaults()
<ide> */
<ide> public function setDefaultTypes(array $types)
<ide> /**
<ide> * Gets default types of current type map.
<ide> *
<del> * @return array<string, string>
<add> * @return array<int|string, string>
<ide> */
<ide> public function getDefaultTypes(): array
<ide> {
<ide><path>src/ORM/Query.php
<ide> public function delete(?string $table = null)
<ide> * Can be combined with the where() method to create delete queries.
<ide> *
<ide> * @param array $columns The columns to insert into.
<del> * @param array<string, string> $types A map between columns & their datatypes.
<add> * @param array<string> $types A map between columns & their datatypes.
<ide> * @return $this
<ide> */
<ide> public function insert(array $columns, array $types = []) | 6 |
Ruby | Ruby | use full path to du | 89479912ecbfe343a7d002c9b71d2359cc1cbde2 | <ide><path>Library/Homebrew/extend/pathname.rb
<ide> def abv
<ide> out=''
<ide> n=`find #{to_s} -type f | wc -l`.to_i
<ide> out<<"#{n} files, " if n > 1
<del> out<<`du -hd0 #{to_s} | cut -d"\t" -f1`.strip
<add> out<<`/usr/bin/du -hd0 #{to_s} | cut -d"\t" -f1`.strip
<ide> end
<ide>
<ide> # attempts to retrieve the version component of this path, so generally | 1 |
Javascript | Javascript | fix arrayproxy arrangedobject handling - fixes , | ffa4493782813ed92d06ea5ce0bed3c14df5ec5e | <ide><path>packages/ember-runtime/lib/system/array_proxy.js
<ide> require('ember-runtime/system/object');
<ide> @submodule ember-runtime
<ide> */
<ide>
<add>var OUT_OF_RANGE_EXCEPTION = "Index out of range";
<add>var EMPTY = [];
<ide>
<ide> var get = Ember.get, set = Ember.set;
<ide>
<ide> Ember.ArrayProxy = Ember.Object.extend(Ember.MutableArray,
<ide> // No dependencies since Enumerable notifies length of change
<ide> }),
<ide>
<del> replace: function(idx, amt, objects) {
<del> Ember.assert('The content property of '+ this.constructor + ' should be set before modifying it', this.get('content'));
<del> if (get(this, 'content')) this.replaceContent(idx, amt, objects);
<add> _replace: function(idx, amt, objects) {
<add> var content = get(this, 'content');
<add> Ember.assert('The content property of '+ this.constructor + ' should be set before modifying it', content);
<add> if (content) this.replaceContent(idx, amt, objects);
<add> return this;
<add> },
<add>
<add> replace: function() {
<add> if (get(this, 'arrangedContent') === get(this, 'content')) {
<add> this._replace.apply(this, arguments);
<add> } else {
<add> throw new Ember.Error("Using replace on an arranged ArrayProxy is not allowed.");
<add> }
<add> },
<add>
<add> _insertAt: function(idx, object) {
<add> var content = this.get('content');
<add> if (idx > get(this, 'content.length')) throw new Error(OUT_OF_RANGE_EXCEPTION);
<add> this._replace(idx, 0, [object]);
<add> return this;
<add> },
<add>
<add> insertAt: function(idx, object) {
<add> if (get(this, 'arrangedContent') === get(this, 'content')) {
<add> return this._insertAt(idx, object);
<add> } else {
<add> throw new Ember.Error("Using insertAt on an arranged ArrayProxy is not allowed.");
<add> }
<add> },
<add>
<add> removeAt: function(start, len) {
<add> if ('number' === typeof start) {
<add> var content = get(this, 'content'),
<add> arrangedContent = get(this, 'arrangedContent'),
<add> indices = [], i;
<add>
<add> if ((start < 0) || (start >= get(this, 'length'))) {
<add> throw new Error(OUT_OF_RANGE_EXCEPTION);
<add> }
<add>
<add> if (len === undefined) len = 1;
<add>
<add> // Get a list of indices in original content to remove
<add> for (i=start; i<start+len; i++) {
<add> // Use arrangedContent here so we avoid confusion with objects transformed by objectAtContent
<add> indices.push(content.indexOf(arrangedContent.objectAt(i)));
<add> }
<add>
<add> // Replace in reverse order since indices will change
<add> indices.sort(function(a,b) { return b - a; });
<add>
<add> Ember.beginPropertyChanges();
<add> for (i=0; i<indices.length; i++) {
<add> this._replace(indices[i], 1, EMPTY);
<add> }
<add> Ember.endPropertyChanges();
<add> }
<add>
<add> return this ;
<add> },
<add>
<add> pushObject: function(obj) {
<add> this._insertAt(get(this, 'content.length'), obj) ;
<add> return obj ;
<add> },
<add>
<add> pushObjects: function(objects) {
<add> this._replace(get(this, 'length'), 0, objects);
<ide> return this;
<ide> },
<ide>
<add> setObjects: function(objects) {
<add> if (objects.length === 0) return this.clear();
<add>
<add> var len = get(this, 'length');
<add> this._replace(0, len, objects);
<add> return this;
<add> },
<add>
<add> unshiftObject: function(obj) {
<add> this._insertAt(0, obj) ;
<add> return obj ;
<add> },
<add>
<add> unshiftObjects: function(objects) {
<add> this._replace(0, 0, objects);
<add> return this;
<add> },
<add>
<add> slice: function() {
<add> var arr = this.toArray();
<add> return arr.slice.apply(arr, arguments);
<add> },
<add>
<ide> arrangedContentArrayWillChange: function(item, idx, removedCnt, addedCnt) {
<ide> this.arrayContentWillChange(idx, removedCnt, addedCnt);
<ide> },
<ide><path>packages/ember-runtime/tests/system/array_proxy/arranged_content_test.js
<add>var array;
<add>
<add>module("Ember.ArrayProxy - arrangedContent", {
<add> setup: function() {
<add> Ember.run(function() {
<add> array = Ember.ArrayProxy.createWithMixins({
<add> content: Ember.A([1,2,4,5]),
<add> arrangedContent: Ember.computed(function() {
<add> var content = this.get('content');
<add> return content && Ember.A(content.slice().sort(function(a,b) {
<add> if (a == null) { a = -1; }
<add> if (b == null) { b = -1; }
<add> return b - a;
<add> }));
<add> }).property('content.[]')
<add> });
<add> });
<add> },
<add> teardown: function() {
<add> Ember.run(function() {
<add> array.destroy();
<add> });
<add> }
<add>});
<add>
<add>test("addObject - adds to end of 'content' if not present", function() {
<add> Ember.run(function() { array.addObject(3); });
<add> deepEqual(array.get('content'), [1,2,4,5,3], 'adds to end of content');
<add> deepEqual(array.get('arrangedContent'), [5,4,3,2,1], 'arrangedContent stays sorted');
<add>
<add> Ember.run(function() { array.addObject(1); });
<add> deepEqual(array.get('content'), [1,2,4,5,3], 'does not add existing number to content');
<add>});
<add>
<add>test("addObjects - adds to end of 'content' if not present", function() {
<add> Ember.run(function() { array.addObjects([1,3,6]); });
<add> deepEqual(array.get('content'), [1,2,4,5,3,6], 'adds to end of content');
<add> deepEqual(array.get('arrangedContent'), [6,5,4,3,2,1], 'arrangedContent stays sorted');
<add>});
<add>
<add>test("compact - returns arrangedContent without nulls", function() {
<add> Ember.run(function() { array.set('content', Ember.A([1,3,null,2])); });
<add> deepEqual(array.compact(), [3,2,1]);
<add>});
<add>
<add>test("indexOf - returns index of object in arrangedContent", function() {
<add> equal(array.indexOf(4), 1, 'returns arranged index');
<add>});
<add>
<add>test("insertAt - raises, indeterminate behavior", function() {
<add> raises(function() {
<add> Ember.run(function() { array.insertAt(2,3); });
<add> });
<add>});
<add>
<add>test("lastIndexOf - returns last index of object in arrangedContent", function() {
<add> Ember.run(function() { array.pushObject(4); });
<add> equal(array.lastIndexOf(4), 2, 'returns last arranged index');
<add>});
<add>
<add>test("nextObject - returns object at index in arrangedContent", function() {
<add> equal(array.nextObject(1), 4, 'returns object at index');
<add>});
<add>
<add>test("objectAt - returns object at index in arrangedContent", function() {
<add> equal(array.objectAt(1), 4, 'returns object at index');
<add>});
<add>
<add>// Not sure if we need a specific test for it, since it's internal
<add>test("objectAtContent - returns object at index in arrangedContent", function() {
<add> equal(array.objectAtContent(1), 4, 'returns object at index');
<add>});
<add>
<add>test("objectsAt - returns objects at indices in arrangedContent", function() {
<add> deepEqual(array.objectsAt([0,2,4]), [5,2,undefined], 'returns objects at indices');
<add>});
<add>
<add>test("popObject - removes last object in arrangedContent", function() {
<add> var popped;
<add> Ember.run(function() { popped = array.popObject(); });
<add> equal(popped, 1, 'returns last object');
<add> deepEqual(array.get('content'), [2,4,5], 'removes from content');
<add>});
<add>
<add>test("pushObject - adds to end of content even if it already exists", function() {
<add> Ember.run(function() { array.pushObject(1); });
<add> deepEqual(array.get('content'), [1,2,4,5,1], 'adds to end of content');
<add>});
<add>
<add>test("pushObjects - adds multiple to end of content even if it already exists", function() {
<add> Ember.run(function() { array.pushObjects([1,2,4]); });
<add> deepEqual(array.get('content'), [1,2,4,5,1,2,4], 'adds to end of content');
<add>});
<add>
<add>test("removeAt - removes from index in arrangedContent", function() {
<add> Ember.run(function() { array.removeAt(1,2); });
<add> deepEqual(array.get('content'), [1,5]);
<add>});
<add>
<add>test("removeObject - removes object from content", function() {
<add> Ember.run(function() { array.removeObject(2); });
<add> deepEqual(array.get('content'), [1,4,5]);
<add>});
<add>
<add>test("removeObjects - removes objects from content", function() {
<add> Ember.run(function() { array.removeObjects([2,4,6]); });
<add> deepEqual(array.get('content'), [1,5]);
<add>});
<add>
<add>test("replace - raises, indeterminate behavior", function() {
<add> raises(function() {
<add> Ember.run(function() { array.replace(1, 2, [3]); });
<add> });
<add>});
<add>
<add>test("replaceContent - does a standard array replace on content", function() {
<add> Ember.run(function() { array.replaceContent(1, 2, [3]); });
<add> deepEqual(array.get('content'), [1,3,5]);
<add>});
<add>
<add>test("reverseObjects - raises, use Sortable#sortAscending", function() {
<add> raises(function() {
<add> Ember.run(function() { array.reverseObjects(); });
<add> });
<add>});
<add>
<add>test("setObjects - replaces entire content", function() {
<add> Ember.run(function() { array.setObjects([6,7,8]); });
<add> deepEqual(array.get('content'), [6,7,8], 'replaces content');
<add>});
<add>
<add>test("shiftObject - removes from start of arrangedContent", function() {
<add> var shifted;
<add> Ember.run(function() { shifted = array.shiftObject(); });
<add> equal(shifted, 5, 'returns first object');
<add> deepEqual(array.get('content'), [1,2,4], 'removes object from content');
<add>});
<add>
<add>test("slice - returns a slice of the arrangedContent", function() {
<add> deepEqual(array.slice(1,3), [4,2], 'returns sliced arrangedContent');
<add>});
<add>
<add>test("toArray - returns copy of arrangedContent", function() {
<add> deepEqual(array.toArray(), [5,4,2,1]);
<add>});
<add>
<add>test("unshiftObject - adds to start of content", function() {
<add> Ember.run(function(){ array.unshiftObject(6); });
<add> deepEqual(array.get('content'), [6,1,2,4,5], 'adds to start of content');
<add>});
<add>
<add>test("unshiftObjects - adds to start of content", function() {
<add> Ember.run(function(){ array.unshiftObjects([6,7]); });
<add> deepEqual(array.get('content'), [6,7,1,2,4,5], 'adds to start of content');
<add>});
<add>
<add>test("without - returns arrangedContent without object", function() {
<add> deepEqual(array.without(2), [5,4,1], 'returns arranged without object');
<add>});
<add>
<add>test("lastObject - returns last arranged object", function() {
<add> equal(array.get('lastObject'), 1, 'returns last arranged object');
<add>});
<add>
<add>test("firstObject - returns first arranged object", function() {
<add> equal(array.get('firstObject'), 5, 'returns first arranged object');
<add>});
<add>
<add>
<add>module("Ember.ArrayProxy - arrangedContent matching content", {
<add> setup: function() {
<add> Ember.run(function() {
<add> array = Ember.ArrayProxy.createWithMixins({
<add> content: Ember.A([1,2,4,5])
<add> });
<add> });
<add> },
<add> teardown: function() {
<add> Ember.run(function() {
<add> array.destroy();
<add> });
<add> }
<add>});
<add>
<add>test("insertAt - inserts object at specified index", function() {
<add> Ember.run(function() { array.insertAt(2, 3); });
<add> deepEqual(array.get('content'), [1,2,3,4,5]);
<add>});
<add>
<add>test("replace - does a standard array replace", function() {
<add> Ember.run(function() { array.replace(1, 2, [3]); });
<add> deepEqual(array.get('content'), [1,3,5]);
<add>});
<add>
<add>test("reverseObjects - reverses content", function() {
<add> Ember.run(function() { array.reverseObjects(); });
<add> deepEqual(array.get('content'), [5,4,2,1]);
<add>});
<add>
<add>module("Ember.ArrayProxy - arrangedContent with transforms", {
<add> setup: function() {
<add> Ember.run(function() {
<add> array = Ember.ArrayProxy.createWithMixins({
<add> content: Ember.A([1,2,4,5]),
<add>
<add> arrangedContent: Ember.computed(function() {
<add> var content = this.get('content');
<add> return content && Ember.A(content.slice().sort(function(a,b) {
<add> if (a == null) { a = -1; }
<add> if (b == null) { b = -1; }
<add> return b - a;
<add> }));
<add> }).property('content.[]'),
<add>
<add> objectAtContent: function(idx) {
<add> var obj = this.get('arrangedContent').objectAt(idx);
<add> return obj && obj.toString();
<add> }
<add> });
<add> });
<add> },
<add> teardown: function() {
<add> Ember.run(function() {
<add> array.destroy();
<add> });
<add> }
<add>});
<add>
<add>test("indexOf - returns index of object in arrangedContent", function() {
<add> equal(array.indexOf('4'), 1, 'returns arranged index');
<add>});
<add>
<add>test("lastIndexOf - returns last index of object in arrangedContent", function() {
<add> Ember.run(function() { array.pushObject(4); });
<add> equal(array.lastIndexOf('4'), 2, 'returns last arranged index');
<add>});
<add>
<add>test("nextObject - returns object at index in arrangedContent", function() {
<add> equal(array.nextObject(1), '4', 'returns object at index');
<add>});
<add>
<add>test("objectAt - returns object at index in arrangedContent", function() {
<add> equal(array.objectAt(1), '4', 'returns object at index');
<add>});
<add>
<add>// Not sure if we need a specific test for it, since it's internal
<add>test("objectAtContent - returns object at index in arrangedContent", function() {
<add> equal(array.objectAtContent(1), '4', 'returns object at index');
<add>});
<add>
<add>test("objectsAt - returns objects at indices in arrangedContent", function() {
<add> deepEqual(array.objectsAt([0,2,4]), ['5','2',undefined], 'returns objects at indices');
<add>});
<add>
<add>test("popObject - removes last object in arrangedContent", function() {
<add> var popped;
<add> Ember.run(function() { popped = array.popObject(); });
<add> equal(popped, '1', 'returns last object');
<add> deepEqual(array.get('content'), [2,4,5], 'removes from content');
<add>});
<add>
<add>test("removeObject - removes object from content", function() {
<add> Ember.run(function() { array.removeObject('2'); });
<add> deepEqual(array.get('content'), [1,4,5]);
<add>});
<add>
<add>test("removeObjects - removes objects from content", function() {
<add> Ember.run(function() { array.removeObjects(['2','4','6']); });
<add> deepEqual(array.get('content'), [1,5]);
<add>});
<add>
<add>test("shiftObject - removes from start of arrangedContent", function() {
<add> var shifted;
<add> Ember.run(function() { shifted = array.shiftObject(); });
<add> equal(shifted, '5', 'returns first object');
<add> deepEqual(array.get('content'), [1,2,4], 'removes object from content');
<add>});
<add>
<add>test("slice - returns a slice of the arrangedContent", function() {
<add> deepEqual(array.slice(1,3), ['4','2'], 'returns sliced arrangedContent');
<add>});
<add>
<add>test("toArray - returns copy of arrangedContent", function() {
<add> deepEqual(array.toArray(), ['5','4','2','1']);
<add>});
<add>
<add>test("without - returns arrangedContent without object", function() {
<add> deepEqual(array.without('2'), ['5','4','1'], 'returns arranged without object');
<add>});
<add>
<add>test("lastObject - returns last arranged object", function() {
<add> equal(array.get('lastObject'), '1', 'returns last arranged object');
<add>});
<add>
<add>test("firstObject - returns first arranged object", function() {
<add> equal(array.get('firstObject'), '5', 'returns first arranged object');
<add>});
<ide>\ No newline at end of file | 2 |
Ruby | Ruby | remove unused returning value `stream` | 51b017652a4725f51e6ee01737f52ff63d5b8424 | <ide><path>activerecord/lib/active_record/schema_dumper.rb
<ide> def table(table, stream)
<ide> stream.puts "# #{e.message}"
<ide> stream.puts
<ide> end
<del>
<del> stream
<ide> end
<ide>
<ide> # Keep it for indexing materialized views | 1 |
Text | Text | add example code for process.getgroups() | f59d4e05a209173406465a26330465413264a443 | <ide><path>doc/api/process.md
<ide> The `process.getgroups()` method returns an array with the supplementary group
<ide> IDs. POSIX leaves it unspecified if the effective group ID is included but
<ide> Node.js ensures it always is.
<ide>
<add>```js
<add>if (process.getgroups) {
<add> console.log(process.getgroups()); // [ 16, 21, 297 ]
<add>}
<add>```
<add>
<ide> This function is only available on POSIX platforms (i.e. not Windows or
<ide> Android).
<ide> | 1 |
Ruby | Ruby | remove support for rails server rails_env=env-name | dce0afd47f334f61a4ab22acccef7c5e9d6e8b0a | <ide><path>railties/lib/rails/commands/server.rb
<ide> def parse!(args)
<ide>
<ide> opt_parser.parse! args
<ide>
<del> # Handle's environment like RAILS_ENV=production passed in directly
<del> if index = args.index {|arg| arg.include?("RAILS_ENV")}
<del> options[:environment] ||= args.delete_at(index).split('=').last
<del> end
<del>
<ide> options[:server] = args.shift
<ide> options
<ide> end
<ide><path>railties/test/commands/server_test.rb
<ide> class Rails::ServerTest < ActiveSupport::TestCase
<ide>
<ide> def test_environment_with_server_option
<del> args = ["thin", "RAILS_ENV=production"]
<add> args = ["thin", "-e", "production"]
<ide> options = Rails::Server::Options.new.parse!(args)
<ide> assert_equal 'production', options[:environment]
<ide> assert_equal 'thin', options[:server]
<ide> end
<ide>
<ide> def test_environment_without_server_option
<del> args = ["RAILS_ENV=production"]
<add> args = ["-e", "production"]
<ide> options = Rails::Server::Options.new.parse!(args)
<ide> assert_equal 'production', options[:environment]
<ide> assert_nil options[:server] | 2 |
Java | Java | add factory methods to testsubscriber | 76f001bc1211e126aa5ad18bc0acb4fd37cd929e | <ide><path>src/main/java/rx/observers/TestSubscriber.java
<ide> public TestSubscriber() {
<ide> this(-1);
<ide> }
<ide>
<add> @Experimental
<add> public static <T> TestSubscriber<T> create() {
<add> return new TestSubscriber<T>();
<add> }
<add>
<add> @Experimental
<add> public static <T> TestSubscriber<T> create(long initialRequest) {
<add> return new TestSubscriber<T>(initialRequest);
<add> }
<add>
<add> @Experimental
<add> public static <T> TestSubscriber<T> create(Observer<T> delegate, long initialRequest) {
<add> return new TestSubscriber<T>(delegate, initialRequest);
<add> }
<add>
<add> @Experimental
<add> public static <T> TestSubscriber<T> create(Subscriber<T> delegate) {
<add> return new TestSubscriber<T>(delegate);
<add> }
<add>
<add> @Experimental
<add> public static <T> TestSubscriber<T> create(Observer<T> delegate) {
<add> return new TestSubscriber<T>(delegate);
<add> }
<add>
<ide> @Override
<ide> public void onStart() {
<ide> if (initialRequest >= 0) {
<ide><path>src/test/java/rx/internal/operators/OnSubscribeRangeTest.java
<ide> public void testRangeWithOverflow5() {
<ide> @Test
<ide> public void testBackpressureViaRequest() {
<ide> OnSubscribeRange o = new OnSubscribeRange(1, RxRingBuffer.SIZE);
<del> TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
<add> TestSubscriber<Integer> ts = TestSubscriber.create();
<ide> ts.assertReceivedOnNext(Collections.<Integer> emptyList());
<ide> ts.requestMore(1);
<ide> o.call(ts);
<ide> public void testNoBackpressure() {
<ide> }
<ide>
<ide> OnSubscribeRange o = new OnSubscribeRange(1, list.size());
<del> TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
<add> TestSubscriber<Integer> ts = TestSubscriber.create();
<ide> ts.assertReceivedOnNext(Collections.<Integer> emptyList());
<ide> ts.requestMore(Long.MAX_VALUE); // infinite
<ide> o.call(ts);
<ide> public void testNoBackpressure() {
<ide> void testWithBackpressureOneByOne(int start) {
<ide> Observable<Integer> source = Observable.range(start, 100);
<ide>
<del> TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
<add> TestSubscriber<Integer> ts = TestSubscriber.create();
<ide> ts.requestMore(1);
<ide> source.subscribe(ts);
<ide>
<ide> void testWithBackpressureOneByOne(int start) {
<ide> void testWithBackpressureAllAtOnce(int start) {
<ide> Observable<Integer> source = Observable.range(start, 100);
<ide>
<del> TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
<add> TestSubscriber<Integer> ts = TestSubscriber.create();
<ide> ts.requestMore(100);
<ide> source.subscribe(ts);
<ide>
<ide> public void testWithBackpressureAllAtOnce() {
<ide> public void testWithBackpressureRequestWayMore() {
<ide> Observable<Integer> source = Observable.range(50, 100);
<ide>
<del> TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
<add> TestSubscriber<Integer> ts = TestSubscriber.create();
<ide> ts.requestMore(150);
<ide> source.subscribe(ts);
<ide> | 2 |
Python | Python | improve docs for consistency as markdown format | adaed1f84a0d980a660eb7d5ff271408374e5bef | <ide><path>examples/lstm_stateful.py
<ide> def gen_uniform_amp(amp=1, xn=10000):
<ide> -amp and +amp
<ide> and of length xn
<ide>
<del> Arguments:
<add> # Arguments
<ide> amp: maximum/minimum range of uniform data
<ide> xn: length of series
<ide> """
<ide><path>keras/activations.py
<ide> def hard_sigmoid(x):
<ide> def exponential(x):
<ide> """Exponential (base e) activation function.
<ide>
<del> # Arguments:
<add> # Arguments
<ide> x: Input tensor.
<ide>
<ide> # Returns
<ide><path>keras/engine/network.py
<ide> def from_config(cls, config, custom_objects=None):
<ide> def add_unprocessed_node(layer, node_data):
<ide> """Add node to layer list
<ide>
<del> Args:
<add> # Arguments
<ide> layer: layer object
<ide> node_data: Node data specifying layer call
<ide> """
<ide> def add_unprocessed_node(layer, node_data):
<ide> def process_node(layer, node_data):
<ide> """Reconstruct node by linking to inbound layers
<ide>
<del> Args:
<add> # Arguments
<ide> layer: Layer to process
<ide> node_data: List of layer configs
<ide>
<del> Raises:
<add> # Raises
<ide> ValueError: For incorrect layer config
<ide> LookupError: If layer required is not found
<ide> """
<ide><path>keras/engine/training_utils.py
<ide> def is_sequence(seq):
<ide> def should_run_validation(validation_freq, epoch):
<ide> """Checks if validation should be run this epoch.
<ide>
<del> Arguments:
<del> validation_freq: Integer or list. If an integer, specifies how many training
<del> epochs to run before a new validation run is performed. If a list,
<del> specifies the epochs on which to run validation.
<del> epoch: Integer, the number of the training epoch just completed.
<del>
<del> Returns:
<del> Bool, True if validation should be run.
<del>
<del> Raises:
<del> ValueError: if `validation_freq` is an Integer and less than 1, or if
<del> it is neither an Integer nor a Sequence.
<add> # Arguments
<add> validation_freq: Integer or list. If an integer, specifies how many training
<add> epochs to run before a new validation run is performed. If a list,
<add> specifies the epochs on which to run validation.
<add> epoch: Integer, the number of the training epoch just completed.
<add>
<add> # Returns
<add> Bool, True if validation should be run.
<add>
<add> # Raises
<add> ValueError: if `validation_freq` is an Integer and less than 1, or if
<add> it is neither an Integer nor a Sequence.
<ide> """
<ide> # `epoch` is 0-indexed internally but 1-indexed in the public API.
<ide> one_indexed_epoch = epoch + 1
<ide><path>keras/utils/test_utils.py
<ide> class tf_file_io_proxy(object):
<ide> recommended to use method `get_filepath(filename)` in tests to make them
<ide> pass with and without a real GCS bucket during testing. See example below.
<ide>
<del> Arguments:
<add> # Arguments
<ide> file_io_module: String identifier of the file_io module import to patch. E.g
<ide> 'keras.engine.saving.tf_file_io'
<ide> bucket_name: String identifier of *a real* GCS bucket (with or without the
<ide> 'gs://' prefix). A bucket name provided with argument precedes what is
<ide> specified using the GCS_TEST_BUCKET environment variable.
<ide>
<del> Example:
<add> # Example
<ide> ```python
<ide> model = Sequential()
<ide> model.add(Dense(2, input_shape=(3,)))
<ide><path>keras/utils/vis_utils.py
<ide> def plot_model(model,
<ide> expand_nested: whether to expand nested models into clusters.
<ide> dpi: dot DPI.
<ide>
<del> # Returns:
<add> # Returns
<ide> A Jupyter notebook Image object if Jupyter is installed.
<ide> This enables in-line display of the model plots in notebooks.
<ide> """ | 6 |
Python | Python | rename the call to the function too! | b298bce746abdebbaa81e21383a3202656662607 | <ide><path>keras/engine/training.py
<ide> def predict(self,
<ide> 'information of where went wrong, or file a '
<ide> 'issue/bug to `tf.keras`.')
<ide> callbacks.on_predict_end()
<del> all_outputs = tf.__internal__.nest.map_structure_up_to(batch_outputs, potentially_variable_concat, outputs)
<add> all_outputs = tf.__internal__.nest.map_structure_up_to(batch_outputs, potentially_ragged_concat, outputs)
<ide>
<ide> # If originally PSS strategy was used, then replace it back since predict
<ide> # is running under `OneDeviceStrategy` after the swap and once its done | 1 |
Python | Python | fix flake8 errors | 983f3a709f4531a16241c7838cafd5cf2702a829 | <ide><path>libcloud/compute/drivers/vultr.py
<ide> def require_api_key(self):
<ide>
<ide> try:
<ide> return self.method \
<del> not in self.unauthenticated_endpoints[self.action]
<add> not in self.unauthenticated_endpoints[self.action]
<ide> except KeyError:
<ide> return True
<ide>
<ide> def _to_node(self, data):
<ide> if 'status' in data:
<ide> state = self.NODE_STATE_MAP.get(data['status'], NodeState.UNKNOWN)
<ide> if state == NodeState.RUNNING and \
<del> data['power_status'] != 'running':
<add> data['power_status'] != 'running':
<ide> state = NodeState.STOPPED
<ide> else:
<ide> state = NodeState.UNKNOWN
<ide> def _to_node(self, data):
<ide> private_ips = []
<ide> created_at = parse_date(data['date_created'])
<ide>
<del> # TODO: remove extra keys and return Node with full api because we know:
<add> # TODO: remove extra keys and return Node with full api:
<ide> # TODO: size = None, # type: NodeSize
<ide> # TODO: image = None, # type: NodeImage
<ide> # response ordering
<ide> extra_keys = [
<ide> "ram", "disk", "vcpu_count",
<ide> "location", # Location name
<del> "DCID", # Location id in which to create the server. See v1/regions/list
<del> "default_password", "pending_charges", "cost_per_month", "current_bandwidth_gb",
<del> "allowed_bandwidth_gb", "netmask_v4", "gateway_v4", "power_status",
<del> "server_state",
<add> "DCID", # Location id. See v1/regions/list
<add> "default_password", "pending_charges", "cost_per_month",
<add> "current_bandwidth_gb", "allowed_bandwidth_gb", "netmask_v4",
<add> "gateway_v4", "power_status", "server_state",
<ide> "VPSPLANID", # Plan id, see /v1/plans/list
<ide> "v6_networks",
<ide> # TODO: Does we really need kvm_url?
<ide> def _to_node(self, data):
<ide> extra[key] = data[key]
<ide>
<ide> node = Node(id=data['SUBID'], name=data['label'], state=state,
<del> public_ips=public_ips, private_ips=private_ips, extra=extra,
<del> created_at=created_at, driver=self)
<add> public_ips=public_ips, private_ips=private_ips,
<add> extra=extra, created_at=created_at, driver=self)
<ide>
<ide> return node
<ide>
<ide> def _to_size(self, data):
<ide> }
<ide> ram = int(data['ram'])
<ide> disk = int(data['disk'])
<del> bandwidth = int(float(data['bandwidth'])) # NodeSize accepted int instead float
<add> # NodeSize accepted int instead float
<add> bandwidth = int(float(data['bandwidth']))
<ide> price = float(data['price_per_month'])
<ide>
<ide> return NodeSize(id=data['VPSPLANID'], name=data['name'], | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.