content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Text
Text
remove arrows from test name assertion
891a64fa3dd8c8d950e0011c0eabf2690476b480
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-projects/american-british-translator.md <ide> async (getUserInput) => { <ide> }; <ide> ``` <ide> <del>The `/api/translate` route should handle the way time is written in American and British English. For example, ten thirty is written as "10.30" in British English and "10:30" in American English. <add>The `/api/translate` route should handle the way time is written in American and British English. For example, ten thirty is written as "10.30" in British English and "10:30" in American English. The `span` element should wrap the entire time string, i.e. `<span class="highlight">10:30</span>`. <ide> <ide> ```js <ide> async (getUserInput) => { <ide> async (getUserInput) => { <ide> const getTests = await $.get(getUserInput('url') + '/_api/get-tests'); <ide> assert.isArray(getTests); <ide> const unitTests = getTests.filter((test) => { <del> return !!test.context.match(/Unit Tests ->/gi); <add> return !!test.context.match(/Unit Tests/gi); <ide> }); <ide> assert.isAtLeast(unitTests.length, 24, 'At least 24 tests passed'); <ide> unitTests.forEach((test) => { <ide> async (getUserInput) => { <ide> const getTests = await $.get(getUserInput('url') + '/_api/get-tests'); <ide> assert.isArray(getTests); <ide> const functTests = getTests.filter((test) => { <del> return !!test.context.match(/Functional Tests ->/gi); <add> return !!test.context.match(/Functional Tests/gi); <ide> }); <ide> assert.isAtLeast(functTests.length, 6, 'At least 6 tests passed'); <ide> functTests.forEach((test) => {
1
Ruby
Ruby
extract method to share path expansion logic
cbceb78f38a1e51d02c19cd33f7299f3d0a79e95
<ide><path>actionpack/lib/action_dispatch/testing/integration.rb <ide> def process(method, path, params: nil, headers: nil, env: nil, xhr: false, as: n <ide> request_encoder = RequestEncoder.encoder(as) <ide> <ide> if path =~ %r{://} <del> location = URI.parse(path) <del> https! URI::HTTPS === location if location.scheme <del> if url_host = location.host <del> default = Rack::Request::DEFAULT_PORTS[location.scheme] <del> url_host += ":#{location.port}" if default != location.port <del> host! url_host <add> path = build_expanded_path(path, request_encoder) do |location| <add> https! URI::HTTPS === location if location.scheme <add> <add> if url_host = location.host <add> default = Rack::Request::DEFAULT_PORTS[location.scheme] <add> url_host += ":#{location.port}" if default != location.port <add> host! url_host <add> end <ide> end <del> path = request_encoder.append_format_to location.path <del> path = location.query ? "#{path}?#{location.query}" : path <ide> elsif as <del> location = URI.parse(path) <del> path = request_encoder.append_format_to location.path <del> path = location.query ? "#{path}?#{location.query}" : path <add> path = build_expanded_path(path, request_encoder) <ide> end <ide> <ide> hostname, port = host.split(':') <ide> def build_full_uri(path, env) <ide> "#{env['rack.url_scheme']}://#{env['SERVER_NAME']}:#{env['SERVER_PORT']}#{path}" <ide> end <ide> <add> def build_expanded_path(path, request_encoder) <add> location = URI.parse(path) <add> yield location if block_given? <add> path = request_encoder.append_format_to location.path <add> location.query ? "#{path}?#{location.query}" : path <add> end <add> <ide> class RequestEncoder # :nodoc: <ide> @encoders = {} <ide>
1
Javascript
Javascript
allow dispatch many times without listener
b381bed10cf24a3009a9e805fbe4cea081d4590b
<ide><path>lib/internal/event_target.js <ide> class EventTarget { <ide> } <ide> <ide> const root = this[kEvents].get(type); <del> if (root === undefined || root.next === undefined) <add> if (root === undefined || root.next === undefined) { <add> if (event !== undefined) <add> event[kIsBeingDispatched] = false; <ide> return true; <add> } <ide> <ide> let handler = root.next; <ide> let next; <ide><path>test/parallel/test-eventtarget.js <ide> let asyncTest = Promise.resolve(); <ide> deepStrictEqual(event.composedPath(), []); <ide> <ide> <add> eventTarget2.dispatchEvent(event); <add> strictEqual(event.eventPhase, Event.NONE); <add> strictEqual(event.target, eventTarget2); <add> deepStrictEqual(event.composedPath(), []); <add>} <add>{ <add> // Same event dispatched multiple times, without listeners added. <add> const event = new Event('foo'); <add> const eventTarget1 = new EventTarget(); <add> const eventTarget2 = new EventTarget(); <add> <add> eventTarget1.dispatchEvent(event); <add> strictEqual(event.eventPhase, Event.NONE); <add> strictEqual(event.target, eventTarget1); <add> deepStrictEqual(event.composedPath(), []); <add> <ide> eventTarget2.dispatchEvent(event); <ide> strictEqual(event.eventPhase, Event.NONE); <ide> strictEqual(event.target, eventTarget2);
2
Python
Python
fix calls to pricing
04b29e1454fafd148b2b19bc5571ee534eceb741
<ide><path>libcloud/test/test_pricing.py <ide> def test_get_gce_image_price_non_premium_image(self): <ide> image_name = "debian-10-buster-v20220519" <ide> cores = 4 <ide> size_name = "c2d-standard-4" <del> price = libcloud.pricing.get_gce_image_price(image_name, size_name, cores) <add> price = libcloud.pricing.get_image_price("gce", image_name, size_name, cores) <ide> self.assertTrue(price == 0) <ide> <ide> def test_get_gce_image_price_RHEL_image(self): <ide> def test_get_gce_image_price_RHEL_image(self): <ide> size_name = "n2d-highcpu-2" <ide> prices = libcloud.pricing.get_pricing("compute", "gce_images") <ide> correct_price = float(prices["RHEL"]["4vcpu or less"]["price"]) <del> fetched_price = libcloud.pricing.get_gce_image_price( <del> image_name, size_name, cores <add> fetched_price = libcloud.pricing.get_image_price( <add> "gce", image_name, size_name, cores <ide> ) <ide> self.assertTrue(fetched_price == correct_price) <ide> <ide> def test_get_gce_image_price_Windows_image(self): <ide> size_name = "n2d-highcpu-2" <ide> prices = libcloud.pricing.get_pricing("compute", "gce_images") <ide> correct_price = float(prices["Windows Server"]["any"]["price"]) * 2 <del> fetched_price = libcloud.pricing.get_gce_image_price( <del> image_name, size_name, cores <add> fetched_price = libcloud.pricing.get_image_price( <add> "gce", image_name, size_name, cores <ide> ) <ide> self.assertTrue(fetched_price == correct_price) <ide> <ide> def test_get_gce_image_price_SLES_SAP_image(self): <ide> size_name = "n2d-highcpu-2" <ide> prices = libcloud.pricing.get_pricing("compute", "gce_images") <ide> correct_price = float(prices["SLES for SAP"]["1-2vcpu"]["price"]) <del> fetched_price = libcloud.pricing.get_gce_image_price( <del> image_name, size_name, cores <add> fetched_price = libcloud.pricing.get_image_price( <add> "gce", image_name, size_name, cores <ide> ) <ide> self.assertTrue(fetched_price == correct_price) <ide>
1
Python
Python
use a name that exists in both python2 and 3,
c7734491f87ac711ff5d749213e8cac0adb3686b
<ide><path>tests/modeltests/custom_pk/fields.py <ide> def __init__(self, *args, **kwargs): <ide> def pre_save(self, instance, add): <ide> value = getattr(instance, self.attname, None) <ide> if not value: <del> value = MyWrapper(''.join(random.sample(string.lowercase, 10))) <add> value = MyWrapper(''.join(random.sample(string.ascii_lowercase, 10))) <ide> setattr(instance, self.attname, value) <ide> return value <ide>
1
PHP
PHP
return new static instance instead of collection
f703cf23b120b5b5338f57b4841a565d69765ce3
<ide><path>src/Illuminate/Support/Collection.php <ide> public function values() <ide> */ <ide> public function fetch($key) <ide> { <del> return new Collection(array_fetch($this, $key)); <add> return new static(array_fetch($this, $key)); <ide> } <ide> <ide> /** <ide> public function collapse() <ide> $results = array_merge($results, $values); <ide> } <ide> <del> return new Collection($results); <add> return new static($results); <ide> } <ide> <ide> /** <ide> public function merge($items) <ide> <ide> $results = array_merge($this->items, $items); <ide> <del> return new Collection($results); <add> return new static($results); <ide> } <ide> <ide> /**
1
Javascript
Javascript
remove unused eslint directive
93d5ac9a311282517a03b47ca9b54be7847aef0f
<ide><path>src/scales/scale.time.js <del>/* global window: false */ <ide> 'use strict'; <ide> <ide> var adapter = require('../core/core.adapters')._date;
1
Go
Go
fix typos in nsinit logs
0aacca3ae6fa7d46a3e2c4e60e71f67c9a4c64e5
<ide><path>pkg/libcontainer/nsinit/exec.go <ide> func (ns *linuxNs) Exec(container *libcontainer.Container, term Terminal, args [ <ide> if err != nil { <ide> return -1, err <ide> } <del> ns.logger.Printf("writting pid %d to file\n", command.Process.Pid) <add> ns.logger.Printf("writing pid %d to file\n", command.Process.Pid) <ide> if err := ns.stateWriter.WritePid(command.Process.Pid, started); err != nil { <ide> command.Process.Kill() <ide> return -1, err <ide><path>pkg/libcontainer/nsinit/nsinit/main.go <ide> func main() { <ide> registerFlags() <ide> <ide> if flag.NArg() < 1 { <del> log.Fatalf("wrong number of argments %d", flag.NArg()) <add> log.Fatalf("wrong number of arguments %d", flag.NArg()) <ide> } <ide> container, err := loadContainer() <ide> if err != nil { <ide> func main() { <ide> l.Fatal(err) <ide> } <ide> if flag.NArg() < 2 { <del> l.Fatalf("wrong number of argments %d", flag.NArg()) <add> l.Fatalf("wrong number of arguments %d", flag.NArg()) <ide> } <ide> syncPipe, err := nsinit.NewSyncPipeFromFd(0, uintptr(pipeFd)) <ide> if err != nil {
2
Go
Go
use checker assert for docker_api_build_test.go
253f975fdbc13bc8a84fba1a3f8a4e518cb86d8e
<ide><path>integration-cli/docker_api_build_test.go <ide> import ( <ide> "archive/tar" <ide> "bytes" <ide> "net/http" <del> "strings" <ide> <add> "github.com/docker/docker/pkg/integration/checker" <ide> "github.com/go-check/check" <ide> ) <ide> <ide> func (s *DockerSuite) TestBuildApiDockerfilePath(c *check.C) { <ide> defer tw.Close() <ide> <ide> dockerfile := []byte("FROM busybox") <del> if err := tw.WriteHeader(&tar.Header{ <add> err := tw.WriteHeader(&tar.Header{ <ide> Name: "Dockerfile", <ide> Size: int64(len(dockerfile)), <del> }); err != nil { <del> c.Fatalf("failed to write tar file header: %v", err) <del> } <del> if _, err := tw.Write(dockerfile); err != nil { <del> c.Fatalf("failed to write tar file content: %v", err) <del> } <del> if err := tw.Close(); err != nil { <del> c.Fatalf("failed to close tar archive: %v", err) <del> } <add> }) <add> //failed to write tar file header <add> c.Assert(err, checker.IsNil) <add> <add> _, err = tw.Write(dockerfile) <add> // failed to write tar file content <add> c.Assert(err, checker.IsNil) <add> <add> // failed to close tar archive <add> c.Assert(tw.Close(), checker.IsNil) <ide> <ide> res, body, err := sockRequestRaw("POST", "/build?dockerfile=../Dockerfile", buffer, "application/x-tar") <del> c.Assert(err, check.IsNil) <del> c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError) <add> c.Assert(err, checker.IsNil) <add> c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError) <ide> <ide> out, err := readBody(body) <del> if err != nil { <del> c.Fatal(err) <del> } <add> c.Assert(err, checker.IsNil) <ide> <del> if !strings.Contains(string(out), "Forbidden path outside the build context") { <del> c.Fatalf("Didn't complain about leaving build context: %s", out) <del> } <add> // Didn't complain about leaving build context <add> c.Assert(string(out), checker.Contains, "Forbidden path outside the build context") <ide> } <ide> <ide> func (s *DockerSuite) TestBuildApiDockerFileRemote(c *check.C) { <ide> COPY * /tmp/ <ide> RUN find / -name ba* <ide> RUN find /tmp/`, <ide> }) <del> if err != nil { <del> c.Fatal(err) <del> } <add> c.Assert(err, checker.IsNil) <ide> defer server.Close() <ide> <ide> res, body, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+server.URL()+"/testD", nil, "application/json") <del> c.Assert(err, check.IsNil) <del> c.Assert(res.StatusCode, check.Equals, http.StatusOK) <add> c.Assert(err, checker.IsNil) <add> c.Assert(res.StatusCode, checker.Equals, http.StatusOK) <ide> <ide> buf, err := readBody(body) <del> if err != nil { <del> c.Fatal(err) <del> } <add> c.Assert(err, checker.IsNil) <ide> <ide> // Make sure Dockerfile exists. <ide> // Make sure 'baz' doesn't exist ANYWHERE despite being mentioned in the URL <ide> out := string(buf) <del> if !strings.Contains(out, "/tmp/Dockerfile") || <del> strings.Contains(out, "baz") { <del> c.Fatalf("Incorrect output: %s", out) <del> } <add> c.Assert(out, checker.Contains, "/tmp/Dockerfile") <add> c.Assert(out, checker.Not(checker.Contains), "baz") <ide> } <ide> <ide> func (s *DockerSuite) TestBuildApiRemoteTarballContext(c *check.C) { <ide> func (s *DockerSuite) TestBuildApiRemoteTarballContext(c *check.C) { <ide> defer tw.Close() <ide> <ide> dockerfile := []byte("FROM busybox") <del> if err := tw.WriteHeader(&tar.Header{ <add> err := tw.WriteHeader(&tar.Header{ <ide> Name: "Dockerfile", <ide> Size: int64(len(dockerfile)), <del> }); err != nil { <del> c.Fatalf("failed to write tar file header: %v", err) <del> } <del> if _, err := tw.Write(dockerfile); err != nil { <del> c.Fatalf("failed to write tar file content: %v", err) <del> } <del> if err := tw.Close(); err != nil { <del> c.Fatalf("failed to close tar archive: %v", err) <del> } <add> }) <add> // failed to write tar file header <add> c.Assert(err, checker.IsNil) <add> <add> _, err = tw.Write(dockerfile) <add> // failed to write tar file content <add> c.Assert(err, checker.IsNil) <add> <add> // failed to close tar archive <add> c.Assert(tw.Close(), checker.IsNil) <ide> <ide> server, err := fakeBinaryStorage(map[string]*bytes.Buffer{ <ide> "testT.tar": buffer, <ide> }) <del> c.Assert(err, check.IsNil) <add> c.Assert(err, checker.IsNil) <ide> <ide> defer server.Close() <ide> <ide> res, b, err := sockRequestRaw("POST", "/build?remote="+server.URL()+"/testT.tar", nil, "application/tar") <del> c.Assert(err, check.IsNil) <del> c.Assert(res.StatusCode, check.Equals, http.StatusOK) <add> c.Assert(err, checker.IsNil) <add> c.Assert(res.StatusCode, checker.Equals, http.StatusOK) <ide> b.Close() <ide> } <ide> <ide> func (s *DockerSuite) TestBuildApiRemoteTarballContextWithCustomDockerfile(c *ch <ide> <ide> dockerfile := []byte(`FROM busybox <ide> RUN echo 'wrong'`) <del> if err := tw.WriteHeader(&tar.Header{ <add> err := tw.WriteHeader(&tar.Header{ <ide> Name: "Dockerfile", <ide> Size: int64(len(dockerfile)), <del> }); err != nil { <del> c.Fatalf("failed to write tar file header: %v", err) <del> } <del> if _, err := tw.Write(dockerfile); err != nil { <del> c.Fatalf("failed to write tar file content: %v", err) <del> } <add> }) <add> // failed to write tar file header <add> c.Assert(err, checker.IsNil) <add> <add> _, err = tw.Write(dockerfile) <add> // failed to write tar file content <add> c.Assert(err, checker.IsNil) <ide> <ide> custom := []byte(`FROM busybox <ide> RUN echo 'right' <ide> `) <del> if err := tw.WriteHeader(&tar.Header{ <add> err = tw.WriteHeader(&tar.Header{ <ide> Name: "custom", <ide> Size: int64(len(custom)), <del> }); err != nil { <del> c.Fatalf("failed to write tar file header: %v", err) <del> } <del> if _, err := tw.Write(custom); err != nil { <del> c.Fatalf("failed to write tar file content: %v", err) <del> } <add> }) <add> <add> // failed to write tar file header <add> c.Assert(err, checker.IsNil) <ide> <del> if err := tw.Close(); err != nil { <del> c.Fatalf("failed to close tar archive: %v", err) <del> } <add> _, err = tw.Write(custom) <add> // failed to write tar file content <add> c.Assert(err, checker.IsNil) <add> <add> // failed to close tar archive <add> c.Assert(tw.Close(), checker.IsNil) <ide> <ide> server, err := fakeBinaryStorage(map[string]*bytes.Buffer{ <ide> "testT.tar": buffer, <ide> }) <del> c.Assert(err, check.IsNil) <add> c.Assert(err, checker.IsNil) <ide> <ide> defer server.Close() <ide> url := "/build?dockerfile=custom&remote=" + server.URL() + "/testT.tar" <ide> res, body, err := sockRequestRaw("POST", url, nil, "application/tar") <del> c.Assert(err, check.IsNil) <del> c.Assert(res.StatusCode, check.Equals, http.StatusOK) <add> c.Assert(err, checker.IsNil) <add> c.Assert(res.StatusCode, checker.Equals, http.StatusOK) <ide> <ide> defer body.Close() <ide> content, err := readBody(body) <del> c.Assert(err, check.IsNil) <add> c.Assert(err, checker.IsNil) <ide> <del> if strings.Contains(string(content), "wrong") { <del> c.Fatalf("Build used the wrong dockerfile.") <del> } <add> // Build used the wrong dockerfile. <add> c.Assert(string(content), checker.Not(checker.Contains), "wrong") <ide> } <ide> <ide> func (s *DockerSuite) TestBuildApiLowerDockerfile(c *check.C) { <ide> func (s *DockerSuite) TestBuildApiLowerDockerfile(c *check.C) { <ide> "dockerfile": `FROM busybox <ide> RUN echo from dockerfile`, <ide> }, false) <del> if err != nil { <del> c.Fatal(err) <del> } <add> c.Assert(err, checker.IsNil) <ide> defer git.Close() <ide> <ide> res, body, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json") <del> c.Assert(err, check.IsNil) <del> c.Assert(res.StatusCode, check.Equals, http.StatusOK) <add> c.Assert(err, checker.IsNil) <add> c.Assert(res.StatusCode, checker.Equals, http.StatusOK) <ide> <ide> buf, err := readBody(body) <del> if err != nil { <del> c.Fatal(err) <del> } <add> c.Assert(err, checker.IsNil) <ide> <ide> out := string(buf) <del> if !strings.Contains(out, "from dockerfile") { <del> c.Fatalf("Incorrect output: %s", out) <del> } <add> c.Assert(out, checker.Contains, "from dockerfile") <ide> } <ide> <ide> func (s *DockerSuite) TestBuildApiBuildGitWithF(c *check.C) { <ide> RUN echo from baz`, <ide> "Dockerfile": `FROM busybox <ide> RUN echo from Dockerfile`, <ide> }, false) <del> if err != nil { <del> c.Fatal(err) <del> } <add> c.Assert(err, checker.IsNil) <ide> defer git.Close() <ide> <ide> // Make sure it tries to 'dockerfile' query param value <ide> res, body, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+git.RepoURL, nil, "application/json") <del> c.Assert(err, check.IsNil) <del> c.Assert(res.StatusCode, check.Equals, http.StatusOK) <add> c.Assert(err, checker.IsNil) <add> c.Assert(res.StatusCode, checker.Equals, http.StatusOK) <ide> <ide> buf, err := readBody(body) <del> if err != nil { <del> c.Fatal(err) <del> } <add> c.Assert(err, checker.IsNil) <ide> <ide> out := string(buf) <del> if !strings.Contains(out, "from baz") { <del> c.Fatalf("Incorrect output: %s", out) <del> } <add> c.Assert(out, checker.Contains, "from baz") <ide> } <ide> <ide> func (s *DockerSuite) TestBuildApiDoubleDockerfile(c *check.C) { <ide> RUN echo from Dockerfile`, <ide> "dockerfile": `FROM busybox <ide> RUN echo from dockerfile`, <ide> }, false) <del> if err != nil { <del> c.Fatal(err) <del> } <add> c.Assert(err, checker.IsNil) <ide> defer git.Close() <ide> <ide> // Make sure it tries to 'dockerfile' query param value <ide> res, body, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json") <del> c.Assert(err, check.IsNil) <del> c.Assert(res.StatusCode, check.Equals, http.StatusOK) <add> c.Assert(err, checker.IsNil) <add> c.Assert(res.StatusCode, checker.Equals, http.StatusOK) <ide> <ide> buf, err := readBody(body) <del> if err != nil { <del> c.Fatal(err) <del> } <add> c.Assert(err, checker.IsNil) <ide> <ide> out := string(buf) <del> if !strings.Contains(out, "from Dockerfile") { <del> c.Fatalf("Incorrect output: %s", out) <del> } <add> c.Assert(out, checker.Contains, "from Dockerfile") <ide> } <ide> <ide> func (s *DockerSuite) TestBuildApiDockerfileSymlink(c *check.C) { <ide> func (s *DockerSuite) TestBuildApiDockerfileSymlink(c *check.C) { <ide> tw := tar.NewWriter(buffer) <ide> defer tw.Close() <ide> <del> if err := tw.WriteHeader(&tar.Header{ <add> err := tw.WriteHeader(&tar.Header{ <ide> Name: "Dockerfile", <ide> Typeflag: tar.TypeSymlink, <ide> Linkname: "/etc/passwd", <del> }); err != nil { <del> c.Fatalf("failed to write tar file header: %v", err) <del> } <del> if err := tw.Close(); err != nil { <del> c.Fatalf("failed to close tar archive: %v", err) <del> } <add> }) <add> // failed to write tar file header <add> c.Assert(err, checker.IsNil) <add> <add> // failed to close tar archive <add> c.Assert(tw.Close(), checker.IsNil) <ide> <ide> res, body, err := sockRequestRaw("POST", "/build", buffer, "application/x-tar") <del> c.Assert(err, check.IsNil) <del> c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError) <add> c.Assert(err, checker.IsNil) <add> c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError) <ide> <ide> out, err := readBody(body) <del> if err != nil { <del> c.Fatal(err) <del> } <add> c.Assert(err, checker.IsNil) <ide> <ide> // The reason the error is "Cannot locate specified Dockerfile" is because <ide> // in the builder, the symlink is resolved within the context, therefore <ide> // Dockerfile -> /etc/passwd becomes etc/passwd from the context which is <ide> // a nonexistent file. <del> if !strings.Contains(string(out), "Cannot locate specified Dockerfile: Dockerfile") { <del> c.Fatalf("Didn't complain about leaving build context: %s", out) <del> } <add> c.Assert(string(out), checker.Contains, "Cannot locate specified Dockerfile: Dockerfile", check.Commentf("Didn't complain about leaving build context")) <ide> }
1
Ruby
Ruby
add forgotten testcase
ccadfc36953a8547dc9386eb77eb4fc1147817f3
<ide><path>activesupport/test/core_ext/pathname_test.rb <add>require 'test/unit' <add>require File.dirname(__FILE__) + '/../../lib/active_support/core_ext/pathname' <add> <add>class TestPathname < Test::Unit::TestCase <add> <add> def test_clean_within <add> assert_equal "Hi", Pathname.clean_within("Hi") <add> assert_equal "Hi", Pathname.clean_within("Hi/a/b/../..") <add> assert_equal "Hello\nWorld", Pathname.clean_within("Hello/a/b/../..\na/b/../../World/c/..") <add> end <add> <add>end
1
Text
Text
enable docker socket and service on fedora
7a93a87c1a254abbf8e68093d4be241097694bb1
<ide><path>docs/installation/linux/fedora.md <ide> There are two ways to install Docker Engine. You can install with the `dnf` pac <ide> <ide> $ sudo dnf install docker-engine <ide> <del>5. Start the Docker daemon. <add>5. Enable the socket and service. <add> <add> $ sudo systemctl enable docker.socket docker.service <add> <add>6. Start the Docker daemon. <ide> <ide> $ sudo systemctl start docker <ide> <del>6. Verify `docker` is installed correctly by running a test image in a container. <add>7. Verify `docker` is installed correctly by running a test image in a container. <ide> <ide> <ide> $ sudo docker run hello-world <ide> There are two ways to install Docker Engine. You can install with the `dnf` pac <ide> <ide> This script adds the `docker.repo` repository and installs Docker. <ide> <del>4. Start the Docker daemon. <add>4. Enable the socket and service. <add> <add> $ sudo systemctl enable docker.socket docker.service <add> <add>5. Start the Docker daemon. <ide> <ide> $ sudo systemctl start docker <ide> <del>5. Verify `docker` is installed correctly by running a test image in a container. <add>6. Verify `docker` is installed correctly by running a test image in a container. <ide> <ide> $ sudo docker run hello-world <ide> <ide> To create the `docker` group and add your user: <ide> <ide> $ docker run hello-world <ide> <del>## Start the docker daemon at boot <del> <del>To ensure Docker starts when you boot your system, do the following: <del> <del> $ sudo systemctl enable docker <del> <ide> If you need to add an HTTP Proxy, set a different directory or partition for the <ide> Docker runtime files, or make other customizations, read our Systemd article to <ide> learn how to [customize your Systemd Docker daemon options](../../admin/systemd.md).
1
Ruby
Ruby
fix typo on form_tag_helper.rb
eab2b999edb167a0e4a373671009ffbbc5707295
<ide><path>actionpack/lib/action_view/helpers/form_tag_helper.rb <ide> def text_field_tag(name, value = nil, options = {}) <ide> # # => <label for="name">Name</label> <ide> # <ide> # label_tag 'name', 'Your name' <del> # # => <label for="name">Your Name</label> <add> # # => <label for="name">Your name</label> <ide> # <ide> # label_tag 'name', nil, class: 'small_label' <ide> # # => <label for="name" class="small_label">Name</label>
1
Python
Python
add attachment support in emailoperator
d4fa61ad1a6a33798700c421fc04cb7b3ffdb5ee
<ide><path>airflow/operators/email_operator.py <ide> class EmailOperator(BaseOperator): <ide> :param html_content: content of the email (templated), html markup <ide> is allowed <ide> :type html_content: string <add> :param files: file names to attach in email <add> :type files: list <ide> """ <ide> <ide> template_fields = ('subject', 'html_content') <ide> def __init__( <ide> to, <ide> subject, <ide> html_content, <add> files=[], <ide> *args, **kwargs): <ide> super(EmailOperator, self).__init__(*args, **kwargs) <ide> self.to = to <ide> self.subject = subject <ide> self.html_content = html_content <add> self.files = files <ide> <ide> def execute(self, context): <del> send_email(self.to, self.subject, self.html_content) <add> send_email(self.to, self.subject, self.html_content, files=self.files) <ide><path>airflow/utils.py <ide> from datetime import datetime, timedelta <ide> from email.mime.text import MIMEText <ide> from email.mime.multipart import MIMEMultipart <add>from email.mime.application import MIMEApplication <ide> import errno <ide> from functools import wraps <ide> import imp <ide> def ask_yesno(question): <ide> print("Please respond by yes or no.") <ide> <ide> <del>def send_email(to, subject, html_content): <add>def send_email(to, subject, html_content, files=[]): <ide> SMTP_MAIL_FROM = conf.get('smtp', 'SMTP_MAIL_FROM') <ide> <ide> if isinstance(to, basestring): <ide> def send_email(to, subject, html_content): <ide> mime_text = MIMEText(html_content, 'html') <ide> msg.attach(mime_text) <ide> <add> for fname in files: <add> basename = os.path.basename(fname) <add> with open(fname, "rb") as f: <add> msg.attach(MIMEApplication( <add> f.read(), <add> Content_Disposition='attachment; filename="%s"' % basename, <add> Name=basename <add> )) <add> <ide> send_MIME_email(SMTP_MAIL_FROM, to, msg) <ide> <ide>
2
Javascript
Javascript
change reactid.attr_name to "data-reactid"
67cf44e7c18e068e3f39462b7ac7149eee58d3e5
<ide><path>src/core/ReactID.js <ide> <ide> var invariant = require('invariant'); <ide> var ReactMount = require('ReactMount'); <del>var ATTR_NAME = 'id'; <add>var ATTR_NAME = 'data-reactid'; <ide> var nodeCache = {}; <ide> <ide> /** <ide> function getNode(id) { <ide> } <ide> <ide> return nodeCache[id] = <del> document.getElementById(id) || // TODO Quit using getElementById. <ide> ReactMount.findReactRenderedDOMNodeSlow(id); <ide> } <ide> <ide><path>src/core/ReactMount.js <ide> function getReactRootID(container) { <ide> * <ide> * ReactMount.renderComponent(component, $('container')); <ide> * <del> * TODO Update this comment when ReactID.ATTR_NAME changes. <del> * <div id="container"> <-- Supplied `container`. <del> * <div id=".reactRoot[3]"> <-- Rendered reactRoot of React component. <del> * // ... <add> * <div id="container"> <-- Supplied `container`. <add> * <div data-reactid=".reactRoot[3]"> <-- Rendered reactRoot of React <add> * // ... component. <ide> * </div> <ide> * </div> <ide> *
2
Javascript
Javascript
improve tick width for vertical bars
6bb6e5aa4b110bf4f084747691b145a1caefb63a
<ide><path>src/controllers/controller.bar.js <ide> module.exports = function(Chart) { <ide> <ide> // Appearance <ide> base: reset ? yScalePoint : this.calculateBarBase(this.index, index), <del> width: this.calculateBarWidth(numBars), <add> width: this.calculateBarWidth(index), <ide> backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.getValueAtIndexOrDefault(dataset.backgroundColor, index, rectangleElementOptions.backgroundColor), <ide> borderSkipped: custom.borderSkipped ? custom.borderSkipped : rectangleElementOptions.borderSkipped, <ide> borderColor: custom.borderColor ? custom.borderColor : helpers.getValueAtIndexOrDefault(dataset.borderColor, index, rectangleElementOptions.borderColor), <ide> module.exports = function(Chart) { <ide> <ide> }, <ide> <del> getRuler: function() { <add> getRuler: function(index) { <ide> var meta = this.getMeta(); <ide> var xScale = this.getScaleForId(meta.xAxisID); <ide> var yScale = this.getScaleForId(meta.yAxisID); <ide> var datasetCount = this.getBarCount(); <ide> <del> var tickWidth = (function() { <del> var min = xScale.getPixelForTick(1) - xScale.getPixelForTick(0); <del> for (var i = 2; i < xScale.ticks.length; i++) { <del> min = Math.min(xScale.getPixelForTick(i) - xScale.getPixelForTick(i - 1), min); <del> } <del> return min; <del> }).call(this); <add> var tickWidth; <add> <add> if (xScale.options.type === 'category') { <add> tickWidth = xScale.getPixelForTick(index + 1) - xScale.getPixelForTick(index); <add> } else { <add> // Average width <add> tickWidth = xScale.width / xScale.ticks.length; <add> } <ide> var categoryWidth = tickWidth * xScale.options.categoryPercentage; <ide> var categorySpacing = (tickWidth - (tickWidth * xScale.options.categoryPercentage)) / 2; <ide> var fullBarWidth = categoryWidth / datasetCount; <ide> module.exports = function(Chart) { <ide> }; <ide> }, <ide> <del> calculateBarWidth: function() { <add> calculateBarWidth: function(index) { <ide> var xScale = this.getScaleForId(this.getMeta().xAxisID); <del> var ruler = this.getRuler(); <add> var ruler = this.getRuler(index); <ide> return xScale.options.stacked ? ruler.categoryWidth : ruler.barWidth; <ide> }, <ide> <ide> module.exports = function(Chart) { <ide> var xScale = this.getScaleForId(meta.xAxisID); <ide> var barIndex = this.getBarIndex(datasetIndex); <ide> <del> var ruler = this.getRuler(); <add> var ruler = this.getRuler(index); <ide> var leftTick = xScale.getPixelForValue(null, index, datasetIndex, this.chart.isCombo); <ide> leftTick -= this.chart.isCombo ? (ruler.tickWidth / 2) : 0; <ide>
1
Javascript
Javascript
add a fallback component name for warnings
dcbb4301f0a505c8bac72f7beac1604869a3846a
<ide><path>packages/react-reconciler/src/ReactFiberClassComponent.js <ide> export default function( <ide> shouldUpdate !== undefined, <ide> '%s.shouldComponentUpdate(): Returned undefined instead of a ' + <ide> 'boolean value. Make sure to return true or false.', <del> getComponentName(workInProgress) || 'Unknown', <add> getComponentName(workInProgress) || 'Component', <ide> ); <ide> } <ide> <ide> export default function( <ide> name, <ide> name, <ide> ); <del> } <del> <del> const state = instance.state; <del> if (state && (typeof state !== 'object' || isArray(state))) { <del> warning( <del> false, <del> '%s.state: must be set to an object or null', <del> getComponentName(workInProgress), <del> ); <del> } <del> if (typeof instance.getChildContext === 'function') { <del> warning( <del> typeof type.childContextTypes === 'object', <del> '%s.getChildContext(): childContextTypes must be defined in order to ' + <del> 'use getChildContext().', <del> getComponentName(workInProgress), <del> ); <add> const state = instance.state; <add> if (state && (typeof state !== 'object' || isArray(state))) { <add> warning(false, '%s.state: must be set to an object or null', name); <add> } <add> if (typeof instance.getChildContext === 'function') { <add> warning( <add> typeof type.childContextTypes === 'object', <add> '%s.getChildContext(): childContextTypes must be defined in order to ' + <add> 'use getChildContext().', <add> name, <add> ); <add> } <ide> } <ide> } <ide> <ide> export default function( <ide> '%s.componentWillMount(): Assigning directly to this.state is ' + <ide> "deprecated (except inside a component's " + <ide> 'constructor). Use setState instead.', <del> getComponentName(workInProgress), <add> getComponentName(workInProgress) || 'Component', <ide> ); <ide> } <ide> updater.enqueueReplaceState(instance, instance.state, null); <ide> export default function( <ide> true) || <ide> typeof instance.UNSAFE_componentWillReceiveProps === 'function' <ide> ) { <del> const componentName = getComponentName(workInProgress) || 'Unknown'; <add> const componentName = getComponentName(workInProgress) || 'Component'; <ide> if (!didWarnAboutWillReceivePropsAndDerivedState[componentName]) { <ide> warning( <ide> false,
1
PHP
PHP
apply fixes from styleci
c22ac4bcb9ed425d599827e89ba274c4ae58f6c9
<ide><path>tests/Support/SupportCollectionTest.php <ide> public function testGroupByMultiLevelAndClosurePreservingKeys() <ide> 'skilllevel', <ide> function ($item) { <ide> return $item['roles']; <del> } <add> }, <ide> ], true); <ide> <ide> $expected_result = [
1
Ruby
Ruby
remove unnecessary begin block
e887232b7ec991e451e7dfc7ee23d6d91c023958
<ide><path>Library/Homebrew/macos.rb <ide> def xctoolchain_path <ide> <ide> def sdk_path(v = version) <ide> (@sdk_path ||= {}).fetch(v.to_s) do <del> @sdk_path[v.to_s] = begin <del> opts = [] <del> # First query Xcode itself <del> opts << `#{locate('xcodebuild')} -version -sdk macosx#{v} Path 2>/dev/null`.chomp unless Xcode.bad_xcode_select_path? <del> # Xcode.prefix is pretty smart, so lets look inside to find the sdk <del> opts << "#{Xcode.prefix}/Platforms/MacOSX.platform/Developer/SDKs/MacOSX#{v}.sdk" <del> # Xcode < 4.3 style <del> opts << "/Developer/SDKs/MacOSX#{v}.sdk" <del> opts.map{|a| Pathname.new(a) }.detect { |p| p.directory? } <del> end <add> opts = [] <add> # First query Xcode itself <add> opts << `#{locate('xcodebuild')} -version -sdk macosx#{v} Path 2>/dev/null`.chomp unless Xcode.bad_xcode_select_path? <add> # Xcode.prefix is pretty smart, so lets look inside to find the sdk <add> opts << "#{Xcode.prefix}/Platforms/MacOSX.platform/Developer/SDKs/MacOSX#{v}.sdk" <add> # Xcode < 4.3 style <add> opts << "/Developer/SDKs/MacOSX#{v}.sdk" <add> @sdk_path[v.to_s] = opts.map { |a| Pathname.new(a) }.detect(&:directory?) <ide> end <ide> end <ide>
1
Text
Text
add version metadata to timers/promises
2f49720beee7f4c03a75c3793bf76e76cf044bc3
<ide><path>doc/api/timers.md <ide> added: v0.0.1 <ide> Cancels a `Timeout` object created by [`setTimeout()`][]. <ide> <ide> ## Timers Promises API <add><!-- YAML <add>added: v15.0.0 <add>--> <ide> <ide> > Stability: 1 - Experimental <ide> <ide> const timersPromises = require('timers/promises'); <ide> ``` <ide> <ide> ### `timersPromises.setTimeout([delay[, value[, options]]])` <add><!-- YAML <add>added: v15.0.0 <add>--> <ide> <ide> * `delay` {number} The number of milliseconds to wait before resolving the <ide> `Promise`. **Default**: `1`. <ide> const timersPromises = require('timers/promises'); <ide> cancel the scheduled `Timeout`. <ide> <ide> ### `timersPromises.setImmediate([value[, options]])` <add><!-- YAML <add>added: v15.0.0 <add>--> <ide> <ide> * `value` {any} A value with which the `Promise` is resolved. <ide> * `options` {Object}
1
Ruby
Ruby
handle invalid signed blob ids gracefully
af0caadb8d9781770399c1804976af4a71d1313b
<ide><path>activestorage/app/controllers/active_storage/blobs_controller.rb <ide> # security-through-obscurity factor of the signed blob references, you'll need to implement your own <ide> # authenticated redirection controller. <ide> class ActiveStorage::BlobsController < ActionController::Base <add> include ActiveStorage::SetBlob <add> <ide> def show <del> if blob = ActiveStorage::Blob.find_signed(params[:signed_id]) <del> expires_in ActiveStorage::Blob.service.url_expires_in <del> redirect_to blob.service_url(disposition: params[:disposition]) <del> else <del> head :not_found <del> end <add> expires_in ActiveStorage::Blob.service.url_expires_in <add> redirect_to @blob.service_url(disposition: params[:disposition]) <ide> end <ide> end <ide><path>activestorage/app/controllers/active_storage/previews_controller.rb <ide> # frozen_string_literal: true <ide> <ide> class ActiveStorage::PreviewsController < ActionController::Base <add> include ActiveStorage::SetBlob <add> <ide> def show <del> if blob = ActiveStorage::Blob.find_signed(params[:signed_blob_id]) <del> expires_in ActiveStorage::Blob.service.url_expires_in <del> redirect_to ActiveStorage::Preview.new(blob, params[:variation_key]).processed.service_url(disposition: params[:disposition]) <del> else <del> head :not_found <del> end <add> expires_in ActiveStorage::Blob.service.url_expires_in <add> redirect_to ActiveStorage::Preview.new(@blob, params[:variation_key]).processed.service_url(disposition: params[:disposition]) <ide> end <ide> end <ide><path>activestorage/app/controllers/active_storage/variants_controller.rb <ide> # security-through-obscurity factor of the signed blob and variation reference, you'll need to implement your own <ide> # authenticated redirection controller. <ide> class ActiveStorage::VariantsController < ActionController::Base <add> include ActiveStorage::SetBlob <add> <ide> def show <del> if blob = ActiveStorage::Blob.find_signed(params[:signed_blob_id]) <del> expires_in ActiveStorage::Blob.service.url_expires_in <del> redirect_to ActiveStorage::Variant.new(blob, params[:variation_key]).processed.service_url(disposition: params[:disposition]) <del> else <del> head :not_found <del> end <add> expires_in ActiveStorage::Blob.service.url_expires_in <add> redirect_to ActiveStorage::Variant.new(@blob, params[:variation_key]).processed.service_url(disposition: params[:disposition]) <ide> end <ide> end <ide><path>activestorage/app/controllers/concerns/active_storage/set_blob.rb <add># frozen_string_literal: true <add> <add>module ActiveStorage::SetBlob <add> extend ActiveSupport::Concern <add> <add> included do <add> before_action :set_blob <add> end <add> <add> private <add> def set_blob <add> @blob = ActiveStorage::Blob.find_signed(params[:signed_blob_id] || params[:signed_id]) <add> rescue ActiveSupport::MessageVerifier::InvalidSignature <add> head :not_found <add> end <add>end <ide><path>activestorage/test/controllers/blobs_controller_test.rb <ide> class ActiveStorage::BlobsControllerTest < ActionDispatch::IntegrationTest <ide> @blob = create_file_blob filename: "racecar.jpg" <ide> end <ide> <add> test "showing blob with invalid signed ID" do <add> get rails_service_blob_url("invalid", "racecar.jpg") <add> assert_response :not_found <add> end <add> <ide> test "showing blob utilizes browser caching" do <ide> get rails_blob_url(@blob) <ide> <ide><path>activestorage/test/controllers/previews_controller_test.rb <ide> class ActiveStorage::PreviewsControllerTest < ActionDispatch::IntegrationTest <ide> assert_equal 77, image.width <ide> assert_equal 100, image.height <ide> end <add> <add> test "showing preview with invalid signed blob ID" do <add> get rails_blob_preview_url( <add> filename: @blob.filename, <add> signed_blob_id: "invalid", <add> variation_key: ActiveStorage::Variation.encode(resize: "100x100")) <add> <add> assert_response :not_found <add> end <ide> end <ide><path>activestorage/test/controllers/variants_controller_test.rb <ide> class ActiveStorage::VariantsControllerTest < ActionDispatch::IntegrationTest <ide> assert_equal 100, image.width <ide> assert_equal 67, image.height <ide> end <add> <add> test "showing variant with invalid signed blob ID" do <add> get rails_blob_variation_url( <add> filename: @blob.filename, <add> signed_blob_id: "invalid", <add> variation_key: ActiveStorage::Variation.encode(resize: "100x100")) <add> <add> assert_response :not_found <add> end <ide> end
7
PHP
PHP
rewrite redis job to one json_decode()
daa49838d9557c526e28abd75f1825f8c05dd998
<ide><path>src/Illuminate/Queue/Jobs/RedisJob.php <ide> class RedisJob extends Job implements JobContract <ide> protected $redis; <ide> <ide> /** <del> * The Redis job payload. <add> * The Redis raw job payload. <ide> * <ide> * @var string <ide> */ <ide> protected $job; <ide> <add> /** <add> * The Redis decoded job payload. <add> * <add> * @var array <add> */ <add> protected $decodedJob; <add> <ide> /** <ide> * The Redis job payload inside the reserved queue. <ide> * <ide> class RedisJob extends Job implements JobContract <ide> public function __construct(Container $container, RedisQueue $redis, $job, $reserved, $queue) <ide> { <ide> $this->job = $job; <add> $this->decodedJob = json_decode($job, true); <ide> $this->redis = $redis; <ide> $this->queue = $queue; <ide> $this->reserved = $reserved; <ide> public function __construct(Container $container, RedisQueue $redis, $job, $rese <ide> */ <ide> public function fire() <ide> { <del> $this->resolveAndFire(json_decode($this->getRawBody(), true)); <add> $this->resolveAndFire($this->decodedJob); <ide> } <ide> <ide> /** <ide> public function release($delay = 0) <ide> */ <ide> public function attempts() <ide> { <del> return Arr::get(json_decode($this->job, true), 'attempts'); <add> return Arr::get($this->decodedJob, 'attempts'); <ide> } <ide> <ide> /** <ide> public function attempts() <ide> */ <ide> public function getJobId() <ide> { <del> return Arr::get(json_decode($this->job, true), 'id'); <add> return Arr::get($this->decodedJob, 'id'); <ide> } <ide> <ide> /** <ide> public function getRedisQueue() <ide> return $this->redis; <ide> } <ide> <del> /** <del> * Get the underlying Redis job. <del> * <del> * @return string <del> */ <del> public function getRedisJob() <del> { <del> return $this->job; <del> } <del> <ide> /** <ide> * Get the underlying reserved Redis job. <ide> * <ide><path>tests/Queue/RedisQueueIntegrationTest.php <ide> public function testPopProperlyPopsJobOffOfRedis() <ide> $redisJob = $this->queue->pop(); <ide> $after = time(); <ide> <del> $this->assertEquals($job, unserialize(json_decode($redisJob->getRedisJob())->data->command)); <add> $this->assertEquals($job, unserialize(json_decode($redisJob->getRawBody())->data->command)); <ide> $this->assertEquals(1, $redisJob->attempts()); <ide> $this->assertEquals($job, unserialize(json_decode($redisJob->getReservedJob())->data->command)); <ide> $this->assertEquals(2, json_decode($redisJob->getReservedJob())->attempts);
2
Python
Python
add pcg64dxsm to performance-measuring script
781254a751e6a808c14544de5f010d8a8cfe5d2e
<ide><path>doc/source/reference/random/performance.py <ide> import pandas as pd <ide> <ide> import numpy as np <del>from numpy.random import MT19937, PCG64, Philox, SFC64 <add>from numpy.random import MT19937, PCG64, PCG64DXSM, Philox, SFC64 <ide> <del>PRNGS = [MT19937, PCG64, Philox, SFC64] <add>PRNGS = [MT19937, PCG64, PCG64DXSM, Philox, SFC64] <ide> <ide> funcs = {} <ide> integers = 'integers(0, 2**{bits},size=1000000, dtype="uint{bits}")' <ide> col[key] = 1000 * min(t) <ide> table['RandomState'] = pd.Series(col) <ide> <del>columns = ['MT19937','PCG64','Philox','SFC64', 'RandomState'] <add>columns = ['MT19937','PCG64','PCG64DXSM','Philox','SFC64', 'RandomState'] <ide> table = pd.DataFrame(table) <ide> order = np.log(table).mean().sort_values().index <ide> table = table.T
1
Javascript
Javascript
use point.size() in getmaxoverflow
91fec4a3970a91baa534c585f4301aebfb18ee37
<ide><path>src/controllers/controller.bubble.js <ide> export default class BubbleController extends DatasetController { <ide> getMaxOverflow() { <ide> const me = this; <ide> const meta = me._cachedMeta; <del> let i = (meta.data || []).length - 1; <add> const data = meta.data; <ide> let max = 0; <del> for (; i >= 0; --i) { <del> max = Math.max(max, me.getStyle(i, true).radius); <add> for (let i = data.length - 1; i >= 0; --i) { <add> max = Math.max(max, data[i].size()); <ide> } <ide> return max > 0 && max; <ide> }
1
Ruby
Ruby
fix spelling error
4be3c2c92fed516aca2fcb1ba9fc253bda580d25
<ide><path>activeresource/lib/active_resource/base.rb <ide> def timeout=(timeout) <ide> @timeout = timeout <ide> end <ide> <del> # Gets tthe number of seconds after which requests to the REST API should time out. <add> # Gets the number of seconds after which requests to the REST API should time out. <ide> def timeout <ide> if defined?(@timeout) <ide> @timeout
1
PHP
PHP
reduce line length
d0d30dd2730c177eb1001c2509b389c4ec22efdc
<ide><path>src/Illuminate/Console/Scheduling/Event.php <ide> public function everyThirtyMinutes() <ide> */ <ide> public function days($days) <ide> { <del> $this->spliceIntoPosition(5, implode(',', is_array($days) ? $days : func_get_args())); <add> $days = is_array($days) ? $days : func_get_args(); <ide> <del> return $this; <add> return $this->spliceIntoPosition(5, implode(',', $days)); <ide> } <ide> <ide> /**
1
Javascript
Javascript
use strings instead of arrays in cff.wrap
dae18a271007310ce07a2c2434fface62dcb8f16
<ide><path>fonts.js <ide> CFF.prototype = { <ide> }, <ide> <ide> wrap: function wrap(name, glyphs, charstrings, subrs, properties) { <del> function stringToArray(str) { <del> var array = []; <del> for (var i = 0; i < str.length; ++i) <del> array[i] = str.charCodeAt(i); <add> var fields = { <add> "header": "\x01\x00\x04\x04", // major version, minor version, header size, offset size <add> <add> "names": this.createCFFIndexHeader([name]), <add> <add> "topDict": (function topDict(self) { <add> return function() { <add> var dict = <add> "\x00\x01\x01\x01\x30" + <add> "\xf8\x1b\x00" + // version <add> "\xf8\x1b\x01" + // Notice <add> "\xf8\x1b\x02" + // FullName <add> "\xf8\x1b\x03" + // FamilyName <add> "\xf8\x1b\x04" + // Weight <add> "\x1c\x00\x00\x10"; // Encoding <add> <add> var boundingBox = properties.bbox; <add> for (var i = 0; i < boundingBox.length; i++) <add> dict += self.encodeNumber(boundingBox[i]); <add> dict += "\x05"; // FontBBox; <add> <add> var offset = fields.header.length + <add> fields.names.length + <add> (dict.length + (4 + 4 + 7)) + <add> fields.strings.length + <add> fields.globalSubrs.length; <add> dict += self.encodeNumber(offset) + "\x0f"; // Charset <add> <add> offset = offset + (glyphs.length * 2) + 1; <add> dict += self.encodeNumber(offset) + "\x11"; // Charstrings <add> <add> dict += self.encodeNumber(fields.private.length); <add> var offset = offset + fields.charstrings.length; <add> dict += self.encodeNumber(offset) + "\x12"; // Private <add> <add> return dict; <add> }; <add> })(this), <add> <add> "strings": (function strings(self) { <add> var strings = [ <add> "Version 0.11", // Version <add> "See original notice", // Notice <add> name, // FullName <add> name, // FamilyName <add> "Medium" // Weight <add> ]; <add> return self.createCFFIndexHeader(strings); <add> })(this), <add> <add> "globalSubrs": this.createCFFIndexHeader([]), <add> <add> "charset": (function charset(self) { <add> var charset = "\x00"; // Encoding <add> <add> var count = glyphs.length; <add> for (var i = 0; i < count; i++) { <add> var index = CFFStrings.indexOf(charstrings[i].glyph.glyph); <add> // Some characters like asterikmath && circlecopyrt are missing from the <add> // original strings, for the moment let's map them to .notdef and see <add> // later if it cause any problems <add> if (index == -1) <add> index = 0; <ide> <del> return array; <add> var bytes = FontsUtils.integerToBytes(index, 2); <add> charset += String.fromCharCode(bytes[0]) + String.fromCharCode(bytes[1]); <add> } <add> return charset; <add> })(this), <add> <add> "charstrings": this.createCFFIndexHeader([[0x8B, 0x0E]].concat(glyphs), true), <add> <add> "private": (function(self) { <add> var data = <add> "\x8b\x14" + // defaultWidth <add> "\x8b\x15" + // nominalWidth <add> "\x8b\x0a" + // StdHW <add> "\x8b\x0a" + // StdVW <add> "\x8b\x8b\x0c\x0c" + // StemSnapH <add> "\x8b\x8b\x0c\x0d"; // StemSnapV <add> data += self.encodeNumber(data.length + 4) + "\x13"; // Subrs offset <add> <add> return data; <add> })(this), <add> <add> "localSubrs": this.createCFFIndexHeader(subrs, true) <ide> }; <add> fields.topDict = fields.topDict(); <ide> <del> var cff = new Uint8Array(kMaxFontFileSize); <del> var currentOffset = 0; <del> <del> // Font header (major version, minor version, header size, offset size) <del> var header = "\x01\x00\x04\x04"; <del> currentOffset += header.length; <del> cff.set(stringToArray(header)); <del> <del> // Names Index <del> var nameIndex = stringToArray(this.createCFFIndexHeader([name])); <del> cff.set(nameIndex, currentOffset); <del> currentOffset += nameIndex.length; <del> <del> // Calculate strings before writing the TopDICT index in order <del> // to calculate correct relative offsets for storing 'charset' <del> // and 'charstrings' data <del> var version = ""; <del> var notice = ""; <del> var fullName = ""; <del> var familyName = ""; <del> var weight = ""; <del> var strings = [version, notice, fullName, <del> familyName, weight]; <del> var stringsIndex = stringToArray(this.createCFFIndexHeader(strings)); <del> var stringsDataLength = stringsIndex.length; <del> <del> // Create the global subroutines index <del> var globalSubrsIndex = stringToArray(this.createCFFIndexHeader([])); <del> <del> // Fill the charset header (first byte is the encoding) <del> var charset = [0x00]; <del> var glyphsCount = glyphs.length; <del> for (var i = 0; i < glyphsCount; i++) { <del> var index = CFFStrings.indexOf(charstrings[i].glyph); <del> if (index == -1) <del> index = CFFStrings.length + strings.indexOf(charstrings[i].glyph); <del> <del> var bytes = FontsUtils.integerToBytes(index, 2); <del> charset.push(bytes[0]); <del> charset.push(bytes[1]); <del> } <ide> <del> var charstringsIndex = stringToArray(this.createCFFIndexHeader([[0x8B, 0x0E]].concat(glyphs), true)); <del> <del> //Top Dict Index <del> var topDictIndex = [ <del> 0x00, 0x01, 0x01, 0x01, 0x30, <del> 248, 27, 0, // version <del> 248, 28, 1, // Notice <del> 248, 29, 2, // FullName <del> 248, 30, 3, // FamilyName <del> 248, 31, 4 // Weight <del> ]; <del> <del> var fontBBox = properties.bbox; <del> for (var i = 0; i < fontBBox.length; i++) <del> topDictIndex = topDictIndex.concat(stringToArray(this.encodeNumber(fontBBox[i]))); <del> topDictIndex.push(5) // FontBBox; <del> <del> var charsetOffset = currentOffset + <del> (topDictIndex.length + (4 + 4 + 4 + 7)) + <del> stringsIndex.length + <del> globalSubrsIndex.length; <del> topDictIndex = topDictIndex.concat(stringToArray(this.encodeNumber(charsetOffset))); <del> topDictIndex.push(15); // charset <del> <del> topDictIndex = topDictIndex.concat([28, 0, 0, 16]) // Encoding <del> <del> var charstringsOffset = charsetOffset + (glyphsCount * 2) + 1; <del> topDictIndex = topDictIndex.concat(stringToArray(this.encodeNumber(charstringsOffset))); <del> topDictIndex.push(17); // charstrings <del> <del> topDictIndex = topDictIndex.concat([28, 0, 55]) <del> var privateOffset = charstringsOffset + charstringsIndex.length; <del> topDictIndex = topDictIndex.concat(stringToArray(this.encodeNumber(privateOffset))); <del> topDictIndex.push(18); // Private <del> <del> var indexes = [ <del> topDictIndex, stringsIndex, <del> globalSubrsIndex, charset, <del> charstringsIndex <del> ]; <del> <del> for (var i = 0; i < indexes.length; i++) { <del> var index = indexes[i]; <del> cff.set(index, currentOffset); <del> currentOffset += index.length; <add> var cff = []; <add> for (var index in fields) { <add> var field = fields[index]; <add> for (var i = 0; i < field.length; i++) <add> cff.push(field.charCodeAt(i)); <ide> } <ide> <del> // Private Data <del> var defaultWidth = stringToArray(this.encodeNumber(0)); <del> var privateData = [].concat( <del> defaultWidth, [20], <del> [139, 21], // nominalWidth <del> [ <del> 119, 159, 248, 97, 159, 247, 87, 159, 6, <del> 30, 10, 3, 150, 37, 255, 12, 9, <del> 139, 12, <del> 10, 172, 10, <del> 172, 150, 143, 146, 150, 146, 12, 12, <del> 247, 32, 11, <del> 247, 10, 161, 147, 154, 150, 143, 12, 13, <del> 139, 12, 14, <del> 28, 0, 55, 19 // Subrs offset <del> ]); <del> cff.set(privateData, currentOffset); <del> currentOffset += privateData.length; <del> <del> <del> // Local subrs <del> var subrsData = stringToArray(this.createCFFIndexHeader(subrs, true)); <del> cff.set(subrsData, currentOffset); <del> currentOffset += subrsData.length; <del> <del> var fontData = []; <del> for (var i = 0; i < currentOffset; i++) <del> fontData.push(cff[i]); <del> <del> return fontData; <add> return cff; <ide> } <ide> }; <ide>
1
Python
Python
fix bytes vs str issues in tests
700147f601a881d756128e5e4d9aeb3a356cb7b2
<ide><path>numpy/lib/tests/test_io.py <ide> <ide> from numpy.lib._iotools import ConverterError, ConverterLockError, \ <ide> ConversionWarning <del>from numpy.compat import asbytes, asbytes_nested <add>from numpy.compat import asbytes, asbytes_nested, bytes <ide> <ide> if sys.version_info[0] >= 3: <ide> from io import BytesIO <ide> def test_array(self): <ide> np.savetxt(c, a, fmt=fmt) <ide> c.seek(0) <ide> assert_equal(c.readlines(), <del> [(fmt + ' ' + fmt + '\n') % (1, 2), <del> (fmt + ' ' + fmt + '\n') % (3, 4)]) <add> asbytes_nested( <add> [(fmt + ' ' + fmt + '\n') % (1, 2), <add> (fmt + ' ' + fmt + '\n') % (3, 4)])) <ide> <ide> a = np.array([[1, 2], [3, 4]], int) <ide> c = StringIO() <ide> def test_1D(self): <ide> np.savetxt(c, a, fmt='%d') <ide> c.seek(0) <ide> lines = c.readlines() <del> assert_equal(lines, ['1\n', '2\n', '3\n', '4\n']) <add> assert_equal(lines, asbytes_nested(['1\n', '2\n', '3\n', '4\n'])) <ide> <ide> def test_record(self): <ide> a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')]) <ide> def test_delimiter(self): <ide> c = StringIO() <ide> np.savetxt(c, a, delimiter=asbytes(','), fmt='%d') <ide> c.seek(0) <del> assert_equal(c.readlines(), ['1,2\n', '3,4\n']) <add> assert_equal(c.readlines(), asbytes_nested(['1,2\n', '3,4\n'])) <ide> <ide> def test_format(self): <ide> a = np.array([(1, 2), (3, 4)]) <ide> def test_invalid_converter(self): <ide> def test_dtype_with_converters(self): <ide> dstr = "2009; 23; 46" <ide> test = np.ndfromtxt(StringIO(dstr,), <del> delimiter=";", dtype=float, converters={0:str}) <add> delimiter=";", dtype=float, converters={0:bytes}) <ide> control = np.array([('2009', 23., 46)], <ide> dtype=[('f0', '|S4'), ('f1', float), ('f2', float)]) <ide> assert_equal(test, control) <ide> def test_userconverters_with_explicit_dtype(self): <ide> "Test user_converters w/ explicit (standard) dtype" <ide> data = StringIO('skip,skip,2001-01-01,1.0,skip') <ide> test = np.genfromtxt(data, delimiter=",", names=None, dtype=float, <del> usecols=(2, 3), converters={2: str}) <add> usecols=(2, 3), converters={2: bytes}) <ide> control = np.array([('2001-01-01', 1.)], <ide> dtype=[('', '|S10'), ('', float)]) <ide> assert_equal(test, control) <ide><path>numpy/lib/tests/test_twodim_base.py <ide> triu_indices_from, tril_indices, tril_indices_from ) <ide> <ide> import numpy as np <add>from numpy.compat import asbytes, asbytes_nested <ide> <ide> def get_mat(n): <ide> data = arange(n) <ide> def test_eye_bounds(self): <ide> assert_equal(eye(3, 2, -3), [[0, 0], [0, 0], [0, 0]]) <ide> <ide> def test_strings(self): <del> assert_equal(eye(2, 2, dtype='S3'), [['1', ''], ['', '1']]) <add> assert_equal(eye(2, 2, dtype='S3'), <add> asbytes_nested([['1', ''], ['', '1']])) <ide> <ide> def test_bool(self): <ide> assert_equal(eye(2, 2, dtype=bool), [[True, False], [False, True]])
2
Mixed
Javascript
enable suspense + rename placeholder
8af6728c6f105d37f9c0006288a6d1ac3903dc71
<ide><path>fixtures/unstable-async/suspense/README.md <ide> No. The APIs being tested here are unstable and some of them have still not been <ide> <ide> Clone the React repository. <ide> <del>First, open this file locally: <del> <del>* `packages/shared/ReactFeatureFlags.js` (make sure you didn't open a similarly named file!) <del> <del>Set [the `enableSuspense` flag](https://github.com/facebook/react/blob/d79238f1eeb6634ba7a3df23c3b2709b56cbb8b2/packages/shared/ReactFeatureFlags.js#L19) to `true` and save the file. <del> <del>**After you've done that,** follow these steps: <add>Follow these steps: <ide> <ide> ```shell <ide> # 1: Build react from source <ide> cd /path/to/react <ide> yarn <del>yarn build dom-client,core,react-cache,schedule --type=NODE <add>yarn build dom-client,core,react-cache,scheduler --type=NODE <ide> <ide> # 2: Install fixture dependencies <ide> cd fixtures/unstable-async/suspense/ <ide><path>fixtures/unstable-async/suspense/src/components/App.js <del>import React, {Placeholder, PureComponent} from 'react'; <add>import React, {unstable_Suspense as Suspense, PureComponent} from 'react'; <ide> import {unstable_scheduleCallback} from 'scheduler'; <ide> import { <ide> unstable_trace as trace, <ide> export default class App extends PureComponent { <ide> }}> <ide> Return to list <ide> </button> <del> <Placeholder delayMs={2000} fallback={<Spinner size="large" />}> <add> <Suspense maxDuration={2000} fallback={<Spinner size="large" />}> <ide> <UserPageLoader id={id} /> <del> </Placeholder> <add> </Suspense> <ide> </div> <ide> ); <ide> } <ide> <ide> renderList(loadingId) { <ide> return ( <del> <Placeholder delayMs={1500} fallback={<Spinner size="large" />}> <add> <Suspense maxDuration={1500} fallback={<Spinner size="large" />}> <ide> <ContributorListPage <ide> loadingId={loadingId} <ide> onUserClick={this.handleUserClick} <ide> /> <del> </Placeholder> <add> </Suspense> <ide> ); <ide> } <ide> } <ide><path>fixtures/unstable-async/suspense/src/components/UserPage.js <del>import React, {Placeholder} from 'react'; <add>import React, {unstable_Suspense as Suspense} from 'react'; <ide> import {createResource} from 'react-cache'; <ide> import Spinner from './Spinner'; <ide> import {cache} from '../cache'; <ide> export default function UserPage({id}) { <ide> alignItems: 'start', <ide> }}> <ide> <UserDetails id={id} /> <del> <Placeholder delayMs={1000} fallback={<Spinner size="medium" />}> <add> <Suspense maxDuration={1000} fallback={<Spinner size="medium" />}> <ide> <Repositories id={id} /> <del> </Placeholder> <add> </Suspense> <ide> </div> <ide> ); <ide> } <ide> function Img({src, alt, ...rest}) { <ide> <ide> function UserPicture({source}) { <ide> return ( <del> <Placeholder delayMs={1500} fallback={<img src={source} alt="poster" />}> <add> <Suspense maxDuration={1500} fallback={<img src={source} alt="poster" />}> <ide> <Img <ide> src={source} <ide> alt="profile picture" <ide> function UserPicture({source}) { <ide> borderRadius: '0.5rem', <ide> }} <ide> /> <del> </Placeholder> <add> </Suspense> <ide> ); <ide> } <ide> <add><path>packages/react-dom/src/__tests__/ReactDOMServerSuspense-test.internal.js <del><path>packages/react-dom/src/__tests__/ReactDOMServerPlaceholders-test.internal.js <ide> function initModules() { <ide> jest.resetModuleRegistry(); <ide> <ide> ReactFeatureFlags = require('shared/ReactFeatureFlags'); <del> ReactFeatureFlags.enableSuspense = true; <ide> ReactFeatureFlags.enableSuspenseServerRenderer = true; <ide> <ide> React = require('react'); <ide> const {resetModules, serverRender} = ReactDOMServerIntegrationUtils( <ide> initModules, <ide> ); <ide> <del>describe('ReactDOMServerPlaceholders', () => { <add>describe('ReactDOMServerSuspense', () => { <ide> beforeEach(() => { <ide> resetModules(); <ide> }); <ide> describe('ReactDOMServerPlaceholders', () => { <ide> throw new Promise(() => {}); <ide> }; <ide> const e = await serverRender( <del> <React.Placeholder fallback={<div />}> <add> <React.unstable_Suspense fallback={<div />}> <ide> <Suspended /> <del> </React.Placeholder>, <add> </React.unstable_Suspense>, <ide> ); <ide> <ide> expect(e.tagName).toBe('DIV'); <ide><path>packages/react-dom/src/server/ReactPartialRenderer.js <ide> import { <ide> REACT_FRAGMENT_TYPE, <ide> REACT_STRICT_MODE_TYPE, <ide> REACT_CONCURRENT_MODE_TYPE, <del> REACT_PLACEHOLDER_TYPE, <add> REACT_SUSPENSE_TYPE, <ide> REACT_PORTAL_TYPE, <ide> REACT_PROFILER_TYPE, <ide> REACT_PROVIDER_TYPE, <ide> class ReactDOMServerRenderer { <ide> this.stack.push(frame); <ide> return ''; <ide> } <del> case REACT_PLACEHOLDER_TYPE: { <add> case REACT_SUSPENSE_TYPE: { <ide> if (enableSuspenseServerRenderer) { <ide> const nextChildren = toArray( <ide> // Always use the fallback when synchronously rendering to string. <ide><path>packages/react-reconciler/src/ReactFiber.js <ide> import { <ide> ContextProvider, <ide> ContextConsumer, <ide> Profiler, <del> PlaceholderComponent, <add> SuspenseComponent, <ide> FunctionComponentLazy, <ide> ClassComponentLazy, <ide> ForwardRefLazy, <ide> import { <ide> REACT_PROVIDER_TYPE, <ide> REACT_CONTEXT_TYPE, <ide> REACT_CONCURRENT_MODE_TYPE, <del> REACT_PLACEHOLDER_TYPE, <add> REACT_SUSPENSE_TYPE, <ide> REACT_PURE_TYPE, <ide> } from 'shared/ReactSymbols'; <ide> <ide> export function createFiberFromElement( <ide> break; <ide> case REACT_PROFILER_TYPE: <ide> return createFiberFromProfiler(pendingProps, mode, expirationTime, key); <del> case REACT_PLACEHOLDER_TYPE: <del> fiberTag = PlaceholderComponent; <add> case REACT_SUSPENSE_TYPE: <add> fiberTag = SuspenseComponent; <ide> break; <ide> default: { <ide> if (typeof type === 'object' && type !== null) { <ide><path>packages/react-reconciler/src/ReactFiberBeginWork.js <ide> import { <ide> ContextProvider, <ide> ContextConsumer, <ide> Profiler, <del> PlaceholderComponent, <add> SuspenseComponent, <ide> PureComponent, <ide> PureComponentLazy, <ide> } from 'shared/ReactWorkTags'; <ide> import { <ide> } from 'shared/ReactSideEffectTags'; <ide> import ReactSharedInternals from 'shared/ReactSharedInternals'; <ide> import { <del> enableSuspense, <ide> debugRenderPhaseSideEffects, <ide> debugRenderPhaseSideEffectsForStrictMode, <ide> enableProfilerTimer, <ide> function mountIndeterminateComponent( <ide> } <ide> } <ide> <del>function updatePlaceholderComponent( <add>function updateSuspenseComponent( <ide> current, <ide> workInProgress, <ide> renderExpirationTime, <ide> ) { <del> if (enableSuspense) { <del> const nextProps = workInProgress.pendingProps; <del> <del> // Check if we already attempted to render the normal state. If we did, <del> // and we timed out, render the placeholder state. <del> const alreadyCaptured = <del> (workInProgress.effectTag & DidCapture) === NoEffect; <del> <del> let nextDidTimeout; <del> if (current !== null && workInProgress.updateQueue !== null) { <del> // We're outside strict mode. Something inside this Placeholder boundary <del> // suspended during the last commit. Switch to the placholder. <del> workInProgress.updateQueue = null; <del> nextDidTimeout = true; <del> } else { <del> nextDidTimeout = !alreadyCaptured; <del> } <add> const nextProps = workInProgress.pendingProps; <ide> <del> if ((workInProgress.mode & StrictMode) !== NoEffect) { <del> if (nextDidTimeout) { <del> // If the timed-out view commits, schedule an update effect to record <del> // the committed time. <del> workInProgress.effectTag |= Update; <del> } else { <del> // The state node points to the time at which placeholder timed out. <del> // We can clear it once we switch back to the normal children. <del> workInProgress.stateNode = null; <del> } <del> } <add> // Check if we already attempted to render the normal state. If we did, <add> // and we timed out, render the placeholder state. <add> const alreadyCaptured = (workInProgress.effectTag & DidCapture) === NoEffect; <ide> <del> // If the `children` prop is a function, treat it like a render prop. <del> // TODO: This is temporary until we finalize a lower level API. <del> const children = nextProps.children; <del> let nextChildren; <del> if (typeof children === 'function') { <del> nextChildren = children(nextDidTimeout); <del> } else { <del> nextChildren = nextDidTimeout ? nextProps.fallback : children; <del> } <add> let nextDidTimeout; <add> if (current !== null && workInProgress.updateQueue !== null) { <add> // We're outside strict mode. Something inside this Placeholder boundary <add> // suspended during the last commit. Switch to the placholder. <add> workInProgress.updateQueue = null; <add> nextDidTimeout = true; <add> } else { <add> nextDidTimeout = !alreadyCaptured; <add> } <ide> <del> if (current !== null && nextDidTimeout !== workInProgress.memoizedState) { <del> // We're about to switch from the placeholder children to the normal <del> // children, or vice versa. These are two different conceptual sets that <del> // happen to be stored in the same set. Call this special function to <del> // force the new set not to match with the current set. <del> // TODO: The proper way to model this is by storing each set separately. <del> forceUnmountCurrentAndReconcile( <del> current, <del> workInProgress, <del> nextChildren, <del> renderExpirationTime, <del> ); <add> if ((workInProgress.mode & StrictMode) !== NoEffect) { <add> if (nextDidTimeout) { <add> // If the timed-out view commits, schedule an update effect to record <add> // the committed time. <add> workInProgress.effectTag |= Update; <ide> } else { <del> reconcileChildren( <del> current, <del> workInProgress, <del> nextChildren, <del> renderExpirationTime, <del> ); <add> // The state node points to the time at which placeholder timed out. <add> // We can clear it once we switch back to the normal children. <add> workInProgress.stateNode = null; <ide> } <del> workInProgress.memoizedProps = nextProps; <del> workInProgress.memoizedState = nextDidTimeout; <del> return workInProgress.child; <add> } <add> <add> // If the `children` prop is a function, treat it like a render prop. <add> // TODO: This is temporary until we finalize a lower level API. <add> const children = nextProps.children; <add> let nextChildren; <add> if (typeof children === 'function') { <add> nextChildren = children(nextDidTimeout); <ide> } else { <del> return null; <add> nextChildren = nextDidTimeout ? nextProps.fallback : children; <add> } <add> <add> if (current !== null && nextDidTimeout !== workInProgress.memoizedState) { <add> // We're about to switch from the placeholder children to the normal <add> // children, or vice versa. These are two different conceptual sets that <add> // happen to be stored in the same set. Call this special function to <add> // force the new set not to match with the current set. <add> // TODO: The proper way to model this is by storing each set separately. <add> forceUnmountCurrentAndReconcile( <add> current, <add> workInProgress, <add> nextChildren, <add> renderExpirationTime, <add> ); <add> } else { <add> reconcileChildren( <add> current, <add> workInProgress, <add> nextChildren, <add> renderExpirationTime, <add> ); <ide> } <add> workInProgress.memoizedProps = nextProps; <add> workInProgress.memoizedState = nextDidTimeout; <add> return workInProgress.child; <ide> } <ide> <ide> function updatePortalComponent( <ide> function beginWork( <ide> return updateHostComponent(current, workInProgress, renderExpirationTime); <ide> case HostText: <ide> return updateHostText(current, workInProgress); <del> case PlaceholderComponent: <del> return updatePlaceholderComponent( <add> case SuspenseComponent: <add> return updateSuspenseComponent( <ide> current, <ide> workInProgress, <ide> renderExpirationTime, <ide><path>packages/react-reconciler/src/ReactFiberCommitWork.js <ide> import type {CapturedValue, CapturedError} from './ReactCapturedValue'; <ide> import { <ide> enableSchedulerTracing, <ide> enableProfilerTimer, <del> enableSuspense, <ide> } from 'shared/ReactFeatureFlags'; <ide> import { <ide> ClassComponent, <ide> import { <ide> HostText, <ide> HostPortal, <ide> Profiler, <del> PlaceholderComponent, <add> SuspenseComponent, <ide> } from 'shared/ReactWorkTags'; <ide> import { <ide> invokeGuardedCallback, <ide> function commitLifeCycles( <ide> } <ide> return; <ide> } <del> case PlaceholderComponent: { <del> if (enableSuspense) { <del> if ((finishedWork.mode & StrictMode) === NoEffect) { <del> // In loose mode, a placeholder times out by scheduling a synchronous <del> // update in the commit phase. Use `updateQueue` field to signal that <del> // the Timeout needs to switch to the placeholder. We don't need an <del> // entire queue. Any non-null value works. <del> // $FlowFixMe - Intentionally using a value other than an UpdateQueue. <del> finishedWork.updateQueue = emptyObject; <del> scheduleWork(finishedWork, Sync); <del> } else { <del> // In strict mode, the Update effect is used to record the time at <del> // which the placeholder timed out. <del> const currentTime = requestCurrentTime(); <del> finishedWork.stateNode = {timedOutAt: currentTime}; <del> } <add> case SuspenseComponent: { <add> if ((finishedWork.mode & StrictMode) === NoEffect) { <add> // In loose mode, a placeholder times out by scheduling a synchronous <add> // update in the commit phase. Use `updateQueue` field to signal that <add> // the Timeout needs to switch to the placeholder. We don't need an <add> // entire queue. Any non-null value works. <add> // $FlowFixMe - Intentionally using a value other than an UpdateQueue. <add> finishedWork.updateQueue = emptyObject; <add> scheduleWork(finishedWork, Sync); <add> } else { <add> // In strict mode, the Update effect is used to record the time at <add> // which the placeholder timed out. <add> const currentTime = requestCurrentTime(); <add> finishedWork.stateNode = {timedOutAt: currentTime}; <ide> } <ide> return; <ide> } <ide> function commitWork(current: Fiber | null, finishedWork: Fiber): void { <ide> case Profiler: { <ide> return; <ide> } <del> case PlaceholderComponent: { <add> case SuspenseComponent: { <ide> return; <ide> } <ide> default: { <ide><path>packages/react-reconciler/src/ReactFiberCompleteWork.js <ide> import { <ide> Fragment, <ide> Mode, <ide> Profiler, <del> PlaceholderComponent, <add> SuspenseComponent, <ide> ForwardRefLazy, <ide> PureComponent, <ide> PureComponentLazy, <ide> function completeWork( <ide> case ForwardRef: <ide> case ForwardRefLazy: <ide> break; <del> case PlaceholderComponent: <add> case SuspenseComponent: <ide> break; <ide> case Fragment: <ide> break; <ide><path>packages/react-reconciler/src/ReactFiberScheduler.js <ide> import { <ide> enableUserTimingAPI, <ide> replayFailedUnitOfWorkWithInvokeGuardedCallback, <ide> warnAboutDeprecatedLifecycles, <del> enableSuspense, <ide> } from 'shared/ReactFeatureFlags'; <ide> import getComponentName from 'shared/getComponentName'; <ide> import invariant from 'shared/invariant'; <ide> function renderRoot( <ide> } <ide> } <ide> <del> if (enableSuspense && !isExpired && nextLatestAbsoluteTimeoutMs !== -1) { <add> if (!isExpired && nextLatestAbsoluteTimeoutMs !== -1) { <ide> // The tree was suspended. <ide> const suspendedExpirationTime = expirationTime; <ide> markSuspendedPriorityLevel(root, suspendedExpirationTime); <ide> function retrySuspendedRoot( <ide> fiber: Fiber, <ide> suspendedTime: ExpirationTime, <ide> ) { <del> if (enableSuspense) { <del> let retryTime; <add> let retryTime; <ide> <del> if (isPriorityLevelSuspended(root, suspendedTime)) { <del> // Ping at the original level <del> retryTime = suspendedTime; <add> if (isPriorityLevelSuspended(root, suspendedTime)) { <add> // Ping at the original level <add> retryTime = suspendedTime; <ide> <del> markPingedPriorityLevel(root, retryTime); <del> } else { <del> // Placeholder already timed out. Compute a new expiration time <del> const currentTime = requestCurrentTime(); <del> retryTime = computeExpirationForFiber(currentTime, fiber); <del> markPendingPriorityLevel(root, retryTime); <del> } <del> <del> // TODO: If the placeholder fiber has already rendered the primary children <del> // without suspending (that is, all of the promises have already resolved), <del> // we should not trigger another update here. One case this happens is when <del> // we are in sync mode and a single promise is thrown both on initial render <del> // and on update; we attach two .then(retrySuspendedRoot) callbacks and each <del> // one performs Sync work, rerendering the Placeholder. <del> <del> if ((fiber.mode & ConcurrentMode) !== NoContext) { <del> if (root === nextRoot && nextRenderExpirationTime === suspendedTime) { <del> // Received a ping at the same priority level at which we're currently <del> // rendering. Restart from the root. <del> nextRoot = null; <del> } <del> } <add> markPingedPriorityLevel(root, retryTime); <add> } else { <add> // Suspense already timed out. Compute a new expiration time <add> const currentTime = requestCurrentTime(); <add> retryTime = computeExpirationForFiber(currentTime, fiber); <add> markPendingPriorityLevel(root, retryTime); <add> } <ide> <del> scheduleWorkToRoot(fiber, retryTime); <del> const rootExpirationTime = root.expirationTime; <del> if (rootExpirationTime !== NoWork) { <del> requestWork(root, rootExpirationTime); <add> // TODO: If the placeholder fiber has already rendered the primary children <add> // without suspending (that is, all of the promises have already resolved), <add> // we should not trigger another update here. One case this happens is when <add> // we are in sync mode and a single promise is thrown both on initial render <add> // and on update; we attach two .then(retrySuspendedRoot) callbacks and each <add> // one performs Sync work, rerendering the Suspense. <add> <add> if ((fiber.mode & ConcurrentMode) !== NoContext) { <add> if (root === nextRoot && nextRenderExpirationTime === suspendedTime) { <add> // Received a ping at the same priority level at which we're currently <add> // rendering. Restart from the root. <add> nextRoot = null; <ide> } <ide> } <add> <add> scheduleWorkToRoot(fiber, retryTime); <add> const rootExpirationTime = root.expirationTime; <add> if (rootExpirationTime !== NoWork) { <add> requestWork(root, rootExpirationTime); <add> } <ide> } <ide> <ide> function scheduleWorkToRoot(fiber: Fiber, expirationTime): FiberRoot | null { <ide> function onSuspend( <ide> msUntilTimeout: number, <ide> ): void { <ide> root.expirationTime = rootExpirationTime; <del> if (enableSuspense && msUntilTimeout === 0 && !shouldYield()) { <add> if (msUntilTimeout === 0 && !shouldYield()) { <ide> // Don't wait an additional tick. Commit the tree immediately. <ide> root.pendingCommitExpirationTime = suspendedExpirationTime; <ide> root.finishedWork = finishedWork; <ide> function onYield(root) { <ide> } <ide> <ide> function onTimeout(root, finishedWork, suspendedExpirationTime) { <del> if (enableSuspense) { <del> // The root timed out. Commit it. <del> root.pendingCommitExpirationTime = suspendedExpirationTime; <del> root.finishedWork = finishedWork; <del> // Read the current time before entering the commit phase. We can be <del> // certain this won't cause tearing related to batching of event updates <del> // because we're at the top of a timer event. <del> recomputeCurrentRendererTime(); <del> currentSchedulerTime = currentRendererTime; <del> flushRoot(root, suspendedExpirationTime); <del> } <add> // The root timed out. Commit it. <add> root.pendingCommitExpirationTime = suspendedExpirationTime; <add> root.finishedWork = finishedWork; <add> // Read the current time before entering the commit phase. We can be <add> // certain this won't cause tearing related to batching of event updates <add> // because we're at the top of a timer event. <add> recomputeCurrentRendererTime(); <add> currentSchedulerTime = currentRendererTime; <add> flushRoot(root, suspendedExpirationTime); <ide> } <ide> <ide> function onCommit(root, expirationTime) { <ide> function performWorkOnRoot( <ide> // If this root previously suspended, clear its existing timeout, since <ide> // we're about to try rendering again. <ide> const timeoutHandle = root.timeoutHandle; <del> if (enableSuspense && timeoutHandle !== noTimeout) { <add> if (timeoutHandle !== noTimeout) { <ide> root.timeoutHandle = noTimeout; <ide> // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above <ide> cancelTimeout(timeoutHandle); <ide> function performWorkOnRoot( <ide> // If this root previously suspended, clear its existing timeout, since <ide> // we're about to try rendering again. <ide> const timeoutHandle = root.timeoutHandle; <del> if (enableSuspense && timeoutHandle !== noTimeout) { <add> if (timeoutHandle !== noTimeout) { <ide> root.timeoutHandle = noTimeout; <ide> // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above <ide> cancelTimeout(timeoutHandle); <ide><path>packages/react-reconciler/src/ReactFiberUnwindWork.js <ide> import { <ide> HostComponent, <ide> HostPortal, <ide> ContextProvider, <del> PlaceholderComponent, <add> SuspenseComponent, <ide> } from 'shared/ReactWorkTags'; <ide> import { <ide> DidCapture, <ide> import { <ide> Update as UpdateEffect, <ide> LifecycleEffectMask, <ide> } from 'shared/ReactSideEffectTags'; <del>import {enableSuspense, enableSchedulerTracing} from 'shared/ReactFeatureFlags'; <add>import {enableSchedulerTracing} from 'shared/ReactFeatureFlags'; <ide> import {StrictMode, ConcurrentMode} from './ReactTypeOfMode'; <ide> <ide> import {createCapturedValue} from './ReactCapturedValue'; <ide> function throwException( <ide> sourceFiber.firstEffect = sourceFiber.lastEffect = null; <ide> <ide> if ( <del> enableSuspense && <ide> value !== null && <ide> typeof value === 'object' && <ide> typeof value.then === 'function' <ide> function throwException( <ide> let earliestTimeoutMs = -1; <ide> let startTimeMs = -1; <ide> do { <del> if (workInProgress.tag === PlaceholderComponent) { <add> if (workInProgress.tag === SuspenseComponent) { <ide> const current = workInProgress.alternate; <ide> if ( <ide> current !== null && <ide> function throwException( <ide> // Do not search any further. <ide> break; <ide> } <del> let timeoutPropMs = workInProgress.pendingProps.delayMs; <add> let timeoutPropMs = workInProgress.pendingProps.maxDuration; <ide> if (typeof timeoutPropMs === 'number') { <ide> if (timeoutPropMs <= 0) { <ide> earliestTimeoutMs = 0; <ide> function throwException( <ide> workInProgress = workInProgress.return; <ide> } while (workInProgress !== null); <ide> <del> // Schedule the nearest Placeholder to re-render the timed out view. <add> // Schedule the nearest Suspense to re-render the timed out view. <ide> workInProgress = returnFiber; <ide> do { <del> if (workInProgress.tag === PlaceholderComponent) { <add> if (workInProgress.tag === SuspenseComponent) { <ide> const didTimeout = workInProgress.memoizedState; <ide> if (!didTimeout) { <ide> // Found the nearest boundary. <ide> function throwException( <ide> // If the boundary is outside of strict mode, we should *not* suspend <ide> // the commit. Pretend as if the suspended component rendered null and <ide> // keep rendering. In the commit phase, we'll schedule a subsequent <del> // synchronous update to re-render the Placeholder. <add> // synchronous update to re-render the Suspense. <ide> // <ide> // Note: It doesn't matter whether the component that suspended was <del> // inside a strict mode tree. If the Placeholder is outside of it, we <add> // inside a strict mode tree. If the Suspense is outside of it, we <ide> // should *not* suspend the commit. <ide> if ((workInProgress.mode & StrictMode) === NoEffect) { <ide> workInProgress.effectTag |= UpdateEffect; <ide> function unwindWork( <ide> popHostContext(workInProgress); <ide> return null; <ide> } <del> case PlaceholderComponent: { <add> case SuspenseComponent: { <ide> const effectTag = workInProgress.effectTag; <ide> if (effectTag & ShouldCapture) { <ide> workInProgress.effectTag = (effectTag & ~ShouldCapture) | DidCapture; <ide><path>packages/react-reconciler/src/__tests__/ReactPure-test.internal.js <ide> describe('pure', () => { <ide> jest.resetModules(); <ide> ReactFeatureFlags = require('shared/ReactFeatureFlags'); <ide> ReactFeatureFlags.debugRenderPhaseSideEffectsForStrictMode = false; <del> ReactFeatureFlags.enableSuspense = true; <ide> React = require('react'); <ide> ReactNoop = require('react-noop-renderer'); <ide> }); <ide> describe('pure', () => { <ide> function sharedTests(label, pure) { <ide> describe(`${label}`, () => { <ide> it('bails out on props equality', async () => { <del> const {Placeholder} = React; <add> const {unstable_Suspense: Suspense} = React; <ide> <ide> function Counter({count}) { <ide> return <Text text={count} />; <ide> } <ide> Counter = pure(Counter); <ide> <ide> ReactNoop.render( <del> <Placeholder> <add> <Suspense> <ide> <Counter count={0} /> <del> </Placeholder>, <add> </Suspense>, <ide> ); <ide> expect(ReactNoop.flush()).toEqual([]); <ide> await Promise.resolve(); <ide> describe('pure', () => { <ide> <ide> // Should bail out because props have not changed <ide> ReactNoop.render( <del> <Placeholder> <add> <Suspense> <ide> <Counter count={0} /> <del> </Placeholder>, <add> </Suspense>, <ide> ); <ide> expect(ReactNoop.flush()).toEqual([]); <ide> expect(ReactNoop.getChildren()).toEqual([span(0)]); <ide> <ide> // Should update because count prop changed <ide> ReactNoop.render( <del> <Placeholder> <add> <Suspense> <ide> <Counter count={1} /> <del> </Placeholder>, <add> </Suspense>, <ide> ); <ide> expect(ReactNoop.flush()).toEqual([1]); <ide> expect(ReactNoop.getChildren()).toEqual([span(1)]); <ide> }); <ide> }); <ide> <ide> it("does not bail out if there's a context change", async () => { <del> const {Placeholder} = React; <add> const {unstable_Suspense: Suspense} = React; <ide> <ide> const CountContext = React.createContext(0); <ide> <ide> describe('pure', () => { <ide> state = {count: 0}; <ide> render() { <ide> return ( <del> <Placeholder> <add> <Suspense> <ide> <CountContext.Provider value={this.state.count}> <ide> <Counter label="Count" /> <ide> </CountContext.Provider> <del> </Placeholder> <add> </Suspense> <ide> ); <ide> } <ide> } <ide> describe('pure', () => { <ide> }); <ide> <ide> it('accepts custom comparison function', async () => { <del> const {Placeholder} = React; <add> const {unstable_Suspense: Suspense} = React; <ide> <ide> function Counter({count}) { <ide> return <Text text={count} />; <ide> describe('pure', () => { <ide> }); <ide> <ide> ReactNoop.render( <del> <Placeholder> <add> <Suspense> <ide> <Counter count={0} /> <del> </Placeholder>, <add> </Suspense>, <ide> ); <ide> expect(ReactNoop.flush()).toEqual([]); <ide> await Promise.resolve(); <ide> describe('pure', () => { <ide> <ide> // Should bail out because props have not changed <ide> ReactNoop.render( <del> <Placeholder> <add> <Suspense> <ide> <Counter count={0} /> <del> </Placeholder>, <add> </Suspense>, <ide> ); <ide> expect(ReactNoop.flush()).toEqual(['Old count: 0, New count: 0']); <ide> expect(ReactNoop.getChildren()).toEqual([span(0)]); <ide> <ide> // Should update because count prop changed <ide> ReactNoop.render( <del> <Placeholder> <add> <Suspense> <ide> <Counter count={1} /> <del> </Placeholder>, <add> </Suspense>, <ide> ); <ide> expect(ReactNoop.flush()).toEqual(['Old count: 0, New count: 1', 1]); <ide> expect(ReactNoop.getChildren()).toEqual([span(1)]); <ide><path>packages/react-reconciler/src/__tests__/ReactSuspense-test.internal.js <ide> let React; <ide> let ReactTestRenderer; <ide> let ReactFeatureFlags; <ide> let ReactCache; <del>let Placeholder; <add>let Suspense; <ide> <ide> // let JestReact; <ide> <ide> describe('ReactSuspense', () => { <ide> ReactFeatureFlags = require('shared/ReactFeatureFlags'); <ide> ReactFeatureFlags.debugRenderPhaseSideEffectsForStrictMode = false; <ide> ReactFeatureFlags.replayFailedUnitOfWorkWithInvokeGuardedCallback = false; <del> ReactFeatureFlags.enableSuspense = true; <ide> React = require('react'); <ide> ReactTestRenderer = require('react-test-renderer'); <ide> // JestReact = require('jest-react'); <ide> ReactCache = require('react-cache'); <ide> <del> Placeholder = React.Placeholder; <add> Suspense = React.unstable_Suspense; <ide> <ide> function invalidateCache() { <ide> cache = ReactCache.createCache(invalidateCache); <ide> describe('ReactSuspense', () => { <ide> function Foo() { <ide> ReactTestRenderer.unstable_yield('Foo'); <ide> return ( <del> <Placeholder> <add> <Suspense> <ide> <Bar> <ide> <AsyncText text="A" ms={100} /> <ide> <Text text="B" /> <ide> </Bar> <del> </Placeholder> <add> </Suspense> <ide> ); <ide> } <ide> <ide> describe('ReactSuspense', () => { <ide> }); <ide> <ide> it('suspends siblings and later recovers each independently', () => { <del> // Render two sibling Placeholder components <add> // Render two sibling Suspense components <ide> const root = ReactTestRenderer.create( <ide> <React.Fragment> <del> <Placeholder delayMs={1000} fallback={<Text text="Loading A..." />}> <add> <Suspense maxDuration={1000} fallback={<Text text="Loading A..." />}> <ide> <AsyncText text="A" ms={5000} /> <del> </Placeholder> <del> <Placeholder delayMs={3000} fallback={<Text text="Loading B..." />}> <add> </Suspense> <add> <Suspense maxDuration={3000} fallback={<Text text="Loading B..." />}> <ide> <AsyncText text="B" ms={6000} /> <del> </Placeholder> <add> </Suspense> <ide> </React.Fragment>, <ide> { <ide> unstable_isConcurrent: true, <ide> describe('ReactSuspense', () => { <ide> expect(root).toFlushWithoutYielding(); <ide> expect(root).toMatchRenderedOutput('Loading A...Loading B...'); <ide> <del> // Advance time by enough that the first Placeholder's promise resolves and <del> // switches back to the normal view. The second Placeholder should still <add> // Advance time by enough that the first Suspense's promise resolves and <add> // switches back to the normal view. The second Suspense should still <ide> // show the placeholder <ide> jest.advanceTimersByTime(1000); <ide> // TODO: Should we throw if you forget to call toHaveYielded? <ide> expect(ReactTestRenderer).toHaveYielded(['Promise resolved [A]']); <ide> expect(root).toFlushAndYield(['A']); <ide> expect(root).toMatchRenderedOutput('ALoading B...'); <ide> <del> // Advance time by enough that the second Placeholder's promise resolves <add> // Advance time by enough that the second Suspense's promise resolves <ide> // and switches back to the normal view <ide> jest.advanceTimersByTime(1000); <ide> expect(ReactTestRenderer).toHaveYielded(['Promise resolved [B]']); <ide> describe('ReactSuspense', () => { <ide> } <ide> <ide> const root = ReactTestRenderer.create( <del> <Placeholder delayMs={1000} fallback={<Text text="Loading..." />}> <add> <Suspense maxDuration={1000} fallback={<Text text="Loading..." />}> <ide> <Async /> <ide> <Text text="Sibling" /> <del> </Placeholder>, <add> </Suspense>, <ide> { <ide> unstable_isConcurrent: true, <ide> }, <ide><path>packages/react-reconciler/src/__tests__/ReactSuspenseWithNoopRenderer-test.internal.js <ide> let ReactFeatureFlags; <ide> let Fragment; <ide> let ReactNoop; <ide> let ReactCache; <del>let Placeholder; <add>let Suspense; <ide> let StrictMode; <ide> let ConcurrentMode; <ide> let lazy; <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> ReactFeatureFlags = require('shared/ReactFeatureFlags'); <ide> ReactFeatureFlags.debugRenderPhaseSideEffectsForStrictMode = false; <ide> ReactFeatureFlags.replayFailedUnitOfWorkWithInvokeGuardedCallback = false; <del> ReactFeatureFlags.enableSuspense = true; <ide> React = require('react'); <ide> Fragment = React.Fragment; <ide> ReactNoop = require('react-noop-renderer'); <ide> ReactCache = require('react-cache'); <del> Placeholder = React.Placeholder; <add> Suspense = React.unstable_Suspense; <ide> StrictMode = React.StrictMode; <ide> ConcurrentMode = React.unstable_ConcurrentMode; <ide> lazy = React.lazy; <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> function Foo() { <ide> ReactNoop.yield('Foo'); <ide> return ( <del> <Placeholder> <add> <Suspense> <ide> <Bar> <ide> <AsyncText text="A" ms={100} /> <ide> <Text text="B" /> <ide> </Bar> <del> </Placeholder> <add> </Suspense> <ide> ); <ide> } <ide> <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> }); <ide> <ide> it('suspends siblings and later recovers each independently', async () => { <del> // Render two sibling Placeholder components <add> // Render two sibling Suspense components <ide> ReactNoop.render( <ide> <Fragment> <del> <Placeholder delayMs={1000} fallback={<Text text="Loading A..." />}> <add> <Suspense maxDuration={1000} fallback={<Text text="Loading A..." />}> <ide> <AsyncText text="A" ms={5000} /> <del> </Placeholder> <del> <Placeholder delayMs={3000} fallback={<Text text="Loading B..." />}> <add> </Suspense> <add> <Suspense maxDuration={3000} fallback={<Text text="Loading B..." />}> <ide> <AsyncText text="B" ms={6000} /> <del> </Placeholder> <add> </Suspense> <ide> </Fragment>, <ide> ); <ide> expect(ReactNoop.flush()).toEqual([ <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> span('Loading B...'), <ide> ]); <ide> <del> // Advance time by enough that the first Placeholder's promise resolves and <del> // switches back to the normal view. The second Placeholder should still <add> // Advance time by enough that the first Suspense's promise resolves and <add> // switches back to the normal view. The second Suspense should still <ide> // show the placeholder <ide> ReactNoop.expire(1000); <ide> await advanceTimers(1000); <ide> <ide> expect(ReactNoop.flush()).toEqual(['Promise resolved [A]', 'A']); <ide> expect(ReactNoop.getChildren()).toEqual([span('A'), span('Loading B...')]); <ide> <del> // Advance time by enough that the second Placeholder's promise resolves <add> // Advance time by enough that the second Suspense's promise resolves <ide> // and switches back to the normal view <ide> ReactNoop.expire(1000); <ide> await advanceTimers(1000); <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> <ide> it('continues rendering siblings after suspending', async () => { <ide> ReactNoop.render( <del> <Placeholder> <add> <Suspense> <ide> <Text text="A" /> <ide> <AsyncText text="B" /> <ide> <Text text="C" /> <ide> <Text text="D" /> <del> </Placeholder>, <add> </Suspense>, <ide> ); <ide> // B suspends. Continue rendering the remaining siblings. <ide> expect(ReactNoop.flush()).toEqual(['A', 'Suspend! [B]', 'C', 'D']); <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> const errorBoundary = React.createRef(); <ide> function App() { <ide> return ( <del> <Placeholder> <add> <Suspense> <ide> <ErrorBoundary ref={errorBoundary}> <ide> <AsyncText text="Result" ms={1000} /> <ide> </ErrorBoundary> <del> </Placeholder> <add> </Suspense> <ide> ); <ide> } <ide> <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> const errorBoundary = React.createRef(); <ide> function App() { <ide> return ( <del> <Placeholder delayMs={1000} fallback={<Text text="Loading..." />}> <add> <Suspense maxDuration={1000} fallback={<Text text="Loading..." />}> <ide> <ErrorBoundary ref={errorBoundary}> <ide> <AsyncText text="Result" ms={3000} /> <ide> </ErrorBoundary> <del> </Placeholder> <add> </Suspense> <ide> ); <ide> } <ide> <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> it('can update at a higher priority while in a suspended state', async () => { <ide> function App(props) { <ide> return ( <del> <Placeholder> <add> <Suspense> <ide> <Text text={props.highPri} /> <ide> <AsyncText text={props.lowPri} /> <del> </Placeholder> <add> </Suspense> <ide> ); <ide> } <ide> <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> it('keeps working on lower priority work after being pinged', async () => { <ide> function App(props) { <ide> return ( <del> <Placeholder> <add> <Suspense> <ide> <AsyncText text="A" /> <ide> {props.showB && <Text text="B" />} <del> </Placeholder> <add> </Suspense> <ide> ); <ide> } <ide> <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> return <Text text="(empty)" />; <ide> } <ide> return ( <del> <Placeholder> <add> <Suspense> <ide> <AsyncText ms={2000} text="Async" /> <del> </Placeholder> <add> </Suspense> <ide> ); <ide> } <ide> <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> it('forces an expiration after an update times out', async () => { <ide> ReactNoop.render( <ide> <Fragment> <del> <Placeholder fallback={<Text text="Loading..." />}> <add> <Suspense fallback={<Text text="Loading..." />}> <ide> <AsyncText text="Async" ms={20000} /> <del> </Placeholder> <add> </Suspense> <ide> <Text text="Sync" /> <ide> </Fragment>, <ide> ); <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> ReactNoop.render( <ide> <Fragment> <ide> <Text text="Sync" /> <del> <Placeholder delayMs={1000} fallback={<Text text="Loading outer..." />}> <add> <Suspense <add> maxDuration={1000} <add> fallback={<Text text="Loading outer..." />}> <ide> <AsyncText text="Outer content" ms={2000} /> <del> <Placeholder <del> delayMs={2500} <add> <Suspense <add> maxDuration={2500} <ide> fallback={<Text text="Loading inner..." />}> <ide> <AsyncText text="Inner content" ms={5000} /> <del> </Placeholder> <del> </Placeholder> <add> </Suspense> <add> </Suspense> <ide> </Fragment>, <ide> ); <ide> <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> ReactNoop.flushSync(() => <ide> ReactNoop.render( <ide> <Fragment> <del> <Placeholder fallback={<Text text="Loading..." />}> <add> <Suspense fallback={<Text text="Loading..." />}> <ide> <AsyncText text="Async" /> <del> </Placeholder> <add> </Suspense> <ide> <Text text="Sync" /> <ide> </Fragment>, <ide> ), <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> ReactNoop.flushSync(() => <ide> ReactNoop.render( <ide> <Fragment> <del> <Placeholder fallback={<Text text="Loading (outer)..." />}> <del> <Placeholder fallback={<AsyncText text="Loading (inner)..." />}> <add> <Suspense fallback={<Text text="Loading (outer)..." />}> <add> <Suspense fallback={<AsyncText text="Loading (inner)..." />}> <ide> <AsyncText text="Async" /> <del> </Placeholder> <add> </Suspense> <ide> <Text text="Sync" /> <del> </Placeholder> <add> </Suspense> <ide> </Fragment>, <ide> ), <ide> ); <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> expect(ReactNoop.getChildren()).toEqual([span('Loading (outer)...')]); <ide> }); <ide> <del> it('expires early with a `delayMs` option', async () => { <add> it('expires early with a `maxDuration` option', async () => { <ide> ReactNoop.render( <ide> <Fragment> <del> <Placeholder delayMs={1000} fallback={<Text text="Loading..." />}> <add> <Suspense maxDuration={1000} fallback={<Text text="Loading..." />}> <ide> <AsyncText text="Async" ms={3000} /> <del> </Placeholder> <add> </Suspense> <ide> <Text text="Sync" /> <ide> </Fragment>, <ide> ); <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> <ide> it('resolves successfully even if fallback render is pending', async () => { <ide> ReactNoop.render( <del> <Placeholder delayMs={1000} fallback={<Text text="Loading..." />}> <add> <Suspense maxDuration={1000} fallback={<Text text="Loading..." />}> <ide> <AsyncText text="Async" ms={3000} /> <del> </Placeholder>, <add> </Suspense>, <ide> ); <ide> expect(ReactNoop.flushNextYield()).toEqual(['Suspend! [Async]']); <ide> await advanceTimers(1500); <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> expect(() => { <ide> ReactNoop.flushSync(() => <ide> ReactNoop.render( <del> <Placeholder>{() => <AsyncText text="Async" />}</Placeholder>, <add> <Suspense>{() => <AsyncText text="Async" />}</Suspense>, <ide> ), <ide> ); <ide> }).toThrow('An update was suspended, but no placeholder UI was provided.'); <ide> }); <ide> <del> it('a Placeholder component correctly handles more than one suspended child', async () => { <add> it('a Suspense component correctly handles more than one suspended child', async () => { <ide> ReactNoop.render( <del> <Placeholder delayMs={0}> <add> <Suspense maxDuration={0}> <ide> <AsyncText text="A" ms={100} /> <ide> <AsyncText text="B" ms={100} /> <del> </Placeholder>, <add> </Suspense>, <ide> ); <ide> expect(ReactNoop.expire(10000)).toEqual(['Suspend! [A]', 'Suspend! [B]']); <ide> expect(ReactNoop.getChildren()).toEqual([]); <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> <ide> it('can resume rendering earlier than a timeout', async () => { <ide> ReactNoop.render( <del> <Placeholder delayMs={1000} fallback={<Text text="Loading..." />}> <add> <Suspense maxDuration={1000} fallback={<Text text="Loading..." />}> <ide> <AsyncText text="Async" ms={100} /> <del> </Placeholder>, <add> </Suspense>, <ide> ); <ide> expect(ReactNoop.flush()).toEqual(['Suspend! [Async]', 'Loading...']); <ide> expect(ReactNoop.getChildren()).toEqual([]); <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> it('starts working on an update even if its priority falls between two suspended levels', async () => { <ide> function App(props) { <ide> return ( <del> <Placeholder delayMs={10000}> <add> <Suspense maxDuration={10000}> <ide> {props.text === 'C' ? ( <ide> <Text text="C" /> <ide> ) : ( <ide> <AsyncText text={props.text} ms={10000} /> <ide> )} <del> </Placeholder> <add> </Suspense> <ide> ); <ide> } <ide> <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> it('can hide a tree to unblock its surroundings', async () => { <ide> function App() { <ide> return ( <del> <Placeholder delayMs={1000}> <add> <Suspense maxDuration={1000}> <ide> {didTimeout => ( <ide> <Fragment> <ide> <div hidden={didTimeout}> <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> {didTimeout ? <Text text="Loading..." /> : null} <ide> </Fragment> <ide> )} <del> </Placeholder> <add> </Suspense> <ide> ); <ide> } <ide> <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> } <ide> render() { <ide> return ( <del> <Placeholder fallback={<Text text="Loading..." />}> <add> <Suspense fallback={<Text text="Loading..." />}> <ide> <AsyncText ms={20000} text={this.props.text} /> <del> </Placeholder> <add> </Suspense> <ide> ); <ide> } <ide> } <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> function Never() { <ide> // Throws a promise that resolves after some arbitrarily large <ide> // number of seconds. The idea is that this component will never <del> // resolve. It's always wrapped by a Placeholder. <add> // resolve. It's always wrapped by a Suspense. <ide> throw new Promise(resolve => setTimeout(() => resolve(), 10000)); <ide> } <ide> <ide> function Delay({ms}) { <ide> return ( <del> <Placeholder delayMs={ms}> <add> <Suspense maxDuration={ms}> <ide> {didTimeout => { <ide> if (didTimeout) { <ide> // Once ms has elapsed, render null. This allows the rest of the <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> } <ide> return <Never />; <ide> }} <del> </Placeholder> <add> </Suspense> <ide> ); <ide> } <ide> <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> it('times out immediately', async () => { <ide> function App() { <ide> return ( <del> <Placeholder delayMs={1000} fallback={<Text text="Loading..." />}> <add> <Suspense maxDuration={1000} fallback={<Text text="Loading..." />}> <ide> <AsyncText ms={100} text="Result" /> <del> </Placeholder> <add> </Suspense> <ide> ); <ide> } <ide> <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> expect(ReactNoop.getChildren()).toEqual([span('Result')]); <ide> }); <ide> <del> it('times out immediately when Placeholder is in loose mode, even if the suspender is async', async () => { <add> it('times out immediately when Suspense is in loose mode, even if the suspender is async', async () => { <ide> class UpdatingText extends React.Component { <ide> state = {step: 1}; <ide> render() { <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> const text = React.createRef(null); <ide> function App() { <ide> return ( <del> <Placeholder delayMs={1000} fallback={<Spinner />}> <add> <Suspense maxDuration={1000} fallback={<Spinner />}> <ide> <ConcurrentMode> <ide> <UpdatingText ref={text} /> <ide> <Text text="Sibling" /> <ide> </ConcurrentMode> <del> </Placeholder> <add> </Suspense> <ide> ); <ide> } <ide> <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> function App() { <ide> return ( <ide> <StrictMode> <del> <Placeholder delayMs={1000} fallback={<Text text="Loading..." />}> <add> <Suspense <add> maxDuration={1000} <add> fallback={<Text text="Loading..." />}> <ide> <ConcurrentMode> <ide> <UpdatingText ref={text1} initialText="Async: 1"> <ide> {text => ( <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> )} <ide> </UpdatingText> <ide> </ConcurrentMode> <del> </Placeholder> <add> </Suspense> <ide> <ConcurrentMode> <ide> <UpdatingText ref={text2} initialText="Sync: 1"> <ide> {text => ( <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> function App() { <ide> return ( <ide> <Fragment> <del> <Placeholder delayMs={1000} fallback={<Text text="Loading..." />}> <add> <Suspense <add> maxDuration={1000} <add> fallback={<Text text="Loading..." />}> <ide> <ConcurrentMode> <ide> <UpdatingText ref={text1} initialText="Async: 1"> <ide> {text => ( <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> )} <ide> </UpdatingText> <ide> </ConcurrentMode> <del> </Placeholder> <add> </Suspense> <ide> <ConcurrentMode> <ide> <UpdatingText ref={text2} initialText="Sync: 1"> <ide> {text => ( <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> <ide> function App() { <ide> return ( <del> <Placeholder <del> delayMs={1000} <add> <Suspense <add> maxDuration={1000} <ide> fallback={<TextWithLifecycle text="Loading..." />}> <ide> <TextWithLifecycle text="A" /> <ide> <AsyncTextWithLifecycle ms={100} text="B" /> <ide> <TextWithLifecycle text="C" /> <del> </Placeholder> <add> </Suspense> <ide> ); <ide> } <ide> <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> } <ide> <ide> ReactNoop.renderLegacySyncRoot( <del> <Placeholder fallback={<Text text="Loading..." />}> <add> <Suspense fallback={<Text text="Loading..." />}> <ide> <AsyncTextInConstructor ms={100} text="Hi" /> <del> </Placeholder>, <add> </Suspense>, <ide> ); <ide> <ide> expect(ReactNoop.getChildren()).toEqual([span('Loading...')]); <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> class Demo extends React.Component { <ide> render() { <ide> return ( <del> <Placeholder fallback={<Fallback />}> <add> <Suspense fallback={<Fallback />}> <ide> <AsyncText text="Hi" ms={100} /> <del> </Placeholder> <add> </Suspense> <ide> ); <ide> } <ide> } <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> const LazyText = Promise.resolve(Text); <ide> <ide> ReactNoop.render( <del> <Placeholder fallback={<Text text="Loading..." />}> <add> <Suspense fallback={<Text text="Loading..." />}> <ide> <LazyText text="Hi" /> <del> </Placeholder>, <add> </Suspense>, <ide> ); <ide> expect(ReactNoop.flush()).toEqual(['Loading...']); <ide> expect(ReactNoop.getChildren()).toEqual([]); <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> <ide> // Should not suspend on update <ide> ReactNoop.render( <del> <Placeholder fallback={<Text text="Loading..." />}> <add> <Suspense fallback={<Text text="Loading..." />}> <ide> <LazyText text="Hi again" /> <del> </Placeholder>, <add> </Suspense>, <ide> ); <ide> expect(ReactNoop.flush()).toEqual(['Hi again']); <ide> expect(ReactNoop.getChildren()).toEqual([span('Hi again')]); <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> const LazyText = Promise.reject(new Error('Bad network')); <ide> <ide> ReactNoop.render( <del> <Placeholder fallback={<Text text="Loading..." />}> <add> <Suspense fallback={<Text text="Loading..." />}> <ide> <LazyText text="Hi" /> <del> </Placeholder>, <add> </Suspense>, <ide> ); <ide> expect(ReactNoop.flush()).toEqual(['Loading...']); <ide> <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> <ide> function Parent({swap}) { <ide> return ( <del> <Placeholder fallback={<Text text="Loading..." />}> <add> <Suspense fallback={<Text text="Loading..." />}> <ide> {swap <ide> ? [ <ide> <LazyChildB key="B" label="B" />, <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> <LazyChildA key="A" label="A" />, <ide> <LazyChildB key="B" label="B" />, <ide> ]} <del> </Placeholder> <add> </Suspense> <ide> ); <ide> } <ide> <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> const LazyText = Promise.resolve({default: Text}); <ide> <ide> ReactNoop.render( <del> <Placeholder fallback={<Text text="Loading..." />}> <add> <Suspense fallback={<Text text="Loading..." />}> <ide> <LazyText text="Hi" /> <del> </Placeholder>, <add> </Suspense>, <ide> ); <ide> expect(ReactNoop.flush()).toEqual(['Loading...']); <ide> expect(ReactNoop.getChildren()).toEqual([]); <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> <ide> // Should not suspend on update <ide> ReactNoop.render( <del> <Placeholder fallback={<Text text="Loading..." />}> <add> <Suspense fallback={<Text text="Loading..." />}> <ide> <LazyText text="Hi again" /> <del> </Placeholder>, <add> </Suspense>, <ide> ); <ide> expect(ReactNoop.flush()).toEqual(['Hi again']); <ide> expect(ReactNoop.getChildren()).toEqual([span('Hi again')]); <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> const LazyText = Promise.resolve(T); <ide> <ide> ReactNoop.render( <del> <Placeholder fallback={<Text text="Loading..." />}> <add> <Suspense fallback={<Text text="Loading..." />}> <ide> <LazyText /> <del> </Placeholder>, <add> </Suspense>, <ide> ); <ide> expect(ReactNoop.flush()).toEqual(['Loading...']); <ide> expect(ReactNoop.getChildren()).toEqual([]); <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> T.defaultProps = {text: 'Hi again'}; <ide> <ide> ReactNoop.render( <del> <Placeholder fallback={<Text text="Loading..." />}> <add> <Suspense fallback={<Text text="Loading..." />}> <ide> <LazyText text="Hi again" /> <del> </Placeholder>, <add> </Suspense>, <ide> ); <ide> expect(ReactNoop.flush()).toEqual(['Hi again']); <ide> expect(ReactNoop.getChildren()).toEqual([span('Hi again')]); <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> <ide> const stateful = React.createRef(null); <ide> ReactNoop.render( <del> <Placeholder fallback={<Text text="Loading..." />}> <add> <Suspense fallback={<Text text="Loading..." />}> <ide> <Lazy> <ide> <Stateful ref={stateful} /> <ide> </Lazy> <del> </Placeholder>, <add> </Suspense>, <ide> ); <ide> expect(ReactNoop.flush()).toEqual(['Loading...']); <ide> expect(ReactNoop.getChildren()).toEqual([]); <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> }); <ide> <ide> ReactNoop.render( <del> <Placeholder fallback={<Text text="Loading..." />}> <add> <Suspense fallback={<Text text="Loading..." />}> <ide> <Text text="A" /> <ide> <Text text="B" /> <ide> <LazyText text="C" /> <del> </Placeholder>, <add> </Suspense>, <ide> ); <ide> // Render first two siblings. The lazy component should not have <ide> // started loading yet. <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> }); <ide> <ide> ReactNoop.render( <del> <Placeholder fallback={<Text text="Loading..." />}> <add> <Suspense fallback={<Text text="Loading..." />}> <ide> <LazyFoo /> <del> </Placeholder>, <add> </Suspense>, <ide> ); <ide> expect(ReactNoop.flush()).toEqual(['Started loading', 'Loading...']); <ide> expect(ReactNoop.getChildren()).toEqual([]); <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> <ide> const ref = React.createRef(); <ide> ReactNoop.render( <del> <Placeholder fallback={<Text text="Loading..." />}> <add> <Suspense fallback={<Text text="Loading..." />}> <ide> <LazyClass /> <ide> <LazyForwardRef ref={ref} /> <del> </Placeholder>, <add> </Suspense>, <ide> ); <ide> expect(ReactNoop.flush()).toEqual(['Loading...']); <ide> expect(ReactNoop.getChildren()).toEqual([]); <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> <ide> function App() { <ide> return ( <del> <Placeholder <del> delayMs={1000} <add> <Suspense <add> maxDuration={1000} <ide> fallback={<TextWithLifecycle text="Loading..." />}> <ide> <TextWithLifecycle text="A" /> <ide> <AsyncTextWithLifecycle ms={100} text="B" /> <ide> <TextWithLifecycle text="C" /> <del> </Placeholder> <add> </Suspense> <ide> ); <ide> } <ide> <ide><path>packages/react/src/React.js <ide> import { <ide> REACT_FRAGMENT_TYPE, <ide> REACT_PROFILER_TYPE, <ide> REACT_STRICT_MODE_TYPE, <del> REACT_PLACEHOLDER_TYPE, <add> REACT_SUSPENSE_TYPE, <ide> } from 'shared/ReactSymbols'; <del>import {enableSuspense} from 'shared/ReactFeatureFlags'; <ide> <ide> import {Component, PureComponent} from './ReactBaseClasses'; <ide> import {createRef} from './ReactCreateRef'; <ide> const React = { <ide> <ide> createContext, <ide> forwardRef, <add> lazy, <ide> pure, <ide> <ide> Fragment: REACT_FRAGMENT_TYPE, <ide> StrictMode: REACT_STRICT_MODE_TYPE, <ide> unstable_ConcurrentMode: REACT_CONCURRENT_MODE_TYPE, <add> unstable_Suspense: REACT_SUSPENSE_TYPE, <ide> unstable_Profiler: REACT_PROFILER_TYPE, <ide> <ide> createElement: __DEV__ ? createElementWithValidation : createElement, <ide> const React = { <ide> __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: ReactSharedInternals, <ide> }; <ide> <del>if (enableSuspense) { <del> React.Placeholder = REACT_PLACEHOLDER_TYPE; <del> React.lazy = lazy; <del>} <del> <ide> export default React; <ide><path>packages/react/src/__tests__/ReactProfiler-test.internal.js <ide> let AdvanceTime; <ide> <ide> function loadModules({ <ide> enableProfilerTimer = true, <del> enableSuspense = false, <ide> enableSchedulerTracing = true, <ide> replayFailedUnitOfWorkWithInvokeGuardedCallback = false, <ide> useNoopRenderer = false, <ide> function loadModules({ <ide> ReactFeatureFlags.debugRenderPhaseSideEffectsForStrictMode = false; <ide> ReactFeatureFlags.enableProfilerTimer = enableProfilerTimer; <ide> ReactFeatureFlags.enableSchedulerTracing = enableSchedulerTracing; <del> ReactFeatureFlags.enableSuspense = enableSuspense; <ide> ReactFeatureFlags.replayFailedUnitOfWorkWithInvokeGuardedCallback = replayFailedUnitOfWorkWithInvokeGuardedCallback; <ide> <ide> React = require('react'); <ide> describe('Profiler', () => { <ide> jest.resetModules(); <ide> <ide> loadModules({ <del> enableSuspense: true, <ide> enableSchedulerTracing: true, <ide> ...params, <ide> }); <ide> describe('Profiler', () => { <ide> SchedulerTracing.unstable_trace(interaction.name, mockNow(), () => { <ide> ReactNoop.render( <ide> <React.unstable_Profiler id="test-profiler" onRender={onRender}> <del> <React.Placeholder fallback={<Text text="Loading..." />}> <add> <React.unstable_Suspense fallback={<Text text="Loading..." />}> <ide> <AsyncText text="Async" ms={20000} /> <del> </React.Placeholder> <add> </React.unstable_Suspense> <ide> <Text text="Sync" /> <ide> <Monkey ref={monkey} /> <ide> </React.unstable_Profiler>, <ide> describe('Profiler', () => { <ide> () => { <ide> ReactTestRenderer.create( <ide> <React.unstable_Profiler id="app" onRender={onRender}> <del> <React.Placeholder <del> delayMs={1000} <add> <React.unstable_Suspense <add> maxDuration={1000} <ide> fallback={<Text text="loading" />}> <ide> <AsyncText text="loaded" ms={2000} /> <del> </React.Placeholder> <add> </React.unstable_Suspense> <ide> </React.unstable_Profiler>, <ide> ); <ide> }, <ide> describe('Profiler', () => { <ide> () => { <ide> ReactTestRenderer.create( <ide> <React.unstable_Profiler id="app" onRender={onRender}> <del> <React.Placeholder <del> delayMs={1000} <add> <React.unstable_Suspense <add> maxDuration={1000} <ide> fallback={<Text text="loading" />}> <ide> <AsyncComponentWithCascadingWork text="loaded" ms={2000} /> <del> </React.Placeholder> <add> </React.unstable_Suspense> <ide> </React.unstable_Profiler>, <ide> ); <ide> }, <ide> describe('Profiler', () => { <ide> () => { <ide> renderer = ReactTestRenderer.create( <ide> <React.unstable_Profiler id="app" onRender={onRender}> <del> <React.Placeholder <del> delayMs={1000} <add> <React.unstable_Suspense <add> maxDuration={1000} <ide> fallback={<Text text="loading" />}> <ide> <AsyncText text="loaded" ms={2000} /> <del> </React.Placeholder> <add> </React.unstable_Suspense> <ide> </React.unstable_Profiler>, <ide> { <ide> unstable_isConcurrent: true, <ide> describe('Profiler', () => { <ide> () => { <ide> renderer = ReactTestRenderer.create( <ide> <React.unstable_Profiler id="app" onRender={onRender}> <del> <React.Placeholder <del> delayMs={2000} <add> <React.unstable_Suspense <add> maxDuration={2000} <ide> fallback={<Text text="loading" />}> <ide> <AsyncText text="loaded" ms={1000} /> <del> </React.Placeholder> <add> </React.unstable_Suspense> <ide> </React.unstable_Profiler>, <ide> {unstable_isConcurrent: true}, <ide> ); <ide> describe('Profiler', () => { <ide> () => { <ide> renderer = ReactTestRenderer.create( <ide> <React.unstable_Profiler id="app" onRender={onRender}> <del> <React.Placeholder <del> delayMs={2000} <add> <React.unstable_Suspense <add> maxDuration={2000} <ide> fallback={<Text text="loading" />}> <ide> <AsyncText text="loaded" ms={1000} /> <del> </React.Placeholder> <add> </React.unstable_Suspense> <ide> <Text text="initial" /> <ide> </React.unstable_Profiler>, <ide> ); <ide> describe('Profiler', () => { <ide> () => { <ide> renderer.update( <ide> <React.unstable_Profiler id="app" onRender={onRender}> <del> <React.Placeholder <del> delayMs={2000} <add> <React.unstable_Suspense <add> maxDuration={2000} <ide> fallback={<Text text="loading" />}> <ide> <AsyncText text="loaded" ms={1000} /> <del> </React.Placeholder> <add> </React.unstable_Suspense> <ide> <Text text="updated" /> <ide> </React.unstable_Profiler>, <ide> ); <ide> describe('Profiler', () => { <ide> () => { <ide> renderer = ReactTestRenderer.create( <ide> <React.unstable_Profiler id="app" onRender={onRender}> <del> <React.Placeholder <del> delayMs={2000} <add> <React.unstable_Suspense <add> maxDuration={2000} <ide> fallback={<Text text="loading" />}> <ide> <AsyncText text="loaded" ms={1000} /> <del> </React.Placeholder> <add> </React.unstable_Suspense> <ide> <Text text="initial" /> <ide> </React.unstable_Profiler>, <ide> {unstable_isConcurrent: true}, <ide> describe('Profiler', () => { <ide> () => { <ide> renderer.update( <ide> <React.unstable_Profiler id="app" onRender={onRender}> <del> <React.Placeholder <del> delayMs={2000} <add> <React.unstable_Suspense <add> maxDuration={2000} <ide> fallback={<Text text="loading" />}> <ide> <AsyncText text="loaded" ms={1000} /> <del> </React.Placeholder> <add> </React.unstable_Suspense> <ide> <Text text="updated" /> <ide> </React.unstable_Profiler>, <ide> ); <ide><path>packages/react/src/__tests__/ReactProfilerDOM-test.internal.js <ide> function loadModules() { <ide> ReactFeatureFlags.debugRenderPhaseSideEffectsForStrictMode = false; <ide> ReactFeatureFlags.enableProfilerTimer = true; <ide> ReactFeatureFlags.enableSchedulerTracing = true; <del> ReactFeatureFlags.enableSuspense = true; <ide> <ide> React = require('react'); <ide> SchedulerTracing = require('scheduler/tracing'); <ide> describe('ProfilerDOM', () => { <ide> const root = ReactDOM.unstable_createRoot(element); <ide> batch = root.createBatch(); <ide> batch.render( <del> <React.Placeholder delayMS={100} fallback={<Text text="Loading..." />}> <add> <React.unstable_Suspense <add> maxDuration={100} <add> fallback={<Text text="Loading..." />}> <ide> <AsyncText text="Text" ms={200} /> <del> </React.Placeholder>, <add> </React.unstable_Suspense>, <ide> ); <ide> batch.then( <ide> SchedulerTracing.unstable_wrap(() => { <ide><path>packages/shared/ReactFeatureFlags.js <ide> * @flow strict <ide> */ <ide> <del>// Exports ReactDOM.createRoot <ide> export const enableUserTimingAPI = __DEV__; <ide> <del>// Suspense <del>export const enableSuspense = false; <ide> // Helps identify side effects in begin-phase lifecycle hooks and setState reducers: <ide> export const debugRenderPhaseSideEffects = false; <ide> <ide><path>packages/shared/ReactSymbols.js <ide> export const REACT_CONCURRENT_MODE_TYPE = hasSymbol <ide> export const REACT_FORWARD_REF_TYPE = hasSymbol <ide> ? Symbol.for('react.forward_ref') <ide> : 0xead0; <del>export const REACT_PLACEHOLDER_TYPE = hasSymbol <del> ? Symbol.for('react.placeholder') <add>export const REACT_SUSPENSE_TYPE = hasSymbol <add> ? Symbol.for('react.suspense') <ide> : 0xead1; <ide> export const REACT_PURE_TYPE = hasSymbol ? Symbol.for('react.pure') : 0xead3; <ide> <ide><path>packages/shared/ReactWorkTags.js <ide> export const ContextProvider = 12; <ide> export const ForwardRef = 13; <ide> export const ForwardRefLazy = 14; <ide> export const Profiler = 15; <del>export const PlaceholderComponent = 16; <add>export const SuspenseComponent = 16; <ide> export const PureComponent = 17; <ide> export const PureComponentLazy = 18; <ide><path>packages/shared/forks/ReactFeatureFlags.native-fabric-fb.js <ide> import typeof * as FabricFeatureFlagsType from './ReactFeatureFlags.native-fabri <ide> export const debugRenderPhaseSideEffects = false; <ide> export const debugRenderPhaseSideEffectsForStrictMode = false; <ide> export const enableUserTimingAPI = __DEV__; <del>export const enableSuspense = false; <ide> export const warnAboutDeprecatedLifecycles = false; <ide> export const replayFailedUnitOfWorkWithInvokeGuardedCallback = __DEV__; <ide> export const enableProfilerTimer = __PROFILE__; <ide><path>packages/shared/forks/ReactFeatureFlags.native-fabric-oss.js <ide> import typeof * as FabricFeatureFlagsType from './ReactFeatureFlags.native-fabri <ide> export const debugRenderPhaseSideEffects = false; <ide> export const debugRenderPhaseSideEffectsForStrictMode = false; <ide> export const enableUserTimingAPI = __DEV__; <del>export const enableSuspense = false; <ide> export const warnAboutDeprecatedLifecycles = false; <ide> export const replayFailedUnitOfWorkWithInvokeGuardedCallback = __DEV__; <ide> export const enableProfilerTimer = __PROFILE__; <ide><path>packages/shared/forks/ReactFeatureFlags.native-fb.js <ide> import typeof * as FeatureFlagsShimType from './ReactFeatureFlags.native-fb'; <ide> <ide> // Re-export dynamic flags from the fbsource version. <ide> export const { <del> enableSuspense, <ide> debugRenderPhaseSideEffects, <ide> debugRenderPhaseSideEffectsForStrictMode, <ide> warnAboutDeprecatedLifecycles, <ide><path>packages/shared/forks/ReactFeatureFlags.native-oss.js <ide> import typeof * as FeatureFlagsShimType from './ReactFeatureFlags.native-oss'; <ide> <ide> export const debugRenderPhaseSideEffects = false; <ide> export const debugRenderPhaseSideEffectsForStrictMode = false; <del>export const enableSuspense = false; <ide> export const enableUserTimingAPI = __DEV__; <ide> export const replayFailedUnitOfWorkWithInvokeGuardedCallback = __DEV__; <ide> export const warnAboutDeprecatedLifecycles = false; <ide><path>packages/shared/forks/ReactFeatureFlags.persistent.js <ide> import typeof * as PersistentFeatureFlagsType from './ReactFeatureFlags.persiste <ide> export const debugRenderPhaseSideEffects = false; <ide> export const debugRenderPhaseSideEffectsForStrictMode = false; <ide> export const enableUserTimingAPI = __DEV__; <del>export const enableSuspense = false; <ide> export const warnAboutDeprecatedLifecycles = false; <ide> export const replayFailedUnitOfWorkWithInvokeGuardedCallback = __DEV__; <ide> export const enableProfilerTimer = __PROFILE__; <ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.js <ide> import typeof * as PersistentFeatureFlagsType from './ReactFeatureFlags.persiste <ide> export const debugRenderPhaseSideEffects = false; <ide> export const debugRenderPhaseSideEffectsForStrictMode = false; <ide> export const enableUserTimingAPI = __DEV__; <del>export const enableSuspense = false; <ide> export const warnAboutDeprecatedLifecycles = false; <ide> export const replayFailedUnitOfWorkWithInvokeGuardedCallback = false; <ide> export const enableProfilerTimer = false; <ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.www.js <ide> import typeof * as PersistentFeatureFlagsType from './ReactFeatureFlags.persiste <ide> export const debugRenderPhaseSideEffects = false; <ide> export const debugRenderPhaseSideEffectsForStrictMode = false; <ide> export const enableUserTimingAPI = __DEV__; <del>export const enableSuspense = true; <ide> export const warnAboutDeprecatedLifecycles = false; <ide> export const replayFailedUnitOfWorkWithInvokeGuardedCallback = false; <ide> export const enableProfilerTimer = false; <ide><path>packages/shared/forks/ReactFeatureFlags.www.js <ide> import typeof * as FeatureFlagsShimType from './ReactFeatureFlags.www'; <ide> <ide> // Re-export dynamic flags from the www version. <ide> export const { <del> enableSuspense, <ide> debugRenderPhaseSideEffects, <ide> debugRenderPhaseSideEffectsForStrictMode, <ide> enableSuspenseServerRenderer, <ide><path>packages/shared/getComponentName.js <ide> import { <ide> REACT_PROFILER_TYPE, <ide> REACT_PROVIDER_TYPE, <ide> REACT_STRICT_MODE_TYPE, <del> REACT_PLACEHOLDER_TYPE, <add> REACT_SUSPENSE_TYPE, <ide> } from 'shared/ReactSymbols'; <ide> import {refineResolvedThenable} from 'shared/ReactLazyComponent'; <ide> <ide> function getComponentName(type: mixed): string | null { <ide> return `Profiler`; <ide> case REACT_STRICT_MODE_TYPE: <ide> return 'StrictMode'; <del> case REACT_PLACEHOLDER_TYPE: <del> return 'Placeholder'; <add> case REACT_SUSPENSE_TYPE: <add> return 'Suspense'; <ide> } <ide> if (typeof type === 'object') { <ide> switch (type.$$typeof) { <ide><path>packages/shared/isValidElementType.js <ide> import { <ide> REACT_PROFILER_TYPE, <ide> REACT_PROVIDER_TYPE, <ide> REACT_STRICT_MODE_TYPE, <del> REACT_PLACEHOLDER_TYPE, <add> REACT_SUSPENSE_TYPE, <ide> REACT_PURE_TYPE, <ide> } from 'shared/ReactSymbols'; <ide> <ide> export default function isValidElementType(type: mixed) { <ide> type === REACT_CONCURRENT_MODE_TYPE || <ide> type === REACT_PROFILER_TYPE || <ide> type === REACT_STRICT_MODE_TYPE || <del> type === REACT_PLACEHOLDER_TYPE || <add> type === REACT_SUSPENSE_TYPE || <ide> (typeof type === 'object' && <ide> type !== null && <ide> (typeof type.then === 'function' ||
30
PHP
PHP
implement parsed body methods
f79582299a20ddb4504a43b9e2d6fb2ea1b54d76
<ide><path>src/Network/Request.php <ide> public function withCookieParams(array $cookies) <ide> return $new; <ide> } <ide> <add> /** <add> * Get the parsed request body data. <add> * <add> * If the request Content-Type is either application/x-www-form-urlencoded <add> * or multipart/form-data, nd the request method is POST, this will be the <add> * post data. For other content types, it may be the deserialized request <add> * body. <add> * <add> * @return null|array|object The deserialized body parameters, if any. <add> * These will typically be an array or object. <add> */ <add> public function getParsedBody() <add> { <add> return $this->data; <add> } <add> <add> /** <add> * Update the parsed body and get a new instance. <add> * <add> * @param null|array|object $data The deserialized body data. This will <add> * typically be in an array or object. <add> * @return static <add> */ <add> public function withParsedBody($data) <add> { <add> $new = clone $this; <add> $new->data = $data; <add> return $new; <add> } <add> <ide> /** <ide> * Get/Set value from the request's environment data. <ide> * Fallback to using env() if key not set in $environment property. <ide><path>tests/TestCase/Network/RequestTest.php <ide> public function testWithParam() <ide> $this->assertSame('Admin', $result->param('prefix')); <ide> } <ide> <add> /** <add> * Test getting the parsed body parameters. <add> * <add> * @return void <add> */ <add> public function testGetParsedBody() <add> { <add> $data = ['title' => 'First', 'body' => 'Best Article!']; <add> $request = new Request(['post' => $data]); <add> $this->assertSame($data, $request->getParsedBody()); <add> <add> $request = new Request(); <add> $this->assertSame([], $request->getParsedBody()); <add> } <add> <add> /** <add> * Test replacing the parsed body parameters. <add> * <add> * @return void <add> */ <add> public function testWithParsedBody() <add> { <add> $data = ['title' => 'First', 'body' => 'Best Article!']; <add> $request = new Request([]); <add> $new = $request->withParsedBody($data); <add> <add> $this->assertNotSame($request, $new); <add> $this->assertSame([], $request->getParsedBody()); <add> $this->assertSame($data, $new->getParsedBody()); <add> } <add> <ide> /** <ide> * Test updating POST data in a psr7 fashion. <ide> *
2
Javascript
Javascript
use passive events where possible
d584fcdc6e10b9f4d4e9eec775731e7ffc0fb501
<ide><path>packages/react-events/src/Press.js <ide> const targetEventTypes = [ <ide> 'pointerdown', <ide> 'pointercancel', <ide> ]; <del>const rootEventTypes = [ <del> {name: 'keyup', passive: false}, <del> {name: 'pointerup', passive: false}, <del> 'pointermove', <del> 'scroll', <del>]; <add>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) {
1
PHP
PHP
fix bug with assigning middleware
a75a9cdadac503b7c2d6e03ccd5d67b38d25d6fc
<ide><path>src/Illuminate/Routing/Route.php <ide> public function middleware($middleware = null) <ide> $middleware = [$middleware]; <ide> } <ide> <del> $this->action['middleware'] = array_merge($this->action['middleware'], $middleware); <add> $this->action['middleware'] = array_merge( <add> array_get($this->action['middleware'], []), $middleware <add> ); <ide> <ide> return $this; <ide> }
1
Python
Python
fix regularization in embedding
e8a6ae298d7fdbd5ad4e5fe25c2d5ff82d0178a3
<ide><path>keras/layers/embeddings.py <ide> class Embedding(Layer): <ide> @input_dim: size of vocabulary (highest input integer + 1) <ide> @out_dim: size of dense representation <ide> ''' <del> def __init__(self, input_dim, output_dim, init='uniform', weights=None, W_regularizer=None, W_constraint=None, mask_zero=False): <add> def __init__(self, input_dim, output_dim, init='uniform', <add> W_regularizer=None, activity_regularizer=None, W_constraint=None, <add> mask_zero=False, weights=None): <add> <ide> super(Embedding,self).__init__() <ide> self.init = initializations.get(init) <ide> self.input_dim = input_dim <ide> def __init__(self, input_dim, output_dim, init='uniform', weights=None, W_regula <ide> <ide> self.params = [self.W] <ide> self.constraints = [W_constraint] <del> self.regularizers = [W_regularizer] <add> <add> self.regularizers = [] <add> if W_regularizer: <add> W_regularizer.set_param(self.W) <add> self.regularizers.append(W_regularizer) <add> if activity_regularizer: <add> activity_regularizer.set_layer(self) <add> self.regularizers.append(activity_regularizer) <ide> <ide> if weights is not None: <ide> self.set_weights(weights) <ide><path>keras/models.py <ide> def compile(self, optimizer, loss, class_mode="categorical", theano_mode=None): <ide> <ide> train_loss = self.loss(self.y, self.y_train, self.weights) <ide> test_score = self.loss(self.y, self.y_test, self.weights) <del> <ide> <ide> if class_mode == "categorical": <ide> train_accuracy = T.mean(T.eq(T.argmax(self.y, axis=-1), T.argmax(self.y_train, axis=-1)))
2
Javascript
Javascript
add inline cache to processmoduledependencies
c9f7567f1207813f5c61237af588f2d3d2dcb5cb
<ide><path>lib/Compilation.js <ide> class Compilation { <ide> <ide> let currentBlock = module; <ide> <add> let factoryCacheKey; <add> let factoryCacheValue; <add> let listCacheKey; <add> let listCacheValue; <add> <ide> const processDependency = dep => { <ide> this.moduleGraph.setParents(dep, currentBlock, module); <ide> const resourceIdent = dep.getResourceIdentifier(); <ide> if (resourceIdent) { <del> const factory = this.dependencyFactories.get(dep.constructor); <del> if (factory === undefined) { <del> throw new Error( <del> `No module factory available for dependency type: ${dep.constructor.name}` <del> ); <del> } <del> let innerMap = dependencies.get(factory); <del> if (innerMap === undefined) { <del> dependencies.set(factory, (innerMap = new Map())); <add> const constructor = dep.constructor; <add> let innerMap; <add> if (factoryCacheKey === constructor) { <add> innerMap = factoryCacheValue; <add> if (listCacheKey === resourceIdent) { <add> listCacheValue.push(dep); <add> return; <add> } <add> } else { <add> const factory = this.dependencyFactories.get(dep.constructor); <add> if (factory === undefined) { <add> throw new Error( <add> `No module factory available for dependency type: ${dep.constructor.name}` <add> ); <add> } <add> innerMap = dependencies.get(factory); <add> if (innerMap === undefined) { <add> dependencies.set(factory, (innerMap = new Map())); <add> } <add> factoryCacheKey = constructor; <add> factoryCacheValue = innerMap; <ide> } <ide> let list = innerMap.get(resourceIdent); <ide> if (list === undefined) innerMap.set(resourceIdent, (list = [])); <ide> list.push(dep); <add> listCacheKey = resourceIdent; <add> listCacheValue = list; <ide> } <ide> }; <ide> <ide> class Compilation { <ide> <ide> const sortedDependencies = []; <ide> <del> for (const pair1 of dependencies) { <del> for (const pair2 of pair1[1]) { <add> for (const [factory, innerMap] of dependencies) { <add> for (const dependencies of innerMap.values()) { <ide> sortedDependencies.push({ <del> factory: pair1[0], <del> dependencies: pair2[1] <add> factory, <add> dependencies, <add> originModule: module <ide> }); <ide> } <ide> } <ide> class Compilation { <ide> asyncLib.forEach( <ide> sortedDependencies, <ide> (item, callback) => { <del> this.handleModuleCreation( <del> { <del> factory: item.factory, <del> dependencies: item.dependencies, <del> originModule: module <del> }, <del> err => { <del> // In V8, the Error objects keep a reference to the functions on the stack. These warnings & <del> // errors are created inside closures that keep a reference to the Compilation, so errors are <del> // leaking the Compilation object. <del> if (err && this.bail) { <del> // eslint-disable-next-line no-self-assign <del> err.stack = err.stack; <del> return callback(err); <del> } <del> callback(); <add> this.handleModuleCreation(item, err => { <add> // In V8, the Error objects keep a reference to the functions on the stack. These warnings & <add> // errors are created inside closures that keep a reference to the Compilation, so errors are <add> // leaking the Compilation object. <add> if (err && this.bail) { <add> // eslint-disable-next-line no-self-assign <add> err.stack = err.stack; <add> return callback(err); <ide> } <del> ); <add> callback(); <add> }); <ide> }, <ide> err => { <ide> this.processDependenciesQueue.decreaseParallelism();
1
Python
Python
fix error message [ci skip]
9bdc9e81f5f8affe464d1ff3c6bc35c08aa2a0d6
<ide><path>spacy/cli/_util.py <ide> def load_project_config(path: Path) -> Dict[str, Any]: <ide> msg.fail(invalid_err, e, exits=1) <ide> errors = validate(ProjectConfigSchema, config) <ide> if errors: <del> msg.fail(invalid_err, "\n".join(errors), exits=1) <add> msg.fail(invalid_err) <add> print("\n".join(errors)) <add> sys.exit(1) <ide> validate_project_commands(config) <ide> # Make sure directories defined in config exist <ide> for subdir in config.get("directories", []):
1
Ruby
Ruby
use common terminology
279c3957237b049dead8d95db81ea1ff665ee78c
<ide><path>actionpack/lib/action_dispatch/middleware/flash.rb <ide> def flash <ide> <ide> # The flash provides a way to pass temporary objects between actions. Anything you place in the flash will be exposed <ide> # to the very next action and then cleared out. This is a great way of doing notices and alerts, such as a create <del> # action that sets <tt>flash[:notice] = "Successfully created"</tt> before redirecting to a display action that can <add> # action that sets <tt>flash[:notice] = "Post successfully created"</tt> before redirecting to a display action that can <ide> # then expose the flash to its template. Actually, that exposure is automatically done. Example: <ide> # <ide> # class PostsController < ActionController::Base <ide> # def create <ide> # # save post <del> # flash[:notice] = "Successfully created post" <add> # flash[:notice] = "Post successfully created" <ide> # redirect_to posts_path(@post) <ide> # end <ide> # <ide> def flash <ide> # Since the +notice+ and +alert+ keys are a common idiom, convenience accessors are available: <ide> # <ide> # flash.alert = "You must be logged in" <del> # flash.notice = "Successfully created post" <add> # flash.notice = "Post successfully created" <ide> # <ide> # This example just places a string in the flash, but you can put any object in there. And of course, you can put as <ide> # many as you like at a time too. Just remember: They'll be gone by the time the next action has been performed.
1
Javascript
Javascript
open universal nav links on the same tab
2c3de17c746bdb9884af52da21af062b8f17ab31
<ide><path>client/src/components/Header/components/NavLinks.js <ide> function NavLinks({ displayMenu }) { <ide> role='menu' <ide> > <ide> <li className='nav-news' role='menuitem'> <del> <Link external={true} to='/news'> <add> <Link external={true} sameTab={true} to='/news'> <ide> /news <ide> </Link> <ide> </li> <ide> <li className='nav-forum' role='menuitem'> <del> <Link external={true} to='/forum'> <add> <Link external={true} sameTab={true} to='/forum'> <ide> /forum <ide> </Link> <ide> </li> <ide><path>client/src/components/helpers/Link.js <ide> import { Link as GatsbyLink } from 'gatsby'; <ide> const propTypes = { <ide> children: PropTypes.any, <ide> external: PropTypes.bool, <add> sameTab: PropTypes.bool, <ide> to: PropTypes.string.isRequired <ide> }; <ide> <del>const Link = ({ children, to, external, ...other }) => { <add>const Link = ({ children, to, external, sameTab, ...other }) => { <ide> if (!external && /^\/(?!\/)/.test(to)) { <ide> return ( <ide> <GatsbyLink to={to} {...other}> <ide> {children} <ide> </GatsbyLink> <ide> ); <add> } else if (sameTab && external) { <add> return ( <add> <a href={to} {...other}> <add> {children} <add> </a> <add> ); <ide> } <ide> <ide> return (
2
Python
Python
add depthwise conv2d for theano and cntk
cdbe1542d7b694d96e428fcba340fa82bc4cc8e5
<ide><path>keras/applications/mobilenet.py <ide> from ..layers import GlobalAveragePooling2D <ide> from ..layers import GlobalMaxPooling2D <ide> from ..layers import Conv2D <add>from ..layers import DepthwiseConv2D <ide> from .. import initializers <ide> from .. import regularizers <ide> from .. import constraints <ide> def preprocess_input(x): <ide> return imagenet_utils.preprocess_input(x, mode='tf') <ide> <ide> <del>class DepthwiseConv2D(Conv2D): <del> """Depthwise separable 2D convolution. <del> <del> Depthwise Separable convolutions consists in performing <del> just the first step in a depthwise spatial convolution <del> (which acts on each input channel separately). <del> The `depth_multiplier` argument controls how many <del> output channels are generated per input channel in the depthwise step. <del> <del> # Arguments <del> kernel_size: An integer or tuple/list of 2 integers, specifying the <del> width and height of the 2D convolution window. <del> Can be a single integer to specify the same value for <del> all spatial dimensions. <del> strides: An integer or tuple/list of 2 integers, <del> specifying the strides of the convolution along the width and height. <del> Can be a single integer to specify the same value for <del> all spatial dimensions. <del> Specifying any stride value != 1 is incompatible with specifying <del> any `dilation_rate` value != 1. <del> padding: one of `'valid'` or `'same'` (case-insensitive). <del> depth_multiplier: The number of depthwise convolution output channels <del> for each input channel. <del> The total number of depthwise convolution output <del> channels will be equal to `filters_in * depth_multiplier`. <del> data_format: A string, <del> one of `channels_last` (default) or `channels_first`. <del> The ordering of the dimensions in the inputs. <del> `channels_last` corresponds to inputs with shape <del> `(batch, height, width, channels)` while `channels_first` <del> corresponds to inputs with shape <del> `(batch, channels, height, width)`. <del> It defaults to the `image_data_format` value found in your <del> Keras config file at `~/.keras/keras.json`. <del> If you never set it, then it will be 'channels_last'. <del> activation: Activation function to use <del> (see [activations](../activations.md)). <del> If you don't specify anything, no activation is applied <del> (ie. 'linear' activation: `a(x) = x`). <del> use_bias: Boolean, whether the layer uses a bias vector. <del> depthwise_initializer: Initializer for the depthwise kernel matrix <del> (see [initializers](../initializers.md)). <del> bias_initializer: Initializer for the bias vector <del> (see [initializers](../initializers.md)). <del> depthwise_regularizer: Regularizer function applied to <del> the depthwise kernel matrix <del> (see [regularizer](../regularizers.md)). <del> bias_regularizer: Regularizer function applied to the bias vector <del> (see [regularizer](../regularizers.md)). <del> activity_regularizer: Regularizer function applied to <del> the output of the layer (its 'activation'). <del> (see [regularizer](../regularizers.md)). <del> depthwise_constraint: Constraint function applied to <del> the depthwise kernel matrix <del> (see [constraints](../constraints.md)). <del> bias_constraint: Constraint function applied to the bias vector <del> (see [constraints](../constraints.md)). <del> <del> # Input shape <del> 4D tensor with shape: <del> `[batch, channels, rows, cols]` if data_format='channels_first' <del> or 4D tensor with shape: <del> `[batch, rows, cols, channels]` if data_format='channels_last'. <del> <del> # Output shape <del> 4D tensor with shape: <del> `[batch, filters, new_rows, new_cols]` if data_format='channels_first' <del> or 4D tensor with shape: <del> `[batch, new_rows, new_cols, filters]` if data_format='channels_last'. <del> `rows` and `cols` values might have changed due to padding. <del> """ <del> <del> def __init__(self, <del> kernel_size, <del> strides=(1, 1), <del> padding='valid', <del> depth_multiplier=1, <del> data_format=None, <del> activation=None, <del> use_bias=True, <del> depthwise_initializer='glorot_uniform', <del> bias_initializer='zeros', <del> depthwise_regularizer=None, <del> bias_regularizer=None, <del> activity_regularizer=None, <del> depthwise_constraint=None, <del> bias_constraint=None, <del> **kwargs): <del> super(DepthwiseConv2D, self).__init__( <del> filters=None, <del> kernel_size=kernel_size, <del> strides=strides, <del> padding=padding, <del> data_format=data_format, <del> activation=activation, <del> use_bias=use_bias, <del> bias_regularizer=bias_regularizer, <del> activity_regularizer=activity_regularizer, <del> bias_constraint=bias_constraint, <del> **kwargs) <del> self.depth_multiplier = depth_multiplier <del> self.depthwise_initializer = initializers.get(depthwise_initializer) <del> self.depthwise_regularizer = regularizers.get(depthwise_regularizer) <del> self.depthwise_constraint = constraints.get(depthwise_constraint) <del> self.bias_initializer = initializers.get(bias_initializer) <del> <del> def build(self, input_shape): <del> if len(input_shape) < 4: <del> raise ValueError('Inputs to `DepthwiseConv2D` should have rank 4. ' <del> 'Received input shape:', str(input_shape)) <del> if self.data_format == 'channels_first': <del> channel_axis = 1 <del> else: <del> channel_axis = 3 <del> if input_shape[channel_axis] is None: <del> raise ValueError('The channel dimension of the inputs to ' <del> '`DepthwiseConv2D` ' <del> 'should be defined. Found `None`.') <del> input_dim = int(input_shape[channel_axis]) <del> depthwise_kernel_shape = (self.kernel_size[0], <del> self.kernel_size[1], <del> input_dim, <del> self.depth_multiplier) <del> <del> self.depthwise_kernel = self.add_weight( <del> shape=depthwise_kernel_shape, <del> initializer=self.depthwise_initializer, <del> name='depthwise_kernel', <del> regularizer=self.depthwise_regularizer, <del> constraint=self.depthwise_constraint) <del> <del> if self.use_bias: <del> self.bias = self.add_weight(shape=(input_dim * self.depth_multiplier,), <del> initializer=self.bias_initializer, <del> name='bias', <del> regularizer=self.bias_regularizer, <del> constraint=self.bias_constraint) <del> else: <del> self.bias = None <del> # Set input spec. <del> self.input_spec = InputSpec(ndim=4, axes={channel_axis: input_dim}) <del> self.built = True <del> <del> def call(self, inputs, training=None): <del> outputs = K.depthwise_conv2d( <del> inputs, <del> self.depthwise_kernel, <del> strides=self.strides, <del> padding=self.padding, <del> dilation_rate=self.dilation_rate, <del> data_format=self.data_format) <del> <del> if self.bias: <del> outputs = K.bias_add( <del> outputs, <del> self.bias, <del> data_format=self.data_format) <del> <del> if self.activation is not None: <del> return self.activation(outputs) <del> <del> return outputs <del> <del> def compute_output_shape(self, input_shape): <del> if self.data_format == 'channels_first': <del> rows = input_shape[2] <del> cols = input_shape[3] <del> out_filters = input_shape[1] * self.depth_multiplier <del> elif self.data_format == 'channels_last': <del> rows = input_shape[1] <del> cols = input_shape[2] <del> out_filters = input_shape[3] * self.depth_multiplier <del> <del> rows = conv_utils.conv_output_length(rows, self.kernel_size[0], <del> self.padding, <del> self.strides[0]) <del> cols = conv_utils.conv_output_length(cols, self.kernel_size[1], <del> self.padding, <del> self.strides[1]) <del> <del> if self.data_format == 'channels_first': <del> return (input_shape[0], out_filters, rows, cols) <del> elif self.data_format == 'channels_last': <del> return (input_shape[0], rows, cols, out_filters) <del> <del> def get_config(self): <del> config = super(DepthwiseConv2D, self).get_config() <del> config.pop('filters') <del> config.pop('kernel_initializer') <del> config.pop('kernel_regularizer') <del> config.pop('kernel_constraint') <del> config['depth_multiplier'] = self.depth_multiplier <del> config['depthwise_initializer'] = initializers.serialize(self.depthwise_initializer) <del> config['depthwise_regularizer'] = regularizers.serialize(self.depthwise_regularizer) <del> config['depthwise_constraint'] = constraints.serialize(self.depthwise_constraint) <del> return config <del> <del> <ide> def MobileNet(input_shape=None, <ide> alpha=1.0, <ide> depth_multiplier=1, <ide> def MobileNet(input_shape=None, <ide> classes=1000): <ide> """Instantiates the MobileNet architecture. <ide> <del> Note that only TensorFlow is supported for now, <del> therefore it only works with the data format <del> `image_data_format='channels_last'` in your Keras config <del> at `~/.keras/keras.json`. <del> <ide> To load a MobileNet model via `load_model`, import the custom <del> objects `relu6` and `DepthwiseConv2D` and pass them to the <del> `custom_objects` parameter. <add> objects `relu6` and pass them to the `custom_objects` parameter. <ide> E.g. <ide> model = load_model('mobilenet.h5', custom_objects={ <del> 'relu6': mobilenet.relu6, <del> 'DepthwiseConv2D': mobilenet.DepthwiseConv2D}) <add> 'relu6': mobilenet.relu6}) <ide> <ide> # Arguments <ide> input_shape: optional shape tuple, only to be specified <ide> def MobileNet(input_shape=None, <ide> backend that does not support separable convolutions. <ide> """ <ide> <del> if K.backend() != 'tensorflow': <del> raise RuntimeError('Only TensorFlow backend is currently supported, ' <del> 'as other backends do not support ' <del> 'depthwise convolution.') <del> <ide> if not (weights in {'imagenet', None} or os.path.exists(weights)): <ide> raise ValueError('The `weights` argument should be either ' <ide> '`None` (random initialization), `imagenet` ' <ide><path>keras/backend/cntk_backend.py <ide> def separable_conv2d(x, depthwise_kernel, pointwise_kernel, strides=(1, 1), <ide> <ide> def depthwise_conv2d(x, depthwise_kernel, strides=(1, 1), padding='valid', <ide> data_format=None, dilation_rate=(1, 1)): <del> raise NotImplementedError <add> if data_format is None: <add> data_format = image_data_format() <add> if data_format not in {'channels_first', 'channels_last'}: <add> raise ValueError('Unknown data_format ' + str(data_format)) <add> <add> x = _preprocess_conv2d_input(x, data_format) <add> depthwise_kernel = _preprocess_conv2d_kernel(depthwise_kernel, data_format) <add> depthwise_kernel = C.reshape(C.transpose(depthwise_kernel, (1, 0, 2, 3)), <add> (-1, 1) + depthwise_kernel.shape[2:]) <add> padding = _preprocess_border_mode(padding) <add> if dilation_rate == (1, 1): <add> strides = (1,) + strides <add> x = C.convolution(depthwise_kernel, x, <add> strides=strides, <add> auto_padding=[False, padding, padding], <add> groups=x.shape[0]) <add> else: <add> if dilation_rate[0] != dilation_rate[1]: <add> raise ValueError('CNTK Backend: non-square dilation_rate is ' <add> 'not supported.') <add> if strides != (1, 1): <add> raise ValueError('Invalid strides for dilated convolution') <add> x = C.convolution(depthwise_kernel, x, <add> strides=dilation_rate[0], <add> auto_padding=[False, padding, padding], <add> groups=x.shape[0]) <add> return _postprocess_conv2d_output(x, data_format) <ide> <ide> <ide> def conv3d(x, kernel, strides=(1, 1, 1), padding='valid', <ide><path>keras/backend/theano_backend.py <ide> def separable_conv2d(x, depthwise_kernel, pointwise_kernel, strides=(1, 1), <ide> <ide> def depthwise_conv2d(x, depthwise_kernel, strides=(1, 1), padding='valid', <ide> data_format=None, dilation_rate=(1, 1)): <del> raise NotImplementedError <add> """2D convolution with separable filters. <add> <add> # Arguments <add> x: input tensor <add> depthwise_kernel: convolution kernel for the depthwise convolution. <add> strides: strides tuple (length 2). <add> padding: string, `"same"` or `"valid"`. <add> data_format: string, `"channels_last"` or `"channels_first"`. <add> dilation_rate: tuple of integers, <add> dilation rates for the separable convolution. <add> <add> # Returns <add> Output tensor. <add> <add> # Raises <add> ValueError: if `data_format` is neither `"channels_last"` or `"channels_first"`. <add> """ <add> if data_format is None: <add> data_format = image_data_format() <add> if data_format not in {'channels_first', 'channels_last'}: <add> raise ValueError('Unknown data_format ', data_format) <add> <add> if hasattr(x, '_keras_shape'): <add> image_shape = _preprocess_conv2d_image_shape(int_shape(x), data_format) <add> else: <add> image_shape = None <add> if hasattr(depthwise_kernel, '_keras_shape'): <add> depthwise_kernel_shape = depthwise_kernel._keras_shape <add> else: <add> # Will only work if `kernel` is a shared variable. <add> depthwise_kernel_shape = depthwise_kernel.eval().shape <add> depthwise_kernel_shape = _preprocess_conv2d_filter_shape(depthwise_kernel_shape, data_format) <add> <add> x = _preprocess_conv2d_input(x, data_format) <add> depthwise_kernel = _preprocess_conv2d_kernel(depthwise_kernel, data_format) <add> th_padding = _preprocess_padding(padding) <add> <add> input_depth = depthwise_kernel_shape[1] <add> output_depth = depthwise_kernel_shape[0] <add> depthwise_kernel_shape = (input_depth * output_depth, 1) + depthwise_kernel_shape[2:] <add> depthwise_kernel = depthwise_kernel.dimshuffle((1, 0, 2, 3)) <add> depthwise_kernel = reshape(depthwise_kernel, depthwise_kernel_shape) <add> depthwise_kernel = depthwise_kernel[:, :, ::-1, ::-1] <add> <add> conv_out = T.nnet.conv2d(x, depthwise_kernel, <add> border_mode=th_padding, <add> subsample=strides, <add> input_shape=image_shape, <add> filter_shape=depthwise_kernel_shape, <add> filter_dilation=dilation_rate, <add> num_groups=input_depth) <add> conv_out = _postprocess_conv2d_output(conv_out, x, padding, <add> depthwise_kernel_shape, strides, data_format) <add> return conv_out <ide> <ide> <ide> def conv3d(x, kernel, strides=(1, 1, 1), <ide><path>keras/layers/convolutional.py <ide> def __init__(self, filters, <ide> **kwargs) <ide> <ide> <add>class DepthwiseConv2D(Conv2D): <add> """Depthwise separable 2D convolution. <add> <add> Depthwise Separable convolutions consists in performing <add> just the first step in a depthwise spatial convolution <add> (which acts on each input channel separately). <add> The `depth_multiplier` argument controls how many <add> output channels are generated per input channel in the depthwise step. <add> <add> # Arguments <add> kernel_size: An integer or tuple/list of 2 integers, specifying the <add> width and height of the 2D convolution window. <add> Can be a single integer to specify the same value for <add> all spatial dimensions. <add> strides: An integer or tuple/list of 2 integers, <add> specifying the strides of the convolution along the width and height. <add> Can be a single integer to specify the same value for <add> all spatial dimensions. <add> Specifying any stride value != 1 is incompatible with specifying <add> any `dilation_rate` value != 1. <add> padding: one of `'valid'` or `'same'` (case-insensitive). <add> depth_multiplier: The number of depthwise convolution output channels <add> for each input channel. <add> The total number of depthwise convolution output <add> channels will be equal to `filters_in * depth_multiplier`. <add> data_format: A string, <add> one of `channels_last` (default) or `channels_first`. <add> The ordering of the dimensions in the inputs. <add> `channels_last` corresponds to inputs with shape <add> `(batch, height, width, channels)` while `channels_first` <add> corresponds to inputs with shape <add> `(batch, channels, height, width)`. <add> It defaults to the `image_data_format` value found in your <add> Keras config file at `~/.keras/keras.json`. <add> If you never set it, then it will be 'channels_last'. <add> activation: Activation function to use <add> (see [activations](../activations.md)). <add> If you don't specify anything, no activation is applied <add> (ie. 'linear' activation: `a(x) = x`). <add> use_bias: Boolean, whether the layer uses a bias vector. <add> depthwise_initializer: Initializer for the depthwise kernel matrix <add> (see [initializers](../initializers.md)). <add> bias_initializer: Initializer for the bias vector <add> (see [initializers](../initializers.md)). <add> depthwise_regularizer: Regularizer function applied to <add> the depthwise kernel matrix <add> (see [regularizer](../regularizers.md)). <add> bias_regularizer: Regularizer function applied to the bias vector <add> (see [regularizer](../regularizers.md)). <add> activity_regularizer: Regularizer function applied to <add> the output of the layer (its 'activation'). <add> (see [regularizer](../regularizers.md)). <add> depthwise_constraint: Constraint function applied to <add> the depthwise kernel matrix <add> (see [constraints](../constraints.md)). <add> bias_constraint: Constraint function applied to the bias vector <add> (see [constraints](../constraints.md)). <add> <add> # Input shape <add> 4D tensor with shape: <add> `[batch, channels, rows, cols]` if data_format='channels_first' <add> or 4D tensor with shape: <add> `[batch, rows, cols, channels]` if data_format='channels_last'. <add> <add> # Output shape <add> 4D tensor with shape: <add> `[batch, filters, new_rows, new_cols]` if data_format='channels_first' <add> or 4D tensor with shape: <add> `[batch, new_rows, new_cols, filters]` if data_format='channels_last'. <add> `rows` and `cols` values might have changed due to padding. <add> """ <add> <add> def __init__(self, <add> kernel_size, <add> strides=(1, 1), <add> padding='valid', <add> depth_multiplier=1, <add> data_format=None, <add> activation=None, <add> use_bias=True, <add> depthwise_initializer='glorot_uniform', <add> bias_initializer='zeros', <add> depthwise_regularizer=None, <add> bias_regularizer=None, <add> activity_regularizer=None, <add> depthwise_constraint=None, <add> bias_constraint=None, <add> **kwargs): <add> super(DepthwiseConv2D, self).__init__( <add> filters=None, <add> kernel_size=kernel_size, <add> strides=strides, <add> padding=padding, <add> data_format=data_format, <add> activation=activation, <add> use_bias=use_bias, <add> bias_regularizer=bias_regularizer, <add> activity_regularizer=activity_regularizer, <add> bias_constraint=bias_constraint, <add> **kwargs) <add> self.depth_multiplier = depth_multiplier <add> self.depthwise_initializer = initializers.get(depthwise_initializer) <add> self.depthwise_regularizer = regularizers.get(depthwise_regularizer) <add> self.depthwise_constraint = constraints.get(depthwise_constraint) <add> self.bias_initializer = initializers.get(bias_initializer) <add> <add> def build(self, input_shape): <add> if len(input_shape) < 4: <add> raise ValueError('Inputs to `DepthwiseConv2D` should have rank 4. ' <add> 'Received input shape:', str(input_shape)) <add> if self.data_format == 'channels_first': <add> channel_axis = 1 <add> else: <add> channel_axis = 3 <add> if input_shape[channel_axis] is None: <add> raise ValueError('The channel dimension of the inputs to ' <add> '`DepthwiseConv2D` ' <add> 'should be defined. Found `None`.') <add> input_dim = int(input_shape[channel_axis]) <add> depthwise_kernel_shape = (self.kernel_size[0], <add> self.kernel_size[1], <add> input_dim, <add> self.depth_multiplier) <add> <add> self.depthwise_kernel = self.add_weight( <add> shape=depthwise_kernel_shape, <add> initializer=self.depthwise_initializer, <add> name='depthwise_kernel', <add> regularizer=self.depthwise_regularizer, <add> constraint=self.depthwise_constraint) <add> <add> if self.use_bias: <add> self.bias = self.add_weight(shape=(input_dim * self.depth_multiplier,), <add> initializer=self.bias_initializer, <add> name='bias', <add> regularizer=self.bias_regularizer, <add> constraint=self.bias_constraint) <add> else: <add> self.bias = None <add> # Set input spec. <add> self.input_spec = InputSpec(ndim=4, axes={channel_axis: input_dim}) <add> self.built = True <add> <add> def call(self, inputs, training=None): <add> outputs = K.depthwise_conv2d( <add> inputs, <add> self.depthwise_kernel, <add> strides=self.strides, <add> padding=self.padding, <add> dilation_rate=self.dilation_rate, <add> data_format=self.data_format) <add> <add> if self.bias: <add> outputs = K.bias_add( <add> outputs, <add> self.bias, <add> data_format=self.data_format) <add> <add> if self.activation is not None: <add> return self.activation(outputs) <add> <add> return outputs <add> <add> def compute_output_shape(self, input_shape): <add> if self.data_format == 'channels_first': <add> rows = input_shape[2] <add> cols = input_shape[3] <add> out_filters = input_shape[1] * self.depth_multiplier <add> elif self.data_format == 'channels_last': <add> rows = input_shape[1] <add> cols = input_shape[2] <add> out_filters = input_shape[3] * self.depth_multiplier <add> <add> rows = conv_utils.conv_output_length(rows, self.kernel_size[0], <add> self.padding, <add> self.strides[0]) <add> cols = conv_utils.conv_output_length(cols, self.kernel_size[1], <add> self.padding, <add> self.strides[1]) <add> if self.data_format == 'channels_first': <add> return (input_shape[0], out_filters, rows, cols) <add> elif self.data_format == 'channels_last': <add> return (input_shape[0], rows, cols, out_filters) <add> <add> def get_config(self): <add> config = super(DepthwiseConv2D, self).get_config() <add> config.pop('filters') <add> config.pop('kernel_initializer') <add> config.pop('kernel_regularizer') <add> config.pop('kernel_constraint') <add> config['depth_multiplier'] = self.depth_multiplier <add> config['depthwise_initializer'] = initializers.serialize(self.depthwise_initializer) <add> config['depthwise_regularizer'] = regularizers.serialize(self.depthwise_regularizer) <add> config['depthwise_constraint'] = constraints.serialize(self.depthwise_constraint) <add> return config <add> <add> <ide> class UpSampling1D(Layer): <ide> """Upsampling layer for 1D inputs. <ide> <ide><path>tests/keras/applications/applications_test.py <ide> def test_inceptionresnetv2(): <ide> _test_app_pooling(app, last_dim) <ide> <ide> <del>@pytest.mark.skipif((K.backend() != 'tensorflow'), <del> reason='MobileNets are supported only on TensorFlow') <ide> def test_mobilenet(): <ide> app = applications.MobileNet <ide> last_dim = 1024 <ide><path>tests/keras/backend/backend_test.py <ide> def test_conv2d(self): <ide> with pytest.raises(ValueError): <ide> k.conv2d(k.variable(xval), k.variable(kernel_val), data_format='channels_middle') <ide> <add> def test_depthwise_conv_2d(self): <add> # TF kernel shape: (rows, cols, input_depth, depth_multiplier) <add> # channels_first input shape: (n, input_depth, rows, cols) <add> for (input_shape, kernel_shape, data_format) in [ <add> ((2, 3, 4, 5), (2, 2, 3, 4), 'channels_first'), <add> ((2, 3, 5, 6), (4, 3, 3, 4), 'channels_first'), <add> ((1, 6, 5, 3), (3, 3, 3, 2), 'channels_last')]: <add> check_two_tensor_operation('depthwise_conv2d', <add> input_shape, kernel_shape, <add> BACKENDS, cntk_dynamicity=True, <add> data_format=data_format) <add> <add> # Test invalid use cases <add> for k in BACKENDS: <add> with pytest.raises(ValueError): <add> k.depthwise_conv2d(k.variable(np.ones(input_shape)), <add> k.variable(np.ones(kernel_shape)), <add> data_format='channels_middle') <add> <ide> def test_conv3d(self): <ide> # TH input shape: (samples, input_depth, conv_dim1, conv_dim2, conv_dim3) <ide> # TF input shape: (samples, conv_dim1, conv_dim2, conv_dim3, input_depth) <ide> def test_depthwise_conv_2d(self, k): <ide> for z_i in np.split(z, 6, axis=1 if data_format == 'channels_first' else -1): <ide> assert_allclose(z_i, z_i[0] * np.ones_like(z_i)) <ide> <del> # Test invalid use cases <del> with pytest.raises(ValueError): <del> k.depthwise_conv2d(k.variable(x_val), k.variable(kernel_val), data_format='channels_middle') <del> <ide> def test_pool2d(self): <ide> check_single_tensor_operation('pool2d', (5, 10, 12, 3), <ide> BACKENDS, cntk_dynamicity=True, <ide><path>tests/keras/layers/convolutional_test.py <ide> def test_separable_conv_2d(): <ide> batch_input_shape=(None, None, 5, None))]) <ide> <ide> <add>@keras_test <add>def test_depthwise_conv_2d(): <add> num_samples = 2 <add> stack_size = 3 <add> num_row = 7 <add> num_col = 6 <add> <add> for padding in _convolution_paddings: <add> for strides in [(1, 1), (2, 2)]: <add> for multiplier in [1, 2]: <add> if padding == 'same' and strides != (1, 1): <add> continue <add> <add> layer_test(convolutional.DepthwiseConv2D, <add> kwargs={'kernel_size': (3, 3), <add> 'padding': padding, <add> 'strides': strides, <add> 'depth_multiplier': multiplier}, <add> input_shape=(num_samples, <add> num_row, <add> num_col, <add> stack_size)) <add> <add> layer_test(convolutional.DepthwiseConv2D, <add> kwargs={'kernel_size': 3, <add> 'padding': padding, <add> 'data_format': 'channels_first', <add> 'activation': None, <add> 'depthwise_regularizer': 'l2', <add> 'bias_regularizer': 'l2', <add> 'activity_regularizer': 'l2', <add> 'depthwise_constraint': 'unit_norm', <add> 'strides': strides, <add> 'depth_multiplier': multiplier}, <add> input_shape=(num_samples, stack_size, num_row, num_col)) <add> <add> # Test invalid use case <add> with pytest.raises(ValueError): <add> Sequential([convolutional.DepthwiseConv2D( <add> kernel_size=3, <add> padding=padding, <add> batch_input_shape=(None, None, 5, None))]) <add> <add> <ide> @keras_test <ide> def test_globalpooling_1d(): <ide> layer_test(pooling.GlobalMaxPooling1D,
7
PHP
PHP
fix cs issues
7c95d16df8006e3fb95e0a2591c17fb02b6a0d8c
<ide><path>tests/TestCase/Core/Retry/CommandRetryTest.php <ide> public function testExceedAttempts() <ide> */ <ide> public function testRespectStrategy() <ide> { <del> $count = 0; <del> $action = function () use (&$count) { <add> $action = function () { <ide> throw new Exception('this is failing'); <ide> }; <ide> <ide><path>tests/test_app/TestApp/View/Helper/TextHelperTestObject.php <ide> public function attach(TextMock $string) <ide> $this->_engine = $string; <ide> } <ide> <add> /** <add> * @return mixed <add> */ <ide> public function engine() <ide> { <ide> return $this->_engine;
2
Javascript
Javascript
rename a few things for clarity
d1aac46a5a5b5c6c7179342de7d6820efd6da8b7
<ide><path>d3.js <ide> })(); <ide> } <ide> function d3_geo_projectionMutator(projectAt) { <del> var project, rotate, rotation, projectRotate, k = 150, x = 480, y = 250, λ = 0, φ = 0, δλ = 0, δφ = 0, δγ = 0, δx, δy, clip = d3_geo_cut, clipAngle = null, resample = d3_geo_resample(projectPoint); <add> var project, rotatePoint, rotateToRadians, projectRotate, k = 150, x = 480, y = 250, λ = 0, φ = 0, δλ = 0, δφ = 0, δγ = 0, δx, δy, clip = d3_geo_cut, clipAngle = null, projectResample = d3_geo_resample(projectPoint); <ide> function projection(coordinates) { <ide> coordinates = projectRotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians); <ide> return [ coordinates[0] * k + δx, δy - coordinates[1] * k ]; <ide> return [ coordinates[0] * d3_degrees, coordinates[1] * d3_degrees ]; <ide> } <ide> projection.object = function(object) { <del> object = clip(rotation(object)); <del> resample(object); <add> object = clip(rotateToRadians(object)); <add> projectResample(object); <ide> return object; <ide> }; <ide> projection.clipAngle = function(_) { <ide> δγ = _.length > 2 ? _[2] % 360 * d3_radians : 0; <ide> return reset(); <ide> }; <del> d3.rebind(projection, resample, "precision"); <add> d3.rebind(projection, projectResample, "precision"); <ide> function reset() { <del> projectRotate = d3_geo_compose(rotate = d3_geo_rotation(δλ, δφ, δγ), project); <add> projectRotate = d3_geo_compose(rotatePoint = d3_geo_rotation(δλ, δφ, δγ), project); <ide> var center = project(λ, φ); <ide> δx = x - center[0] * k; <ide> δy = y + center[1] * k; <ide> return projection; <ide> } <del> var rotation = d3_geo_type({ <add> var rotateToRadians = d3_geo_type({ <ide> point: function(coordinates) { <del> return rotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians); <add> return rotatePoint(coordinates[0] * d3_radians, coordinates[1] * d3_radians); <ide> }, <ide> Sphere: d3_identity <ide> }); <ide><path>src/geo/projection.js <ide> function d3_geo_projection(project) { <ide> <ide> function d3_geo_projectionMutator(projectAt) { <ide> var project, <del> rotate, <del> rotation, // TODO rename: rotateObject? disambiguate from rotate, which is for points <add> rotatePoint, <add> rotateToRadians, // TODO: would rotateObjectToRadians be clearer? <ide> projectRotate, <ide> k = 150, // scale <ide> x = 480, // translate <ide> function d3_geo_projectionMutator(projectAt) { <ide> δx, // center <ide> δy, <ide> clip = d3_geo_cut, // TODO rename: it's often cutting, not clipping! <add> // Although cutting is a special case of clipping with <add> // an infinitesimally small "outside". <ide> clipAngle = null, <del> resample = d3_geo_resample(projectPoint); <add> projectResample = d3_geo_resample(projectPoint); <ide> <ide> function projection(coordinates) { <ide> coordinates = projectRotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians); <ide> function d3_geo_projectionMutator(projectAt) { <ide> } <ide> <ide> projection.object = function(object) { <del> object = clip(rotation(object)); <del> resample(object); <add> object = clip(rotateToRadians(object)); <add> projectResample(object); <ide> return object; <ide> }; <ide> <ide> function d3_geo_projectionMutator(projectAt) { <ide> return reset(); <ide> }; <ide> <del> d3.rebind(projection, resample, "precision"); <add> d3.rebind(projection, projectResample, "precision"); <ide> <ide> function reset() { <del> projectRotate = d3_geo_compose(rotate = d3_geo_rotation(δλ, δφ, δγ), project); <add> projectRotate = d3_geo_compose(rotatePoint = d3_geo_rotation(δλ, δφ, δγ), project); <ide> var center = project(λ, φ); <ide> δx = x - center[0] * k; <ide> δy = y + center[1] * k; <ide> return projection; <ide> } <ide> <del> // TODO rename: this is not just rotation, it also converts to radians! <ide> // TODO don't create new objects for rotation? (since clipping does the same?) <ide> // TODO don't call rotate when rotate is a no-op <del> var rotation = d3_geo_type({ <add> var rotateToRadians = d3_geo_type({ <ide> point: function(coordinates) { <del> return rotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians); <add> return rotatePoint(coordinates[0] * d3_radians, coordinates[1] * d3_radians); <ide> }, <ide> Sphere: d3_identity <ide> });
2
Javascript
Javascript
show error when hotonly hmr fails
5345a38c36dec279fca9a938327925e13c6e5f25
<ide><path>hot/only-dev-server.js <ide> if(module.hot) { <ide> console.warn("Ignored an update to declined module " + data.chain.join(" -> ")); <ide> }, <ide> onErrored: function(data) { <add> console.error(data.error); <ide> console.warn("Ignored an error while updating module " + data.moduleId + " (" + data.type + ")"); <ide> } <ide> }).then(function(renewedModules) {
1
Python
Python
resolve line-too-long in benchmarks
f9fb9b44cea161cea007a963aead676888281c6e
<ide><path>keras/benchmarks/benchmark_util.py <ide> def generate_benchmark_params_cpu_gpu(*params_list): <ide> *params_list: A list of tuples represents the benchmark parameters. <ide> <ide> Returns: <del> A list of strings with the benchmark name extended with CPU and GPU suffix. <add> A list of strings with the benchmark name extended with CPU and GPU <add> suffix. <ide> """ <ide> benchmark_params = [] <ide> for params in params_list: <ide> def measure_performance( <ide> y: Target data. See `y` in the `fit()` method of `keras.Model`. <ide> epochs: Integer. Number of epochs to train the model. <ide> If unspecified, `epochs` will default to 2. <del> batch_size: Integer. Number of samples per gradient update. If unspecified, <del> `batch_size` will default to 32. <del> run_iters: Integer. Number of iterations to run the performance measurement. <del> If unspecified, `run_iters` will default to 4. <add> batch_size: Integer. Number of samples per gradient update. If <add> unspecified, `batch_size` will default to 32. <add> run_iters: Integer. Number of iterations to run the performance <add> measurement. If unspecified, `run_iters` will default to 4. <ide> optimizer: String (name of optimizer) or optimizer instance. See <ide> `tf.keras.optimizers`. <ide> loss: String (name of objective function), objective function or <ide> `tf.keras.losses.Loss` instance. See `tf.keras.losses`. <del> metrics: Lists of metrics to be evaluated by the model during training. See <del> `metrics` in the `compile()` method of `keras.Model`. <add> metrics: Lists of metrics to be evaluated by the model during training. <add> See `metrics` in the `compile()` method of `keras.Model`. <ide> verbose: 0, 1, 2. Verbosity mode. See `verbose` in the `fit()` method of <ide> `keras.Model`. If unspecified, `verbose` will default to 0. <ide> num_gpus: Number of GPUs to run the model. <ide><path>keras/benchmarks/distribution_util.py <ide> def _collective_communication(all_reduce_alg): <ide> """Return a CollectiveCommunication based on all_reduce_alg. <ide> <ide> Args: <del> all_reduce_alg: a string specifying which collective communication to pick, <del> or None. <add> all_reduce_alg: a string specifying which collective communication to <add> pick, or None. <ide> <ide> Returns: <ide> tf.distribute.experimental.CollectiveCommunication object <ide> def _mirrored_cross_device_ops(all_reduce_alg, num_packs): <ide> """Return a CrossDeviceOps based on all_reduce_alg and num_packs. <ide> <ide> Args: <del> all_reduce_alg: a string specifying which cross device op to pick, or None. <add> all_reduce_alg: a string specifying which cross device op to pick, or <add> None. <ide> num_packs: an integer specifying number of packs for the cross device op. <ide> <ide> Returns: <ide> tf.distribute.CrossDeviceOps object or None. <ide> <ide> Raises: <del> ValueError: if `all_reduce_alg` not in [None, "nccl", "hierarchical_copy"]. <add> ValueError: if `all_reduce_alg` not in [None, "nccl", <add> "hierarchical_copy"]. <ide> """ <ide> if all_reduce_alg is None: <ide> return None <ide><path>keras/benchmarks/eager_microbenchmarks_test.py <ide> def _get_benchmark_name(self): <ide> f_self = f_locals.get("self", None) <ide> if isinstance(f_self, tf.test.Benchmark): <ide> name = frame[3] # Get the method name <del> # This is a hack to get around the fact that some methods might have a <del> # disable_tfrt decorator around them. In that case a function called <del> # 'decorated' wraps the real called function underneath and so we <del> # peek one deeper into the stack to get the real name. <add> # This is a hack to get around the fact that some methods might <add> # have a disable_tfrt decorator around them. In that case a <add> # function called 'decorated' wraps the real called function <add> # underneath and so we peek one deeper into the stack to get the <add> # real name. <ide> if name == "decorated": <ide> continue <ide> else: <ide><path>keras/benchmarks/keras_examples_benchmarks/cifar10_cnn_benchmark_test.py <ide> def __init__(self): <ide> self.epochs = 5 <ide> <ide> def _build_model(self): <del> """Model from https://github.com/keras-team/keras/blob/master/examples/cifar10_cnn.py.""" <add> """Model from <add> https://github.com/keras-team/keras/blob/master/examples/cifar10_cnn.py. <add> """ <ide> model = tf.keras.Sequential() <ide> model.add( <ide> tf.keras.layers.Conv2D( <ide><path>keras/benchmarks/keras_examples_benchmarks/mnist_conv_custom_training_benchmark_test.py <ide> def distributed_train_step( <ide> loss_fn: See `loss_fn` in `train_function()` method. <ide> optimizer: See `optimizer` in `train_function()` method. <ide> batch_size: See `batch_size` in `train_function()` method. <del> distribution_strategy: See `distribution_strategy` in `train_function()` <del> method. <add> distribution_strategy: See `distribution_strategy` in <add> `train_function()` method. <ide> <ide> Returns: <ide> Sum of per_replica_losses. <ide> def train_function( <ide> <ide> Args: <ide> model: Model function to be benchmarked. <del> train_dataset: `tf.data` dataset. Should return a tuple of either (inputs, <del> targets) or (inputs, targets, sample_weights). <add> train_dataset: `tf.data` dataset. Should return a tuple of either <add> (inputs, targets) or (inputs, targets, sample_weights). <ide> loss_fn: `tf.keras.losses.Loss` instance. <ide> optimizer: `tf.keras.optimizers` instance. <ide> epochs: Integer. Number of epochs to train the model. If unspecified, <ide><path>keras/benchmarks/keras_examples_benchmarks/text_classification_transformer_benchmark_test.py <ide> def __init__(self): <ide> ) <ide> <ide> def _build_model(self): <del> """Model from https://keras.io/examples/nlp/text_classification_with_transformer/.""" <add> """Model from <add> https://keras.io/examples/nlp/text_classification_with_transformer/.""" <ide> embed_dim = 32 <ide> num_heads = 2 <ide> ff_dim = 32 <ide><path>keras/benchmarks/layer_benchmarks/run_xprof.py <ide> <ide> from tensorflow.python.profiler import profiler_v2 as profiler <ide> <del>def run_with_xprof(self, func, num_iters_xprof=100, enable_python_trace=True, <del> logdir='/tmp/layer_benchmark_xprof/'): <del> suid = str(uuid.uuid4()) <del> if enable_python_trace: <del> options = profiler.ProfilerOptions(python_tracer_level=1) <del> logdir = os.path.join(logdir, str(uuid.uuid4()) + "_with_python") <del> else: <del> options = profiler.ProfilerOptions(python_tracer_level=0) <del> logdir = os.path.join(logdir, suid) <ide> <del> start = time.time() <del> with profiler.Profile(logdir, options): <del> for _ in range(num_iters_xprof): <del> func() <del> total_time = time.time() - start <del> us_per_example = float("{0:.3f}".format(total_time * 1e6 / num_iters_xprof)) <del> return logdir, us_per_example <add>def run_with_xprof( <add> self, <add> func, <add> num_iters_xprof=100, <add> enable_python_trace=True, <add> logdir="/tmp/layer_benchmark_xprof/", <add>): <add> suid = str(uuid.uuid4()) <add> if enable_python_trace: <add> options = profiler.ProfilerOptions(python_tracer_level=1) <add> logdir = os.path.join(logdir, str(uuid.uuid4()) + "_with_python") <add> else: <add> options = profiler.ProfilerOptions(python_tracer_level=0) <add> logdir = os.path.join(logdir, suid) <add> <add> start = time.time() <add> with profiler.Profile(logdir, options): <add> for _ in range(num_iters_xprof): <add> func() <add> total_time = time.time() - start <add> us_per_example = float("{0:.3f}".format(total_time * 1e6 / num_iters_xprof)) <add> return logdir, us_per_example <ide><path>keras/benchmarks/metrics_memory_benchmark_test.py <ide> def benchmark_auc_memory_usage(self): <ide> memory_usage_2 = memory_profiler.memory_usage( <ide> (self.uneven_thresholds_auc) <ide> ) <del> # memory usage is a list of number which sampled when running the function <del> # The pure memory consumption is approximately max(usage) - min(usage) <add> # memory usage is a list of number which sampled when running the <add> # function The pure memory consumption is approximately max(usage) - <add> # min(usage) <ide> memory_usage_1 = max(memory_usage_1) - min(memory_usage_1) <ide> memory_usage_2 = max(memory_usage_2) - min(memory_usage_2) <ide> <ide><path>keras/benchmarks/optimizer_benchmarks_test.py <ide> def benchmark_optimizer(self, optimizer, num_iters): <ide> <ide> Args: <ide> optimizer: The optimizer instance to be benchmarked. <del> num_iters: The number of iterations to run for performance measurement. <add> num_iters: The number of iterations to run for performance <add> measurement. <ide> """ <ide> model, train_x, train_y = bidirect_imdb_lstm_config() <ide> metrics, wall_time, extras = benchmark_util.measure_performance(
9
Java
Java
update webmvcconfigurer#addinterceptors javadoc
627a9be65460dae2bd4c4050070fb721a6a70743
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurer.java <ide> default void addFormatters(FormatterRegistry registry) { <ide> <ide> /** <ide> * Add Spring MVC lifecycle interceptors for pre- and post-processing of <del> * controller method invocations. Interceptors can be registered to apply <del> * to all requests or be limited to a subset of URL patterns. <del> * <p><strong>Note</strong> that interceptors registered here only apply to <del> * controllers and not to resource handler requests. To intercept requests for <del> * static resources either declare a <del> * {@link org.springframework.web.servlet.handler.MappedInterceptor MappedInterceptor} <del> * bean or switch to advanced configuration mode by extending <del> * {@link org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport <del> * WebMvcConfigurationSupport} and then override {@code resourceHandlerMapping}. <add> * controller method invocations and resource handler requests. <add> * Interceptors can be registered to apply to all requests or be limited <add> * to a subset of URL patterns. <ide> */ <ide> default void addInterceptors(InterceptorRegistry registry) { <ide> }
1
Javascript
Javascript
remove performwithpriority from scheduler
7d77d795c2c647effbea40272de3834bb38f4e52
<ide><path>src/renderers/noop/ReactNoopEntry.js <ide> import type {UpdateQueue} from 'ReactFiberUpdateQueue'; <ide> var ReactFiberInstrumentation = require('ReactFiberInstrumentation'); <ide> var ReactFiberReconciler = require('ReactFiberReconciler'); <ide> var ReactInstanceMap = require('ReactInstanceMap'); <del>var {TaskPriority} = require('ReactPriorityLevel'); <ide> var emptyObject = require('fbjs/lib/emptyObject'); <ide> <ide> var expect = require('jest-matchers'); <ide> var ReactNoop = { <ide> return !!scheduledCallback; <ide> }, <ide> <del> taskUpdates(fn: Function) { <del> NoopRenderer.performWithPriority(TaskPriority, fn); <del> }, <del> <ide> batchedUpdates: NoopRenderer.batchedUpdates, <ide> <ide> deferredUpdates: NoopRenderer.deferredUpdates, <ide><path>src/renderers/shared/fiber/ReactFiberReconciler.js <ide> <ide> import type {Fiber} from 'ReactFiber'; <ide> import type {FiberRoot} from 'ReactFiberRoot'; <del>import type {PriorityLevel} from 'ReactPriorityLevel'; <ide> import type {ReactNodeList} from 'ReactTypes'; <ide> <ide> var ReactFeatureFlags = require('ReactFeatureFlags'); <ide> export type Reconciler<C, I, TI> = { <ide> parentComponent: ?React$Component<any, any>, <ide> callback: ?Function, <ide> ): void, <del> performWithPriority(priorityLevel: PriorityLevel, fn: Function): void, <ide> batchedUpdates<A>(fn: () => A): A, <ide> unbatchedUpdates<A>(fn: () => A): A, <ide> flushSync<A>(fn: () => A): A, <ide> module.exports = function<T, P, I, TI, PI, C, CX, PL>( <ide> var { <ide> scheduleUpdate, <ide> getPriorityContext, <del> performWithPriority, <ide> batchedUpdates, <ide> unbatchedUpdates, <ide> flushSync, <ide> module.exports = function<T, P, I, TI, PI, C, CX, PL>( <ide> scheduleTopLevelUpdate(current, element, callback); <ide> }, <ide> <del> performWithPriority, <del> <ide> batchedUpdates, <ide> <ide> unbatchedUpdates, <ide><path>src/renderers/shared/fiber/ReactFiberScheduler.js <ide> module.exports = function<T, P, I, TI, PI, C, CX, PL>( <ide> scheduleUpdateImpl(fiber, TaskPriority, true); <ide> } <ide> <del> function performWithPriority(priorityLevel: PriorityLevel, fn: Function) { <del> const previousPriorityContext = priorityContext; <del> priorityContext = priorityLevel; <del> try { <del> fn(); <del> } finally { <del> priorityContext = previousPriorityContext; <del> } <del> } <del> <ide> function batchedUpdates<A, R>(fn: (a: A) => R, a: A): R { <ide> const previousIsBatchingUpdates = isBatchingUpdates; <ide> isBatchingUpdates = true; <ide> module.exports = function<T, P, I, TI, PI, C, CX, PL>( <ide> return { <ide> scheduleUpdate: scheduleUpdate, <ide> getPriorityContext: getPriorityContext, <del> performWithPriority: performWithPriority, <ide> batchedUpdates: batchedUpdates, <ide> unbatchedUpdates: unbatchedUpdates, <ide> flushSync: flushSync,
3
Javascript
Javascript
fix logarithmicdepthbuffer bug
856b01d8e398e89f066e67b6de2ba7a580a12f1c
<ide><path>src/renderers/webgl/WebGLCapabilities.js <ide> function WebGLCapabilities( gl, extensions, parameters ) { <ide> <ide> } <ide> <del> var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true && !! extensions.get( 'EXT_frag_depth' ); <add> var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; <ide> <ide> var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS ); <ide> var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
1
Text
Text
fix changelog format
13fd153429e337ad8b9690fcf00c1019037c917f
<ide><path>activesupport/CHANGELOG.md <ide> <ide> *Ricardo Díaz* <ide> <del> <ide> * Fix modulo operations involving durations <ide> <ide> Rails 5.1 introduce an `ActiveSupport::Duration::Scalar` class as a wrapper
1
Text
Text
fix invalid syntax
50ecd8ad4059309d503fc6c0783fb8a80784965f
<ide><path>guide/english/python/lists/list-pop/index.md <ide> If the index passed to the pop() method is not in the range, it throws IndexErro <ide> ```py <ide> cities = ['New York', 'Dallas', 'San Antonio', 'Houston', 'San Francisco']; <ide> <del>print "City popped is : ", cities.pop() <del>print "City at index 2 is : ", cities.pop(2) <add>print("City popped is : ", cities.pop()) <add>print("City at index 2 is : ", cities.pop(2)) <ide> ``` <ide> <ide> #### Output
1
Javascript
Javascript
add test for withcredentials option
73273ccbe9baa4ca784c94c65b599978abcf1ee4
<ide><path>test/unit/api_spec.js <ide> describe('api', function() { <ide> done.fail(reason); <ide> }); <ide> }); <add> <add> describe('Cross-origin', function() { <add> var loadingTask; <add> function _checkCanLoad(expectSuccess, filename, options) { <add> if (isNodeJS()) { <add> pending('Cannot simulate cross-origin requests in Node.js'); <add> } <add> var params = buildGetDocumentParams(filename, options); <add> var url = new URL(params.url); <add> if (url.hostname === 'localhost') { <add> url.hostname = '127.0.0.1'; <add> } else if (params.url.hostname === '127.0.0.1') { <add> url.hostname = 'localhost'; <add> } else { <add> pending('Can only run cross-origin test on localhost!'); <add> } <add> params.url = url.href; <add> loadingTask = getDocument(params); <add> return loadingTask.promise.then(function(pdf) { <add> return pdf.destroy(); <add> }).then(function() { <add> expect(expectSuccess).toEqual(true); <add> }, function(error) { <add> if (expectSuccess) { <add> // For ease of debugging. <add> expect(error).toEqual('There should not be any error'); <add> } <add> expect(expectSuccess).toEqual(false); <add> }); <add> } <add> function testCanLoad(filename, options) { <add> return _checkCanLoad(true, filename, options); <add> } <add> function testCannotLoad(filename, options) { <add> return _checkCanLoad(false, filename, options); <add> } <add> afterEach(function(done) { <add> if (loadingTask) { <add> loadingTask.destroy().then(done); <add> } else { <add> done(); <add> } <add> }); <add> it('server disallows cors', function(done) { <add> testCannotLoad('basicapi.pdf').then(done); <add> }); <add> it('server allows cors without credentials, default withCredentials', <add> function(done) { <add> testCanLoad('basicapi.pdf?cors=withoutCredentials').then(done); <add> }); <add> it('server allows cors without credentials, and withCredentials=false', <add> function(done) { <add> testCanLoad('basicapi.pdf?cors=withoutCredentials', { <add> withCredentials: false, <add> }).then(done); <add> }); <add> it('server allows cors without credentials, but withCredentials=true', <add> function(done) { <add> testCannotLoad('basicapi.pdf?cors=withoutCredentials', { <add> withCredentials: true, <add> }).then(done); <add> }); <add> it('server allows cors with credentials, and withCredentials=true', <add> function(done) { <add> testCanLoad('basicapi.pdf?cors=withCredentials', { <add> withCredentials: true, <add> }).then(done); <add> }); <add> it('server allows cors with credentials, and withCredentials=false', <add> function(done) { <add> // The server supports even more than we need, so if the previous tests <add> // pass, then this should pass for sure. <add> // The only case where this test fails is when the server does not reply <add> // with the Access-Control-Allow-Origin header. <add> testCanLoad('basicapi.pdf?cors=withCredentials', { <add> withCredentials: false, <add> }).then(done); <add> }); <add> }); <ide> }); <ide> describe('Page', function() { <ide> var loadingTask; <ide><path>test/webserver.js <ide> function WebServer() { <ide> this.cacheExpirationTime = 0; <ide> this.disableRangeRequests = false; <ide> this.hooks = { <del> 'GET': [], <add> 'GET': [crossOriginHandler], <ide> 'POST': [], <ide> }; <ide> } <ide> WebServer.prototype = { <ide> }, <ide> }; <ide> <add>// This supports the "Cross-origin" test in test/unit/api_spec.js <add>// It is here instead of test.js so that when the test will still complete as <add>// expected if the user does "gulp server" and then visits <add>// http://localhost:8888/test/unit/unit_test.html?spec=Cross-origin <add>function crossOriginHandler(req, res) { <add> if (req.url === '/test/pdfs/basicapi.pdf?cors=withCredentials') { <add> res.setHeader('Access-Control-Allow-Origin', req.headers['origin']); <add> res.setHeader('Access-Control-Allow-Credentials', 'true'); <add> } <add> if (req.url === '/test/pdfs/basicapi.pdf?cors=withoutCredentials') { <add> res.setHeader('Access-Control-Allow-Origin', req.headers['origin']); <add> } <add>} <add> <ide> exports.WebServer = WebServer;
2
PHP
PHP
remove countable use and add trailing slash
7f73b2dcd816e6c45ca65172011f8739ab210ba4
<ide><path>src/Illuminate/Foundation/helpers.php <ide> function trans($id = null, $parameters = [], $domain = 'messages', $locale = nul <ide> * Translates the given message based on a count. <ide> * <ide> * @param string $id <del> * @param int|array|Countable $number <add> * @param int|array|\Countable $number <ide> * @param array $parameters <ide> * @param string $domain <ide> * @param string $locale <ide><path>src/Illuminate/Translation/Translator.php <ide> <ide> namespace Illuminate\Translation; <ide> <del>use Countable; <ide> use Illuminate\Support\Arr; <ide> use Illuminate\Support\Str; <ide> use Illuminate\Support\Collection; <ide> protected function sortReplacements(array $replace) <ide> * Get a translation according to an integer value. <ide> * <ide> * @param string $key <del> * @param int|array|Countable $number <add> * @param int|array|\Countable $number <ide> * @param array $replace <ide> * @param string $locale <ide> * @return string <ide> public function choice($key, $number, array $replace = [], $locale = null) <ide> { <ide> $line = $this->get($key, $replace, $locale = $locale ?: $this->locale ?: $this->fallback); <ide> <del> if (is_array($number) || $number instanceof Countable) { <add> if (is_array($number) || $number instanceof \Countable) { <ide> $number = count($number); <ide> } <ide> <ide> public function trans($id, array $parameters = [], $domain = 'messages', $locale <ide> * Get a translation according to an integer value. <ide> * <ide> * @param string $id <del> * @param int|array|Countable $number <add> * @param int|array|\Countable $number <ide> * @param array $parameters <ide> * @param string $domain <ide> * @param string $locale
2
Javascript
Javascript
replace multi line string with concat
c87bddf4b10a0f9fb5345306aa3f60dd2cabb058
<ide><path>test/RawModule.test.js <ide> describe("RawModule", () => { <ide> }); <ide> <ide> describe("readableIdentifier", () => { <del> it("returns result of calling provided requestShortener\"s shorten method\ <del> on readableIdentifierStr attribute", () => { <add> it("returns result of calling provided requestShortener\"s shorten method " + <add> "on readableIdentifierStr attribute", () => { <ide> const requestShortener = new RequestShortener(path.resolve()); <ide> should.exist(myRawModule.readableIdentifier(requestShortener)); <ide> }); <ide> describe("RawModule", () => { <ide> }); <ide> <ide> describe("source", () => { <del> it("returns a new OriginalSource instance with sourceStr attribute and\ <del> return value of identifier() function provided as constructor arguments", <add> it("returns a new OriginalSource instance with sourceStr attribute and " + <add> "return value of identifier() function provided as constructor arguments", <ide> () => { <ide> const originalSource = new OriginalSource(myRawModule.sourceStr, myRawModule.identifier()); <ide> myRawModule.useSourceMap = true; <ide> myRawModule.source().should.match(originalSource); <ide> }); <ide> <del> it("returns a new RawSource instance with sourceStr attribute provided\ <del> as constructor argument if useSourceMap is falsey", () => { <add> it("returns a new RawSource instance with sourceStr attribute provided " + <add> "as constructor argument if useSourceMap is falsey", () => { <ide> const rawSource = new RawSource(myRawModule.sourceStr); <ide> myRawModule.useSourceMap = false; <ide> myRawModule.source().should.match(rawSource);
1
Ruby
Ruby
fix a variable name in error message (#190)
967988c4441ed49338b8e31a1a5ff8a7f6061c88
<ide><path>Library/Homebrew/extend/fileutils.rb <ide> def run <ide> # group_id.to_s makes OS X 10.6.7 (ruby-1.8.7-p174) and earlier happy. <ide> chown(nil, group_id.to_s, tmpdir) <ide> rescue Errno::EPERM <del> opoo "Failed setting group \"#{Etc.getgrgid(group_id).name}\" on #{tmp}" <add> opoo "Failed setting group \"#{Etc.getgrgid(group_id).name}\" on #{tmpdir}" <ide> end <ide> <ide> begin
1
Ruby
Ruby
remove redundant curlies from hash arguments
411ccbdab2608c62aabdb320d52cb02d446bb39c
<ide><path>actioncable/test/channel/base_test.rb <ide> def rm_rf <ide> setup do <ide> @user = User.new "lifo" <ide> @connection = TestConnection.new(@user) <del> @channel = ChatChannel.new @connection, "{id: 1}", { id: 1 } <add> @channel = ChatChannel.new @connection, "{id: 1}", id: 1 <ide> end <ide> <ide> test "should subscribe to a channel on initialize" do <ide><path>actioncable/test/channel/periodic_timers_test.rb <ide> def ping <ide> <ide> test "timer start and stop" do <ide> @connection.server.event_loop.expects(:timer).times(3).returns(stub(shutdown: nil)) <del> channel = ChatChannel.new @connection, "{id: 1}", { id: 1 } <add> channel = ChatChannel.new @connection, "{id: 1}", id: 1 <ide> <ide> channel.unsubscribe_from_channel <ide> assert_equal [], channel.send(:active_periodic_timers) <ide><path>actioncable/test/channel/rejection_test.rb <ide> def subscribed <ide> <ide> test "subscription rejection" do <ide> @connection.expects(:subscriptions).returns mock().tap { |m| m.expects(:remove_subscription).with instance_of(SecretChannel) } <del> @channel = SecretChannel.new @connection, "{id: 1}", { id: 1 } <add> @channel = SecretChannel.new @connection, "{id: 1}", id: 1 <ide> <ide> expected = { "identifier" => "{id: 1}", "type" => "reject_subscription" } <ide> assert_equal expected, @connection.last_transmission <ide><path>actioncable/test/channel/stream_test.rb <ide> class StreamTest < ActionCable::TestCase <ide> run_in_eventmachine do <ide> connection = TestConnection.new <ide> connection.expects(:pubsub).returns mock().tap { |m| m.expects(:subscribe).with("test_room_1", kind_of(Proc), kind_of(Proc)).returns stub_everything(:pubsub) } <del> channel = ChatChannel.new connection, "{id: 1}", { id: 1 } <add> channel = ChatChannel.new connection, "{id: 1}", id: 1 <ide> <ide> connection.expects(:pubsub).returns mock().tap { |m| m.expects(:unsubscribe) } <ide> channel.unsubscribe_from_channel <ide> class StreamTest < ActionCable::TestCase <ide> run_in_eventmachine do <ide> connection = TestConnection.new <ide> <del> ChatChannel.new connection, "{id: 1}", { id: 1 } <add> ChatChannel.new connection, "{id: 1}", id: 1 <ide> assert_nil connection.last_transmission <ide> <ide> wait_for_async <ide><path>actioncable/test/connection/base_test.rb <ide> def call(*) <ide> <ide> env = Rack::MockRequest.env_for( <ide> "/test", <del> { "HTTP_CONNECTION" => "upgrade", "HTTP_UPGRADE" => "websocket", <del> "HTTP_HOST" => "localhost", "HTTP_ORIGIN" => "http://rubyonrails.org", "rack.hijack" => CallMeMaybe.new } <add> "HTTP_CONNECTION" => "upgrade", "HTTP_UPGRADE" => "websocket", <add> "HTTP_HOST" => "localhost", "HTTP_ORIGIN" => "http://rubyonrails.org", "rack.hijack" => CallMeMaybe.new <ide> ) <ide> <ide> connection = ActionCable::Connection::Base.new(@server, env) <ide><path>actionpack/lib/action_dispatch/journey/route.rb <ide> def self.call(_); true; end <ide> def self.verb; ""; end <ide> end <ide> <del> VERB_TO_CLASS = VERBS.each_with_object({ all: All }) do |verb, hash| <add> VERB_TO_CLASS = VERBS.each_with_object(all: All) do |verb, hash| <ide> klass = const_get verb <ide> hash[verb] = klass <ide> hash[verb.downcase] = klass <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <ide> def frame; @hash; end <ide> <ide> def initialize(set) #:nodoc: <ide> @set = set <del> @scope = Scope.new({ path_names: @set.resources_path_names }) <add> @scope = Scope.new(path_names: @set.resources_path_names) <ide> @concerns = {} <ide> end <ide> <ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <ide> def recognize_path(path, environment = {}) <ide> extras = environment[:extras] || {} <ide> <ide> begin <del> env = Rack::MockRequest.env_for(path, {method: method}) <add> env = Rack::MockRequest.env_for(path, method: method) <ide> rescue URI::InvalidURIError => e <ide> raise ActionController::RoutingError, e.message <ide> end <ide><path>actionpack/lib/action_dispatch/testing/assertions/routing.rb <ide> def recognized_request_for(path, extras = {}, msg) <ide> request.request_method = method if method <ide> <ide> params = fail_on(ActionController::RoutingError, msg) do <del> @routes.recognize_path(path, { method: method, extras: extras }) <add> @routes.recognize_path(path, method: method, extras: extras) <ide> end <ide> request.path_parameters = params.with_indifferent_access <ide> <ide><path>actionpack/lib/action_dispatch/testing/integration.rb <ide> def process_with_kwargs(http_method, path, *args) <ide> process(http_method, path, *args) <ide> else <ide> non_kwarg_request_warning if args.any? <del> process(http_method, path, { params: args[0], headers: args[1] }) <add> process(http_method, path, params: args[0], headers: args[1]) <ide> end <ide> end <ide> <ide><path>actionpack/test/abstract/translation_test.rb <ide> class TranslationController < AbstractController::Base <ide> class TranslationControllerTest < ActiveSupport::TestCase <ide> def setup <ide> @controller = TranslationController.new <del> I18n.backend.store_translations(:en, { <del> one: { <add> I18n.backend.store_translations(:en, one: { <ide> two: "bar", <ide> }, <ide> abstract_controller: { <ide> def setup <ide> no_action: "no_action_tr", <ide> }, <ide> }, <del> }, <del> }) <add> }) <ide> end <ide> <ide> def test_action_controller_base_responds_to_translate <ide><path>actionpack/test/controller/flash_hash_test.rb <ide> def test_keep_sweep <ide> <ide> def test_update_sweep <ide> @hash["hello"] = "world" <del> @hash.update({"hi" => "mom"}) <add> @hash.update("hi" => "mom") <ide> <ide> @hash.sweep <ide> assert_equal({"hello" => "world", "hi" => "mom"}, @hash.to_hash) <ide> def test_update_sweep <ide> def test_update_delete_sweep <ide> @hash["hello"] = "world" <ide> @hash.delete "hello" <del> @hash.update({"hello" => "mom"}) <add> @hash.update("hello" => "mom") <ide> <ide> @hash.sweep <ide> assert_equal({"hello" => "mom"}, @hash.to_hash) <ide> def test_clear_sweep <ide> <ide> def test_replace_sweep <ide> @hash["hello"] = "world" <del> @hash.replace({"hi" => "mom"}) <add> @hash.replace("hi" => "mom") <ide> <ide> @hash.sweep <ide> assert_equal({"hi" => "mom"}, @hash.to_hash) <ide><path>actionpack/test/controller/live_stream_test.rb <ide> def basic_sse <ide> response.headers["Content-Type"] = "text/event-stream" <ide> sse = SSE.new(response.stream) <ide> sse.write("{\"name\":\"John\"}") <del> sse.write({ name: "Ryan" }) <add> sse.write(name: "Ryan") <ide> ensure <ide> sse.close <ide> end <ide> <ide> def sse_with_event <ide> sse = SSE.new(response.stream, event: "send-name") <ide> sse.write("{\"name\":\"John\"}") <del> sse.write({ name: "Ryan" }) <add> sse.write(name: "Ryan") <ide> ensure <ide> sse.close <ide> end <ide> def index <ide> response.headers["Content-Type"] = "text/event-stream" <ide> sse = SSE.new(response.stream) <ide> sse.write("{\"name\":\"John\"}") <del> sse.write({ name: "Ryan" }) <add> sse.write(name: "Ryan") <ide> ensure <ide> sse.close <ide> end <ide><path>actionpack/test/controller/new_base/render_action_test.rb <ide> class ControllerLayoutTest < Rack::TestCase <ide> <ide> module RenderActionWithBothLayouts <ide> class BasicController < ActionController::Base <del> self.view_paths = [ActionView::FixtureResolver.new({ <del> "render_action_with_both_layouts/basic/hello_world.html.erb" => "Hello World!", <add> self.view_paths = [ActionView::FixtureResolver.new( "render_action_with_both_layouts/basic/hello_world.html.erb" => "Hello World!", <ide> "layouts/application.html.erb" => "Oh Hi <%= yield %> Bye", <del> "layouts/render_action_with_both_layouts/basic.html.erb" => "With Controller Layout! <%= yield %> Bye" <del> })] <add> "layouts/render_action_with_both_layouts/basic.html.erb" => "With Controller Layout! <%= yield %> Bye")] <ide> <ide> def hello_world <ide> render action: "hello_world" <ide><path>actionpack/test/controller/parameters/always_permitted_parameters_test.rb <ide> def teardown <ide> end <ide> <ide> test "permits parameters that are whitelisted" do <del> params = ActionController::Parameters.new({ <del> book: { pages: 65 }, <del> format: "json" <del> }) <add> params = ActionController::Parameters.new( book: { pages: 65 }, <add> format: "json") <ide> permitted = params.permit book: [:pages] <ide> assert permitted.permitted? <ide> end <ide><path>actionpack/test/controller/parameters/log_on_unpermitted_params_test.rb <ide> def teardown <ide> end <ide> <ide> test "logs on unexpected param" do <del> params = ActionController::Parameters.new({ <del> book: { pages: 65 }, <del> fishing: "Turnips" <del> }) <add> params = ActionController::Parameters.new( book: { pages: 65 }, <add> fishing: "Turnips") <ide> <ide> assert_logged("Unpermitted parameter: fishing") do <ide> params.permit(book: [:pages]) <ide> end <ide> end <ide> <ide> test "logs on unexpected params" do <del> params = ActionController::Parameters.new({ <del> book: { pages: 65 }, <add> params = ActionController::Parameters.new( book: { pages: 65 }, <ide> fishing: "Turnips", <del> car: "Mersedes" <del> }) <add> car: "Mersedes") <ide> <ide> assert_logged("Unpermitted parameters: fishing, car") do <ide> params.permit(book: [:pages]) <ide> end <ide> end <ide> <ide> test "logs on unexpected nested param" do <del> params = ActionController::Parameters.new({ <del> book: { pages: 65, title: "Green Cats and where to find then." } <del> }) <add> params = ActionController::Parameters.new( book: { pages: 65, title: "Green Cats and where to find then." }) <ide> <ide> assert_logged("Unpermitted parameter: title") do <ide> params.permit(book: [:pages]) <ide> end <ide> end <ide> <ide> test "logs on unexpected nested params" do <del> params = ActionController::Parameters.new({ <del> book: { pages: 65, title: "Green Cats and where to find then.", author: "G. A. Dog" } <del> }) <add> params = ActionController::Parameters.new( book: { pages: 65, title: "Green Cats and where to find then.", author: "G. A. Dog" }) <ide> <ide> assert_logged("Unpermitted parameters: title, author") do <ide> params.permit(book: [:pages]) <ide><path>actionpack/test/controller/parameters/multi_parameter_attributes_test.rb <ide> <ide> class MultiParameterAttributesTest < ActiveSupport::TestCase <ide> test "permitted multi-parameter attribute keys" do <del> params = ActionController::Parameters.new({ <del> book: { <add> params = ActionController::Parameters.new( book: { <ide> "shipped_at(1i)" => "2012", <ide> "shipped_at(2i)" => "3", <ide> "shipped_at(3i)" => "25", <ide> class MultiParameterAttributesTest < ActiveSupport::TestCase <ide> "published_at(3i)" => "5", <ide> "price(1)" => "R$", <ide> "price(2f)" => "2.02" <del> } <del> }) <add> }) <ide> <ide> permitted = params.permit book: [ :shipped_at, :price ] <ide> <ide><path>actionpack/test/controller/parameters/nested_parameters_permit_test.rb <ide> def assert_filtered_out(params, key) <ide> end <ide> <ide> test "permitted nested parameters" do <del> params = ActionController::Parameters.new({ <del> book: { <add> params = ActionController::Parameters.new( book: { <ide> title: "Romeo and Juliet", <ide> authors: [{ <ide> name: "William Shakespeare", <ide> def assert_filtered_out(params, key) <ide> isbn: "x" <ide> } <ide> }, <del> magazine: "Mjallo!" <del> }) <add> magazine: "Mjallo!") <ide> <ide> permitted = params.permit book: [ :title, { authors: [ :name ] }, { details: :pages }, :id ] <ide> <ide> def assert_filtered_out(params, key) <ide> end <ide> <ide> test "permitted nested parameters with a string or a symbol as a key" do <del> params = ActionController::Parameters.new({ <del> book: { <add> params = ActionController::Parameters.new( book: { <ide> "authors" => [ <ide> { name: "William Shakespeare", born: "1564-04-26" }, <ide> { name: "Christopher Marlowe" } <ide> ] <del> } <del> }) <add> }) <ide> <ide> permitted = params.permit book: [ { "authors" => [ :name ] } ] <ide> <ide> def assert_filtered_out(params, key) <ide> end <ide> <ide> test "nested arrays with strings" do <del> params = ActionController::Parameters.new({ <del> book: { <add> params = ActionController::Parameters.new( book: { <ide> genres: ["Tragedy"] <del> } <del> }) <add> }) <ide> <ide> permitted = params.permit book: {genres: []} <ide> assert_equal ["Tragedy"], permitted[:book][:genres] <ide> end <ide> <ide> test "permit may specify symbols or strings" do <del> params = ActionController::Parameters.new({ <del> book: { <add> params = ActionController::Parameters.new( book: { <ide> title: "Romeo and Juliet", <ide> author: "William Shakespeare" <ide> }, <del> magazine: "Shakespeare Today" <del> }) <add> magazine: "Shakespeare Today") <ide> <ide> permitted = params.permit({book: ["title", :author]}, "magazine") <ide> assert_equal "Romeo and Juliet", permitted[:book][:title] <ide> def assert_filtered_out(params, key) <ide> end <ide> <ide> test "nested array with strings that should be hashes" do <del> params = ActionController::Parameters.new({ <del> book: { <add> params = ActionController::Parameters.new( book: { <ide> genres: ["Tragedy"] <del> } <del> }) <add> }) <ide> <ide> permitted = params.permit book: { genres: :type } <ide> assert_empty permitted[:book][:genres] <ide> end <ide> <ide> test "nested array with strings that should be hashes and additional values" do <del> params = ActionController::Parameters.new({ <del> book: { <add> params = ActionController::Parameters.new( book: { <ide> title: "Romeo and Juliet", <ide> genres: ["Tragedy"] <del> } <del> }) <add> }) <ide> <ide> permitted = params.permit book: [ :title, { genres: :type } ] <ide> assert_equal "Romeo and Juliet", permitted[:book][:title] <ide> assert_empty permitted[:book][:genres] <ide> end <ide> <ide> test "nested string that should be a hash" do <del> params = ActionController::Parameters.new({ <del> book: { <add> params = ActionController::Parameters.new( book: { <ide> genre: "Tragedy" <del> } <del> }) <add> }) <ide> <ide> permitted = params.permit book: { genre: :type } <ide> assert_nil permitted[:book][:genre] <ide> end <ide> <ide> test "fields_for-style nested params" do <del> params = ActionController::Parameters.new({ <del> book: { <add> params = ActionController::Parameters.new( book: { <ide> authors_attributes: { <ide> '0': { name: "William Shakespeare", age_of_death: "52" }, <ide> '1': { name: "Unattributed Assistant" }, <ide> '2': { name: %w(injected names) } <ide> } <del> } <del> }) <add> }) <ide> permitted = params.permit book: { authors_attributes: [ :name ] } <ide> <ide> assert_not_nil permitted[:book][:authors_attributes]["0"] <ide> def assert_filtered_out(params, key) <ide> end <ide> <ide> test "fields_for-style nested params with negative numbers" do <del> params = ActionController::Parameters.new({ <del> book: { <add> params = ActionController::Parameters.new( book: { <ide> authors_attributes: { <ide> '-1': { name: "William Shakespeare", age_of_death: "52" }, <ide> '-2': { name: "Unattributed Assistant" } <ide> } <del> } <del> }) <add> }) <ide> permitted = params.permit book: { authors_attributes: [:name] } <ide> <ide> assert_not_nil permitted[:book][:authors_attributes]["-1"] <ide> def assert_filtered_out(params, key) <ide> end <ide> <ide> test "nested number as key" do <del> params = ActionController::Parameters.new({ <del> product: { <add> params = ActionController::Parameters.new( product: { <ide> properties: { <ide> "0" => "prop0", <ide> "1" => "prop1" <ide> } <del> } <del> }) <add> }) <ide> params = params.require(:product).permit(properties: ["0"]) <ide> assert_not_nil params[:properties]["0"] <ide> assert_nil params[:properties]["1"] <ide><path>actionpack/test/controller/parameters/parameters_permit_test.rb <ide> def walk_permitted params <ide> test "permitted takes a default value when Parameters.permit_all_parameters is set" do <ide> begin <ide> ActionController::Parameters.permit_all_parameters = true <del> params = ActionController::Parameters.new({ person: { <add> params = ActionController::Parameters.new(person: { <ide> age: "32", name: { first: "David", last: "Heinemeier Hansson" } <del> }}) <add> }) <ide> <ide> assert params.slice(:person).permitted? <ide> assert params[:person][:name].permitted? <ide><path>actionpack/test/controller/parameters/raise_on_unpermitted_params_test.rb <ide> def teardown <ide> end <ide> <ide> test "raises on unexpected params" do <del> params = ActionController::Parameters.new({ <del> book: { pages: 65 }, <del> fishing: "Turnips" <del> }) <add> params = ActionController::Parameters.new( book: { pages: 65 }, <add> fishing: "Turnips") <ide> <ide> assert_raises(ActionController::UnpermittedParameters) do <ide> params.permit(book: [:pages]) <ide> end <ide> end <ide> <ide> test "raises on unexpected nested params" do <del> params = ActionController::Parameters.new({ <del> book: { pages: 65, title: "Green Cats and where to find then." } <del> }) <add> params = ActionController::Parameters.new( book: { pages: 65, title: "Green Cats and where to find then." }) <ide> <ide> assert_raises(ActionController::UnpermittedParameters) do <ide> params.permit(book: [:pages]) <ide><path>actionpack/test/controller/params_wrapper_test.rb <ide> module Admin; class User; end; end <ide> <ide> module ParamsWrapperTestHelp <ide> def with_default_wrapper_options(&block) <del> @controller.class._set_wrapper_options({format: [:json]}) <add> @controller.class._set_wrapper_options(format: [:json]) <ide> @controller.class.inherited(@controller.class) <ide> yield <ide> end <ide> def test_filtered_parameters <ide> with_default_wrapper_options do <ide> @request.env["CONTENT_TYPE"] = "application/json" <ide> post :parse, params: { "username" => "sikachu" } <del> assert_equal @request.filtered_parameters, { "controller" => "params_wrapper_test/users", "action" => "parse", "username" => "sikachu", "user" => { "username" => "sikachu" } } <add> assert_equal @request.filtered_parameters, "controller" => "params_wrapper_test/users", "action" => "parse", "username" => "sikachu", "user" => { "username" => "sikachu" } <ide> end <ide> end <ide> <ide> def test_derived_name_from_controller <ide> with_default_wrapper_options do <ide> @request.env["CONTENT_TYPE"] = "application/json" <ide> post :parse, params: { "username" => "sikachu" } <del> assert_parameters({ "username" => "sikachu", "user" => { "username" => "sikachu" }}) <add> assert_parameters("username" => "sikachu", "user" => { "username" => "sikachu" }) <ide> end <ide> end <ide> <ide> def test_specify_wrapper_name <ide> <ide> @request.env["CONTENT_TYPE"] = "application/json" <ide> post :parse, params: { "username" => "sikachu" } <del> assert_parameters({ "username" => "sikachu", "person" => { "username" => "sikachu" }}) <add> assert_parameters("username" => "sikachu", "person" => { "username" => "sikachu" }) <ide> end <ide> end <ide> <ide> def test_specify_wrapper_model <ide> <ide> @request.env["CONTENT_TYPE"] = "application/json" <ide> post :parse, params: { "username" => "sikachu" } <del> assert_parameters({ "username" => "sikachu", "person" => { "username" => "sikachu" }}) <add> assert_parameters("username" => "sikachu", "person" => { "username" => "sikachu" }) <ide> end <ide> end <ide> <ide> def test_specify_include_option <ide> <ide> @request.env["CONTENT_TYPE"] = "application/json" <ide> post :parse, params: { "username" => "sikachu", "title" => "Developer" } <del> assert_parameters({ "username" => "sikachu", "title" => "Developer", "user" => { "username" => "sikachu" }}) <add> assert_parameters("username" => "sikachu", "title" => "Developer", "user" => { "username" => "sikachu" }) <ide> end <ide> end <ide> <ide> def test_specify_exclude_option <ide> <ide> @request.env["CONTENT_TYPE"] = "application/json" <ide> post :parse, params: { "username" => "sikachu", "title" => "Developer" } <del> assert_parameters({ "username" => "sikachu", "title" => "Developer", "user" => { "username" => "sikachu" }}) <add> assert_parameters("username" => "sikachu", "title" => "Developer", "user" => { "username" => "sikachu" }) <ide> end <ide> end <ide> <ide> def test_specify_both_wrapper_name_and_include_option <ide> <ide> @request.env["CONTENT_TYPE"] = "application/json" <ide> post :parse, params: { "username" => "sikachu", "title" => "Developer" } <del> assert_parameters({ "username" => "sikachu", "title" => "Developer", "person" => { "username" => "sikachu" }}) <add> assert_parameters("username" => "sikachu", "title" => "Developer", "person" => { "username" => "sikachu" }) <ide> end <ide> end <ide> <ide> def test_not_enabled_format <ide> with_default_wrapper_options do <ide> @request.env["CONTENT_TYPE"] = "application/xml" <ide> post :parse, params: { "username" => "sikachu", "title" => "Developer" } <del> assert_parameters({ "username" => "sikachu", "title" => "Developer" }) <add> assert_parameters("username" => "sikachu", "title" => "Developer") <ide> end <ide> end <ide> <ide> def test_wrap_parameters_false <ide> UsersController.wrap_parameters false <ide> @request.env["CONTENT_TYPE"] = "application/json" <ide> post :parse, params: { "username" => "sikachu", "title" => "Developer" } <del> assert_parameters({ "username" => "sikachu", "title" => "Developer" }) <add> assert_parameters("username" => "sikachu", "title" => "Developer") <ide> end <ide> end <ide> <ide> def test_specify_format <ide> <ide> @request.env["CONTENT_TYPE"] = "application/xml" <ide> post :parse, params: { "username" => "sikachu", "title" => "Developer" } <del> assert_parameters({ "username" => "sikachu", "title" => "Developer", "user" => { "username" => "sikachu", "title" => "Developer" }}) <add> assert_parameters("username" => "sikachu", "title" => "Developer", "user" => { "username" => "sikachu", "title" => "Developer" }) <ide> end <ide> end <ide> <ide> def test_not_wrap_reserved_parameters <ide> with_default_wrapper_options do <ide> @request.env["CONTENT_TYPE"] = "application/json" <ide> post :parse, params: { "authenticity_token" => "pwned", "_method" => "put", "utf8" => "&#9731;", "username" => "sikachu" } <del> assert_parameters({ "authenticity_token" => "pwned", "_method" => "put", "utf8" => "&#9731;", "username" => "sikachu", "user" => { "username" => "sikachu" }}) <add> assert_parameters("authenticity_token" => "pwned", "_method" => "put", "utf8" => "&#9731;", "username" => "sikachu", "user" => { "username" => "sikachu" }) <ide> end <ide> end <ide> <ide> def test_no_double_wrap_if_key_exists <ide> with_default_wrapper_options do <ide> @request.env["CONTENT_TYPE"] = "application/json" <ide> post :parse, params: { "user" => { "username" => "sikachu" }} <del> assert_parameters({ "user" => { "username" => "sikachu" }}) <add> assert_parameters("user" => { "username" => "sikachu" }) <ide> end <ide> end <ide> <ide> def test_nested_params <ide> with_default_wrapper_options do <ide> @request.env["CONTENT_TYPE"] = "application/json" <ide> post :parse, params: { "person" => { "username" => "sikachu" }} <del> assert_parameters({ "person" => { "username" => "sikachu" }, "user" => {"person" => { "username" => "sikachu" }}}) <add> assert_parameters("person" => { "username" => "sikachu" }, "user" => {"person" => { "username" => "sikachu" }}) <ide> end <ide> end <ide> <ide> def test_derived_wrapped_keys_from_matching_model <ide> with_default_wrapper_options do <ide> @request.env["CONTENT_TYPE"] = "application/json" <ide> post :parse, params: { "username" => "sikachu", "title" => "Developer" } <del> assert_parameters({ "username" => "sikachu", "title" => "Developer", "user" => { "username" => "sikachu" }}) <add> assert_parameters("username" => "sikachu", "title" => "Developer", "user" => { "username" => "sikachu" }) <ide> end <ide> end <ide> end <ide> def test_derived_wrapped_keys_from_specified_model <ide> <ide> @request.env["CONTENT_TYPE"] = "application/json" <ide> post :parse, params: { "username" => "sikachu", "title" => "Developer" } <del> assert_parameters({ "username" => "sikachu", "title" => "Developer", "person" => { "username" => "sikachu" }}) <add> assert_parameters("username" => "sikachu", "title" => "Developer", "person" => { "username" => "sikachu" }) <ide> end <ide> end <ide> end <ide> def test_not_wrapping_abstract_model <ide> with_default_wrapper_options do <ide> @request.env["CONTENT_TYPE"] = "application/json" <ide> post :parse, params: { "username" => "sikachu", "title" => "Developer" } <del> assert_parameters({ "username" => "sikachu", "title" => "Developer", "user" => { "username" => "sikachu", "title" => "Developer" }}) <add> assert_parameters("username" => "sikachu", "title" => "Developer", "user" => { "username" => "sikachu", "title" => "Developer" }) <ide> end <ide> end <ide> <ide> def test_preserves_query_string_params <ide> @request.env["CONTENT_TYPE"] = "application/json" <ide> get :parse, params: { "user" => { "username" => "nixon" } } <ide> assert_parameters( <del> {"user" => { "username" => "nixon" } } <add> "user" => { "username" => "nixon" } <ide> ) <ide> end <ide> end <ide> def test_empty_parameter_set <ide> @request.env["CONTENT_TYPE"] = "application/json" <ide> post :parse, params: {} <ide> assert_parameters( <del> {"user" => { } } <add> "user" => { } <ide> ) <ide> end <ide> end <ide> def test_derived_name_from_controller <ide> with_default_wrapper_options do <ide> @request.env["CONTENT_TYPE"] = "application/json" <ide> post :parse, params: { "username" => "sikachu" } <del> assert_parameters({"username" => "sikachu", "user" => { "username" => "sikachu" }}) <add> assert_parameters("username" => "sikachu", "user" => { "username" => "sikachu" }) <ide> end <ide> end <ide> <ide> def test_namespace_lookup_from_model <ide> with_default_wrapper_options do <ide> @request.env["CONTENT_TYPE"] = "application/json" <ide> post :parse, params: { "username" => "sikachu", "title" => "Developer" } <del> assert_parameters({ "username" => "sikachu", "title" => "Developer", "user" => { "username" => "sikachu" }}) <add> assert_parameters("username" => "sikachu", "title" => "Developer", "user" => { "username" => "sikachu" }) <ide> end <ide> ensure <ide> Admin.send :remove_const, :User <ide> def test_hierarchy_namespace_lookup_from_model <ide> with_default_wrapper_options do <ide> @request.env["CONTENT_TYPE"] = "application/json" <ide> post :parse, params: { "username" => "sikachu", "title" => "Developer" } <del> assert_parameters({ "username" => "sikachu", "title" => "Developer", "user" => { "title" => "Developer" }}) <add> assert_parameters("username" => "sikachu", "title" => "Developer", "user" => { "title" => "Developer" }) <ide> end <ide> ensure <ide> Object.send :remove_const, :User <ide> def test_does_not_implicitly_wrap_params <ide> with_default_wrapper_options do <ide> @request.env["CONTENT_TYPE"] = "application/json" <ide> post :parse, params: { "username" => "sikachu" } <del> assert_parameters({ "username" => "sikachu" }) <add> assert_parameters("username" => "sikachu") <ide> end <ide> end <ide> <ide> def test_does_wrap_params_if_name_provided <ide> @controller.class.wrap_parameters(name: "guest") <ide> @request.env["CONTENT_TYPE"] = "application/json" <ide> post :parse, params: { "username" => "sikachu" } <del> assert_parameters({ "username" => "sikachu", "guest" => { "username" => "sikachu" }}) <add> assert_parameters("username" => "sikachu", "guest" => { "username" => "sikachu" }) <ide> end <ide> end <ide> end <ide> def test_uses_model_attribute_names_with_irregular_inflection <ide> with_default_wrapper_options do <ide> @request.env["CONTENT_TYPE"] = "application/json" <ide> post :parse, params: { "username" => "sikachu", "test_attr" => "test_value" } <del> assert_parameters({ "username" => "sikachu", "test_attr" => "test_value", "paramswrappernews_item" => { "test_attr" => "test_value" }}) <add> assert_parameters("username" => "sikachu", "test_attr" => "test_value", "paramswrappernews_item" => { "test_attr" => "test_value" }) <ide> end <ide> end <ide> end <ide><path>actionpack/test/controller/redirect_test.rb <ide> def simple_redirect <ide> end <ide> <ide> def redirect_with_status <del> redirect_to({action: "hello_world", status: 301}) <add> redirect_to(action: "hello_world", status: 301) <ide> end <ide> <ide> def redirect_with_status_hash <del> redirect_to({action: "hello_world"}, {status: 301}) <add> redirect_to({action: "hello_world"}, status: 301) <ide> end <ide> <ide> def redirect_with_protocol <ide> def url_redirect_with_status <ide> end <ide> <ide> def url_redirect_with_status_hash <del> redirect_to("http://www.example.com", {status: 301}) <add> redirect_to("http://www.example.com", status: 301) <ide> end <ide> <ide> def relative_url_redirect_with_status <ide> redirect_to("/things/stuff", status: :found) <ide> end <ide> <ide> def relative_url_redirect_with_status_hash <del> redirect_to("/things/stuff", {status: 301}) <add> redirect_to("/things/stuff", status: 301) <ide> end <ide> <ide> def redirect_to_back_with_status <ide><path>actionpack/test/controller/renderer_test.rb <ide> class RendererTest < ActiveSupport::TestCase <ide> end <ide> <ide> test "rendering with user specified defaults" do <del> ApplicationController.renderer.defaults.merge!({ hello: "hello", https: true }) <add> ApplicationController.renderer.defaults.merge!(hello: "hello", https: true) <ide> renderer = ApplicationController.renderer.new <ide> content = renderer.render inline: "<%= request.ssl? %>" <ide> <ide><path>actionpack/test/controller/required_params_test.rb <ide> class ParametersRequireTest < ActiveSupport::TestCase <ide> <ide> test "Deprecated methods are deprecated" do <ide> assert_deprecated do <del> ActionController::Parameters.new(foo: "bar").merge!({bar: "foo"}) <add> ActionController::Parameters.new(foo: "bar").merge!(bar: "foo") <ide> end <ide> end <ide> end <ide><path>actionpack/test/controller/resources_test.rb <ide> def test_assert_routing_accepts_all_as_a_valid_method <ide> match "/products", to: "products#show", via: :all <ide> end <ide> <del> assert_routing({ method: "all", path: "/products" }, { controller: "products", action: "show" }) <add> assert_routing({ method: "all", path: "/products" }, controller: "products", action: "show") <ide> end <ide> end <ide> <ide> def test_assert_routing_fails_when_not_all_http_methods_are_recognized <ide> end <ide> <ide> assert_raises(Minitest::Assertion) do <del> assert_routing({ method: "all", path: "/products" }, { controller: "products", action: "show" }) <add> assert_routing({ method: "all", path: "/products" }, controller: "products", action: "show") <ide> end <ide> end <ide> end <ide><path>actionpack/test/controller/routing_test.rb <ide> def setup <ide> <ide> def test_route_generation_escapes_unsafe_path_characters <ide> assert_equal "/content/act#{@escaped}ion/var#{@escaped}iable/add#{@escaped}itional-1/add#{@escaped}itional-2", <del> url_for(@set, { <del> controller: "content", <add> url_for(@set, controller: "content", <ide> action: "act#{@segment}ion", <ide> variable: "var#{@segment}iable", <del> additional: ["add#{@segment}itional-1", "add#{@segment}itional-2"] <del> }) <add> additional: ["add#{@segment}itional-1", "add#{@segment}itional-2"]) <ide> end <ide> <ide> def test_route_recognition_unescapes_path_components <ide> def test_route_recognition_unescapes_path_components <ide> <ide> def test_route_generation_allows_passing_non_string_values_to_generated_helper <ide> assert_equal "/content/action/variable/1/2", <del> url_for(@set, { <del> controller: "content", <add> url_for(@set, controller: "content", <ide> action: "action", <ide> variable: "variable", <del> additional: [1, 2] <del> }) <add> additional: [1, 2]) <ide> end <ide> end <ide> <ide> def test_default_setup <ide> <ide> assert_equal({controller: "admin/user", action: "show", id: "10"}, rs.recognize_path("/admin/user/show/10")) <ide> <del> assert_equal "/admin/user/show/10", url_for(rs, { controller: "admin/user", action: "show", id: 10 }) <add> assert_equal "/admin/user/show/10", url_for(rs, controller: "admin/user", action: "show", id: 10) <ide> <ide> get URI("http://test.host/admin/user/list/10") <ide> <ide> assert_equal({ controller: "admin/user", action: "list", id: "10" }, <ide> controller.request.path_parameters) <ide> <del> assert_equal "/admin/user/show", controller.url_for({ action: "show", only_path: true }) <del> assert_equal "/admin/user/list/10", controller.url_for({only_path: true}) <add> assert_equal "/admin/user/show", controller.url_for(action: "show", only_path: true) <add> assert_equal "/admin/user/list/10", controller.url_for(only_path: true) <ide> <del> assert_equal "/admin/stuff", controller.url_for({ controller: "stuff", only_path: true }) <del> assert_equal "/stuff", controller.url_for({ controller: "/stuff", only_path: true }) <add> assert_equal "/admin/stuff", controller.url_for(controller: "stuff", only_path: true) <add> assert_equal "/stuff", controller.url_for(controller: "/stuff", only_path: true) <ide> end <ide> <ide> def test_route_with_colon_first <ide> def test_route_with_regexp_for_action <ide> assert_equal({ action: "auth_google", controller: "content" }, rs.recognize_path("/content/auth_google")) <ide> assert_equal({ action: "auth-facebook", controller: "content" }, rs.recognize_path("/content/auth-facebook")) <ide> <del> assert_equal "/content/auth_google", url_for(rs, { controller: "content", action: "auth_google" }) <del> assert_equal "/content/auth-facebook", url_for(rs, { controller: "content", action: "auth-facebook" }) <add> assert_equal "/content/auth_google", url_for(rs, controller: "content", action: "auth_google") <add> assert_equal "/content/auth-facebook", url_for(rs, controller: "content", action: "auth-facebook") <ide> end <ide> <ide> def test_route_with_regexp_for_controller <ide> def test_route_with_regexp_for_controller <ide> assert_equal({controller: "content", action: "foo"}, <ide> rs.recognize_path("/content/foo")) <ide> <del> assert_equal "/admin/user/foo", url_for(rs, { controller: "admin/user", admintoken: "foo", action: "index" }) <del> assert_equal "/content/foo", url_for(rs, { controller: "content", action: "foo" }) <add> assert_equal "/admin/user/foo", url_for(rs, controller: "admin/user", admintoken: "foo", action: "index") <add> assert_equal "/content/foo", url_for(rs, controller: "content", action: "foo") <ide> end <ide> <ide> def test_route_with_regexp_and_captures_for_controller <ide> def test_route_with_regexp_and_dot <ide> end <ide> # Without a file extension <ide> assert_equal "/user/download/file", <del> url_for(rs, { controller: "user", action: "download", file: "file" }) <add> url_for(rs, controller: "user", action: "download", file: "file") <ide> <ide> assert_equal({controller: "user", action: "download", file: "file"}, <ide> rs.recognize_path("/user/download/file")) <ide> <ide> # Now, let's try a file with an extension, really a dot (.) <ide> assert_equal "/user/download/file.jpg", <del> url_for(rs, { controller: "user", action: "download", file: "file.jpg" }) <add> url_for(rs, controller: "user", action: "download", file: "file.jpg") <ide> <ide> assert_equal({controller: "user", action: "download", file: "file.jpg"}, <ide> rs.recognize_path("/user/download/file.jpg")) <ide> def test_changing_controller <ide> get URI("http://test.host/admin/user/index/10") <ide> <ide> assert_equal "/admin/stuff/show/10", <del> controller.url_for({controller: "stuff", action: "show", id: 10, only_path: true}) <add> controller.url_for(controller: "stuff", action: "show", id: 10, only_path: true) <ide> end <ide> <ide> def test_paths_escaped <ide> def test_should_list_options_diff_when_routing_constraints_dont_match <ide> get "post/:id" => "post#show", :constraints => { id: /\d+/ }, :as => "post" <ide> end <ide> assert_raise(ActionController::UrlGenerationError) do <del> url_for(rs, { controller: "post", action: "show", bad_param: "foo", use_route: "post" }) <add> url_for(rs, controller: "post", action: "show", bad_param: "foo", use_route: "post") <ide> end <ide> end <ide> <ide> def test_dynamic_path_allowed <ide> end <ide> <ide> assert_equal "/pages/boo", <del> url_for(rs, { controller: "content", action: "show_file", path: %w(pages boo) }) <add> url_for(rs, controller: "content", action: "show_file", path: %w(pages boo)) <ide> end <ide> <ide> def test_dynamic_recall_paths_allowed <ide> def test_backwards <ide> end <ide> <ide> get URI("http://test.host/pages/show") <del> assert_equal "/page/20", controller.url_for({ id: 20, only_path: true }) <del> assert_equal "/page/20", url_for(rs, { controller: "pages", id: 20, action: "show" }) <del> assert_equal "/pages/boo", url_for(rs, { controller: "pages", action: "boo" }) <add> assert_equal "/page/20", controller.url_for(id: 20, only_path: true) <add> assert_equal "/page/20", url_for(rs, controller: "pages", id: 20, action: "show") <add> assert_equal "/pages/boo", url_for(rs, controller: "pages", action: "boo") <ide> end <ide> <ide> def test_route_with_integer_default <ide> def test_route_with_integer_default <ide> end <ide> end <ide> <del> assert_equal "/page", url_for(rs, { controller: "content", action: "show_page" }) <del> assert_equal "/page", url_for(rs, { controller: "content", action: "show_page", id: 1 }) <del> assert_equal "/page", url_for(rs, { controller: "content", action: "show_page", id: "1" }) <del> assert_equal "/page/10", url_for(rs, { controller: "content", action: "show_page", id: 10 }) <add> assert_equal "/page", url_for(rs, controller: "content", action: "show_page") <add> assert_equal "/page", url_for(rs, controller: "content", action: "show_page", id: 1) <add> assert_equal "/page", url_for(rs, controller: "content", action: "show_page", id: "1") <add> assert_equal "/page/10", url_for(rs, controller: "content", action: "show_page", id: 10) <ide> <ide> assert_equal({controller: "content", action: "show_page", id: 1 }, rs.recognize_path("/page")) <ide> assert_equal({controller: "content", action: "show_page", id: "1"}, rs.recognize_path("/page/1")) <ide> def test_route_with_text_default <ide> end <ide> end <ide> <del> assert_equal "/page/foo", url_for(rs, { controller: "content", action: "show_page", id: "foo" }) <add> assert_equal "/page/foo", url_for(rs, controller: "content", action: "show_page", id: "foo") <ide> assert_equal({ controller: "content", action: "show_page", id: "foo" }, rs.recognize_path("/page/foo")) <ide> <ide> token = "\321\202\320\265\320\272\321\201\321\202" # 'text' in Russian <ide> token.force_encoding(Encoding::BINARY) <ide> escaped_token = CGI::escape(token) <ide> <del> assert_equal "/page/" + escaped_token, url_for(rs, { controller: "content", action: "show_page", id: token }) <add> assert_equal "/page/" + escaped_token, url_for(rs, controller: "content", action: "show_page", id: token) <ide> assert_equal({ controller: "content", action: "show_page", id: token }, rs.recognize_path("/page/#{escaped_token}")) <ide> end <ide> <ide> def test_requirement_should_prevent_optional_id <ide> get "post/:id" => "post#show", :constraints => {id: /\d+/}, :as => "post" <ide> end <ide> <del> assert_equal "/post/10", url_for(rs, { controller: "post", action: "show", id: 10 }) <add> assert_equal "/post/10", url_for(rs, controller: "post", action: "show", id: 10) <ide> <ide> assert_raise(ActionController::UrlGenerationError) do <del> url_for(rs, { controller: "post", action: "show" }) <add> url_for(rs, controller: "post", action: "show") <ide> end <ide> end <ide> <ide> def test_both_requirement_and_optional <ide> end <ide> end <ide> <del> assert_equal "/test", url_for(rs, { controller: "post", action: "show" }) <del> assert_equal "/test", url_for(rs, { controller: "post", action: "show", year: nil }) <add> assert_equal "/test", url_for(rs, controller: "post", action: "show") <add> assert_equal "/test", url_for(rs, controller: "post", action: "show", year: nil) <ide> <ide> assert_equal("http://test.host/test", setup_for_named_route.send(:blog_url)) <ide> end <ide> def test_set_to_nil_forgets <ide> end <ide> <ide> assert_equal "/pages/2005", <del> url_for(rs, { controller: "content", action: "list_pages", year: 2005 }) <add> url_for(rs, controller: "content", action: "list_pages", year: 2005) <ide> assert_equal "/pages/2005/6", <del> url_for(rs, { controller: "content", action: "list_pages", year: 2005, month: 6 }) <add> url_for(rs, controller: "content", action: "list_pages", year: 2005, month: 6) <ide> assert_equal "/pages/2005/6/12", <del> url_for(rs, { controller: "content", action: "list_pages", year: 2005, month: 6, day: 12 }) <add> url_for(rs, controller: "content", action: "list_pages", year: 2005, month: 6, day: 12) <ide> <ide> get URI("http://test.host/pages/2005/6/12") <ide> assert_equal({ controller: "content", action: "list_pages", year: "2005", month: "6", day: "12" }, <ide> controller.request.path_parameters) <ide> <ide> assert_equal "/pages/2005/6/4", <del> controller.url_for({ day: 4, only_path: true }) <add> controller.url_for(day: 4, only_path: true) <ide> <ide> assert_equal "/pages/2005/6", <del> controller.url_for({ day: nil, only_path: true }) <add> controller.url_for(day: nil, only_path: true) <ide> <ide> assert_equal "/pages/2005", <del> controller.url_for({ day: nil, month: nil, only_path: true }) <add> controller.url_for(day: nil, month: nil, only_path: true) <ide> end <ide> <ide> def test_root_url_generation_with_controller_and_action <ide> rs.draw do <ide> root to: "content#index" <ide> end <ide> <del> assert_equal "/", url_for(rs, { controller: "content", action: "index" }) <del> assert_equal "/", url_for(rs, { controller: "content" }) <add> assert_equal "/", url_for(rs, controller: "content", action: "index") <add> assert_equal "/", url_for(rs, controller: "content") <ide> end <ide> <ide> def test_named_root_url_generation_with_controller_and_action <ide> rs.draw do <ide> root to: "content#index", as: "home" <ide> end <ide> <del> assert_equal "/", url_for(rs, { controller: "content", action: "index" }) <del> assert_equal "/", url_for(rs, { controller: "content" }) <add> assert_equal "/", url_for(rs, controller: "content", action: "index") <add> assert_equal "/", url_for(rs, controller: "content") <ide> <ide> assert_equal("http://test.host/", setup_for_named_route.send(:home_url)) <ide> end <ide> def test_named_route_method <ide> end <ide> end <ide> <del> assert_equal "/categories", url_for(rs, { controller: "content", action: "categories" }) <del> assert_equal "/content/hi", url_for(rs, { controller: "content", action: "hi" }) <add> assert_equal "/categories", url_for(rs, controller: "content", action: "categories") <add> assert_equal "/content/hi", url_for(rs, controller: "content", action: "hi") <ide> end <ide> <ide> def test_named_routes_array <ide> def test_nil_defaults <ide> end <ide> end <ide> <del> assert_equal "/journal", url_for(rs, { <del> controller: "content", <add> assert_equal "/journal", url_for(rs, controller: "content", <ide> action: "list_journal", <ide> date: nil, <del> user_id: nil <del> }) <add> user_id: nil) <ide> end <ide> <ide> def setup_request_method_routes_for(method) <ide> def test_subpath_generated <ide> end <ide> end <ide> <del> assert_equal "/books/7/edit", url_for(rs, { controller: "subpath_books", id: 7, action: "edit" }) <del> assert_equal "/items/15/complete", url_for(rs, { controller: "subpath_books", id: 15, action: "complete" }) <del> assert_equal "/posts/new/preview", url_for(rs, { controller: "subpath_books", action: "preview" }) <add> assert_equal "/books/7/edit", url_for(rs, controller: "subpath_books", id: 7, action: "edit") <add> assert_equal "/items/15/complete", url_for(rs, controller: "subpath_books", id: 15, action: "complete") <add> assert_equal "/posts/new/preview", url_for(rs, controller: "subpath_books", action: "preview") <ide> end <ide> <ide> def test_failed_constraints_raises_exception_with_violated_constraints <ide> def test_generate_not_first <ide> end <ide> end <ide> assert_equal "/foo/bar/15?this=hello", <del> url_for(set, { controller: "foo", action: "bar", id: 15, this: "hello" }) <add> url_for(set, controller: "foo", action: "bar", id: 15, this: "hello") <ide> end <ide> <ide> def test_extra_keys_not_first <ide> def test_draw_default_route <ide> <ide> assert_equal 1, set.routes.size <ide> <del> assert_equal "/users/show/10", url_for(set, { controller: "users", action: "show", id: 10 }) <del> assert_equal "/users/index/10", url_for(set, { controller: "users", id: 10 }) <add> assert_equal "/users/show/10", url_for(set, controller: "users", action: "show", id: 10) <add> assert_equal "/users/index/10", url_for(set, controller: "users", id: 10) <ide> <ide> assert_equal({controller: "users", action: "index", id: "10"}, set.recognize_path("/users/index/10")) <ide> assert_equal({controller: "users", action: "index", id: "10"}, set.recognize_path("/users/index/10/")) <ide> def test_generate_with_default_action <ide> get "/people/list", controller: "people", action: "list" <ide> end <ide> <del> url = url_for(set, { controller: "people", action: "list" }) <add> url = url_for(set, controller: "people", action: "list") <ide> assert_equal "/people/list", url <ide> end <ide> <ide> def test_named_routes_are_never_relative_to_modules <ide> assert_equal({ controller: "connection/manage", <ide> action: "index", }, request_path_params("/connection/manage")) <ide> <del> url = controller.url_for({ controller: "connection", only_path: true }) <add> url = controller.url_for(controller: "connection", only_path: true) <ide> assert_equal "/connection/connection", url <ide> <del> url = controller.url_for({ use_route: "family_connection", <del> controller: "connection", only_path: true }) <add> url = controller.url_for(use_route: "family_connection", <add> controller: "connection", only_path: true) <ide> assert_equal "/connection", url <ide> end <ide> <ide> def test_query_params_will_be_shown_when_recalled <ide> get URI("http://test.host/weblog/show/1") <ide> <ide> assert_equal "/weblog/edit?parameter=1", controller.url_for( <del> {action: "edit", parameter: 1, only_path: true}) <add> action: "edit", parameter: 1, only_path: true) <ide> end <ide> <ide> def test_format_is_not_inherit <ide> def test_format_is_not_inherit <ide> controller.request.path_parameters) <ide> <ide> assert_equal "/posts", controller.url_for( <del> {controller: "posts", only_path: true}) <add> controller: "posts", only_path: true) <ide> <ide> assert_equal "/posts.xml", controller.url_for( <del> {controller: "posts", format: "xml", only_path: true}) <add> controller: "posts", format: "xml", only_path: true) <ide> end <ide> <ide> def test_expiry_determination_should_consider_values_with_to_param <ide> def test_expiry_determination_should_consider_values_with_to_param <ide> controller.request.path_parameters) <ide> <ide> assert_equal "/projects/1/weblog/show", <del> controller.url_for({ action: "show", project_id: 1, only_path: true }) <add> controller.url_for(action: "show", project_id: 1, only_path: true) <ide> end <ide> <ide> def test_named_route_in_nested_resource <ide> def test_route_requirement_generate_with_ignore_case <ide> :constraints => {name: /(david|jamis)/i} <ide> end <ide> <del> url = url_for(set, { controller: "pages", action: "show", name: "david" }) <add> url = url_for(set, controller: "pages", action: "show", name: "david") <ide> assert_equal "/page/david", url <ide> assert_raise(ActionController::UrlGenerationError) do <del> url_for(set, { controller: "pages", action: "show", name: "davidjamis" }) <add> url_for(set, controller: "pages", action: "show", name: "davidjamis") <ide> end <del> url = url_for(set, { controller: "pages", action: "show", name: "JAMIS" }) <add> url = url_for(set, controller: "pages", action: "show", name: "JAMIS") <ide> assert_equal "/page/JAMIS", url <ide> end <ide> <ide> def test_route_requirement_with_xi_modifiers <ide> set.recognize_path("/page/JAMIS")) <ide> <ide> assert_equal "/page/JAMIS", <del> url_for(set, { controller: "pages", action: "show", name: "JAMIS" }) <add> url_for(set, controller: "pages", action: "show", name: "JAMIS") <ide> end <ide> <ide> def test_routes_with_symbols <ide> def test_regexp_chunk_should_add_question_mark_for_optionals <ide> get "/hello" => "bar#index" <ide> end <ide> <del> assert_equal "/", url_for(set, { controller: "foo" }) <del> assert_equal "/hello", url_for(set, { controller: "bar" }) <add> assert_equal "/", url_for(set, controller: "foo") <add> assert_equal "/hello", url_for(set, controller: "bar") <ide> <ide> assert_equal({controller: "foo", action: "index"}, set.recognize_path("/")) <ide> assert_equal({controller: "bar", action: "index"}, set.recognize_path("/hello")) <ide> def test_assign_route_options_with_anchor_chars <ide> end <ide> end <ide> <del> assert_equal "/cars/buy/1/2", url_for(set, { controller: "cars", action: "buy", person: "1", car: "2" }) <add> assert_equal "/cars/buy/1/2", url_for(set, controller: "cars", action: "buy", person: "1", car: "2") <ide> <ide> assert_equal({controller: "cars", action: "buy", person: "1", car: "2"}, set.recognize_path("/cars/buy/1/2")) <ide> end <ide> def test_segmentation_of_dot_path <ide> end <ide> end <ide> <del> assert_equal "/books/list.rss", url_for(set, { controller: "books", action: "list" }) <add> assert_equal "/books/list.rss", url_for(set, controller: "books", action: "list") <ide> <ide> assert_equal({controller: "books", action: "list"}, set.recognize_path("/books/list.rss")) <ide> end <ide> def test_segmentation_of_dynamic_dot_path <ide> end <ide> end <ide> <del> assert_equal "/books/list.rss", url_for(set, { controller: "books", action: "list", format: "rss" }) <del> assert_equal "/books/list.xml", url_for(set, { controller: "books", action: "list", format: "xml" }) <del> assert_equal "/books/list", url_for(set, { controller: "books", action: "list" }) <del> assert_equal "/books", url_for(set, { controller: "books", action: "index" }) <add> assert_equal "/books/list.rss", url_for(set, controller: "books", action: "list", format: "rss") <add> assert_equal "/books/list.xml", url_for(set, controller: "books", action: "list", format: "xml") <add> assert_equal "/books/list", url_for(set, controller: "books", action: "list") <add> assert_equal "/books", url_for(set, controller: "books", action: "index") <ide> <ide> assert_equal({controller: "books", action: "list", format: "rss"}, set.recognize_path("/books/list.rss")) <ide> assert_equal({controller: "books", action: "list", format: "xml"}, set.recognize_path("/books/list.xml")) <ide> def test_segmentation_of_dynamic_dot_path <ide> def test_slashes_are_implied <ide> set.draw { ActiveSupport::Deprecation.silence { get("/:controller(/:action(/:id))") } } <ide> <del> assert_equal "/content", url_for(set, { controller: "content", action: "index" }) <del> assert_equal "/content/list", url_for(set, { controller: "content", action: "list" }) <del> assert_equal "/content/show/1", url_for(set, { controller: "content", action: "show", id: "1" }) <add> assert_equal "/content", url_for(set, controller: "content", action: "index") <add> assert_equal "/content/list", url_for(set, controller: "content", action: "list") <add> assert_equal "/content/show/1", url_for(set, controller: "content", action: "show", id: "1") <ide> <ide> assert_equal({controller: "content", action: "index"}, set.recognize_path("/content")) <ide> assert_equal({controller: "content", action: "index"}, set.recognize_path("/content/index")) <ide> def test_default_route_recognition <ide> end <ide> <ide> def test_default_route_should_omit_default_action <del> assert_equal "/accounts", url_for(default_route_set, { controller: "accounts", action: "index" }) <add> assert_equal "/accounts", url_for(default_route_set, controller: "accounts", action: "index") <ide> end <ide> <ide> def test_default_route_should_include_default_action_when_id_present <del> assert_equal "/accounts/index/20", url_for(default_route_set, { controller: "accounts", action: "index", id: "20" }) <add> assert_equal "/accounts/index/20", url_for(default_route_set, controller: "accounts", action: "index", id: "20") <ide> end <ide> <ide> def test_default_route_should_work_with_action_but_no_id <del> assert_equal "/accounts/list_all", url_for(default_route_set, { controller: "accounts", action: "list_all" }) <add> assert_equal "/accounts/list_all", url_for(default_route_set, controller: "accounts", action: "list_all") <ide> end <ide> <ide> def test_default_route_should_uri_escape_pluses <ide> def test_default_route_should_uri_escape_pluses <ide> end <ide> <ide> def test_build_empty_query_string <del> assert_uri_equal "/foo", url_for(default_route_set, { controller: "foo" }) <add> assert_uri_equal "/foo", url_for(default_route_set, controller: "foo") <ide> end <ide> <ide> def test_build_query_string_with_nil_value <del> assert_uri_equal "/foo", url_for(default_route_set, { controller: "foo", x: nil }) <add> assert_uri_equal "/foo", url_for(default_route_set, controller: "foo", x: nil) <ide> end <ide> <ide> def test_simple_build_query_string <del> assert_uri_equal "/foo?x=1&y=2", url_for(default_route_set, { controller: "foo", x: "1", y: "2" }) <add> assert_uri_equal "/foo?x=1&y=2", url_for(default_route_set, controller: "foo", x: "1", y: "2") <ide> end <ide> <ide> def test_convert_ints_build_query_string <del> assert_uri_equal "/foo?x=1&y=2", url_for(default_route_set, { controller: "foo", x: 1, y: 2 }) <add> assert_uri_equal "/foo?x=1&y=2", url_for(default_route_set, controller: "foo", x: 1, y: 2) <ide> end <ide> <ide> def test_escape_spaces_build_query_string <del> assert_uri_equal "/foo?x=hello+world&y=goodbye+world", url_for(default_route_set, { controller: "foo", x: "hello world", y: "goodbye world" }) <add> assert_uri_equal "/foo?x=hello+world&y=goodbye+world", url_for(default_route_set, controller: "foo", x: "hello world", y: "goodbye world") <ide> end <ide> <ide> def test_expand_array_build_query_string <del> assert_uri_equal "/foo?x%5B%5D=1&x%5B%5D=2", url_for(default_route_set, { controller: "foo", x: [1, 2] }) <add> assert_uri_equal "/foo?x%5B%5D=1&x%5B%5D=2", url_for(default_route_set, controller: "foo", x: [1, 2]) <ide> end <ide> <ide> def test_escape_spaces_build_query_string_selected_keys <del> assert_uri_equal "/foo?x=hello+world", url_for(default_route_set, { controller: "foo", x: "hello world" }) <add> assert_uri_equal "/foo?x=hello+world", url_for(default_route_set, controller: "foo", x: "hello world") <ide> end <ide> <ide> def test_generate_with_default_params <ide> def test_generate_with_default_params <ide> end <ide> end <ide> <del> assert_equal "/ibocorp", url_for(set, { controller: "ibocorp", action: "show", page: 1 }) <add> assert_equal "/ibocorp", url_for(set, controller: "ibocorp", action: "show", page: 1) <ide> end <ide> <ide> include ActionDispatch::RoutingVerbs <ide> def test_generate_with_optional_params_recalls_last_request <ide> get URI("http://example.org/blog/2006/07/28") <ide> <ide> assert_equal({controller: "blog", action: "show_date", year: "2006", month: "07", day: "28"}, controller.request.path_parameters) <del> assert_equal("/blog/2006/07/25", controller.url_for({ day: 25, only_path: true })) <del> assert_equal("/blog/2005", controller.url_for({ year: 2005, only_path: true })) <del> assert_equal("/blog/show/123", controller.url_for({ action: "show" , id: 123, only_path: true })) <del> assert_equal("/blog/2006", controller.url_for({ year: 2006, only_path: true })) <del> assert_equal("/blog/2006", controller.url_for({ year: 2006, month: nil, only_path: true })) <add> assert_equal("/blog/2006/07/25", controller.url_for(day: 25, only_path: true)) <add> assert_equal("/blog/2005", controller.url_for(year: 2005, only_path: true)) <add> assert_equal("/blog/show/123", controller.url_for(action: "show" , id: 123, only_path: true)) <add> assert_equal("/blog/2006", controller.url_for(year: 2006, only_path: true)) <add> assert_equal("/blog/2006", controller.url_for(year: 2006, month: nil, only_path: true)) <ide> end <ide> <ide> private <ide><path>actionpack/test/controller/test_case_test.rb <ide> def test_process_without_flash <ide> end <ide> <ide> def test_deprecated_process_with_flash <del> assert_deprecated { process :set_flash, "GET", nil, nil, { "test" => "value" } } <add> assert_deprecated { process :set_flash, "GET", nil, nil, "test" => "value" } <ide> assert_equal ">value<", flash["test"] <ide> end <ide> <ide> def test_process_with_flash <ide> end <ide> <ide> def test_deprecated_process_with_flash_now <del> assert_deprecated { process :set_flash_now, "GET", nil, nil, { "test_now" => "value_now" } } <add> assert_deprecated { process :set_flash_now, "GET", nil, nil, "test_now" => "value_now" } <ide> assert_equal ">value_now<", flash["test_now"] <ide> end <ide> <ide> def test_process_with_session <ide> end <ide> <ide> def test_process_with_session_arg <del> assert_deprecated { process :no_op, "GET", nil, { "string" => "value1", symbol: "value2" } } <add> assert_deprecated { process :no_op, "GET", nil, "string" => "value1", symbol: "value2" } <ide> assert_equal "value1", session["string"] <ide> assert_equal "value1", session[:string] <ide> assert_equal "value2", session["symbol"] <ide> def test_process_with_session_kwarg <ide> def test_deprecated_process_merges_session_arg <ide> session[:foo] = "bar" <ide> assert_deprecated { <del> get :no_op, nil, { bar: "baz" } <add> get :no_op, nil, bar: "baz" <ide> } <ide> assert_equal "bar", session[:foo] <ide> assert_equal "baz", session[:bar] <ide> def test_process_merges_session_arg <ide> <ide> def test_deprecated_merged_session_arg_is_retained_across_requests <ide> assert_deprecated { <del> get :no_op, nil, { foo: "bar" } <add> get :no_op, nil, foo: "bar" <ide> } <ide> assert_equal "bar", session[:foo] <ide> get :no_op <ide> def test_should_not_impose_childless_html_tags_in_xml <ide> <ide> def test_assert_generates <ide> assert_generates "controller/action/5", controller: "controller", action: "action", id: "5" <del> assert_generates "controller/action/7", { id: "7" }, { controller: "controller", action: "action" } <del> assert_generates "controller/action/5", { controller: "controller", action: "action", id: "5", name: "bob" }, {}, { name: "bob" } <del> assert_generates "controller/action/7", { id: "7", name: "bob" }, { controller: "controller", action: "action" }, { name: "bob" } <add> assert_generates "controller/action/7", { id: "7" }, controller: "controller", action: "action" <add> assert_generates "controller/action/5", { controller: "controller", action: "action", id: "5", name: "bob" }, {}, name: "bob" <add> assert_generates "controller/action/7", { id: "7", name: "bob" }, { controller: "controller", action: "action" }, name: "bob" <ide> assert_generates "controller/action/7", { id: "7" }, { controller: "controller", action: "action", name: "bob" }, {} <ide> end <ide> <ide> def test_assert_routing <ide> def test_assert_routing_with_method <ide> with_routing do |set| <ide> set.draw { resources(:content) } <del> assert_routing({ method: "post", path: "content" }, { controller: "content", action: "create" }) <add> assert_routing({ method: "post", path: "content" }, controller: "content", action: "create") <ide> end <ide> end <ide> <ide> def test_assert_routing_in_module <ide> def test_assert_routing_with_glob <ide> with_routing do |set| <ide> set.draw { get("*path" => "pages#show") } <del> assert_routing("/company/about", { controller: "pages", action: "show", path: "company/about" }) <add> assert_routing("/company/about", controller: "pages", action: "show", path: "company/about") <ide> end <ide> end <ide> <ide><path>actionpack/test/controller/url_for_test.rb <ide> def test_nested_optional <ide> self.default_url_options[:host] = "example.com" <ide> } <ide> <del> path = klass.new.fun_path({controller: :articles, <add> path = klass.new.fun_path(controller: :articles, <ide> baz: "baz", <del> zot: "zot"}) <add> zot: "zot") <ide> # :bar key isn't provided <ide> assert_equal "/foo/zot", path <ide> end <ide> def test_trailing_slash_with_protocol <ide> add_host! <ide> options = { trailing_slash: true,protocol: "https", controller: "foo", action: "bar", id: "33"} <ide> assert_equal("https://www.basecamphq.com/foo/bar/33/", W.new.url_for(options) ) <del> assert_equal "https://www.basecamphq.com/foo/bar/33/?query=string", W.new.url_for(options.merge({query: "string"})) <add> assert_equal "https://www.basecamphq.com/foo/bar/33/?query=string", W.new.url_for(options.merge(query: "string")) <ide> end <ide> <ide> def test_trailing_slash_with_only_path <ide> options = {controller: "foo", trailing_slash: true} <del> assert_equal "/foo/", W.new.url_for(options.merge({only_path: true})) <del> options.update({action: "bar", id: "33"}) <del> assert_equal "/foo/bar/33/", W.new.url_for(options.merge({only_path: true})) <del> assert_equal "/foo/bar/33/?query=string", W.new.url_for(options.merge({query: "string",only_path: true})) <add> assert_equal "/foo/", W.new.url_for(options.merge(only_path: true)) <add> options.update(action: "bar", id: "33") <add> assert_equal "/foo/bar/33/", W.new.url_for(options.merge(only_path: true)) <add> assert_equal "/foo/bar/33/?query=string", W.new.url_for(options.merge(query: "string",only_path: true)) <ide> end <ide> <ide> def test_trailing_slash_with_anchor <ide> options = {trailing_slash: true, controller: "foo", action: "bar", id: "33", only_path: true, anchor: "chapter7"} <ide> assert_equal "/foo/bar/33/#chapter7", W.new.url_for(options) <del> assert_equal "/foo/bar/33/?query=string#chapter7", W.new.url_for(options.merge({query: "string"})) <add> assert_equal "/foo/bar/33/?query=string#chapter7", W.new.url_for(options.merge(query: "string")) <ide> end <ide> <ide> def test_trailing_slash_with_params <ide><path>actionpack/test/controller/url_rewriter_test.rb <ide> def test_anchor_should_be_uri_escaped <ide> def test_trailing_slash <ide> options = {controller: "foo", action: "bar", id: "3", only_path: true} <ide> assert_equal "/foo/bar/3", @rewriter.rewrite(@routes, options) <del> assert_equal "/foo/bar/3?query=string", @rewriter.rewrite(@routes, options.merge({query: "string"})) <del> options.update({trailing_slash: true}) <add> assert_equal "/foo/bar/3?query=string", @rewriter.rewrite(@routes, options.merge(query: "string")) <add> options.update(trailing_slash: true) <ide> assert_equal "/foo/bar/3/", @rewriter.rewrite(@routes, options) <del> options.update({query: "string"}) <add> options.update(query: "string") <ide> assert_equal "/foo/bar/3/?query=string", @rewriter.rewrite(@routes, options) <ide> end <ide> end <ide><path>actionpack/test/controller/webservice_test.rb <ide> def params_parsers <ide> end <ide> <ide> def content_length; get_header("rack.input").length; end <del> end.new({ "rack.input" => StringIO.new('{"title":"JSON"}}'), "CONTENT_TYPE" => "application/json" }) <add> end.new("rack.input" => StringIO.new('{"title":"JSON"}}'), "CONTENT_TYPE" => "application/json") <ide> <ide> assert_raises(Interrupt) do <ide> req.request_parameters <ide><path>actionpack/test/dispatch/callbacks_test.rb <ide> def test_to_prepare_and_cleanup_delegation <ide> <ide> def dispatch(&block) <ide> ActionDispatch::Callbacks.new(block || DummyApp.new).call( <del> {"rack.input" => StringIO.new("")} <add> "rack.input" => StringIO.new("") <ide> ) <ide> end <ide> <ide><path>actionpack/test/dispatch/executor_test.rb <ide> def test_callbacks_execute_in_shared_context <ide> private <ide> def call_and_return_body(&block) <ide> app = middleware(block || proc { [200, {}, "response"] }) <del> _, _, body = app.call({"rack.input" => StringIO.new("")}) <add> _, _, body = app.call("rack.input" => StringIO.new("")) <ide> body <ide> end <ide> <ide><path>actionpack/test/dispatch/rack_cache_test.rb <ide> class ReadWriteHash < ::Hash <ide> end <ide> <ide> test "stuff is deep duped" do <del> @store.write(:foo, { bar: :original }) <add> @store.write(:foo, bar: :original) <ide> hash = @store.read(:foo) <ide> hash[:bar] = :changed <ide> hash = @store.read(:foo) <ide><path>actionpack/test/dispatch/reloader_test.rb <ide> def call_and_return_body(&block) <ide> <ide> @response ||= "response" <ide> @reloader ||= Reloader.new(block || proc {[200, {}, @response]}, x) <del> @reloader.call({"rack.input" => StringIO.new("")})[2] <add> @reloader.call("rack.input" => StringIO.new(""))[2] <ide> end <ide> end <ide><path>actionpack/test/dispatch/request/json_params_parsing_test.rb <ide> def teardown <ide> test "parses json params for application json" do <ide> assert_parses( <ide> {"person" => {"name" => "David"}}, <del> "{\"person\": {\"name\": \"David\"}}", { "CONTENT_TYPE" => "application/json" } <add> "{\"person\": {\"name\": \"David\"}}", "CONTENT_TYPE" => "application/json" <ide> ) <ide> end <ide> <ide> test "parses boolean and number json params for application json" do <ide> assert_parses( <ide> {"item" => {"enabled" => false, "count" => 10}}, <del> "{\"item\": {\"enabled\": false, \"count\": 10}}", { "CONTENT_TYPE" => "application/json" } <add> "{\"item\": {\"enabled\": false, \"count\": 10}}", "CONTENT_TYPE" => "application/json" <ide> ) <ide> end <ide> <ide> test "parses json params for application jsonrequest" do <ide> assert_parses( <ide> {"person" => {"name" => "David"}}, <del> "{\"person\": {\"name\": \"David\"}}", { "CONTENT_TYPE" => "application/jsonrequest" } <add> "{\"person\": {\"name\": \"David\"}}", "CONTENT_TYPE" => "application/jsonrequest" <ide> ) <ide> end <ide> <ide> test "does not parse unregistered media types such as application/vnd.api+json" do <ide> assert_parses( <ide> {}, <del> "{\"person\": {\"name\": \"David\"}}", { "CONTENT_TYPE" => "application/vnd.api+json" } <add> "{\"person\": {\"name\": \"David\"}}", "CONTENT_TYPE" => "application/vnd.api+json" <ide> ) <ide> end <ide> <ide> test "nils are stripped from collections" do <ide> assert_parses( <ide> {"person" => []}, <del> "{\"person\":[null]}", { "CONTENT_TYPE" => "application/json" } <add> "{\"person\":[null]}", "CONTENT_TYPE" => "application/json" <ide> ) <ide> assert_parses( <ide> {"person" => ["foo"]}, <del> "{\"person\":[\"foo\",null]}", { "CONTENT_TYPE" => "application/json" } <add> "{\"person\":[\"foo\",null]}", "CONTENT_TYPE" => "application/json" <ide> ) <ide> assert_parses( <ide> {"person" => []}, <del> "{\"person\":[null, null]}", { "CONTENT_TYPE" => "application/json" } <add> "{\"person\":[null, null]}", "CONTENT_TYPE" => "application/json" <ide> ) <ide> end <ide> <ide> def teardown <ide> begin <ide> $stderr = StringIO.new # suppress the log <ide> json = "[\"person]\": {\"name\": \"David\"}}" <del> exception = assert_raise(ActionDispatch::ParamsParser::ParseError) { post "/parse", json, {"CONTENT_TYPE" => "application/json", "action_dispatch.show_exceptions" => false} } <add> exception = assert_raise(ActionDispatch::ParamsParser::ParseError) { post "/parse", json, "CONTENT_TYPE" => "application/json", "action_dispatch.show_exceptions" => false } <ide> assert_equal JSON::ParserError, exception.cause.class <ide> assert_equal exception.cause.message, exception.message <ide> ensure <ide> def teardown <ide> test "parses json params for application json" do <ide> assert_parses( <ide> {"user" => {"username" => "sikachu"}, "username" => "sikachu"}, <del> "{\"username\": \"sikachu\"}", { "CONTENT_TYPE" => "application/json" } <add> "{\"username\": \"sikachu\"}", "CONTENT_TYPE" => "application/json" <ide> ) <ide> end <ide> <ide> test "parses json params for application jsonrequest" do <ide> assert_parses( <ide> {"user" => {"username" => "sikachu"}, "username" => "sikachu"}, <del> "{\"username\": \"sikachu\"}", { "CONTENT_TYPE" => "application/jsonrequest" } <add> "{\"username\": \"sikachu\"}", "CONTENT_TYPE" => "application/jsonrequest" <ide> ) <ide> end <ide> <ide> test "parses json with non-object JSON content" do <ide> assert_parses( <ide> {"user" => {"_json" => "string content" }, "_json" => "string content" }, <del> "\"string content\"", { "CONTENT_TYPE" => "application/json" } <add> "\"string content\"", "CONTENT_TYPE" => "application/json" <ide> ) <ide> end <ide> <ide> def teardown <ide> Mime::Type.register "application/json", :json, %w(application/vnd.rails+json) <ide> assert_parses( <ide> {"user" => {"username" => "meinac"}, "username" => "meinac"}, <del> "{\"username\": \"meinac\"}", { "CONTENT_TYPE" => "application/json" } <add> "{\"username\": \"meinac\"}", "CONTENT_TYPE" => "application/json" <ide> ) <ide> ensure <ide> Mime::Type.unregister :json <ide> def teardown <ide> Mime::Type.register "application/json", :json, %w(application/vnd.rails+json) <ide> assert_parses( <ide> {"user" => {"username" => "meinac"}, "username" => "meinac"}, <del> "{\"username\": \"meinac\"}", { "CONTENT_TYPE" => "application/vnd.rails+json" } <add> "{\"username\": \"meinac\"}", "CONTENT_TYPE" => "application/vnd.rails+json" <ide> ) <ide> ensure <ide> Mime::Type.unregister :json <ide> def assert_parses(expected, actual, headers = {}) <ide> post "/parse", params: actual, headers: headers <ide> assert_response :ok <ide> assert_equal(expected, UsersController.last_request_parameters) <del> assert_equal(expected.merge({"action" => "parse"}), UsersController.last_parameters) <add> assert_equal(expected.merge("action" => "parse"), UsersController.last_parameters) <ide> end <ide> end <ide> <ide><path>actionpack/test/dispatch/response_test.rb <ide> def test_only_set_charset_still_defaults_to_text_html <ide> test "read content type with default charset utf-8" do <ide> original = ActionDispatch::Response.default_charset <ide> begin <del> resp = ActionDispatch::Response.new(200, { "Content-Type" => "text/xml" }) <add> resp = ActionDispatch::Response.new(200, "Content-Type" => "text/xml") <ide> assert_equal("utf-8", resp.charset) <ide> ensure <ide> ActionDispatch::Response.default_charset = original <ide> def test_only_set_charset_still_defaults_to_text_html <ide> original = ActionDispatch::Response.default_charset <ide> begin <ide> ActionDispatch::Response.default_charset = "utf-16" <del> resp = ActionDispatch::Response.new(200, { "Content-Type" => "text/xml" }) <add> resp = ActionDispatch::Response.new(200, "Content-Type" => "text/xml") <ide> assert_equal("utf-16", resp.charset) <ide> ensure <ide> ActionDispatch::Response.default_charset = original <ide><path>actionpack/test/dispatch/routing_assertions_test.rb <ide> def setup <ide> end <ide> <ide> def test_assert_generates <del> assert_generates("/articles", { controller: "articles", action: "index" }) <del> assert_generates("/articles/1", { controller: "articles", action: "show", id: "1" }) <add> assert_generates("/articles", controller: "articles", action: "index") <add> assert_generates("/articles/1", controller: "articles", action: "show", id: "1") <ide> end <ide> <ide> def test_assert_generates_with_defaults <del> assert_generates("/articles/1/edit", { controller: "articles", action: "edit" }, { id: "1" }) <add> assert_generates("/articles/1/edit", { controller: "articles", action: "edit" }, id: "1") <ide> end <ide> <ide> def test_assert_generates_with_extras <del> assert_generates("/articles", { controller: "articles", action: "index", page: "1" }, {}, { page: "1" }) <add> assert_generates("/articles", { controller: "articles", action: "index", page: "1" }, {}, page: "1") <ide> end <ide> <ide> def test_assert_recognizes <ide> def test_assert_recognizes <ide> end <ide> <ide> def test_assert_recognizes_with_extras <del> assert_recognizes({ controller: "articles", action: "index", page: "1" }, "/articles", { page: "1" }) <add> assert_recognizes({ controller: "articles", action: "index", page: "1" }, "/articles", page: "1") <ide> end <ide> <ide> def test_assert_recognizes_with_method <del> assert_recognizes({ controller: "articles", action: "create" }, { path: "/articles", method: :post }) <del> assert_recognizes({ controller: "articles", action: "update", id: "1" }, { path: "/articles/1", method: :put }) <add> assert_recognizes({ controller: "articles", action: "create" }, path: "/articles", method: :post) <add> assert_recognizes({ controller: "articles", action: "update", id: "1" }, path: "/articles/1", method: :put) <ide> end <ide> <ide> def test_assert_recognizes_with_hash_constraint <ide> def test_assert_recognizes_with_block_constraint <ide> <ide> def test_assert_recognizes_with_query_constraint <ide> assert_raise(Assertion) do <del> assert_recognizes({ controller: "query_articles", action: "index", use_query: "false" }, "/query/articles", { use_query: "false" }) <add> assert_recognizes({ controller: "query_articles", action: "index", use_query: "false" }, "/query/articles", use_query: "false") <ide> end <del> assert_recognizes({ controller: "query_articles", action: "index", use_query: "true" }, "/query/articles", { use_query: "true" }) <add> assert_recognizes({ controller: "query_articles", action: "index", use_query: "true" }, "/query/articles", use_query: "true") <ide> end <ide> <ide> def test_assert_recognizes_raises_message <ide> def test_assert_routing_raises_message <ide> end <ide> <ide> def test_assert_routing_with_defaults <del> assert_routing("/articles/1/edit", { controller: "articles", action: "edit", id: "1" }, { id: "1" }) <add> assert_routing("/articles/1/edit", { controller: "articles", action: "edit", id: "1" }, id: "1") <ide> end <ide> <ide> def test_assert_routing_with_extras <del> assert_routing("/articles", { controller: "articles", action: "index", page: "1" }, { }, { page: "1" }) <add> assert_routing("/articles", { controller: "articles", action: "index", page: "1" }, { }, page: "1") <ide> end <ide> <ide> def test_assert_routing_with_hash_constraint <ide> assert_raise(Assertion) do <del> assert_routing("http://test.host/secure/articles", { controller: "secure_articles", action: "index" }) <add> assert_routing("http://test.host/secure/articles", controller: "secure_articles", action: "index") <ide> end <del> assert_routing("https://test.host/secure/articles", { controller: "secure_articles", action: "index", protocol: "https://" }) <add> assert_routing("https://test.host/secure/articles", controller: "secure_articles", action: "index", protocol: "https://") <ide> end <ide> <ide> def test_assert_routing_with_block_constraint <ide> assert_raise(Assertion) do <del> assert_routing("http://test.host/block/articles", { controller: "block_articles", action: "index" }) <add> assert_routing("http://test.host/block/articles", controller: "block_articles", action: "index") <ide> end <del> assert_routing("https://test.host/block/articles", { controller: "block_articles", action: "index" }) <add> assert_routing("https://test.host/block/articles", controller: "block_articles", action: "index") <ide> end <ide> <ide> def test_with_routing <ide> def test_with_routing <ide> <ide> assert_routing("/artikel", controller: "articles", action: "index") <ide> assert_raise(Assertion) do <del> assert_routing("/articles", { controller: "articles", action: "index" }) <add> assert_routing("/articles", controller: "articles", action: "index") <ide> end <ide> end <ide> end <ide><path>actionpack/test/journey/route_test.rb <ide> def test_path_requirements_override_defaults <ide> def test_ip_address <ide> path = Path::Pattern.from_string "/messages/:id(.:format)" <ide> route = Route.build("name", nil, path, {ip: "192.168.1.1"}, [], <del> { controller: "foo", action: "bar" }) <add> controller: "foo", action: "bar") <ide> assert_equal "192.168.1.1", route.ip <ide> end <ide> <ide> def test_default_ip <ide> path = Path::Pattern.from_string "/messages/:id(.:format)" <ide> route = Route.build("name", nil, path, {}, [], <del> { controller: "foo", action: "bar" }) <add> controller: "foo", action: "bar") <ide> assert_equal(//, route.ip) <ide> end <ide> <ide> def test_format_with_star <ide> path = Path::Pattern.from_string "/:controller/*extra" <ide> route = Route.build("name", nil, path, {}, [], <del> { controller: "foo", action: "bar" }) <del> assert_equal "/foo/himom", route.format({ <del> controller: "foo", <del> extra: "himom", <del> }) <add> controller: "foo", action: "bar") <add> assert_equal "/foo/himom", route.format( controller: "foo", <add> extra: "himom") <ide> end <ide> <ide> def test_connects_all_match <ide> path = Path::Pattern.from_string "/:controller(/:action(/:id(.:format)))" <del> route = Route.build("name", nil, path, {action: "bar"}, [], { controller: "foo" }) <add> route = Route.build("name", nil, path, {action: "bar"}, [], controller: "foo") <ide> <del> assert_equal "/foo/bar/10", route.format({ <del> controller: "foo", <add> assert_equal "/foo/bar/10", route.format( controller: "foo", <ide> action: "bar", <del> id: 10 <del> }) <add> id: 10) <ide> end <ide> <ide> def test_extras_are_not_included_if_optional <ide> path = Path::Pattern.from_string "/page/:id(/:action)" <del> route = Route.build("name", nil, path, { }, [], { action: "show" }) <add> route = Route.build("name", nil, path, { }, [], action: "show") <ide> <del> assert_equal "/page/10", route.format({ id: 10 }) <add> assert_equal "/page/10", route.format(id: 10) <ide> end <ide> <ide> def test_extras_are_not_included_if_optional_with_parameter <ide> path = Path::Pattern.from_string "(/sections/:section)/pages/:id" <del> route = Route.build("name", nil, path, { }, [], { action: "show" }) <add> route = Route.build("name", nil, path, { }, [], action: "show") <ide> <del> assert_equal "/pages/10", route.format({id: 10}) <add> assert_equal "/pages/10", route.format(id: 10) <ide> end <ide> <ide> def test_extras_are_not_included_if_optional_parameter_is_nil <ide> path = Path::Pattern.from_string "(/sections/:section)/pages/:id" <del> route = Route.build("name", nil, path, { }, [], { action: "show" }) <add> route = Route.build("name", nil, path, { }, [], action: "show") <ide> <del> assert_equal "/pages/10", route.format({id: 10, section: nil}) <add> assert_equal "/pages/10", route.format(id: 10, section: nil) <ide> end <ide> <ide> def test_score <ide><path>actionpack/test/journey/router_test.rb <ide> def test_does_not_include_missing_keys_message <ide> <ide> def test_X_Cascade <ide> get "/messages(.:format)", to: "foo#bar" <del> resp = router.serve(rails_env({ "REQUEST_METHOD" => "GET", "PATH_INFO" => "/lol" })) <add> resp = router.serve(rails_env("REQUEST_METHOD" => "GET", "PATH_INFO" => "/lol")) <ide> assert_equal ["Not Found"], resp.last <ide> assert_equal "pass", resp[1]["X-Cascade"] <ide> assert_equal 404, resp.first <ide> def test_path_not_found <ide> def test_required_part_in_recall <ide> get "/messages/:a/:b", to: "foo#bar" <ide> <del> path, _ = @formatter.generate(nil, { controller: "foo", action: "bar", a: "a" }, { b: "b" }) <add> path, _ = @formatter.generate(nil, { controller: "foo", action: "bar", a: "a" }, b: "b") <ide> assert_equal "/messages/a/b", path <ide> end <ide> <ide> def test_splat_in_recall <ide> get "/*path", to: "foo#bar" <ide> <del> path, _ = @formatter.generate(nil, { controller: "foo", action: "bar" }, { path: "b" }) <add> path, _ = @formatter.generate(nil, { controller: "foo", action: "bar" }, path: "b") <ide> assert_equal "/b", path <ide> end <ide> <ide> def test_recall_should_be_used_when_scoring <ide> get "/messages/:action(/:id(.:format))", to: "foo#bar" <ide> get "/messages/:id(.:format)", to: "bar#baz" <ide> <del> path, _ = @formatter.generate(nil, { controller: "foo", id: 10 }, { action: "index" }) <add> path, _ = @formatter.generate(nil, { controller: "foo", id: 10 }, action: "index") <ide> assert_equal "/messages/index/10", path <ide> end <ide> <ide> def test_generate_uses_recall_if_needed <ide> path, params = @formatter.generate( <ide> nil, <ide> {controller: "tasks", id: 10}, <del> {action: "index"}) <add> action: "index") <ide> assert_equal "/tasks/index/10", path <ide> assert_equal({}, params) <ide> end <ide> def test_generate_with_name <ide> path, params = @formatter.generate( <ide> "tasks", <ide> {controller: "tasks"}, <del> {controller: "tasks", action: "index"}) <add> controller: "tasks", action: "index") <ide> assert_equal "/tasks", path <ide> assert_equal({}, params) <ide> end <ide> def test_generate_with_name <ide> end <ide> <ide> def test_namespaced_controller <del> get "/:controller(/:action(/:id))", { controller: /.+?/ } <add> get "/:controller(/:action(/:id))", controller: /.+?/ <ide> route = @routes.first <ide> <ide> env = rails_env "PATH_INFO" => "/admin/users/show/10" <ide><path>actionview/test/abstract_unit.rb <ide> def config <ide> config.assets_dir = public_dir <ide> config.javascripts_dir = "#{public_dir}/javascripts" <ide> config.stylesheets_dir = "#{public_dir}/stylesheets" <del> config.assets = ActiveSupport::InheritableOptions.new({ prefix: "assets" }) <add> config.assets = ActiveSupport::InheritableOptions.new(prefix: "assets") <ide> config <ide> end <ide> end <ide><path>actionview/test/actionpack/controller/view_paths_test.rb <ide> def find_all(*args) <ide> "Decorated body", <ide> template.identifier, <ide> template.handler, <del> { <del> virtual_path: template.virtual_path, <add> virtual_path: template.virtual_path, <ide> format: template.formats <del> } <ide> ) <ide> end <ide> end <ide><path>actionview/test/activerecord/polymorphic_routes_test.rb <ide> def test_with_empty_list <ide> def test_with_nil_id <ide> with_test_routes do <ide> exception = assert_raise ArgumentError do <del> polymorphic_url({ id: nil }) <add> polymorphic_url(id: nil) <ide> end <ide> assert_equal "Nil location provided. Can't build URI.", exception.message <ide> end <ide> def test_with_class_list_of_one <ide> <ide> def test_class_with_options <ide> with_test_routes do <del> assert_equal "http://example.com/projects?foo=bar", polymorphic_url(@project.class, { foo: :bar }) <del> assert_equal "/projects?foo=bar", polymorphic_path(@project.class, { foo: :bar }) <add> assert_equal "http://example.com/projects?foo=bar", polymorphic_url(@project.class, foo: :bar) <add> assert_equal "/projects?foo=bar", polymorphic_path(@project.class, foo: :bar) <ide> end <ide> end <ide> <ide><path>actionview/test/template/date_helper_test.rb <ide> def test_select_minute_with_blank_and_step <ide> expected << %(<option value=""></option>\n<option value="00">00</option>\n<option value="15">15</option>\n<option value="30">30</option>\n<option value="45">45</option>\n) <ide> expected << "</select>\n" <ide> <del> assert_dom_equal expected, select_minute(Time.mktime(2003, 8, 16, 8, 4, 18), { include_blank: true , minute_step: 15 }) <add> assert_dom_equal expected, select_minute(Time.mktime(2003, 8, 16, 8, 4, 18), include_blank: true , minute_step: 15) <ide> end <ide> <ide> def test_select_minute_nil_with_blank <ide> def test_select_minute_nil_with_blank_and_step <ide> expected << %(<option value=""></option>\n<option value="00">00</option>\n<option value="15">15</option>\n<option value="30">30</option>\n<option value="45">45</option>\n) <ide> expected << "</select>\n" <ide> <del> assert_dom_equal expected, select_minute(nil, { include_blank: true , minute_step: 15 }) <add> assert_dom_equal expected, select_minute(nil, include_blank: true , minute_step: 15) <ide> end <ide> <ide> def test_select_minute_with_hidden <ide> def test_select_date_with_separator <ide> expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) <ide> expected << "</select>\n" <ide> <del> assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { date_separator: " / ", start_year: 2003, end_year: 2005, prefix: "date[first]"}) <add> assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), date_separator: " / ", start_year: 2003, end_year: 2005, prefix: "date[first]") <ide> end <ide> <ide> def test_select_date_with_separator_and_discard_day <ide> def test_select_date_with_separator_and_discard_day <ide> <ide> expected << %(<input type="hidden" id="date_first_day" name="date[first][day]" value="1" />\n) <ide> <del> assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { date_separator: " / ", discard_day: true, start_year: 2003, end_year: 2005, prefix: "date[first]"}) <add> assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), date_separator: " / ", discard_day: true, start_year: 2003, end_year: 2005, prefix: "date[first]") <ide> end <ide> <ide> def test_select_date_with_separator_discard_month_and_day <ide> def test_select_date_with_separator_discard_month_and_day <ide> expected << %(<input type="hidden" id="date_first_month" name="date[first][month]" value="8" />\n) <ide> expected << %(<input type="hidden" id="date_first_day" name="date[first][day]" value="1" />\n) <ide> <del> assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { date_separator: " / ", discard_month: true, discard_day: true, start_year: 2003, end_year: 2005, prefix: "date[first]"}) <add> assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), date_separator: " / ", discard_month: true, discard_day: true, start_year: 2003, end_year: 2005, prefix: "date[first]") <ide> end <ide> <ide> def test_select_date_with_hidden <ide> expected = %(<input id="date_first_year" name="date[first][year]" type="hidden" value="2003"/>\n) <ide> expected << %(<input id="date_first_month" name="date[first][month]" type="hidden" value="8" />\n) <ide> expected << %(<input id="date_first_day" name="date[first][day]" type="hidden" value="16" />\n) <ide> <del> assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { prefix: "date[first]", use_hidden: true }) <del> assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { date_separator: " / ", prefix: "date[first]", use_hidden: true }) <add> assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), prefix: "date[first]", use_hidden: true) <add> assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), date_separator: " / ", prefix: "date[first]", use_hidden: true) <ide> end <ide> <ide> def test_select_date_with_css_classes_option <ide> def test_select_date_with_css_classes_option <ide> expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) <ide> expected << "</select>\n" <ide> <del> assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), {start_year: 2003, end_year: 2005, prefix: "date[first]", with_css_classes: true}) <add> assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), start_year: 2003, end_year: 2005, prefix: "date[first]", with_css_classes: true) <ide> end <ide> <ide> def test_select_date_with_custom_with_css_classes <ide> def test_select_date_with_css_classes_option_and_html_class_option <ide> expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) <ide> expected << "</select>\n" <ide> <del> assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), {start_year: 2003, end_year: 2005, prefix: "date[first]", with_css_classes: true}, { class: "datetime optional" }) <add> assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), {start_year: 2003, end_year: 2005, prefix: "date[first]", with_css_classes: true}, class: "datetime optional") <ide> end <ide> <ide> def test_select_date_with_custom_with_css_classes_and_html_class_option <ide> def test_select_date_with_custom_with_css_classes_and_html_class_option <ide> expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) <ide> expected << "</select>\n" <ide> <del> assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), {start_year: 2003, end_year: 2005, with_css_classes: { year: "my-year", month: "my-month", day: "my-day" }}, { class: "date optional" }) <add> assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), {start_year: 2003, end_year: 2005, with_css_classes: { year: "my-year", month: "my-month", day: "my-day" }}, class: "date optional") <ide> end <ide> <ide> def test_select_date_with_partial_with_css_classes_and_html_class_option <ide> def test_select_date_with_partial_with_css_classes_and_html_class_option <ide> expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) <ide> expected << "</select>\n" <ide> <del> assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), {start_year: 2003, end_year: 2005, with_css_classes: { month: "my-month custom-grid" }}, { class: "date optional" }) <add> assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), {start_year: 2003, end_year: 2005, with_css_classes: { month: "my-month custom-grid" }}, class: "date optional") <ide> end <ide> <ide> def test_select_date_with_html_class_option <ide> def test_select_date_with_html_class_option <ide> expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) <ide> expected << "</select>\n" <ide> <del> assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { start_year: 2003, end_year: 2005 }, { class: "date optional custom-grid" }) <add> assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { start_year: 2003, end_year: 2005 }, class: "date optional custom-grid") <ide> end <ide> <ide> def test_select_datetime <ide> def test_date_select_with_separator <ide> <ide> expected << "</select>\n" <ide> <del> assert_dom_equal expected, date_select("post", "written_on", { date_separator: " / " }) <add> assert_dom_equal expected, date_select("post", "written_on", date_separator: " / ") <ide> end <ide> <ide> def test_date_select_with_separator_and_order <ide> def test_date_select_with_separator_and_order <ide> expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} <ide> expected << "</select>\n" <ide> <del> assert_dom_equal expected, date_select("post", "written_on", { order: [:day, :month, :year], date_separator: " / " }) <add> assert_dom_equal expected, date_select("post", "written_on", order: [:day, :month, :year], date_separator: " / ") <ide> end <ide> <ide> def test_date_select_with_separator_and_order_and_year_discarded <ide> def test_date_select_with_separator_and_order_and_year_discarded <ide> expected << "</select>\n" <ide> expected << %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n} <ide> <del> assert_dom_equal expected, date_select("post", "written_on", { order: [:day, :month, :year], discard_year: true, date_separator: " / " }) <add> assert_dom_equal expected, date_select("post", "written_on", order: [:day, :month, :year], discard_year: true, date_separator: " / ") <ide> end <ide> <ide> def test_date_select_with_default_prompt <ide> def test_time_select_with_separator <ide> 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 35}>#{sprintf("%02d", i)}</option>\n) } <ide> expected << "</select>\n" <ide> <del> assert_dom_equal expected, time_select("post", "written_on", { time_separator: " - ", include_seconds: true }) <add> assert_dom_equal expected, time_select("post", "written_on", time_separator: " - ", include_seconds: true) <ide> end <ide> <ide> def test_time_select_with_default_prompt <ide> def test_datetime_select_with_separators <ide> 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 35}>#{sprintf("%02d", i)}</option>\n) } <ide> expected << "</select>\n" <ide> <del> assert_dom_equal expected, datetime_select("post", "updated_at", { date_separator: " / ", datetime_separator: " , ", time_separator: " - ", include_seconds: true }) <add> assert_dom_equal expected, datetime_select("post", "updated_at", date_separator: " / ", datetime_separator: " , ", time_separator: " - ", include_seconds: true) <ide> end <ide> <ide> def test_datetime_select_with_integer <ide><path>actionview/test/template/digestor_test.rb <ide> def test_collection_derived_from_record_dependency <ide> <ide> def test_details_are_included_in_cache_key <ide> # Cache the template digest. <del> @finder = FixtureFinder.new({formats: [:html]}) <add> @finder = FixtureFinder.new(formats: [:html]) <ide> old_digest = digest("events/_event") <ide> <ide> # Change the template; the cached digest remains unchanged. <ide><path>actionview/test/template/form_collections_helper_test.rb <ide> def with_collection_check_boxes(*args, &block) <ide> <ide> test "collection radio buttons generates a hidden field using the given :name in :html_options" do <ide> collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] <del> with_collection_radio_buttons :user, :category_ids, collection, :id, :name, {}, { name: "user[other_category_ids]" } <add> with_collection_radio_buttons :user, :category_ids, collection, :id, :name, {}, name: "user[other_category_ids]" <ide> <ide> assert_select "input[type=hidden][name='user[other_category_ids]'][value='']", count: 1 <ide> end <ide> <ide> test "collection radio buttons generates a hidden field with index if it was provided" do <ide> collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] <del> with_collection_radio_buttons :user, :category_ids, collection, :id, :name, { index: 322 } <add> with_collection_radio_buttons :user, :category_ids, collection, :id, :name, index: 322 <ide> <ide> assert_select "input[type=hidden][name='user[322][category_ids]'][value='']", count: 1 <ide> end <ide> def with_collection_check_boxes(*args, &block) <ide> <ide> test "collection check boxes generates a hidden field using the given :name in :html_options" do <ide> collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] <del> with_collection_check_boxes :user, :category_ids, collection, :id, :name, {}, {name: "user[other_category_ids][]"} <add> with_collection_check_boxes :user, :category_ids, collection, :id, :name, {}, name: "user[other_category_ids][]" <ide> <ide> assert_select "input[type=hidden][name='user[other_category_ids][]'][value='']", count: 1 <ide> end <ide> <ide> test "collection check boxes generates a hidden field with index if it was provided" do <ide> collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] <del> with_collection_check_boxes :user, :category_ids, collection, :id, :name, { index: 322 } <add> with_collection_check_boxes :user, :category_ids, collection, :id, :name, index: 322 <ide> <ide> assert_select "input[type=hidden][name='user[322][category_ids][]'][value='']", count: 1 <ide> end <ide><path>actionview/test/template/form_helper_test.rb <ide> def form_for(*) <ide> <ide> setup do <ide> # Create "label" locale for testing I18n label helpers <del> I18n.backend.store_translations "label", { <del> activemodel: { <add> I18n.backend.store_translations "label", activemodel: { <ide> attributes: { <ide> post: { <ide> cost: "Total cost" <ide> def form_for(*) <ide> } <ide> } <ide> } <del> } <ide> <ide> # Create "submit" locale for testing I18n submit helpers <del> I18n.backend.store_translations "submit", { <del> helpers: { <add> I18n.backend.store_translations "submit", helpers: { <ide> submit: { <ide> create: "Create %{model}", <ide> update: "Confirm %{model} changes", <ide> def form_for(*) <ide> } <ide> } <ide> } <del> } <ide> <del> I18n.backend.store_translations "placeholder", { <del> activemodel: { <add> I18n.backend.store_translations "placeholder", activemodel: { <ide> attributes: { <ide> post: { <ide> cost: "Total cost" <ide> def form_for(*) <ide> } <ide> } <ide> } <del> } <ide> <ide> @post = Post.new <ide> @comment = Comment.new <ide> def test_check_box_with_multiple_behavior_and_index <ide> def test_checkbox_disabled_disables_hidden_field <ide> assert_dom_equal( <ide> '<input name="post[secret]" type="hidden" value="0" disabled="disabled"/><input checked="checked" disabled="disabled" id="post_secret" name="post[secret]" type="checkbox" value="1" />', <del> check_box("post", "secret", { disabled: true }) <add> check_box("post", "secret", disabled: true) <ide> ) <ide> end <ide> <ide><path>actionview/test/template/form_options_helper_test.rb <ide> def test_grouped_options_for_select_with_prompt_returns_html_escaped_string <ide> def test_optgroups_with_with_options_with_hash <ide> assert_dom_equal( <ide> "<optgroup label=\"North America\"><option value=\"United States\">United States</option>\n<option value=\"Canada\">Canada</option></optgroup><optgroup label=\"Europe\"><option value=\"Denmark\">Denmark</option>\n<option value=\"Germany\">Germany</option></optgroup>", <del> grouped_options_for_select({"North America" => ["United States","Canada"], "Europe" => ["Denmark","Germany"]}) <add> grouped_options_for_select("North America" => ["United States","Canada"], "Europe" => ["Denmark","Germany"]) <ide> ) <ide> end <ide> <ide> def test_select_with_html_options <ide> @post.category = "" <ide> assert_dom_equal( <ide> "<select class=\"disabled\" disabled=\"disabled\" name=\"post[category]\" id=\"post_category\"><option value=\"\">Please select</option>\n<option value=\"\"></option>\n</select>", <del> select("post", "category", [], { prompt: true, include_blank: true }, { class: "disabled", disabled: true }) <add> select("post", "category", [], { prompt: true, include_blank: true }, class: "disabled", disabled: true) <ide> ) <ide> end <ide> <ide> def test_select_with_index_option <ide> <ide> assert_dom_equal( <ide> expected, <del> select("album[]", "genre", %w[rap rock country], {}, { index: nil }) <add> select("album[]", "genre", %w[rap rock country], {}, index: nil) <ide> ) <ide> end <ide> <ide> def test_collection_select_with_blank_and_selected <ide> <ide> assert_dom_equal( <ide> %{<select id="post_author_name" name="post[author_name]"><option value=""></option>\n<option value="&lt;Abe&gt;" selected="selected">&lt;Abe&gt;</option>\n<option value="Babe">Babe</option>\n<option value="Cabe">Cabe</option></select>}, <del> collection_select("post", "author_name", dummy_posts, "author_name", "author_name", {include_blank: true, selected: "<Abe>"}) <add> collection_select("post", "author_name", dummy_posts, "author_name", "author_name", include_blank: true, selected: "<Abe>") <ide> ) <ide> end <ide> <ide><path>actionview/test/template/form_tag_helper_test.rb <ide> def test_form_tag <ide> end <ide> <ide> def test_form_tag_multipart <del> actual = form_tag({}, { "multipart" => true }) <add> actual = form_tag({}, "multipart" => true) <ide> expected = whole_form("http://www.example.com", enctype: true) <ide> assert_dom_equal expected, actual <ide> end <ide> <ide> def test_form_tag_with_method_patch <del> actual = form_tag({}, { method: :patch }) <add> actual = form_tag({}, method: :patch) <ide> expected = whole_form("http://www.example.com", method: :patch) <ide> assert_dom_equal expected, actual <ide> end <ide> <ide> def test_form_tag_with_method_put <del> actual = form_tag({}, { method: :put }) <add> actual = form_tag({}, method: :put) <ide> expected = whole_form("http://www.example.com", method: :put) <ide> assert_dom_equal expected, actual <ide> end <ide> <ide> def test_form_tag_with_method_delete <del> actual = form_tag({}, { method: :delete }) <add> actual = form_tag({}, method: :delete) <ide> <ide> expected = whole_form("http://www.example.com", method: :delete) <ide> assert_dom_equal expected, actual <ide> def test_form_tag_with_remote_false <ide> end <ide> <ide> def test_form_tag_enforce_utf8_true <del> actual = form_tag({}, { enforce_utf8: true }) <add> actual = form_tag({}, enforce_utf8: true) <ide> expected = whole_form("http://www.example.com", enforce_utf8: true) <ide> assert_dom_equal expected, actual <ide> assert actual.html_safe? <ide> end <ide> <ide> def test_form_tag_enforce_utf8_false <del> actual = form_tag({}, { enforce_utf8: false }) <add> actual = form_tag({}, enforce_utf8: false) <ide> expected = whole_form("http://www.example.com", enforce_utf8: false) <ide> assert_dom_equal expected, actual <ide> assert actual.html_safe? <ide> def test_empty_submit_tag_with_opt_out <ide> def test_submit_tag_having_data_disable_with_string <ide> assert_dom_equal( <ide> %(<input data-disable-with="Processing..." data-confirm="Are you sure?" name='commit' type="submit" value="Save" />), <del> submit_tag("Save", { "data-disable-with" => "Processing...", "data-confirm" => "Are you sure?" }) <add> submit_tag("Save", "data-disable-with" => "Processing...", "data-confirm" => "Are you sure?") <ide> ) <ide> end <ide> <ide> def test_submit_tag_having_data_disable_with_boolean <ide> assert_dom_equal( <ide> %(<input data-confirm="Are you sure?" name='commit' type="submit" value="Save" />), <del> submit_tag("Save", { "data-disable-with" => false, "data-confirm" => "Are you sure?" }) <add> submit_tag("Save", "data-disable-with" => false, "data-confirm" => "Are you sure?") <ide> ) <ide> end <ide> <ide> def test_submit_tag_having_data_hash_disable_with_boolean <ide> assert_dom_equal( <ide> %(<input data-confirm="Are you sure?" name='commit' type="submit" value="Save" />), <del> submit_tag("Save", { data: { confirm: "Are you sure?", disable_with: false } }) <add> submit_tag("Save", data: { confirm: "Are you sure?", disable_with: false }) <ide> ) <ide> end <ide> <ide> def test_submit_tag_with_confirmation <ide> def test_submit_tag_doesnt_have_data_disable_with_twice <ide> assert_equal( <ide> %(<input type="submit" name="commit" value="Save" data-confirm="Are you sure?" data-disable-with="Processing..." />), <del> submit_tag("Save", { "data-disable-with" => "Processing...", "data-confirm" => "Are you sure?" }) <add> submit_tag("Save", "data-disable-with" => "Processing...", "data-confirm" => "Are you sure?") <ide> ) <ide> end <ide> <ide> def test_field_set_tag_in_erb <ide> def test_text_area_tag_options_symbolize_keys_side_effects <ide> options = { option: "random_option" } <ide> text_area_tag "body", "hello world", options <del> assert_equal options, { option: "random_option" } <add> assert_equal options, option: "random_option" <ide> end <ide> <ide> def test_submit_tag_options_symbolize_keys_side_effects <ide> options = { option: "random_option" } <ide> submit_tag "submit value", options <del> assert_equal options, { option: "random_option" } <add> assert_equal options, option: "random_option" <ide> end <ide> <ide> def test_button_tag_options_symbolize_keys_side_effects <ide> options = { option: "random_option" } <ide> button_tag "button value", options <del> assert_equal options, { option: "random_option" } <add> assert_equal options, option: "random_option" <ide> end <ide> <ide> def test_image_submit_tag_options_symbolize_keys_side_effects <ide> options = { option: "random_option" } <ide> image_submit_tag "submit source", options <del> assert_equal options, { option: "random_option" } <add> assert_equal options, option: "random_option" <ide> end <ide> <ide> def test_image_label_tag_options_symbolize_keys_side_effects <ide> options = { option: "random_option" } <ide> label_tag "submit source", "title", options <del> assert_equal options, { option: "random_option" } <add> assert_equal options, option: "random_option" <ide> end <ide> <ide> def protect_against_forgery? <ide><path>actionview/test/template/resolver_patterns_test.rb <ide> def setup <ide> end <ide> <ide> def test_should_return_empty_list_for_unknown_path <del> templates = @resolver.find_all("unknown", "custom_pattern", false, {locale: [], formats: [:html], variants: [], handlers: [:erb]}) <add> templates = @resolver.find_all("unknown", "custom_pattern", false, locale: [], formats: [:html], variants: [], handlers: [:erb]) <ide> assert_equal [], templates, "expected an empty list of templates" <ide> end <ide> <ide> def test_should_return_template_for_declared_path <del> templates = @resolver.find_all("path", "custom_pattern", false, {locale: [], formats: [:html], variants: [], handlers: [:erb]}) <add> templates = @resolver.find_all("path", "custom_pattern", false, locale: [], formats: [:html], variants: [], handlers: [:erb]) <ide> assert_equal 1, templates.size, "expected one template" <ide> assert_equal "Hello custom patterns!", templates.first.source <ide> assert_equal "custom_pattern/path", templates.first.virtual_path <ide> assert_equal [:html], templates.first.formats <ide> end <ide> <ide> def test_should_return_all_templates_when_ambiguous_pattern <del> templates = @resolver.find_all("another", "custom_pattern", false, {locale: [], formats: [:html], variants: [], handlers: [:erb]}) <add> templates = @resolver.find_all("another", "custom_pattern", false, locale: [], formats: [:html], variants: [], handlers: [:erb]) <ide> assert_equal 2, templates.size, "expected two templates" <ide> assert_equal "Another template!", templates[0].source <ide> assert_equal "custom_pattern/another", templates[0].virtual_path <ide> def test_should_return_all_templates_when_ambiguous_pattern <ide> end <ide> <ide> def test_should_return_all_variants_for_any <del> templates = @resolver.find_all("hello_world", "test", false, {locale: [], formats: [:html, :text], variants: :any, handlers: [:erb]}) <add> templates = @resolver.find_all("hello_world", "test", false, locale: [], formats: [:html, :text], variants: :any, handlers: [:erb]) <ide> assert_equal 3, templates.size, "expected three templates" <ide> assert_equal "Hello phone!", templates[0].source <ide> assert_equal "test/hello_world", templates[0].virtual_path <ide><path>actionview/test/template/tag_helper_test.rb <ide> def test_tag_builder_with_unescaped_array_class <ide> end <ide> <ide> def test_content_tag_with_empty_array_class <del> str = content_tag("p", "limelight", {class: []}) <add> str = content_tag("p", "limelight", class: []) <ide> assert_equal '<p class="">limelight</p>', str <ide> end <ide> <ide> def test_tag_builder_disable_escaping <ide> def test_data_attributes <ide> ["data", :data].each { |data| <ide> assert_dom_equal '<a data-a-float="3.14" data-a-big-decimal="-123.456" data-a-number="1" data-array="[1,2,3]" data-hash="{&quot;key&quot;:&quot;value&quot;}" data-string-with-quotes="double&quot;quote&quot;party&quot;" data-string="hello" data-symbol="foo" />', <del> tag("a", { data => { a_float: 3.14, a_big_decimal: BigDecimal.new("-123.456"), a_number: 1, string: "hello", symbol: :foo, array: [1, 2, 3], hash: { key: "value"}, string_with_quotes: 'double"quote"party"' } }) <add> tag("a", data => { a_float: 3.14, a_big_decimal: BigDecimal.new("-123.456"), a_number: 1, string: "hello", symbol: :foo, array: [1, 2, 3], hash: { key: "value"}, string_with_quotes: 'double"quote"party"' }) <ide> assert_dom_equal '<a data-a-float="3.14" data-a-big-decimal="-123.456" data-a-number="1" data-array="[1,2,3]" data-hash="{&quot;key&quot;:&quot;value&quot;}" data-string-with-quotes="double&quot;quote&quot;party&quot;" data-string="hello" data-symbol="foo" />', <ide> tag.a(data: { a_float: 3.14, a_big_decimal: BigDecimal.new("-123.456"), a_number: 1, string: "hello", symbol: :foo, array: [1, 2, 3], hash: { key: "value"}, string_with_quotes: 'double"quote"party"' }) <ide> } <ide> def test_data_attributes <ide> def test_aria_attributes <ide> ["aria", :aria].each { |aria| <ide> assert_dom_equal '<a aria-a-float="3.14" aria-a-big-decimal="-123.456" aria-a-number="1" aria-array="[1,2,3]" aria-hash="{&quot;key&quot;:&quot;value&quot;}" aria-string-with-quotes="double&quot;quote&quot;party&quot;" aria-string="hello" aria-symbol="foo" />', <del> tag("a", { aria => { a_float: 3.14, a_big_decimal: BigDecimal.new("-123.456"), a_number: 1, string: "hello", symbol: :foo, array: [1, 2, 3], hash: { key: "value"}, string_with_quotes: 'double"quote"party"' } }) <add> tag("a", aria => { a_float: 3.14, a_big_decimal: BigDecimal.new("-123.456"), a_number: 1, string: "hello", symbol: :foo, array: [1, 2, 3], hash: { key: "value"}, string_with_quotes: 'double"quote"party"' }) <ide> assert_dom_equal '<a aria-a-float="3.14" aria-a-big-decimal="-123.456" aria-a-number="1" aria-array="[1,2,3]" aria-hash="{&quot;key&quot;:&quot;value&quot;}" aria-string-with-quotes="double&quot;quote&quot;party&quot;" aria-string="hello" aria-symbol="foo" />', <ide> tag.a(aria: { a_float: 3.14, a_big_decimal: BigDecimal.new("-123.456"), a_number: 1, string: "hello", symbol: :foo, array: [1, 2, 3], hash: { key: "value"}, string_with_quotes: 'double"quote"party"' }) <ide> } <ide> end <ide> <ide> def test_link_to_data_nil_equal <del> div_type1 = content_tag(:div, "test", { "data-tooltip" => nil }) <del> div_type2 = content_tag(:div, "test", { data: {tooltip: nil} }) <add> div_type1 = content_tag(:div, "test", "data-tooltip" => nil) <add> div_type2 = content_tag(:div, "test", data: {tooltip: nil}) <ide> assert_dom_equal div_type1, div_type2 <ide> end <ide> <ide> def test_tag_builder_link_to_data_nil_equal <del> div_type1 = tag.div "test", { 'data-tooltip': nil } <del> div_type2 = tag.div "test", { data: {tooltip: nil} } <add> div_type1 = tag.div "test", 'data-tooltip': nil <add> div_type2 = tag.div "test", data: {tooltip: nil} <ide> assert_dom_equal div_type1, div_type2 <ide> end <ide> <ide><path>actionview/test/template/testing/fixture_resolver_test.rb <ide> class FixtureResolverTest < ActiveSupport::TestCase <ide> def test_should_return_empty_list_for_unknown_path <ide> resolver = ActionView::FixtureResolver.new() <del> templates = resolver.find_all("path", "arbitrary", false, {locale: [], formats: [:html], variants: [], handlers: []}) <add> templates = resolver.find_all("path", "arbitrary", false, locale: [], formats: [:html], variants: [], handlers: []) <ide> assert_equal [], templates, "expected an empty list of templates" <ide> end <ide> <ide> def test_should_return_template_for_declared_path <ide> resolver = ActionView::FixtureResolver.new("arbitrary/path.erb" => "this text") <del> templates = resolver.find_all("path", "arbitrary", false, {locale: [], formats: [:html], variants: [], handlers: [:erb]}) <add> templates = resolver.find_all("path", "arbitrary", false, locale: [], formats: [:html], variants: [], handlers: [:erb]) <ide> assert_equal 1, templates.size, "expected one template" <ide> assert_equal "this text", templates.first.source <ide> assert_equal "arbitrary/path", templates.first.virtual_path <ide><path>actionview/test/template/testing/null_resolver_test.rb <ide> class NullResolverTest < ActiveSupport::TestCase <ide> def test_should_return_template_for_any_path <ide> resolver = ActionView::NullResolver.new() <del> templates = resolver.find_all("path.erb", "arbitrary", false, {locale: [], formats: [:html], handlers: []}) <add> templates = resolver.find_all("path.erb", "arbitrary", false, locale: [], formats: [:html], handlers: []) <ide> assert_equal 1, templates.size, "expected one template" <ide> assert_equal "Template generated by Null Resolver", templates.first.source <ide> assert_equal "arbitrary/path.erb", templates.first.virtual_path.to_s <ide><path>activejob/test/support/integration/adapters/sidekiq.rb <ide> def start_workers <ide> end <ide> <ide> require "sidekiq/launcher" <del> sidekiq = Sidekiq::Launcher.new({queues: ["integration_tests"], <add> sidekiq = Sidekiq::Launcher.new(queues: ["integration_tests"], <ide> environment: "test", <ide> concurrency: 1, <del> timeout: 1, <del> }) <add> timeout: 1) <ide> Sidekiq.average_scheduled_poll_interval = 0.5 <ide> Sidekiq.options[:poll_interval_average] = 1 <ide> begin <ide><path>activemodel/lib/active_model/errors.rb <ide> def full_message(attribute, message) <ide> return message if attribute == :base <ide> attr_name = attribute.to_s.tr(".", "_").humanize <ide> attr_name = @base.class.human_attribute_name(attribute, default: attr_name) <del> I18n.t(:"errors.format", { <del> default: "%{attribute} %{message}", <add> I18n.t(:"errors.format", default: "%{attribute} %{message}", <ide> attribute: attr_name, <del> message: message <del> }) <add> message: message) <ide> end <ide> <ide> # Translates an error message in its default scope <ide><path>activemodel/test/cases/forbidden_attributes_protection_test.rb <ide> def to_h <ide> <ide> class ActiveModelMassUpdateProtectionTest < ActiveSupport::TestCase <ide> test "forbidden attributes cannot be used for mass updating" do <del> params = ProtectedParams.new({ "a" => "b" }) <add> params = ProtectedParams.new("a" => "b") <ide> assert_raises(ActiveModel::ForbiddenAttributesError) do <ide> Account.new.sanitize_for_mass_assignment(params) <ide> end <ide> end <ide> <ide> test "permitted attributes can be used for mass updating" do <del> params = ProtectedParams.new({ "a" => "b" }).permit! <add> params = ProtectedParams.new("a" => "b").permit! <ide> assert_equal({ "a" => "b" }, Account.new.sanitize_for_mass_assignment(params)) <ide> end <ide> <ide><path>activemodel/test/cases/type/integer_test.rb <ide> class IntegerTest < ActiveModel::TestCase <ide> test "random objects cast to nil" do <ide> type = Type::Integer.new <ide> assert_nil type.cast([1,2]) <del> assert_nil type.cast({1 => 2}) <add> assert_nil type.cast(1 => 2) <ide> assert_nil type.cast(1..2) <ide> end <ide> <ide><path>activemodel/test/cases/validations/confirmation_validation_test.rb <ide> def test_title_confirmation_with_i18n_attribute <ide> @old_load_path, @old_backend = I18n.load_path.dup, I18n.backend <ide> I18n.load_path.clear <ide> I18n.backend = I18n::Backend::Simple.new <del> I18n.backend.store_translations("en", { <del> errors: { messages: { confirmation: "doesn't match %{attribute}" } }, <del> activemodel: { attributes: { topic: { title: "Test Title"} } } <del> }) <add> I18n.backend.store_translations("en", errors: { messages: { confirmation: "doesn't match %{attribute}" } }, <add> activemodel: { attributes: { topic: { title: "Test Title"} } }) <ide> <ide> Topic.validates_confirmation_of(:title) <ide> <ide><path>activerecord/lib/active_record/connection_adapters/connection_specification.rb <ide> def query_hash <ide> <ide> def raw_config <ide> if uri.opaque <del> query_hash.merge({ <del> "adapter" => @adapter, <del> "database" => uri.opaque }) <add> query_hash.merge( "adapter" => @adapter, <add> "database" => uri.opaque) <ide> else <del> query_hash.merge({ <del> "adapter" => @adapter, <add> query_hash.merge( "adapter" => @adapter, <ide> "username" => uri.user, <ide> "password" => uri.password, <ide> "port" => uri.port, <ide> "database" => database_from_path, <del> "host" => uri.hostname }) <add> "host" => uri.hostname) <ide> end <ide> end <ide> <ide><path>activerecord/test/cases/adapters/mysql2/active_schema_test.rb <ide> def test_drop_table <ide> <ide> def test_create_mysql_database_with_encoding <ide> assert_equal "CREATE DATABASE `matt` DEFAULT CHARACTER SET `utf8`", create_database(:matt) <del> assert_equal "CREATE DATABASE `aimonetti` DEFAULT CHARACTER SET `latin1`", create_database(:aimonetti, {charset: "latin1"}) <del> assert_equal "CREATE DATABASE `matt_aimonetti` DEFAULT CHARACTER SET `big5` COLLATE `big5_chinese_ci`", create_database(:matt_aimonetti, {charset: :big5, collation: :big5_chinese_ci}) <add> assert_equal "CREATE DATABASE `aimonetti` DEFAULT CHARACTER SET `latin1`", create_database(:aimonetti, charset: "latin1") <add> assert_equal "CREATE DATABASE `matt_aimonetti` DEFAULT CHARACTER SET `big5` COLLATE `big5_chinese_ci`", create_database(:matt_aimonetti, charset: :big5, collation: :big5_chinese_ci) <ide> end <ide> <ide> def test_recreate_mysql_database_with_encoding <del> create_database(:luca, {charset: "latin1"}) <del> assert_equal "CREATE DATABASE `luca` DEFAULT CHARACTER SET `latin1`", recreate_database(:luca, {charset: "latin1"}) <add> create_database(:luca, charset: "latin1") <add> assert_equal "CREATE DATABASE `luca` DEFAULT CHARACTER SET `latin1`", recreate_database(:luca, charset: "latin1") <ide> end <ide> <ide> def test_add_column <ide> def test_remove_timestamps <ide> ActiveRecord::Base.connection.create_table :delete_me do |t| <ide> t.timestamps null: true <ide> end <del> ActiveRecord::Base.connection.remove_timestamps :delete_me, { null: true } <add> ActiveRecord::Base.connection.remove_timestamps :delete_me, null: true <ide> assert !column_present?("delete_me", "updated_at", "datetime") <ide> assert !column_present?("delete_me", "created_at", "datetime") <ide> ensure <ide><path>activerecord/test/cases/adapters/mysql2/connection_test.rb <ide> def test_mysql_sql_mode_variable_overrides_strict_mode <ide> <ide> def test_passing_arbitary_flags_to_adapter <ide> run_without_connection do |orig_connection| <del> ActiveRecord::Base.establish_connection(orig_connection.merge({flags: Mysql2::Client::COMPRESS})) <add> ActiveRecord::Base.establish_connection(orig_connection.merge(flags: Mysql2::Client::COMPRESS)) <ide> assert_equal (Mysql2::Client::COMPRESS | Mysql2::Client::FOUND_ROWS), ActiveRecord::Base.connection.raw_connection.query_options[:flags] <ide> end <ide> end <ide> <ide> def test_passing_flags_by_array_to_adapter <ide> run_without_connection do |orig_connection| <del> ActiveRecord::Base.establish_connection(orig_connection.merge({flags: ["COMPRESS"] })) <add> ActiveRecord::Base.establish_connection(orig_connection.merge(flags: ["COMPRESS"])) <ide> assert_equal ["COMPRESS", "FOUND_ROWS"], ActiveRecord::Base.connection.raw_connection.query_options[:flags] <ide> end <ide> end <ide> <ide> def test_mysql_set_session_variable <ide> run_without_connection do |orig_connection| <del> ActiveRecord::Base.establish_connection(orig_connection.deep_merge({variables: {default_week_format: 3}})) <add> ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: {default_week_format: 3})) <ide> session_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.DEFAULT_WEEK_FORMAT" <ide> assert_equal 3, session_mode.rows.first.first.to_i <ide> end <ide> end <ide> <ide> def test_mysql_set_session_variable_to_default <ide> run_without_connection do |orig_connection| <del> ActiveRecord::Base.establish_connection(orig_connection.deep_merge({variables: {default_week_format: :default}})) <add> ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: {default_week_format: :default})) <ide> global_mode = ActiveRecord::Base.connection.exec_query "SELECT @@GLOBAL.DEFAULT_WEEK_FORMAT" <ide> session_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.DEFAULT_WEEK_FORMAT" <ide> assert_equal global_mode.rows, session_mode.rows <ide><path>activerecord/test/cases/adapters/postgresql/connection_test.rb <ide> def test_reconnection_after_actual_disconnection_with_verify <ide> <ide> def test_set_session_variable_true <ide> run_without_connection do |orig_connection| <del> ActiveRecord::Base.establish_connection(orig_connection.deep_merge({variables: {debug_print_plan: true}})) <add> ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: {debug_print_plan: true})) <ide> set_true = ActiveRecord::Base.connection.exec_query "SHOW DEBUG_PRINT_PLAN" <ide> assert_equal set_true.rows, [["on"]] <ide> end <ide> end <ide> <ide> def test_set_session_variable_false <ide> run_without_connection do |orig_connection| <del> ActiveRecord::Base.establish_connection(orig_connection.deep_merge({variables: {debug_print_plan: false}})) <add> ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: {debug_print_plan: false})) <ide> set_false = ActiveRecord::Base.connection.exec_query "SHOW DEBUG_PRINT_PLAN" <ide> assert_equal set_false.rows, [["off"]] <ide> end <ide> def test_set_session_variable_false <ide> def test_set_session_variable_nil <ide> run_without_connection do |orig_connection| <ide> # This should be a no-op that does not raise an error <del> ActiveRecord::Base.establish_connection(orig_connection.deep_merge({variables: {debug_print_plan: nil}})) <add> ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: {debug_print_plan: nil})) <ide> end <ide> end <ide> <ide> def test_set_session_variable_default <ide> run_without_connection do |orig_connection| <ide> # This should execute a query that does not raise an error <del> ActiveRecord::Base.establish_connection(orig_connection.deep_merge({variables: {debug_print_plan: :default}})) <add> ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: {debug_print_plan: :default})) <ide> end <ide> end <ide> <ide><path>activerecord/test/cases/adapters/postgresql/hstore_test.rb <ide> def test_changes_in_place <ide> end <ide> <ide> def test_gen1 <del> assert_equal(%q(" "=>""), @type.serialize({" "=>""})) <add> assert_equal(%q(" "=>""), @type.serialize(" "=>"")) <ide> end <ide> <ide> def test_gen2 <del> assert_equal(%q(","=>""), @type.serialize({","=>""})) <add> assert_equal(%q(","=>""), @type.serialize(","=>"")) <ide> end <ide> <ide> def test_gen3 <del> assert_equal(%q("="=>""), @type.serialize({"="=>""})) <add> assert_equal(%q("="=>""), @type.serialize("="=>"")) <ide> end <ide> <ide> def test_gen4 <del> assert_equal(%q(">"=>""), @type.serialize({">"=>""})) <add> assert_equal(%q(">"=>""), @type.serialize(">"=>"")) <ide> end <ide> <ide> def test_parse1 <ide> class HstoreWithSerialize < Hstore <ide> end <ide> <ide> def test_hstore_with_serialized_attributes <del> HstoreWithSerialize.create! tags: TagCollection.new({"one" => "two"}) <add> HstoreWithSerialize.create! tags: TagCollection.new("one" => "two") <ide> record = HstoreWithSerialize.first <ide> assert_instance_of TagCollection, record.tags <ide> assert_equal({"one" => "two"}, record.tags.to_hash) <ide> def test_hstore_with_serialized_attributes <ide> end <ide> <ide> def test_clone_hstore_with_serialized_attributes <del> HstoreWithSerialize.create! tags: TagCollection.new({"one" => "two"}) <add> HstoreWithSerialize.create! tags: TagCollection.new("one" => "two") <ide> record = HstoreWithSerialize.first <ide> dupe = record.dup <ide> assert_equal({"one" => "two"}, dupe.tags.to_hash) <ide><path>activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb <ide> def test_habtm_collection_size_from_build <ide> end <ide> <ide> def test_habtm_collection_size_from_params <del> devel = Developer.new({ <del> projects_attributes: { <add> devel = Developer.new( projects_attributes: { <ide> "0" => {} <del> } <del> }) <add> }) <ide> <ide> assert_equal 1, devel.projects.size <ide> end <ide><path>activerecord/test/cases/associations/has_many_associations_test.rb <ide> def test_find_all_sanitized <ide> firm = Firm.all.merge!(order: "id").first <ide> summit = firm.clients.where("name = 'Summit'").to_a <ide> assert_equal summit, firm.clients.where("name = ?", "Summit").to_a <del> assert_equal summit, firm.clients.where("name = :name", { name: "Summit" }).to_a <add> assert_equal summit, firm.clients.where("name = :name", name: "Summit").to_a <ide> end <ide> <ide> def test_find_first <ide> def test_joins_with_namespaced_model_should_use_correct_type <ide> old = ActiveRecord::Base.store_full_sti_class <ide> ActiveRecord::Base.store_full_sti_class = true <ide> <del> firm = Namespaced::Firm.create({ name: "Some Company" }) <del> firm.clients.create({ name: "Some Client" }) <add> firm = Namespaced::Firm.create(name: "Some Company") <add> firm.clients.create(name: "Some Client") <ide> <ide> stats = Namespaced::Firm.all.merge!( <ide> select: "#{Namespaced::Firm.table_name}.id, COUNT(#{Namespaced::Client.table_name}.id) AS num_clients", <ide><path>activerecord/test/cases/attribute_methods_test.rb <ide> def setup <ide> <ide> if current_adapter?(:Mysql2Adapter) <ide> test "read attributes_before_type_cast on a boolean" do <del> bool = Boolean.create!({ "value" => false }) <add> bool = Boolean.create!("value" => false) <ide> if RUBY_PLATFORM.include?("java") <ide> # JRuby will return the value before typecast as string. <ide> assert_equal "0", bool.reload.attributes_before_type_cast["value"] <ide><path>activerecord/test/cases/attribute_set_test.rb <ide> class AttributeSetTest < ActiveRecord::TestCase <ide> <ide> test "building with custom types" do <ide> builder = AttributeSet::Builder.new(foo: Type::Float.new) <del> attributes = builder.build_from_database({ foo: "3.3", bar: "4.4" }, { bar: Type::Integer.new }) <add> attributes = builder.build_from_database({ foo: "3.3", bar: "4.4" }, bar: Type::Integer.new) <ide> <ide> assert_equal 3.3, attributes[:foo].value <ide> assert_equal 4, attributes[:bar].value <ide><path>activerecord/test/cases/base_test.rb <ide> def test_custom_mutator <ide> end <ide> <ide> def test_initialize_with_attributes <del> topic = Topic.new({ <del> "title" => "initialized from attributes", "written_on" => "2003-12-12 23:23" <del> }) <add> topic = Topic.new( "title" => "initialized from attributes", "written_on" => "2003-12-12 23:23") <ide> <ide> assert_equal("initialized from attributes", topic.title) <ide> end <ide> <ide> def test_initialize_with_invalid_attribute <del> Topic.new({ "title" => "test", <del> "last_read(1i)" => "2005", "last_read(2i)" => "2", "last_read(3i)" => "31"}) <add> Topic.new("title" => "test", <add> "last_read(1i)" => "2005", "last_read(2i)" => "2", "last_read(3i)" => "31") <ide> rescue ActiveRecord::MultiparameterAssignmentErrors => ex <ide> assert_equal(1, ex.errors.size) <ide> assert_equal("last_read", ex.errors[0].attribute) <ide> def test_attributes_on_dummy_time_with_invalid_time <ide> end <ide> <ide> def test_boolean <del> b_nil = Boolean.create({ "value" => nil }) <add> b_nil = Boolean.create("value" => nil) <ide> nil_id = b_nil.id <del> b_false = Boolean.create({ "value" => false }) <add> b_false = Boolean.create("value" => false) <ide> false_id = b_false.id <del> b_true = Boolean.create({ "value" => true }) <add> b_true = Boolean.create("value" => true) <ide> true_id = b_true.id <ide> <ide> b_nil = Boolean.find(nil_id) <ide> def test_boolean <ide> end <ide> <ide> def test_boolean_without_questionmark <del> b_true = Boolean.create({ "value" => true }) <add> b_true = Boolean.create("value" => true) <ide> true_id = b_true.id <ide> <ide> subclass = Class.new(Boolean).find true_id <ide> def test_boolean_without_questionmark <ide> end <ide> <ide> def test_boolean_cast_from_string <del> b_blank = Boolean.create({ "value" => "" }) <add> b_blank = Boolean.create("value" => "") <ide> blank_id = b_blank.id <del> b_false = Boolean.create({ "value" => "0" }) <add> b_false = Boolean.create("value" => "0") <ide> false_id = b_false.id <del> b_true = Boolean.create({ "value" => "1" }) <add> b_true = Boolean.create("value" => "1") <ide> true_id = b_true.id <ide> <ide> b_blank = Boolean.find(blank_id) <ide><path>activerecord/test/cases/connection_specification/resolver_test.rb <ide> def test_spec_name_on_key_lookup <ide> end <ide> <ide> def test_spec_name_with_inline_config <del> spec = spec({"adapter" => "sqlite3"}) <add> spec = spec("adapter" => "sqlite3") <ide> assert_equal "primary", spec.name, "should default to primary id" <ide> end <ide> end <ide><path>activerecord/test/cases/date_test.rb <ide> def test_assign_valid_dates <ide> <ide> invalid_dates.each do |date_src| <ide> assert_nothing_raised do <del> topic = Topic.new({"last_read(1i)" => date_src[0].to_s, "last_read(2i)" => date_src[1].to_s, "last_read(3i)" => date_src[2].to_s}) <add> topic = Topic.new("last_read(1i)" => date_src[0].to_s, "last_read(2i)" => date_src[1].to_s, "last_read(3i)" => date_src[2].to_s) <ide> # Oracle DATE columns are datetime columns and Oracle adapter returns Time value <ide> if current_adapter?(:OracleAdapter) <ide> assert_equal(topic.last_read.to_date, Time.local(*date_src).to_date, "The date should be modified according to the behavior of the Time object") <ide><path>activerecord/test/cases/log_subscriber_test.rb <ide> def test_basic_payload_name_logging_coloration_generic_sql <ide> logger.sql(event.new(0, sql: verb.to_s)) <ide> assert_match(/#{REGEXP_BOLD}#{REGEXP_MAGENTA} \(0.0ms\)#{REGEXP_CLEAR}/i, logger.debugs.last) <ide> <del> logger.sql(event.new(0, {sql: verb.to_s, name: "SQL"})) <add> logger.sql(event.new(0, sql: verb.to_s, name: "SQL")) <ide> assert_match(/#{REGEXP_BOLD}#{REGEXP_MAGENTA}SQL \(0.0ms\)#{REGEXP_CLEAR}/i, logger.debugs.last) <ide> end <ide> end <ide> def test_basic_payload_name_logging_coloration_named_sql <ide> logger = TestDebugLogSubscriber.new <ide> logger.colorize_logging = true <ide> SQL_COLORINGS.each do |verb, _| <del> logger.sql(event.new(0, {sql: verb.to_s, name: "Model Load"})) <add> logger.sql(event.new(0, sql: verb.to_s, name: "Model Load")) <ide> assert_match(/#{REGEXP_BOLD}#{REGEXP_CYAN}Model Load \(0.0ms\)#{REGEXP_CLEAR}/i, logger.debugs.last) <ide> <del> logger.sql(event.new(0, {sql: verb.to_s, name: "Model Exists"})) <add> logger.sql(event.new(0, sql: verb.to_s, name: "Model Exists")) <ide> assert_match(/#{REGEXP_BOLD}#{REGEXP_CYAN}Model Exists \(0.0ms\)#{REGEXP_CLEAR}/i, logger.debugs.last) <ide> <del> logger.sql(event.new(0, {sql: verb.to_s, name: "ANY SPECIFIC NAME"})) <add> logger.sql(event.new(0, sql: verb.to_s, name: "ANY SPECIFIC NAME")) <ide> assert_match(/#{REGEXP_BOLD}#{REGEXP_CYAN}ANY SPECIFIC NAME \(0.0ms\)#{REGEXP_CLEAR}/i, logger.debugs.last) <ide> end <ide> end <ide><path>activerecord/test/cases/migration/change_table_test.rb <ide> def test_timestamps_creates_updated_at_and_created_at <ide> def test_remove_timestamps_creates_updated_at_and_created_at <ide> with_change_table do |t| <ide> @connection.expect :remove_timestamps, nil, [:delete_me, { null: true }] <del> t.remove_timestamps({ null: true }) <add> t.remove_timestamps(null: true) <ide> end <ide> end <ide> <ide><path>activerecord/test/cases/migration_test.rb <ide> def test_copying_migrations_without_timestamps <ide> @migrations_path = MIGRATIONS_ROOT + "/valid" <ide> @existing_migrations = Dir[@migrations_path + "/*.rb"] <ide> <del> copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/to_copy"}) <add> copied = ActiveRecord::Migration.copy(@migrations_path, bukkits: MIGRATIONS_ROOT + "/to_copy") <ide> assert File.exist?(@migrations_path + "/4_people_have_hobbies.bukkits.rb") <ide> assert File.exist?(@migrations_path + "/5_people_have_descriptions.bukkits.rb") <ide> assert_equal [@migrations_path + "/4_people_have_hobbies.bukkits.rb", @migrations_path + "/5_people_have_descriptions.bukkits.rb"], copied.map(&:filename) <ide> def test_copying_migrations_without_timestamps <ide> assert_equal expected, IO.readlines(@migrations_path + "/4_people_have_hobbies.bukkits.rb")[0].chomp <ide> <ide> files_count = Dir[@migrations_path + "/*.rb"].length <del> copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/to_copy"}) <add> copied = ActiveRecord::Migration.copy(@migrations_path, bukkits: MIGRATIONS_ROOT + "/to_copy") <ide> assert_equal files_count, Dir[@migrations_path + "/*.rb"].length <ide> assert copied.empty? <ide> ensure <ide> def test_copying_migrations_with_timestamps <ide> @existing_migrations = Dir[@migrations_path + "/*.rb"] <ide> <ide> travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do <del> copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) <add> copied = ActiveRecord::Migration.copy(@migrations_path, bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps") <ide> assert File.exist?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb") <ide> assert File.exist?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb") <ide> expected = [@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb", <ide> @migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb"] <ide> assert_equal expected, copied.map(&:filename) <ide> <ide> files_count = Dir[@migrations_path + "/*.rb"].length <del> copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) <add> copied = ActiveRecord::Migration.copy(@migrations_path, bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps") <ide> assert_equal files_count, Dir[@migrations_path + "/*.rb"].length <ide> assert copied.empty? <ide> end <ide> def test_copying_migrations_with_timestamps_to_destination_with_timestamps_in_fu <ide> @existing_migrations = Dir[@migrations_path + "/*.rb"] <ide> <ide> travel_to(Time.utc(2010, 2, 20, 10, 10, 10)) do <del> ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) <add> ActiveRecord::Migration.copy(@migrations_path, bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps") <ide> assert File.exist?(@migrations_path + "/20100301010102_people_have_hobbies.bukkits.rb") <ide> assert File.exist?(@migrations_path + "/20100301010103_people_have_descriptions.bukkits.rb") <ide> <ide> files_count = Dir[@migrations_path + "/*.rb"].length <del> copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) <add> copied = ActiveRecord::Migration.copy(@migrations_path, bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps") <ide> assert_equal files_count, Dir[@migrations_path + "/*.rb"].length <ide> assert copied.empty? <ide> end <ide> def test_copying_migrations_preserving_magic_comments <ide> @migrations_path = MIGRATIONS_ROOT + "/valid" <ide> @existing_migrations = Dir[@migrations_path + "/*.rb"] <ide> <del> copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/magic"}) <add> copied = ActiveRecord::Migration.copy(@migrations_path, bukkits: MIGRATIONS_ROOT + "/magic") <ide> assert File.exist?(@migrations_path + "/4_currencies_have_symbols.bukkits.rb") <ide> assert_equal [@migrations_path + "/4_currencies_have_symbols.bukkits.rb"], copied.map(&:filename) <ide> <ide> expected = "# coding: ISO-8859-15\n# This migration comes from bukkits (originally 1)" <ide> assert_equal expected, IO.readlines(@migrations_path + "/4_currencies_have_symbols.bukkits.rb")[0..1].join.chomp <ide> <ide> files_count = Dir[@migrations_path + "/*.rb"].length <del> copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/magic"}) <add> copied = ActiveRecord::Migration.copy(@migrations_path, bukkits: MIGRATIONS_ROOT + "/magic") <ide> assert_equal files_count, Dir[@migrations_path + "/*.rb"].length <ide> assert copied.empty? <ide> ensure <ide> def test_copying_migrations_to_non_existing_directory <ide> @existing_migrations = [] <ide> <ide> travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do <del> copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) <add> copied = ActiveRecord::Migration.copy(@migrations_path, bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps") <ide> assert File.exist?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb") <ide> assert File.exist?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb") <ide> assert_equal 2, copied.length <ide> def test_copying_migrations_to_empty_directory <ide> @existing_migrations = [] <ide> <ide> travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do <del> copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) <add> copied = ActiveRecord::Migration.copy(@migrations_path, bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps") <ide> assert File.exist?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb") <ide> assert File.exist?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb") <ide> assert_equal 2, copied.length <ide><path>activerecord/test/cases/nested_attributes_test.rb <ide> def test_reject_if_with_a_proc_which_returns_true_always_for_has_one <ide> Pirate.accepts_nested_attributes_for :ship, reject_if: proc {|attributes| true } <ide> pirate = Pirate.new(catchphrase: "Stop wastin' me time") <ide> ship = pirate.create_ship(name: "s1") <del> pirate.update({ship_attributes: { name: "s2", id: ship.id } }) <add> pirate.update(ship_attributes: { name: "s2", id: ship.id }) <ide> assert_equal "s1", ship.reload.name <ide> end <ide> <ide> def test_reject_if_with_a_proc_which_returns_true_always_for_has_many <ide> Man.accepts_nested_attributes_for :interests, reject_if: proc {|attributes| true } <ide> man = Man.create(name: "John") <ide> interest = man.interests.create(topic: "photography") <del> man.update({interests_attributes: { topic: "gardening", id: interest.id } }) <add> man.update(interests_attributes: { topic: "gardening", id: interest.id }) <ide> assert_equal "photography", interest.reload.topic <ide> end <ide> <ide> def test_destroy_works_independent_of_reject_if <ide> Man.accepts_nested_attributes_for :interests, reject_if: proc {|attributes| true }, allow_destroy: true <ide> man = Man.create(name: "Jon") <ide> interest = man.interests.create(topic: "the ladies") <del> man.update({interests_attributes: { _destroy: "1", id: interest.id } }) <add> man.update(interests_attributes: { _destroy: "1", id: interest.id }) <ide> assert man.reload.interests.empty? <ide> end <ide> <ide> def test_has_many_association_updating_a_single_record <ide> Man.accepts_nested_attributes_for(:interests) <ide> man = Man.create(name: "John") <ide> interest = man.interests.create(topic: "photography") <del> man.update({interests_attributes: {topic: "gardening", id: interest.id}}) <add> man.update(interests_attributes: {topic: "gardening", id: interest.id}) <ide> assert_equal "gardening", interest.reload.topic <ide> end <ide> <ide> def test_should_also_work_with_a_HashWithIndifferentAccess <ide> end <ide> <ide> def test_should_work_with_update_as_well <del> @pirate.update({ catchphrase: "Arr", ship_attributes: { id: @ship.id, name: "Mister Pablo" } }) <add> @pirate.update(catchphrase: "Arr", ship_attributes: { id: @ship.id, name: "Mister Pablo" }) <ide> @pirate.reload <ide> <ide> assert_equal "Arr", @pirate.catchphrase <ide> def test_should_not_destroy_an_existing_record_if_allow_destroy_is_false <ide> end <ide> <ide> def test_should_work_with_update_as_well <del> @ship.update({ name: "Mister Pablo", pirate_attributes: { catchphrase: "Arr" } }) <add> @ship.update(name: "Mister Pablo", pirate_attributes: { catchphrase: "Arr" }) <ide> @ship.reload <ide> <ide> assert_equal "Mister Pablo", @ship.name <ide> def test_should_raise_an_UnknownAttributeError_for_non_existing_nested_attribute <ide> end <ide> <ide> def test_should_save_only_one_association_on_create <del> pirate = Pirate.create!({ <del> :catchphrase => "Arr", <del> association_getter => { "foo" => { name: "Grace OMalley" } } <del> }) <add> pirate = Pirate.create!( :catchphrase => "Arr", <add> association_getter => { "foo" => { name: "Grace OMalley" } }) <ide> <ide> assert_equal 1, pirate.reload.send(@association_name).count <ide> end <ide> def test_should_automatically_build_new_associated_models_for_each_entry_in_a_ha <ide> <ide> def test_should_not_assign_destroy_key_to_a_record <ide> assert_nothing_raised do <del> @pirate.send(association_setter, { "foo" => { "_destroy" => "0" }}) <add> @pirate.send(association_setter, "foo" => { "_destroy" => "0" }) <ide> end <ide> end <ide> <ide> def test_numeric_column_changes_from_zero_to_no_empty_string <ide> man = Man.create(name: "John") <ide> interest = man.interests.create(topic: "bar", zine_id: 0) <ide> assert interest.save <del> assert !man.update({interests_attributes: { id: interest.id, zine_id: "foo" }}) <add> assert !man.update(interests_attributes: { id: interest.id, zine_id: "foo" }) <ide> end <ide> end <ide> <ide><path>activerecord/test/cases/persistence_test.rb <ide> def test_update_column_with_default_scope <ide> <ide> def test_update_columns <ide> topic = Topic.find(1) <del> topic.update_columns({ "approved" => true, title: "Sebastian Topic" }) <add> topic.update_columns("approved" => true, title: "Sebastian Topic") <ide> assert topic.approved? <ide> assert_equal "Sebastian Topic", topic.title <ide> topic.reload <ide> def test_update_columns_should_not_use_setter_method <ide> <ide> def test_update_columns_should_raise_exception_if_new_record <ide> topic = Topic.new <del> assert_raises(ActiveRecord::ActiveRecordError) { topic.update_columns({ approved: false }) } <add> assert_raises(ActiveRecord::ActiveRecordError) { topic.update_columns(approved: false) } <ide> end <ide> <ide> def test_update_columns_should_not_leave_the_object_dirty <ide> topic = Topic.find(1) <del> topic.update({ "content" => "--- Have a nice day\n...\n", :author_name => "Jose" }) <add> topic.update("content" => "--- Have a nice day\n...\n", :author_name => "Jose") <ide> <ide> topic.reload <del> topic.update_columns({ content: "--- You too\n...\n", "author_name" => "Sebastian" }) <add> topic.update_columns(content: "--- You too\n...\n", "author_name" => "Sebastian") <ide> assert_equal [], topic.changed <ide> <ide> topic.reload <del> topic.update_columns({ content: "--- Have a nice day\n...\n", author_name: "Jose" }) <add> topic.update_columns(content: "--- Have a nice day\n...\n", author_name: "Jose") <ide> assert_equal [], topic.changed <ide> end <ide> <ide> def test_update_columns_with_one_readonly_attribute <ide> minivan = Minivan.find("m1") <ide> prev_color = minivan.color <ide> prev_name = minivan.name <del> assert_raises(ActiveRecord::ActiveRecordError) { minivan.update_columns({ name: "My old minivan", color: "black" }) } <add> assert_raises(ActiveRecord::ActiveRecordError) { minivan.update_columns(name: "My old minivan", color: "black") } <ide> assert_equal prev_color, minivan.color <ide> assert_equal prev_name, minivan.name <ide> <ide> def test_save_touch_false <ide> self.table_name = :widgets <ide> end <ide> <del> instance = widget.create!({ <del> name: "Bob", <add> instance = widget.create!( name: "Bob", <ide> created_at: 1.day.ago, <del> updated_at: 1.day.ago <del> }) <add> updated_at: 1.day.ago) <ide> <ide> created_at = instance.created_at <ide> updated_at = instance.updated_at <ide><path>activerecord/test/cases/pooled_connections_test.rb <ide> def setup <ide> <ide> # Will deadlock due to lack of Monitor timeouts in 1.9 <ide> def checkout_checkin_connections(pool_size, threads) <del> ActiveRecord::Base.establish_connection(@connection.merge({pool: pool_size, checkout_timeout: 0.5})) <add> ActiveRecord::Base.establish_connection(@connection.merge(pool: pool_size, checkout_timeout: 0.5)) <ide> @connection_count = 0 <ide> @timed_out = 0 <ide> threads.times do <ide> def checkout_checkin_connections(pool_size, threads) <ide> end <ide> <ide> def checkout_checkin_connections_loop(pool_size, loops) <del> ActiveRecord::Base.establish_connection(@connection.merge({pool: pool_size, checkout_timeout: 0.5})) <add> ActiveRecord::Base.establish_connection(@connection.merge(pool: pool_size, checkout_timeout: 0.5)) <ide> @connection_count = 0 <ide> @timed_out = 0 <ide> loops.times do <ide> def test_pooled_connection_checkin_two <ide> end <ide> <ide> def test_pooled_connection_remove <del> ActiveRecord::Base.establish_connection(@connection.merge({pool: 2, checkout_timeout: 0.5})) <add> ActiveRecord::Base.establish_connection(@connection.merge(pool: 2, checkout_timeout: 0.5)) <ide> old_connection = ActiveRecord::Base.connection <ide> extra_connection = ActiveRecord::Base.connection_pool.checkout <ide> ActiveRecord::Base.connection_pool.remove(extra_connection) <ide><path>activerecord/test/cases/relations_test.rb <ide> def test_joins_with_nil_argument <ide> end <ide> <ide> def test_finding_with_hash_conditions_on_joined_table <del> firms = DependentFirm.joins(:account).where({name: "RailsCore", accounts: { credit_limit: 55..60 }}).to_a <add> firms = DependentFirm.joins(:account).where(name: "RailsCore", accounts: { credit_limit: 55..60 }).to_a <ide> assert_equal 1, firms.size <ide> assert_equal companies(:rails_core), firms.first <ide> end <ide> def test_find_all_with_join <ide> end <ide> <ide> def test_find_on_hash_conditions <del> assert_equal Topic.all.merge!(where: {approved: false}).to_a, Topic.where({ approved: false }).to_a <add> assert_equal Topic.all.merge!(where: {approved: false}).to_a, Topic.where(approved: false).to_a <ide> end <ide> <ide> def test_joins_with_string_array <ide><path>activerecord/test/cases/sanitize_test.rb <ide> def test_named_bind_variables <ide> end <ide> <ide> def test_named_bind_arity <del> assert_nothing_raised { bind "name = :name", { name: "37signals" } } <del> assert_nothing_raised { bind "name = :name", { name: "37signals", id: 1 } } <del> assert_raise(ActiveRecord::PreparedStatementInvalid) { bind "name = :name", { id: 1 } } <add> assert_nothing_raised { bind "name = :name", name: "37signals" } <add> assert_nothing_raised { bind "name = :name", name: "37signals", id: 1 } <add> assert_raise(ActiveRecord::PreparedStatementInvalid) { bind "name = :name", id: 1 } <ide> end <ide> <ide> class SimpleEnumerable <ide><path>activerecord/test/cases/validations/i18n_generate_message_validation_test.rb <ide> def test_generate_message_taken_with_custom_message <ide> <ide> test "translation for 'taken' can be overridden" do <ide> reset_i18n_load_path do <del> I18n.backend.store_translations "en", {errors: {attributes: {title: {taken: "Custom taken message" }}}} <add> I18n.backend.store_translations "en", errors: {attributes: {title: {taken: "Custom taken message" }}} <ide> assert_equal "Custom taken message", @topic.errors.generate_message(:title, :taken, value: "title") <ide> end <ide> end <ide> <ide> test "translation for 'taken' can be overridden in activerecord scope" do <ide> reset_i18n_load_path do <del> I18n.backend.store_translations "en", {activerecord: {errors: {messages: {taken: "Custom taken message" }}}} <add> I18n.backend.store_translations "en", activerecord: {errors: {messages: {taken: "Custom taken message" }}} <ide> assert_equal "Custom taken message", @topic.errors.generate_message(:title, :taken, value: "title") <ide> end <ide> end <ide> <ide> test "translation for 'taken' can be overridden in activerecord model scope" do <ide> reset_i18n_load_path do <del> I18n.backend.store_translations "en", {activerecord: {errors: {models: {topic: {taken: "Custom taken message" }}}}} <add> I18n.backend.store_translations "en", activerecord: {errors: {models: {topic: {taken: "Custom taken message" }}}} <ide> assert_equal "Custom taken message", @topic.errors.generate_message(:title, :taken, value: "title") <ide> end <ide> end <ide> <ide> test "translation for 'taken' can be overridden in activerecord attributes scope" do <ide> reset_i18n_load_path do <del> I18n.backend.store_translations "en", {activerecord: {errors: {models: {topic: {attributes: {title: {taken: "Custom taken message" }}}}}}} <add> I18n.backend.store_translations "en", activerecord: {errors: {models: {topic: {attributes: {title: {taken: "Custom taken message" }}}}}} <ide> assert_equal "Custom taken message", @topic.errors.generate_message(:title, :taken, value: "title") <ide> end <ide> end <ide><path>activerecord/test/cases/validations_test.rb <ide> def test_exception_on_create_bang_many <ide> <ide> def test_exception_on_create_bang_with_block <ide> assert_raise(ActiveRecord::RecordInvalid) do <del> WrongReply.create!({ "title" => "OK" }) do |r| <add> WrongReply.create!("title" => "OK") do |r| <ide> r.content = nil <ide> end <ide> end <ide><path>activerecord/test/models/person.rb <ide> def comments=(new_comments) <ide> end <ide> <ide> def best_friend_first_name=(new_name) <del> assign_attributes({ best_friend_attributes: { first_name: new_name } }) <add> assign_attributes(best_friend_attributes: { first_name: new_name }) <ide> end <ide> end <ide> <ide><path>activesupport/test/caching_test.rb <ide> def test_fetch_with_forced_cache_miss_without_block <ide> end <ide> <ide> def test_should_read_and_write_hash <del> assert @cache.write("foo", {a: "b"}) <add> assert @cache.write("foo", a: "b") <ide> assert_equal({a: "b"}, @cache.read("foo")) <ide> end <ide> <ide> def test_logging <ide> end <ide> <ide> def test_log_with_string_namespace <del> @cache.fetch("foo", {namespace: "string_namespace"}) { "bar" } <add> @cache.fetch("foo", namespace: "string_namespace") { "bar" } <ide> assert_match %r{string_namespace:foo}, @buffer.string <ide> end <ide> <ide> def test_log_with_proc_namespace <ide> proc = Proc.new do <ide> "proc_namespace" <ide> end <del> @cache.fetch("foo", {namespace: proc}) { "bar" } <add> @cache.fetch("foo", namespace: proc) { "bar" } <ide> assert_match %r{proc_namespace:foo}, @buffer.string <ide> end <ide> <ide><path>activesupport/test/core_ext/duration_test.rb <ide> def test_inspect <ide> def test_inspect_locale <ide> current_locale = I18n.default_locale <ide> I18n.default_locale = :de <del> I18n.backend.store_translations(:de, { support: { array: { last_word_connector: " und " } } }) <add> I18n.backend.store_translations(:de, support: { array: { last_word_connector: " und " } }) <ide> assert_equal "10 years, 1 month und 1 day", (10.years + 1.month + 1.day).inspect <ide> ensure <ide> I18n.default_locale = current_locale <ide><path>activesupport/test/core_ext/hash/transform_keys_test.rb <ide> def initialize(elements = nil) <ide> end <ide> end <ide> <del> original = HashDescendant.new({ a: "a", b: "b" }) <add> original = HashDescendant.new(a: "a", b: "b") <ide> mapped = original.transform_keys { |k| "#{k}!".to_sym } <ide> <ide> assert_equal({ a: "a", b: "b" }, original) <ide><path>activesupport/test/core_ext/hash_ext_test.rb <ide> def test_transform_keys_with_bang_mutates <ide> transformed_hash = @mixed.dup <ide> transformed_hash.transform_keys!{ |key| key.to_s.upcase } <ide> assert_equal @upcase_strings, transformed_hash <del> assert_equal @mixed, { :a => 1, "b" => 2 } <add> assert_equal @mixed, :a => 1, "b" => 2 <ide> end <ide> <ide> def test_deep_transform_keys! <ide> def test_deep_transform_keys_with_bang_mutates <ide> transformed_hash = @nested_mixed.deep_dup <ide> transformed_hash.deep_transform_keys!{ |key| key.to_s.upcase } <ide> assert_equal @nested_upcase_strings, transformed_hash <del> assert_equal @nested_mixed, { "a" => { b: { "c" => 3 } } } <add> assert_equal @nested_mixed, "a" => { b: { "c" => 3 } } <ide> end <ide> <ide> def test_symbolize_keys <ide> def test_symbolize_keys_with_bang_mutates <ide> transformed_hash = @mixed.dup <ide> transformed_hash.deep_symbolize_keys! <ide> assert_equal @symbols, transformed_hash <del> assert_equal @mixed, { :a => 1, "b" => 2 } <add> assert_equal @mixed, :a => 1, "b" => 2 <ide> end <ide> <ide> def test_deep_symbolize_keys! <ide> def test_deep_symbolize_keys_with_bang_mutates <ide> transformed_hash = @nested_mixed.deep_dup <ide> transformed_hash.deep_symbolize_keys! <ide> assert_equal @nested_symbols, transformed_hash <del> assert_equal @nested_mixed, { "a" => { b: { "c" => 3 } } } <add> assert_equal @nested_mixed, "a" => { b: { "c" => 3 } } <ide> end <ide> <ide> def test_symbolize_keys_preserves_keys_that_cant_be_symbolized <ide> def test_stringify_keys_with_bang_mutates <ide> transformed_hash = @mixed.dup <ide> transformed_hash.stringify_keys! <ide> assert_equal @strings, transformed_hash <del> assert_equal @mixed, { :a => 1, "b" => 2 } <add> assert_equal @mixed, :a => 1, "b" => 2 <ide> end <ide> <ide> def test_deep_stringify_keys! <ide> def test_deep_stringify_keys_with_bang_mutates <ide> transformed_hash = @nested_mixed.deep_dup <ide> transformed_hash.deep_stringify_keys! <ide> assert_equal @nested_strings, transformed_hash <del> assert_equal @nested_mixed, { "a" => { b: { "c" => 3 } } } <add> assert_equal @nested_mixed, "a" => { b: { "c" => 3 } } <ide> end <ide> <ide> def test_symbolize_keys_for_hash_with_indifferent_access <ide> def test_indifferent_update <ide> <ide> def test_update_with_to_hash_conversion <ide> hash = HashWithIndifferentAccess.new <del> hash.update HashByConversion.new({ a: 1 }) <add> hash.update HashByConversion.new(a: 1) <ide> assert_equal hash["a"], 1 <ide> end <ide> <ide> def test_indifferent_merging <ide> <ide> def test_merge_with_to_hash_conversion <ide> hash = HashWithIndifferentAccess.new <del> merged = hash.merge HashByConversion.new({ a: 1 }) <add> merged = hash.merge HashByConversion.new(a: 1) <ide> assert_equal merged["a"], 1 <ide> end <ide> <ide> def test_to_options_on_indifferent_preserves_hash <ide> end <ide> <ide> def test_to_options_on_indifferent_preserves_works_as_hash_with_dup <del> h = HashWithIndifferentAccess.new({ a: { b: "b" } }) <add> h = HashWithIndifferentAccess.new(a: { b: "b" }) <ide> dup = h.dup <ide> <ide> dup[:a][:c] = "c" <ide> def test_deep_merge_with_falsey_values <ide> end <ide> <ide> def test_deep_merge_on_indifferent_access <del> hash_1 = HashWithIndifferentAccess.new({ a: "a", b: "b", c: { c1: "c1", c2: "c2", c3: { d1: "d1" } } }) <del> hash_2 = HashWithIndifferentAccess.new({ a: 1, c: { c1: 2, c3: { d2: "d2" } } }) <add> hash_1 = HashWithIndifferentAccess.new(a: "a", b: "b", c: { c1: "c1", c2: "c2", c3: { d1: "d1" } }) <add> hash_2 = HashWithIndifferentAccess.new(a: 1, c: { c1: 2, c3: { d2: "d2" } }) <ide> hash_3 = { a: 1, c: { c1: 2, c3: { d2: "d2" } } } <ide> expected = { "a" => 1, "b" => "b", "c" => { "c1" => 2, "c2" => "c2", "c3" => { "d1" => "d1", "d2" => "d2" } } } <ide> assert_equal expected, hash_1.deep_merge(hash_2) <ide><path>activesupport/test/core_ext/object/to_query_test.rb <ide> def test_nested_empty_hash <ide> assert_equal "", <ide> {}.to_query <ide> assert_query_equal "a=1&b%5Bc%5D=3", <del> { a: 1, b: { c: 3, d: {} } } <add> a: 1, b: { c: 3, d: {} } <ide> assert_query_equal "", <del> { a: {b: {c: {}}} } <add> a: {b: {c: {}}} <ide> assert_query_equal "b%5Bc%5D=false&b%5Be%5D=&b%5Bf%5D=&p=12", <del> { p: 12, b: { c: false, e: nil, f: "" } } <add> p: 12, b: { c: false, e: nil, f: "" } <ide> assert_query_equal "b%5Bc%5D=3&b%5Bf%5D=", <del> { b: { c: 3, k: {}, f: "" } } <add> b: { c: 3, k: {}, f: "" } <ide> assert_query_equal "b=3", <del> {a: [], b: 3} <add> a: [], b: 3 <ide> end <ide> <ide> def test_hash_with_namespace <ide><path>activesupport/test/json/encoding_test_cases.rb <ide> module EncodingTestCases <ide> [ Custom.new(nil), "null" ], <ide> [ Custom.new(:a), '"a"' ], <ide> [ Custom.new([ :foo, "bar" ]), '["foo","bar"]' ], <del> [ Custom.new({ foo: "hello", bar: "world" }), '{"bar":"world","foo":"hello"}' ], <add> [ Custom.new(foo: "hello", bar: "world"), '{"bar":"world","foo":"hello"}' ], <ide> [ Custom.new(Hashlike.new), '{"bar":"world","foo":"hello"}' ], <ide> [ Custom.new(Custom.new(Custom.new(:a))), '"a"' ]] <ide> <ide><path>activesupport/test/message_encryptor_test.rb <ide> def test_alternative_serialization_method <ide> prev = ActiveSupport.use_standard_json_time_format <ide> ActiveSupport.use_standard_json_time_format = true <ide> encryptor = ActiveSupport::MessageEncryptor.new(SecureRandom.random_bytes(32), SecureRandom.random_bytes(128), serializer: JSONSerializer.new) <del> message = encryptor.encrypt_and_sign({ :foo => 123, "bar" => Time.utc(2010) }) <add> message = encryptor.encrypt_and_sign(:foo => 123, "bar" => Time.utc(2010)) <ide> exp = { "foo" => 123, "bar" => "2010-01-01T00:00:00.000Z" } <ide> assert_equal exp, encryptor.decrypt_and_verify(message) <ide> ensure <ide><path>activesupport/test/message_verifier_test.rb <ide> def test_alternative_serialization_method <ide> prev = ActiveSupport.use_standard_json_time_format <ide> ActiveSupport.use_standard_json_time_format = true <ide> verifier = ActiveSupport::MessageVerifier.new("Hey, I'm a secret!", serializer: JSONSerializer.new) <del> message = verifier.generate({ :foo => 123, "bar" => Time.utc(2010) }) <add> message = verifier.generate(:foo => 123, "bar" => Time.utc(2010)) <ide> exp = { "foo" => 123, "bar" => "2010-01-01T00:00:00.000Z" } <ide> assert_equal exp, verifier.verified(message) <ide> assert_equal exp, verifier.verify(message) <ide><path>activesupport/test/number_helper_i18n_test.rb <ide> def test_number_to_currency_with_empty_i18n_store <ide> <ide> def test_locale_default_format_has_precedence_over_helper_defaults <ide> I18n.backend.store_translations "ts", <del> { number: { format: { separator: ";" } } } <add> number: { format: { separator: ";" } } <ide> <ide> assert_equal("&$ - 10;00", number_to_currency(10, locale: "ts")) <ide> end <ide><path>activesupport/test/number_helper_test.rb <ide> def test_number_to_phone <ide> [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper| <ide> assert_equal("555-1234", number_helper.number_to_phone(5551234)) <ide> assert_equal("800-555-1212", number_helper.number_to_phone(8005551212)) <del> assert_equal("(800) 555-1212", number_helper.number_to_phone(8005551212, {area_code: true})) <del> assert_equal("", number_helper.number_to_phone("", {area_code: true})) <del> assert_equal("800 555 1212", number_helper.number_to_phone(8005551212, {delimiter: " "})) <del> assert_equal("(800) 555-1212 x 123", number_helper.number_to_phone(8005551212, {area_code: true, extension: 123})) <add> assert_equal("(800) 555-1212", number_helper.number_to_phone(8005551212, area_code: true)) <add> assert_equal("", number_helper.number_to_phone("", area_code: true)) <add> assert_equal("800 555 1212", number_helper.number_to_phone(8005551212, delimiter: " ")) <add> assert_equal("(800) 555-1212 x 123", number_helper.number_to_phone(8005551212, area_code: true, extension: 123)) <ide> assert_equal("800-555-1212", number_helper.number_to_phone(8005551212, extension: " ")) <ide> assert_equal("555.1212", number_helper.number_to_phone(5551212, delimiter: ".")) <ide> assert_equal("800-555-1212", number_helper.number_to_phone("8005551212")) <ide> def test_number_to_currency <ide> assert_equal("$1,234,567,890.50", number_helper.number_to_currency(1234567890.50)) <ide> assert_equal("$1,234,567,890.51", number_helper.number_to_currency(1234567890.506)) <ide> assert_equal("-$1,234,567,890.50", number_helper.number_to_currency(-1234567890.50)) <del> assert_equal("-$ 1,234,567,890.50", number_helper.number_to_currency(-1234567890.50, {format: "%u %n"})) <del> assert_equal("($1,234,567,890.50)", number_helper.number_to_currency(-1234567890.50, {negative_format: "(%u%n)"})) <del> assert_equal("$1,234,567,892", number_helper.number_to_currency(1234567891.50, {precision: 0})) <del> assert_equal("$1,234,567,890.5", number_helper.number_to_currency(1234567890.50, {precision: 1})) <del> assert_equal("&pound;1234567890,50", number_helper.number_to_currency(1234567890.50, {unit: "&pound;", separator: ",", delimiter: ""})) <add> assert_equal("-$ 1,234,567,890.50", number_helper.number_to_currency(-1234567890.50, format: "%u %n")) <add> assert_equal("($1,234,567,890.50)", number_helper.number_to_currency(-1234567890.50, negative_format: "(%u%n)")) <add> assert_equal("$1,234,567,892", number_helper.number_to_currency(1234567891.50, precision: 0)) <add> assert_equal("$1,234,567,890.5", number_helper.number_to_currency(1234567890.50, precision: 1)) <add> assert_equal("&pound;1234567890,50", number_helper.number_to_currency(1234567890.50, unit: "&pound;", separator: ",", delimiter: "")) <ide> assert_equal("$1,234,567,890.50", number_helper.number_to_currency("1234567890.50")) <del> assert_equal("1,234,567,890.50 K&#269;", number_helper.number_to_currency("1234567890.50", {unit: "K&#269;", format: "%n %u"})) <del> assert_equal("1,234,567,890.50 - K&#269;", number_helper.number_to_currency("-1234567890.50", {unit: "K&#269;", format: "%n %u", negative_format: "%n - %u"})) <del> assert_equal("0.00", number_helper.number_to_currency(+0.0, {unit: "", negative_format: "(%n)"})) <add> assert_equal("1,234,567,890.50 K&#269;", number_helper.number_to_currency("1234567890.50", unit: "K&#269;", format: "%n %u")) <add> assert_equal("1,234,567,890.50 - K&#269;", number_helper.number_to_currency("-1234567890.50", unit: "K&#269;", format: "%n %u", negative_format: "%n - %u")) <add> assert_equal("0.00", number_helper.number_to_currency(+0.0, unit: "", negative_format: "(%n)")) <ide> end <ide> end <ide> <ide> def test_number_to_percentage <ide> [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper| <ide> assert_equal("100.000%", number_helper.number_to_percentage(100)) <del> assert_equal("100%", number_helper.number_to_percentage(100, {precision: 0})) <del> assert_equal("302.06%", number_helper.number_to_percentage(302.0574, {precision: 2})) <add> assert_equal("100%", number_helper.number_to_percentage(100, precision: 0)) <add> assert_equal("302.06%", number_helper.number_to_percentage(302.0574, precision: 2)) <ide> assert_equal("100.000%", number_helper.number_to_percentage("100")) <ide> assert_equal("1000.000%", number_helper.number_to_percentage("1000")) <ide> assert_equal("123.4%", number_helper.number_to_percentage(123.400, precision: 3, strip_insignificant_zeros: true)) <ide><path>activesupport/test/xml_mini_test.rb <ide> def test_yaml <ide> } <ide> parser = @parsing["yaml"] <ide> assert_equal(expected, parser.call(yaml)) <del> assert_equal({1 => "test"}, parser.call({1 => "test"})) <add> assert_equal({1 => "test"}, parser.call(1 => "test")) <ide> assert_equal({"1 => 'test'"=>nil}, parser.call("{1 => 'test'}")) <ide> end <ide> <ide><path>guides/rails_guides/markdown.rb <ide> def dom_id_text(text) <ide> end <ide> <ide> def engine <del> @engine ||= Redcarpet::Markdown.new(Renderer, { <del> no_intra_emphasis: true, <add> @engine ||= Redcarpet::Markdown.new(Renderer, no_intra_emphasis: true, <ide> fenced_code_blocks: true, <ide> autolink: true, <ide> strikethrough: true, <ide> superscript: true, <del> tables: true <del> }) <add> tables: true) <ide> end <ide> <ide> def extract_raw_header_and_body <ide><path>railties/lib/rails/commands/server.rb <ide> def middleware <ide> end <ide> <ide> def default_options <del> super.merge({ <del> Port: ENV.fetch("PORT", 3000).to_i, <add> super.merge( Port: ENV.fetch("PORT", 3000).to_i, <ide> Host: ENV.fetch("HOST", "localhost").dup, <ide> DoNotReverseLookup: true, <ide> environment: (ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development").dup, <ide> daemonize: false, <ide> caching: nil, <ide> pid: Options::DEFAULT_PID_PATH, <del> restart_cmd: restart_command <del> }) <add> restart_cmd: restart_command) <ide> end <ide> <ide> private <ide><path>railties/lib/rails/generators/actions.rb <ide> def route(routing_code) <ide> sentinel = /\.routes\.draw do\s*\n/m <ide> <ide> in_root do <del> inject_into_file "config/routes.rb", " #{routing_code}\n", { after: sentinel, verbose: false, force: false } <add> inject_into_file "config/routes.rb", " #{routing_code}\n", after: sentinel, verbose: false, force: false <ide> end <ide> end <ide> <ide><path>railties/test/application/assets_test.rb <ide> class ::PostsController < ActionController::Base ; end <ide> <ide> class ::PostsController < ActionController::Base; end <ide> <del> get "/posts", {}, {"HTTPS"=>"off"} <add> get "/posts", {}, "HTTPS"=>"off" <ide> assert_match('src="http://example.com/assets/application.self.js', last_response.body) <del> get "/posts", {}, {"HTTPS"=>"on"} <add> get "/posts", {}, "HTTPS"=>"on" <ide> assert_match('src="https://example.com/assets/application.self.js', last_response.body) <ide> end <ide> <ide><path>railties/test/application/configuration_test.rb <ide> def create <ide> <ide> app "development" <ide> <del> post "/posts", {post: {"title" =>"zomg"}} <add> post "/posts", post: {"title" =>"zomg"} <ide> assert_equal "permitted", last_response.body <ide> end <ide> <ide> def create <ide> <ide> assert_equal :raise, ActionController::Parameters.action_on_unpermitted_parameters <ide> <del> post "/posts", {post: {"title" =>"zomg"}} <add> post "/posts", post: {"title" =>"zomg"} <ide> assert_match "We're sorry, but something went wrong", last_response.body <ide> end <ide> <ide> def create <ide> <ide> assert_equal :raise, ActionController::Parameters.action_on_unpermitted_parameters <ide> <del> post "/posts", {post: {"title" =>"zomg"}, format: "json"} <add> post "/posts", post: {"title" =>"zomg"}, format: "json" <ide> assert_equal 200, last_response.status <ide> end <ide> <ide><path>railties/test/application/mailer_previews_test.rb <ide> def teardown <ide> test "/rails/mailers is accessible with correct configuration" do <ide> add_to_config "config.action_mailer.show_previews = true" <ide> app("production") <del> get "/rails/mailers", {}, {"REMOTE_ADDR" => "4.2.42.42"} <add> get "/rails/mailers", {}, "REMOTE_ADDR" => "4.2.42.42" <ide> assert_equal 200, last_response.status <ide> end <ide> <ide><path>railties/test/generators/create_migration_test.rb <ide> def test_invoke <ide> end <ide> <ide> def test_invoke_pretended <del> create_migration(default_destination_path, {}, { pretend: true }) <add> create_migration(default_destination_path, {}, pretend: true) <ide> <ide> assert_no_file @migration.destination <ide> end <ide> def test_invoke_forced_when_exists_not_identical <ide> <ide> def test_invoke_forced_pretended_when_exists_not_identical <ide> migration_exists! <del> create_migration(default_destination_path, { force: true }, { pretend: true }) do <add> create_migration(default_destination_path, { force: true }, pretend: true) do <ide> "different content" <ide> end <ide> <ide> def test_invoke_forced_pretended_when_exists_not_identical <ide> <ide> def test_invoke_skipped_when_exists_not_identical <ide> migration_exists! <del> create_migration(default_destination_path, {}, { skip: true }) { "different content" } <add> create_migration(default_destination_path, {}, skip: true) { "different content" } <ide> <ide> assert_match(/skip db\/migrate\/2_create_articles.rb\n/, invoke!) <ide> assert_no_file @migration.destination <ide> def test_revoke <ide> <ide> def test_revoke_pretended <ide> migration_exists! <del> create_migration(default_destination_path, {}, { pretend: true }) <add> create_migration(default_destination_path, {}, pretend: true) <ide> <ide> assert_match(/remove db\/migrate\/1_create_articles.rb\n/, revoke!) <ide> assert_file @existing_migration.destination <ide><path>railties/test/generators/model_generator_test.rb <ide> def test_invokes_default_test_framework <ide> <ide> assert_file "test/fixtures/accounts.yml", /name: MyString/, /age: 1/ <ide> assert_generated_fixture("test/fixtures/accounts.yml", <del> {"one"=>{"name"=>"MyString", "age"=>1}, "two"=>{"name"=>"MyString", "age"=>1}}) <add> "one"=>{"name"=>"MyString", "age"=>1}, "two"=>{"name"=>"MyString", "age"=>1}) <ide> end <ide> <ide> def test_fixtures_use_the_references_ids <ide> run_generator ["LineItem", "product:references", "cart:belongs_to"] <ide> <ide> assert_file "test/fixtures/line_items.yml", /product: one\n cart: one/ <ide> assert_generated_fixture("test/fixtures/line_items.yml", <del> {"one"=>{"product"=>"one", "cart"=>"one"}, "two"=>{"product"=>"two", "cart"=>"two"}}) <add> "one"=>{"product"=>"one", "cart"=>"one"}, "two"=>{"product"=>"two", "cart"=>"two"}) <ide> end <ide> <ide> def test_fixtures_use_the_references_ids_and_type <ide> run_generator ["LineItem", "product:references{polymorphic}", "cart:belongs_to"] <ide> <ide> assert_file "test/fixtures/line_items.yml", /product: one\n product_type: Product\n cart: one/ <ide> assert_generated_fixture("test/fixtures/line_items.yml", <del> {"one"=>{"product"=>"one", "product_type"=>"Product", "cart"=>"one"}, <del> "two"=>{"product"=>"two", "product_type"=>"Product", "cart"=>"two"}}) <add> "one"=>{"product"=>"one", "product_type"=>"Product", "cart"=>"one"}, <add> "two"=>{"product"=>"two", "product_type"=>"Product", "cart"=>"two"}) <ide> end <ide> <ide> def test_fixtures_respect_reserved_yml_keywords <ide> run_generator ["LineItem", "no:integer", "Off:boolean", "ON:boolean"] <ide> <ide> assert_generated_fixture("test/fixtures/line_items.yml", <del> {"one"=>{"no"=>1, "Off"=>false, "ON"=>false}, "two"=>{"no"=>1, "Off"=>false, "ON"=>false}}) <add> "one"=>{"no"=>1, "Off"=>false, "ON"=>false}, "two"=>{"no"=>1, "Off"=>false, "ON"=>false}) <ide> end <ide> <ide> def test_fixture_is_skipped <ide> def test_fixture_without_pluralization <ide> ActiveRecord::Base.pluralize_table_names = false <ide> run_generator <ide> assert_generated_fixture("test/fixtures/account.yml", <del> {"one"=>{"name"=>"MyString", "age"=>1}, "two"=>{"name"=>"MyString", "age"=>1}}) <add> "one"=>{"name"=>"MyString", "age"=>1}, "two"=>{"name"=>"MyString", "age"=>1}) <ide> ensure <ide> ActiveRecord::Base.pluralize_table_names = original_pluralize_table_name <ide> end <ide><path>railties/test/railties/engine_test.rb <ide> def index <ide> <ide> boot_rails <ide> <del> get("/bukkits/bukkit", {}, {"SCRIPT_NAME" => "/foo"}) <add> get("/bukkits/bukkit", {}, "SCRIPT_NAME" => "/foo") <ide> assert_equal "/foo/bar", last_response.body <ide> <del> get("/bar", {}, {"SCRIPT_NAME" => "/foo"}) <add> get("/bar", {}, "SCRIPT_NAME" => "/foo") <ide> assert_equal "/foo/bukkits/bukkit", last_response.body <ide> end <ide> <ide> def index <ide> <ide> boot_rails <ide> <del> get("/bukkits/bukkit", {}, {"SCRIPT_NAME" => "/foo"}) <add> get("/bukkits/bukkit", {}, "SCRIPT_NAME" => "/foo") <ide> assert_equal "/foo/bar", last_response.body <ide> <del> get("/bar", {}, {"SCRIPT_NAME" => "/foo"}) <add> get("/bar", {}, "SCRIPT_NAME" => "/foo") <ide> assert_equal "/foo/bukkits/bukkit", last_response.body <ide> end <ide>
100
Javascript
Javascript
fix nits in tools/doc/common.js
50e5eff12ab33f868067fb41601e9d8feb2d8177
<ide><path>tools/doc/common.js <ide> const yaml = require('js-yaml'); <ide> <ide> function isYAMLBlock(text) { <del> return !!text.match(/^<!-- YAML/); <add> return /^<!-- YAML/.test(text); <ide> } <ide> <del>exports.isYAMLBlock = isYAMLBlock; <del> <ide> function arrify(value) { <ide> return Array.isArray(value) ? value : [value]; <ide> } <ide> function extractAndParseYAML(text) { <ide> } <ide> <ide> meta.changes = meta.changes || []; <del> for (const entry of meta.changes) { <del> entry.description = entry.description.replace(/^\^\s*/, ''); <del> } <ide> <ide> return meta; <ide> } <ide> <del>exports.extractAndParseYAML = extractAndParseYAML; <add>module.exports = { isYAMLBlock, extractAndParseYAML };
1
Text
Text
fix nits in stream.md
1cc5c547d5f83097b7190d8186533bf176df6c9f
<ide><path>doc/api/stream.md <ide> that implements an HTTP server: <ide> const http = require('http'); <ide> <ide> const server = http.createServer((req, res) => { <del> // `req` is an http.IncomingMessage, which is a Readable Stream <del> // `res` is an http.ServerResponse, which is a Writable Stream <add> // `req` is an http.IncomingMessage, which is a Readable Stream. <add> // `res` is an http.ServerResponse, which is a Writable Stream. <ide> <ide> let body = ''; <ide> // Get the data as utf8 strings. <ide> // If an encoding is not set, Buffer objects will be received. <ide> req.setEncoding('utf8'); <ide> <del> // Readable streams emit 'data' events once a listener is added <add> // Readable streams emit 'data' events once a listener is added. <ide> req.on('data', (chunk) => { <ide> body += chunk; <ide> }); <ide> <del> // The 'end' event indicates that the entire body has been received <add> // The 'end' event indicates that the entire body has been received. <ide> req.on('end', () => { <ide> try { <ide> const data = JSON.parse(body); <ide> function writeOneMillionTimes(writer, data, encoding, callback) { <ide> do { <ide> i--; <ide> if (i === 0) { <del> // last time! <add> // Last time! <ide> writer.write(data, encoding, callback); <ide> } else { <ide> // See if we should continue, or wait. <ide> function writeOneMillionTimes(writer, data, encoding, callback) { <ide> } <ide> } while (i > 0 && ok); <ide> if (i > 0) { <del> // had to stop early! <del> // write some more once it drains <add> // Had to stop early! <add> // Write some more once it drains. <ide> writer.once('drain', write); <ide> } <ide> } <ide> Calling the [`stream.write()`][stream-write] method after calling <ide> [`stream.end()`][stream-end] will raise an error. <ide> <ide> ```js <del>// Write 'hello, ' and then end with 'world!' <add>// Write 'hello, ' and then end with 'world!'. <ide> const fs = require('fs'); <ide> const file = fs.createWriteStream('example.txt'); <ide> file.write('hello, '); <ide> added: v11.4.0 <ide> <ide> Is `true` if it is safe to call [`writable.write()`][stream-write]. <ide> <add>##### writable.writableFinished <add><!-- YAML <add>added: v12.6.0 <add>--> <add> <add>* {boolean} <add> <add>Is `true` if after the [`'finish'`][] event has been emitted. <add> <ide> ##### writable.writableHighWaterMark <ide> <!-- YAML <ide> added: v9.3.0 <ide> This property contains the number of bytes (or objects) in the queue <ide> ready to be written. The value provides introspection data regarding <ide> the status of the `highWaterMark`. <ide> <del>##### writable.writableFinished <del><!-- YAML <del>added: v12.6.0 <del>--> <del> <del>* {boolean} <del> <del>Is `true` if all data has been flushed to the underlying system. After <del>the [`'finish'`][] event has been emitted. <del> <ide> ##### writable.writableObjectMode <ide> <!-- YAML <ide> added: v12.3.0 <ide> const writable = new Writable(); <ide> <ide> pass.pipe(writable); <ide> pass.unpipe(writable); <del>// readableFlowing is now false <add>// readableFlowing is now false. <ide> <ide> pass.on('data', (chunk) => { console.log(chunk.toString()); }); <del>pass.write('ok'); // Will not emit 'data' <del>pass.resume(); // Must be called to make stream emit 'data' <add>pass.write('ok'); // Will not emit 'data'. <add>pass.resume(); // Must be called to make stream emit 'data'. <ide> ``` <ide> <ide> While `readable.readableFlowing` is `false`, data may be accumulating <ide> cause some amount of data to be read into an internal buffer. <ide> ```javascript <ide> const readable = getReadableStreamSomehow(); <ide> readable.on('readable', function() { <del> // There is some data to read now <add> // There is some data to read now. <ide> let data; <ide> <ide> while (data = this.read()) { <ide> named `file.txt`: <ide> const fs = require('fs'); <ide> const readable = getReadableStreamSomehow(); <ide> const writable = fs.createWriteStream('file.txt'); <del>// All the data from readable goes into 'file.txt' <add>// All the data from readable goes into 'file.txt'. <ide> readable.pipe(writable); <ide> ``` <ide> It is possible to attach multiple `Writable` streams to a single `Readable` <ide> readable.on('readable', () => { <ide> <ide> The `while` loop is necessary when processing data with <ide> `readable.read()`. Only after `readable.read()` returns `null`, <del>[`'readable'`]() will be emitted. <add>[`'readable'`][] will be emitted. <ide> <ide> A `Readable` stream in object mode will always return a single item from <ide> a call to [`readable.read(size)`][stream-read], regardless of the value of the <ide> const fs = require('fs'); <ide> const readable = getReadableStreamSomehow(); <ide> const writable = fs.createWriteStream('file.txt'); <ide> // All the data from readable goes into 'file.txt', <del>// but only for the first second <add>// but only for the first second. <ide> readable.pipe(writable); <ide> setTimeout(() => { <ide> console.log('Stop writing to file.txt.'); <ide> use of a [`Transform`][] stream instead. See the [API for Stream Implementers][] <ide> section for more information. <ide> <ide> ```js <del>// Pull off a header delimited by \n\n <del>// use unshift() if we get too much <del>// Call the callback with (error, header, stream) <add>// Pull off a header delimited by \n\n. <add>// Use unshift() if we get too much. <add>// Call the callback with (error, header, stream). <ide> const { StringDecoder } = require('string_decoder'); <ide> function parseHeader(stream, callback) { <ide> stream.on('error', callback); <ide> function parseHeader(stream, callback) { <ide> while (null !== (chunk = stream.read())) { <ide> const str = decoder.write(chunk); <ide> if (str.match(/\n\n/)) { <del> // Found the header boundary <add> // Found the header boundary. <ide> const split = str.split(/\n\n/); <ide> header += split.shift(); <ide> const remaining = split.join('\n\n'); <ide> const buf = Buffer.from(remaining, 'utf8'); <ide> stream.removeListener('error', callback); <del> // Remove the 'readable' listener before unshifting <add> // Remove the 'readable' listener before unshifting. <ide> stream.removeListener('readable', onReadable); <ide> if (buf.length) <ide> stream.unshift(buf); <ide> const fs = require('fs'); <ide> async function print(readable) { <ide> readable.setEncoding('utf8'); <ide> let data = ''; <del> for await (const k of readable) { <del> data += k; <add> for await (const chunk of readable) { <add> data += chunk; <ide> } <ide> console.log(data); <ide> } <ide> <del>print(fs.createReadStream('file')).catch(console.log); <add>print(fs.createReadStream('file')).catch(console.error); <ide> ``` <ide> <ide> If the loop terminates with a `break` or a `throw`, the stream will be <ide> finished(rs, (err) => { <ide> } <ide> }); <ide> <del>rs.resume(); // drain the stream <add>rs.resume(); // Drain the stream. <ide> ``` <ide> <ide> Especially useful in error handling scenarios where a stream is destroyed <ide> async function run() { <ide> } <ide> <ide> run().catch(console.error); <del>rs.resume(); // drain the stream <add>rs.resume(); // Drain the stream. <ide> ``` <ide> <ide> ### stream.pipeline(...streams, callback) <ide> run().catch(console.error); <ide> * `options` {Object} Options provided to `new stream.Readable([options])`. <ide> By default, `Readable.from()` will set `options.objectMode` to `true`, unless <ide> this is explicitly opted out by setting `options.objectMode` to `false`. <add>* Returns: {stream.Readable} <ide> <ide> A utility method for creating Readable Streams out of iterators. <ide> <ide> on the type of stream being created, as detailed in the chart below: <ide> <ide> | Use-case | Class | Method(s) to implement | <ide> | -------- | ----- | ---------------------- | <del>| Reading only | [`Readable`] | <code>[_read][stream-_read]</code> | <del>| Writing only | [`Writable`] | <code>[_write][stream-_write]</code>, <code>[_writev][stream-_writev]</code>, <code>[_final][stream-_final]</code> | <del>| Reading and writing | [`Duplex`] | <code>[_read][stream-_read]</code>, <code>[_write][stream-_write]</code>, <code>[_writev][stream-_writev]</code>, <code>[_final][stream-_final]</code> | <del>| Operate on written data, then read the result | [`Transform`] | <code>[_transform][stream-_transform]</code>, <code>[_flush][stream-_flush]</code>, <code>[_final][stream-_final]</code> | <add>| Reading only | [`Readable`] | <code>[_read()][stream-_read]</code> | <add>| Writing only | [`Writable`] | <code>[_write()][stream-_write]</code>, <code>[_writev()][stream-_writev]</code>, <code>[_final()][stream-_final]</code> | <add>| Reading and writing | [`Duplex`] | <code>[_read()][stream-_read]</code>, <code>[_write()][stream-_write]</code>, <code>[_writev()][stream-_writev]</code>, <code>[_final()][stream-_final]</code> | <add>| Operate on written data, then read the result | [`Transform`] | <code>[_transform()][stream-_transform]</code>, <code>[_flush()][stream-_flush]</code>, <code>[_final()][stream-_final]</code> | <ide> <ide> The implementation code for a stream should *never* call the "public" methods <ide> of a stream that are intended for use by consumers (as described in the <ide> const { Writable } = require('stream'); <ide> <ide> class MyWritable extends Writable { <ide> constructor(options) { <del> // Calls the stream.Writable() constructor <add> // Calls the stream.Writable() constructor. <ide> super(options); <ide> // ... <ide> } <ide> changes: <ide> * `objectMode` {boolean} Whether this stream should behave <ide> as a stream of objects. Meaning that [`stream.read(n)`][stream-read] returns <ide> a single value instead of a `Buffer` of size `n`. **Default:** `false`. <add> * `emitClose` {boolean} Whether or not the stream should emit `'close'` <add> after it has been destroyed. **Default:** `true`. <ide> * `read` {Function} Implementation for the [`stream._read()`][stream-_read] <ide> method. <ide> * `destroy` {Function} Implementation for the <ide> const { Readable } = require('stream'); <ide> <ide> class MyReadable extends Readable { <ide> constructor(options) { <del> // Calls the stream.Readable(options) constructor <add> // Calls the stream.Readable(options) constructor. <ide> super(options); <ide> // ... <ide> } <ide> class SourceWrapper extends Readable { <ide> <ide> // Every time there's data, push it into the internal buffer. <ide> this._source.ondata = (chunk) => { <del> // If push() returns false, then stop reading from source <add> // If push() returns false, then stop reading from source. <ide> if (!this.push(chunk)) <ide> this._source.readStop(); <ide> }; <ide> <del> // When the source ends, push the EOF-signaling `null` chunk <add> // When the source ends, push the EOF-signaling `null` chunk. <ide> this._source.onend = () => { <ide> this.push(null); <ide> }; <ide> } <del> // _read will be called when the stream wants to pull more data in <del> // the advisory size argument is ignored in this case. <add> // _read() will be called when the stream wants to pull more data in. <add> // The advisory size argument is ignored in this case. <ide> _read(size) { <ide> this._source.readStart(); <ide> } <ide> const myReadable = new Readable({ <ide> process.nextTick(() => this.emit('error', err)); <ide> return; <ide> } <del> // do some work <add> // Do some work. <ide> } <ide> }); <ide> ``` <ide> class MyDuplex extends Duplex { <ide> } <ide> <ide> _write(chunk, encoding, callback) { <del> // The underlying source only deals with strings <add> // The underlying source only deals with strings. <ide> if (Buffer.isBuffer(chunk)) <ide> chunk = chunk.toString(); <ide> this[kSource].writeSomeData(chunk); <ide> the `Readable` side. <ide> ```js <ide> const { Transform } = require('stream'); <ide> <del>// All Transform streams are also Duplex Streams <add>// All Transform streams are also Duplex Streams. <ide> const myTransform = new Transform({ <ide> writableObjectMode: true, <ide> <ide> transform(chunk, encoding, callback) { <del> // Coerce the chunk to a number if necessary <add> // Coerce the chunk to a number if necessary. <ide> chunk |= 0; <ide> <ide> // Transform the chunk into something else. <ide> user programs. <ide> [`stream.write()`][stream-write]. <ide> * `encoding` {string} If the chunk is a string, then this is the <ide> encoding type. If chunk is a buffer, then this is the special <del> value - 'buffer', ignore it in this case. <add> value - `'buffer'`, ignore it in this case. <ide> * `callback` {Function} A callback function (optionally with an error <ide> argument and data) to be called after the supplied `chunk` has been <ide> processed. <ide> const writeable = fs.createWriteStream('./file'); <ide> <ide> (async function() { <ide> for await (const chunk of iterator) { <del> // Handle backpressure on write <add> // Handle backpressure on write(). <ide> if (!writeable.write(chunk)) <ide> await once(writeable, 'drain'); <ide> } <ide> writeable.end(); <del> // Ensure completion without errors <add> // Ensure completion without errors. <ide> await once(writeable, 'finish'); <ide> })(); <ide> ``` <ide> const writeable = fs.createWriteStream('./file'); <ide> (async function() { <ide> const readable = Readable.from(iterator); <ide> readable.pipe(writeable); <del> // Ensure completion without errors <add> // Ensure completion without errors. <ide> await once(writeable, 'finish'); <ide> })(); <ide> ``` <ide> For example, consider the following code: <ide> // WARNING! BROKEN! <ide> net.createServer((socket) => { <ide> <del> // We add an 'end' listener, but never consume the data <add> // We add an 'end' listener, but never consume the data. <ide> socket.on('end', () => { <ide> // It will never get here. <ide> socket.end('The message was received but was not processed.\n'); <ide> The workaround in this situation is to call the <ide> [`stream.resume()`][stream-resume] method to begin the flow of data: <ide> <ide> ```js <del>// Workaround <add>// Workaround. <ide> net.createServer((socket) => { <ide> socket.on('end', () => { <ide> socket.end('The message was received but was not processed.\n');
1
Python
Python
add view (mvc speeking) for the plugins. cpu ok
c813802968290a3e4919dd72c4ade7e31616c4a5
<ide><path>glances/plugins/glances_cpu.py <ide> def update(self): <ide> # Update the history list <ide> self.update_stats_history() <ide> <add> # Update the view <add> self.update_views() <add> <ide> return self.stats <ide> <add> def update_views(self): <add> """Update stats views""" <add> # Call the father's method <add> GlancesPlugin.update_views(self) <add> <add> # Add specifics informations <add> # Alert and log <add> for key in ['user', 'system', 'iowait']: <add> if key in self.stats: <add> self.views[key]['decoration'] = self.get_alert_log(self.stats[key], header=key) <add> self.views['total']['decoration'] = self.get_alert_log(self.stats['total'], header="system") <add> # Alert only <add> for key in ['steal']: <add> if key in self.stats: <add> self.views[key]['decoration'] = self.get_alert(self.stats[key], header=key) <add> # Optional <add> for key in ['nice', 'irq', 'iowait', 'steal']: <add> if key in self.stats: <add> self.views[key]['optional'] = True <add> <ide> def msg_curse(self, args=None): <ide> """Return the list to display in the UI""" <ide> # Init the return message <ide> def msg_curse(self, args=None): <ide> msg = '{0:>5}%'.format(self.stats['total']) <ide> if idle_tag: <ide> ret.append(self.curse_add_line( <del> msg, self.get_alert_log(self.stats['total'], header="system"))) <add> msg, self.get_views(key='total', option='decoration'))) <ide> else: <ide> ret.append(self.curse_add_line(msg)) <ide> # Nice CPU <ide> if 'nice' in self.stats: <ide> msg = ' {0:8}'.format(_("nice:")) <del> ret.append(self.curse_add_line(msg, optional=True)) <add> ret.append(self.curse_add_line(msg, optional=self.get_views(key='nice', option='optional'))) <ide> msg = '{0:>5}%'.format(self.stats['nice']) <del> ret.append(self.curse_add_line(msg, optional=True)) <add> ret.append(self.curse_add_line(msg, optional=self.get_views(key='nice', option='optional'))) <ide> # New line <ide> ret.append(self.curse_new_line()) <ide> # User CPU <ide> def msg_curse(self, args=None): <ide> ret.append(self.curse_add_line(msg)) <ide> msg = '{0:>5}%'.format(self.stats['user']) <ide> ret.append(self.curse_add_line( <del> msg, self.get_alert_log(self.stats['user'], header="user"))) <add> msg, self.get_views(key='user', option='decoration'))) <ide> elif 'idle' in self.stats: <ide> msg = '{0:8}'.format(_("idle:")) <ide> ret.append(self.curse_add_line(msg)) <ide> def msg_curse(self, args=None): <ide> # IRQ CPU <ide> if 'irq' in self.stats: <ide> msg = ' {0:8}'.format(_("irq:")) <del> ret.append(self.curse_add_line(msg, optional=True)) <add> ret.append(self.curse_add_line(msg, optional=self.get_views(key='irq', option='optional'))) <ide> msg = '{0:>5}%'.format(self.stats['irq']) <del> ret.append(self.curse_add_line(msg, optional=True)) <add> ret.append(self.curse_add_line(msg, optional=self.get_views(key='irq', option='optional'))) <ide> # New line <ide> ret.append(self.curse_new_line()) <ide> # System CPU <ide> def msg_curse(self, args=None): <ide> ret.append(self.curse_add_line(msg)) <ide> msg = '{0:>5}%'.format(self.stats['system']) <ide> ret.append(self.curse_add_line( <del> msg, self.get_alert_log(self.stats['system'], header="system"))) <add> msg, self.get_views(key='system', option='decoration'))) <ide> else: <ide> msg = '{0:8}'.format(_("core:")) <ide> ret.append(self.curse_add_line(msg)) <ide> def msg_curse(self, args=None): <ide> # IOWait CPU <ide> if 'iowait' in self.stats: <ide> msg = ' {0:8}'.format(_("iowait:")) <del> ret.append(self.curse_add_line(msg, optional=True)) <add> ret.append(self.curse_add_line(msg, optional=self.get_views(key='iowait', option='optional'))) <ide> msg = '{0:>5}%'.format(self.stats['iowait']) <ide> ret.append(self.curse_add_line( <del> msg, self.get_alert_log(self.stats['iowait'], header="iowait"), optional=True)) <add> msg, self.get_views(key='iowait', option='decoration'), <add> optional=self.get_views(key='iowait', option='optional'))) <ide> # New line <ide> ret.append(self.curse_new_line()) <ide> # Idle CPU <ide> def msg_curse(self, args=None): <ide> # Steal CPU usage <ide> if 'steal' in self.stats: <ide> msg = ' {0:8}'.format(_("steal:")) <del> ret.append(self.curse_add_line(msg, optional=True)) <add> ret.append(self.curse_add_line(msg, optional=self.get_views(key='steal', option='optional'))) <ide> msg = '{0:>5}%'.format(self.stats['steal']) <ide> ret.append(self.curse_add_line( <del> msg, self.get_alert(self.stats['steal'], header="steal"), optional=True)) <add> msg, self.get_views(key='steal', option='decoration'), <add> optional=self.get_views(key='steal', option='optional'))) <ide> <ide> # Return the message with decoration <ide> return ret <ide><path>glances/plugins/glances_plugin.py <ide> def __init__(self, args=None, items_history_list=None): <ide> self.actions = GlancesActions() <ide> <ide> # Init the views <del> self.views = None <add> self.views = dict() <ide> <ide> def __repr__(self): <ide> """Return the raw stats.""" <ide> def get_stats_value(self, item, value): <ide> logger.error("Cannot get item({0})=value({1}) ({2})".format(item, value, e)) <ide> return None <ide> <del> def set_views(self, input_viewss): <add> def update_views(self): <add> """Default builder fo the stats views <add> The V of MVC <add> A dict of dict with the needed information to display the stats. <add> Example for the stat xxx: <add> 'xxx': {'decoration': 'DEFAULT', <add> 'optional': False, <add> 'additional': False, <add> 'splittable': False} <add> """ <add> ret = {} <add> for key in self.get_raw().keys(): <add> value = {'decoration': 'DEFAULT', <add> 'optional': False, <add> 'additional': False, <add> 'splittable': False} <add> ret[key] = value <add> self.views = ret <add> return self.views <add> <add> def set_views(self, input_views): <ide> """Set the views to input_views.""" <ide> self.views = input_views <ide> return self.views <ide> <del> def get_views(self): <add> def get_views(self, key=None, option=None): <ide> """Return the views object. <del> A dict of dict with the information to display the stats (The V of MVC) <del> By default return all the key/val: 'xxx': self.get_alert(self.stats['xxx'], header="xxx") <del> """ <del> for key in self.get_raw().keys(): <del> logger.info(">>> key: %s" % key) <del> return self.views <add> If key is None, return all the view for the current plugin <add> else if option is None return the view for the specific key (all option) <add> else return the view fo the specific key/option""" <add> if key is None: <add> return self.views <add> else: <add> if option is None: <add> return self.views[key] <add> else: <add> return self.views[key][option] <ide> <ide> def load_limits(self, config): <ide> """Load the limits from the configuration file."""
2
Go
Go
adjust ipam errors
dc4285b9a4e2dcf79ed83c18d6c523c93fb5e782
<ide><path>libnetwork/bitseq/sequence.go <ide> const ( <ide> ) <ide> <ide> var ( <del> errNoBitAvailable = fmt.Errorf("no bit available") <add> // ErrNoBitAvailable is returned when no more bits are available to set <add> ErrNoBitAvailable = fmt.Errorf("no bit available") <add> // ErrBitAllocated is returned when the specific bit requested is already set <add> ErrBitAllocated = fmt.Errorf("requested bit is already allocated") <ide> ) <ide> <ide> // Handle contains the sequece representing the bitmask and its identifier <ide> func (s *sequence) toString() string { <ide> // GetAvailableBit returns the position of the first unset bit in the bitmask represented by this sequence <ide> func (s *sequence) getAvailableBit(from uint64) (uint64, uint64, error) { <ide> if s.block == blockMAX || s.count == 0 { <del> return invalidPos, invalidPos, errNoBitAvailable <add> return invalidPos, invalidPos, ErrNoBitAvailable <ide> } <ide> bits := from <ide> bitSel := blockFirstBit >> from <ide> func (h *Handle) SetAnyInRange(start, end uint64) (uint64, error) { <ide> return invalidPos, fmt.Errorf("invalid bit range [%d, %d]", start, end) <ide> } <ide> if h.Unselected() == 0 { <del> return invalidPos, errNoBitAvailable <add> return invalidPos, ErrNoBitAvailable <ide> } <ide> return h.set(0, start, end, true, false) <ide> } <ide> <ide> // SetAny atomically sets the first unset bit in the sequence and returns the corresponding ordinal <ide> func (h *Handle) SetAny() (uint64, error) { <ide> if h.Unselected() == 0 { <del> return invalidPos, errNoBitAvailable <add> return invalidPos, ErrNoBitAvailable <ide> } <ide> return h.set(0, 0, h.bits-1, true, false) <ide> } <ide> func (h *Handle) set(ordinal, start, end uint64, any bool, release bool) (uint64 <ide> bytePos, bitPos, err = getFirstAvailable(h.head, start) <ide> ret = posToOrdinal(bytePos, bitPos) <ide> if end < ret { <del> err = errNoBitAvailable <add> err = ErrNoBitAvailable <ide> } <ide> } else { <ide> bytePos, bitPos, err = checkIfAvailable(h.head, ordinal) <ide> func getFirstAvailable(head *sequence, start uint64) (uint64, uint64, error) { <ide> byteOffset += current.count * blockBytes <ide> current = current.next <ide> } <del> return invalidPos, invalidPos, errNoBitAvailable <add> return invalidPos, invalidPos, ErrNoBitAvailable <ide> } <ide> <ide> // checkIfAvailable checks if the bit correspondent to the specified ordinal is unset <ide> func checkIfAvailable(head *sequence, ordinal uint64) (uint64, uint64, error) { <ide> } <ide> } <ide> <del> return invalidPos, invalidPos, fmt.Errorf("requested bit is not available") <add> return invalidPos, invalidPos, ErrBitAllocated <ide> } <ide> <ide> // Given the byte position and the sequences list head, return the pointer to the <ide><path>libnetwork/bitseq/sequence_test.go <ide> func TestSetInRange(t *testing.T) { <ide> if err == nil { <ide> t.Fatalf("Expected failure. Got success with ordinal:%d", o) <ide> } <del> if err != errNoBitAvailable { <add> if err != ErrNoBitAvailable { <ide> t.Fatalf("Unexpected error: %v", err) <ide> } <ide> <ide> func TestSetInRange(t *testing.T) { <ide> if err == nil { <ide> t.Fatalf("Expected failure. Got success with ordinal:%d", o) <ide> } <del> if err != errNoBitAvailable { <add> if err != ErrNoBitAvailable { <ide> t.Fatalf("Unexpected error: %v", err) <ide> } <ide> <ide> func TestSetInRange(t *testing.T) { <ide> if err == nil { <ide> t.Fatalf("Expected failure. Got success with ordinal:%d", o) <ide> } <del> if err != errNoBitAvailable { <add> if err != ErrNoBitAvailable { <ide> t.Fatalf("Unexpected error: %v", err) <ide> } <ide> } <ide><path>libnetwork/controller.go <ide> func (c *controller) RegisterIpamDriver(name string, driver ipamapi.Ipam) error <ide> _, ok := c.ipamDrivers[name] <ide> c.Unlock() <ide> if ok { <del> return driverapi.ErrActiveRegistration(name) <add> return types.ForbiddenErrorf("ipam driver %q already registered", name) <ide> } <ide> locAS, glbAS, err := driver.GetDefaultAddressSpaces() <ide> if err != nil { <del> return fmt.Errorf("ipam driver %s failed to return default address spaces: %v", name, err) <add> return types.InternalErrorf("ipam driver %q failed to return default address spaces: %v", name, err) <ide> } <ide> c.Lock() <ide> c.ipamDrivers[name] = &ipamData{driver: driver, defaultLocalAddressSpace: locAS, defaultGlobalAddressSpace: glbAS} <ide> c.Unlock() <ide> <del> log.Debugf("Registering ipam provider: %s", name) <add> log.Debugf("Registering ipam driver: %q", name) <ide> <ide> return nil <ide> } <ide> func (c *controller) loadIpamDriver(name string) (*ipamData, error) { <ide> id, ok := c.ipamDrivers[name] <ide> c.Unlock() <ide> if !ok { <del> return nil, ErrInvalidNetworkDriver(name) <add> return nil, types.BadRequestErrorf("invalid ipam driver: %q", name) <ide> } <ide> return id, nil <ide> } <ide><path>libnetwork/ipam/allocator.go <ide> func NewAllocator(lcDs, glDs datastore.DataStore) (*Allocator, error) { <ide> func (a *Allocator) refresh(as string) error { <ide> aSpace, err := a.getAddressSpaceFromStore(as) <ide> if err != nil { <del> return fmt.Errorf("error getting pools config from store during init: %v", <del> err) <add> return types.InternalErrorf("error getting pools config from store: %v", err) <ide> } <ide> <ide> if aSpace == nil { <ide> func (a *Allocator) insertBitMask(key SubnetKey, pool *net.IPNet) error { <ide> <ide> store := a.getStore(key.AddressSpace) <ide> if store == nil { <del> return fmt.Errorf("could not find store for address space %s while inserting bit mask", key.AddressSpace) <add> return types.InternalErrorf("could not find store for address space %s while inserting bit mask", key.AddressSpace) <ide> } <ide> <ide> ipVer := getAddressVersion(pool.IP) <ide> func (a *Allocator) retrieveBitmask(k SubnetKey, n *net.IPNet) (*bitseq.Handle, <ide> if !ok { <ide> log.Debugf("Retrieving bitmask (%s, %s)", k.String(), n.String()) <ide> if err := a.insertBitMask(k, n); err != nil { <del> return nil, fmt.Errorf("could not find bitmask in datastore for %s", k.String()) <add> return nil, types.InternalErrorf("could not find bitmask in datastore for %s", k.String()) <ide> } <ide> a.Lock() <ide> bm = a.addresses[k] <ide> func (a *Allocator) getPredefinedPool(as string, ipV6 bool) (*net.IPNet, error) <ide> } <ide> <ide> if as != localAddressSpace && as != globalAddressSpace { <del> return nil, fmt.Errorf("no default pool available for non-default address spaces") <add> return nil, types.NotImplementedErrorf("no default pool availbale for non-default addresss spaces") <ide> } <ide> <ide> aSpace, err := a.getAddrSpace(as) <ide> func (a *Allocator) RequestAddress(poolID string, prefAddress net.IP, opts map[s <ide> <ide> bm, err := a.retrieveBitmask(k, c.Pool) <ide> if err != nil { <del> return nil, nil, fmt.Errorf("could not find bitmask in datastore for %s on address %v request from pool %s: %v", <add> return nil, nil, types.InternalErrorf("could not find bitmask in datastore for %s on address %v request from pool %s: %v", <ide> k.String(), prefAddress, poolID, err) <ide> } <ide> ip, err := a.getAddress(p.Pool, bm, prefAddress, p.Range) <ide> func (a *Allocator) ReleaseAddress(poolID string, address net.IP) error { <ide> p, ok := aSpace.subnets[k] <ide> if !ok { <ide> aSpace.Unlock() <del> return ipamapi.ErrBadPool <add> return types.NotFoundErrorf("cannot find address pool for poolID:%s", poolID) <ide> } <ide> <ide> if address == nil { <ide> aSpace.Unlock() <del> return ipamapi.ErrInvalidRequest <add> return types.BadRequestErrorf("invalid address: nil") <ide> } <ide> <ide> if !p.Pool.Contains(address) { <ide> func (a *Allocator) ReleaseAddress(poolID string, address net.IP) error { <ide> <ide> h, err := types.GetHostPartIP(address, mask) <ide> if err != nil { <del> return fmt.Errorf("failed to release address %s: %v", address.String(), err) <add> return types.InternalErrorf("failed to release address %s: %v", address.String(), err) <ide> } <ide> <ide> bm, err := a.retrieveBitmask(k, c.Pool) <ide> if err != nil { <del> return fmt.Errorf("could not find bitmask in datastore for %s on address %v release from pool %s: %v", <add> return types.InternalErrorf("could not find bitmask in datastore for %s on address %v release from pool %s: %v", <ide> k.String(), address, poolID, err) <ide> } <ide> <ide> func (a *Allocator) getAddress(nw *net.IPNet, bitmask *bitseq.Handle, prefAddres <ide> } else if prefAddress != nil { <ide> hostPart, e := types.GetHostPartIP(prefAddress, base.Mask) <ide> if e != nil { <del> return nil, fmt.Errorf("failed to allocate preferred address %s: %v", prefAddress.String(), e) <add> return nil, types.InternalErrorf("failed to allocate preferred address %s: %v", prefAddress.String(), e) <ide> } <ide> ordinal = ipToUint64(types.GetMinimalIP(hostPart)) <ide> err = bitmask.Set(ordinal) <ide> } else { <ide> ordinal, err = bitmask.SetAnyInRange(ipr.Start, ipr.End) <ide> } <del> if err != nil { <add> <add> switch err { <add> case nil: <add> // Convert IP ordinal for this subnet into IP address <add> return generateAddress(ordinal, base), nil <add> case bitseq.ErrBitAllocated: <add> return nil, ipamapi.ErrIPAlreadyAllocated <add> case bitseq.ErrNoBitAvailable: <ide> return nil, ipamapi.ErrNoAvailableIPs <add> default: <add> return nil, err <ide> } <del> <del> // Convert IP ordinal for this subnet into IP address <del> return generateAddress(ordinal, base), nil <ide> } <ide> <ide> // DumpDatabase dumps the internal info <ide><path>libnetwork/ipam/store.go <ide> package ipam <ide> <ide> import ( <ide> "encoding/json" <del> "fmt" <ide> <ide> log "github.com/Sirupsen/logrus" <ide> "github.com/docker/libnetwork/datastore" <ide> func (a *Allocator) getStore(as string) datastore.DataStore { <ide> func (a *Allocator) getAddressSpaceFromStore(as string) (*addrSpace, error) { <ide> store := a.getStore(as) <ide> if store == nil { <del> return nil, fmt.Errorf("store for address space %s not found", as) <add> return nil, types.InternalErrorf("store for address space %s not found", as) <ide> } <ide> <ide> pc := &addrSpace{id: dsConfigKey + "/" + as, ds: store, alloc: a} <ide> func (a *Allocator) getAddressSpaceFromStore(as string) (*addrSpace, error) { <ide> return nil, nil <ide> } <ide> <del> return nil, fmt.Errorf("could not get pools config from store: %v", err) <add> return nil, types.InternalErrorf("could not get pools config from store: %v", err) <ide> } <ide> <ide> return pc, nil <ide> func (a *Allocator) getAddressSpaceFromStore(as string) (*addrSpace, error) { <ide> func (a *Allocator) writeToStore(aSpace *addrSpace) error { <ide> store := aSpace.store() <ide> if store == nil { <del> return fmt.Errorf("invalid store while trying to write %s address space", aSpace.DataScope()) <add> return types.InternalErrorf("invalid store while trying to write %s address space", aSpace.DataScope()) <ide> } <ide> <ide> err := store.PutObjectAtomic(aSpace) <ide> func (a *Allocator) writeToStore(aSpace *addrSpace) error { <ide> func (a *Allocator) deleteFromStore(aSpace *addrSpace) error { <ide> store := aSpace.store() <ide> if store == nil { <del> return fmt.Errorf("invalid store while trying to delete %s address space", aSpace.DataScope()) <add> return types.InternalErrorf("invalid store while trying to delete %s address space", aSpace.DataScope()) <ide> } <ide> <ide> return store.DeleteObjectAtomic(aSpace) <ide><path>libnetwork/ipam/structures.go <ide> func (s *SubnetKey) String() string { <ide> // FromString populate the SubnetKey object reading it from string <ide> func (s *SubnetKey) FromString(str string) error { <ide> if str == "" || !strings.Contains(str, "/") { <del> return fmt.Errorf("invalid string form for subnetkey: %s", str) <add> return types.BadRequestErrorf("invalid string form for subnetkey: %s", str) <ide> } <ide> <ide> p := strings.Split(str, "/") <ide> if len(p) != 3 && len(p) != 5 { <del> return fmt.Errorf("invalid string form for subnetkey: %s", str) <add> return types.BadRequestErrorf("invalid string form for subnetkey: %s", str) <ide> } <ide> s.AddressSpace = p[0] <ide> s.Subnet = fmt.Sprintf("%s/%s", p[1], p[2]) <ide> func (aSpace *addrSpace) updatePoolDBOnRemoval(k SubnetKey) (func() error, error <ide> return func() error { <ide> bm, err := aSpace.alloc.retrieveBitmask(k, c.Pool) <ide> if err != nil { <del> return fmt.Errorf("could not find bitmask in datastore for pool %s removal: %v", k.String(), err) <add> return types.InternalErrorf("could not find bitmask in datastore for pool %s removal: %v", k.String(), err) <ide> } <ide> return bm.Destroy() <ide> }, nil <ide><path>libnetwork/ipamapi/contract.go <ide> package ipamapi <ide> <ide> import ( <del> "errors" <ide> "net" <add> <add> "github.com/docker/libnetwork/types" <ide> ) <ide> <ide> /******************** <ide> type Callback interface { <ide> <ide> // Weel-known errors returned by IPAM <ide> var ( <del> ErrInvalidIpamService = errors.New("Invalid IPAM Service") <del> ErrInvalidIpamConfigService = errors.New("Invalid IPAM Config Service") <del> ErrIpamNotAvailable = errors.New("IPAM Service not available") <del> ErrIpamInternalError = errors.New("IPAM Internal Error") <del> ErrInvalidAddressSpace = errors.New("Invalid Address Space") <del> ErrInvalidPool = errors.New("Invalid Address Pool") <del> ErrInvalidSubPool = errors.New("Invalid Address SubPool") <del> ErrInvalidRequest = errors.New("Invalid Request") <del> ErrPoolNotFound = errors.New("Address Pool not found") <del> ErrOverlapPool = errors.New("Address pool overlaps with existing pool on this address space") <del> ErrNoAvailablePool = errors.New("No available pool") <del> ErrNoAvailableIPs = errors.New("No available addresses on this pool") <del> ErrIPAlreadyAllocated = errors.New("Address already in use") <del> ErrIPOutOfRange = errors.New("Requested address is out of range") <del> ErrPoolOverlap = errors.New("Pool overlaps with other one on this address space") <del> ErrBadPool = errors.New("Address space does not contain specified address pool") <add> ErrIpamInternalError = types.InternalErrorf("IPAM Internal Error") <add> ErrInvalidAddressSpace = types.BadRequestErrorf("Invalid Address Space") <add> ErrInvalidPool = types.BadRequestErrorf("Invalid Address Pool") <add> ErrInvalidSubPool = types.BadRequestErrorf("Invalid Address SubPool") <add> ErrInvalidRequest = types.BadRequestErrorf("Invalid Request") <add> ErrPoolNotFound = types.BadRequestErrorf("Address Pool not found") <add> ErrOverlapPool = types.ForbiddenErrorf("Address pool overlaps with existing pool on this address space") <add> ErrNoAvailablePool = types.NoServiceErrorf("No available pool") <add> ErrNoAvailableIPs = types.NoServiceErrorf("No available addresses on this pool") <add> ErrIPAlreadyAllocated = types.ForbiddenErrorf("Address already in use") <add> ErrIPOutOfRange = types.BadRequestErrorf("Requested address is out of range") <add> ErrPoolOverlap = types.ForbiddenErrorf("Pool overlaps with other one on this address space") <add> ErrBadPool = types.BadRequestErrorf("Address space does not contain specified address pool") <ide> ) <ide> <ide> /*******************************
7
Javascript
Javascript
avoid unnecessary multiitemcache
349a5e395e083763c7245782d82cfdfb0cff160a
<ide><path>lib/CacheFacade.js <ide> class MultiItemCache { <ide> */ <ide> constructor(items) { <ide> this._items = items; <add> if (items.length === 1) return /** @type {any} */ (items[0]); <ide> } <ide> <ide> /**
1
Python
Python
fix quotation marks
ec359c37ba8f542fae97ff4e51a6d23876dcf185
<ide><path>numpy/testing/_private/utils.py <ide> def assert_string_equal(actual, desired): <ide> raise AssertionError(repr(d1)) <ide> if not diff_list: <ide> return <del> msg = f'Differences in strings:\n{''.join(diff_list).rstrip()}' <add> msg = f"Differences in strings:\n{''.join(diff_list).rstrip()}" <ide> if actual != desired: <ide> raise AssertionError(msg) <ide>
1
Ruby
Ruby
fix unreachable code
5c2dd5779458b056ce3fb4ed4fc207ef1bb695b5
<ide><path>Library/Homebrew/cask/audit.rb <ide> def check_signing <ide> next if result.success? <ide> <ide> # Only fail if signature is wrong, not when no signature is present at all. <del> next result.stderr.include?("not signed at all") <add> next if result.stderr.include?("not signed at all") <ide> <ide> add_warning "Signature verification failed: #{result.merged_output}" <ide> end
1
Mixed
Javascript
update deprecation codes
a12a2d892fadf8d8f6c5482056b937c9e1f89df4
<ide><path>doc/api/deprecations.md <ide> Type: Documentation-only <ide> <ide> Use [`request.destroy()`][] instead of [`request.abort()`][]. <ide> <del><a id="DEP0XXX"></a> <del>### DEP0XXX: `repl.inputStream` and `repl.outputStream` <add><a id="DEP0141"></a> <add>### DEP0141: `repl.inputStream` and `repl.outputStream` <ide> <!-- YAML <ide> changes: <ide> - version: REPLACEME <ide> Type: Documentation-only (supports [`--pending-deprecation`][]) <ide> The `repl` module exported the input and output stream twice. Use `.input` <ide> instead of `.inputStream` and `.output` instead of `.outputStream`. <ide> <del><a id="DEP0XX1"></a> <del>### DEP0XX1: `repl._builtinLibs` <add><a id="DEP0142"></a> <add>### DEP0142: `repl._builtinLibs` <ide> <!-- YAML <ide> changes: <ide> - version: REPLACEME <ide><path>lib/repl.js <ide> function REPLServer(prompt, <ide> deprecate(() => this.input, <ide> 'repl.inputStream and repl.outputStream is deprecated. ' + <ide> 'Use repl.input and repl.output instead', <del> 'DEP0XXX') : <add> 'DEP0141') : <ide> () => this.input, <ide> set: pendingDeprecation ? <ide> deprecate((val) => this.input = val, <ide> 'repl.inputStream and repl.outputStream is deprecated. ' + <ide> 'Use repl.input and repl.output instead', <del> 'DEP0XXX') : <add> 'DEP0141') : <ide> (val) => this.input = val, <ide> enumerable: false, <ide> configurable: true <ide> function REPLServer(prompt, <ide> deprecate(() => this.output, <ide> 'repl.inputStream and repl.outputStream is deprecated. ' + <ide> 'Use repl.input and repl.output instead', <del> 'DEP0XXX') : <add> 'DEP0141') : <ide> () => this.output, <ide> set: pendingDeprecation ? <ide> deprecate((val) => this.output = val, <ide> 'repl.inputStream and repl.outputStream is deprecated. ' + <ide> 'Use repl.input and repl.output instead', <del> 'DEP0XXX') : <add> 'DEP0141') : <ide> (val) => this.output = val, <ide> enumerable: false, <ide> configurable: true <ide> ObjectDefineProperty(module.exports, '_builtinLibs', { <ide> get: pendingDeprecation ? deprecate( <ide> () => _builtinLibs, <ide> 'repl._builtinLibs is deprecated. Check module.builtinModules instead', <del> 'DEP0XX1' <add> 'DEP0142' <ide> ) : () => _builtinLibs, <ide> set: pendingDeprecation ? deprecate( <ide> (val) => _builtinLibs = val, <ide> 'repl._builtinLibs is deprecated. Check module.builtinModules instead', <del> 'DEP0XX1' <add> 'DEP0142' <ide> ) : (val) => _builtinLibs = val, <ide> enumerable: false, <ide> configurable: true <ide><path>test/parallel/test-repl-options.js <ide> repl._builtinLibs; <ide> <ide> common.expectWarning({ <ide> DeprecationWarning: { <del> DEP0XX1: <add> DEP0142: <ide> 'repl._builtinLibs is deprecated. Check module.builtinModules instead', <del> DEP0XXX: 'repl.inputStream and repl.outputStream is deprecated. ' + <add> DEP0141: 'repl.inputStream and repl.outputStream is deprecated. ' + <ide> 'Use repl.input and repl.output instead', <ide> DEP0124: 'REPLServer.rli is deprecated', <ide> }
3
Javascript
Javascript
prevent error thrown when removing event target
2f0bb69708e224fb7b6eb90766578841112a22d2
<ide><path>src/browser/ReactEventTopLevelCallback.js <ide> function findParent(node) { <ide> return parent; <ide> } <ide> <add>// Used to store ancestor hierarchy in top level callback <add>var topLevelCallbackReusableArray = []; <add> <ide> /** <ide> * Top-level callback creator used to implement event handling using delegation. <ide> * This is used via dependency injection. <ide> var ReactEventTopLevelCallback = { <ide> getEventTarget(nativeEvent) <ide> ) || window; <ide> <add> var ancestors = topLevelCallbackReusableArray; <add> ancestors.length = 0; <add> <ide> // Loop through the hierarchy, in case there's any nested components. <del> while (topLevelTarget) { <add> // It's important that we build the array of ancestors before calling any <add> // event handlers, because event handlers can modify the DOM, leading to <add> // inconsistencies with ReactMount's node cache. See #1105. <add> var ancestor = topLevelTarget; <add> while (ancestor) { <add> ancestors.push(ancestor); <add> ancestor = findParent(ancestor); <add> } <add> <add> for (var i = 0, l = ancestors.length; i < l; i++) { <add> topLevelTarget = ancestors[i]; <ide> var topLevelTargetID = ReactMount.getID(topLevelTarget) || ''; <ide> ReactEventEmitter.handleTopLevel( <ide> topLevelType, <ide> topLevelTarget, <ide> topLevelTargetID, <ide> nativeEvent <ide> ); <del> <del> topLevelTarget = findParent(topLevelTarget); <ide> } <add> <add> // Emptying ancestors/topLevelCallbackReusableArray is <add> // not necessary for correctness, but it helps the GC reclaim <add> // any nodes that were left at the end of the search. <add> ancestors.length = 0; <ide> }; <ide> } <ide> <ide><path>src/browser/__tests__/ReactEventTopLevelCallback-test.js <ide> describe('ReactEventTopLevelCallback', function() { <ide> expect(calls[2][EVENT_TARGET_PARAM]) <ide> .toBe(grandParentControl.getDOMNode()); <ide> }); <add> <add> it('should not get confused by disappearing elements', function() { <add> var childContainer = document.createElement('div'); <add> var childControl = <div>Child</div>; <add> var parentContainer = document.createElement('div'); <add> var parentControl = <div>Parent</div>; <add> ReactMount.renderComponent(childControl, childContainer); <add> ReactMount.renderComponent(parentControl, parentContainer); <add> parentControl.getDOMNode().appendChild(childContainer); <add> <add> // ReactEventEmitter.handleTopLevel might remove the target from the DOM. <add> // Here, we have handleTopLevel remove the node when the first event <add> // handlers are called; we'll still expect to receive a second call for <add> // the parent control. <add> var childNode = childControl.getDOMNode(); <add> ReactEventEmitter.handleTopLevel.mockImplementation( <add> function(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { <add> if (topLevelTarget === childNode) { <add> ReactMount.unmountComponentAtNode(childContainer); <add> } <add> } <add> ); <add> <add> var callback = ReactEventTopLevelCallback.createTopLevelCallback('test'); <add> callback({ <add> target: childNode <add> }); <add> <add> var calls = ReactEventEmitter.handleTopLevel.mock.calls; <add> expect(calls.length).toBe(2); <add> expect(calls[0][EVENT_TARGET_PARAM]).toBe(childNode); <add> expect(calls[1][EVENT_TARGET_PARAM]).toBe(parentControl.getDOMNode()); <add> }); <ide> }); <ide> <ide> it('should not fire duplicate events for a React DOM tree', function() {
2
Ruby
Ruby
escape `.`s in hostnames in regexps
63742cd4804b0004fa537b760c96667885de54d2
<ide><path>Library/Homebrew/dev-cmd/bump-formula-pr.rb <ide> def determine_formula_from_url(url) <ide> <ide> def determine_mirror(url) <ide> case url <del> when %r{.*ftp.gnu.org/gnu.*} <add> when %r{.*ftp\.gnu\.org/gnu.*} <ide> url.sub "ftp.gnu.org/gnu", "ftpmirror.gnu.org" <del> when %r{.*download.savannah.gnu.org/*} <add> when %r{.*download\.savannah\.gnu\.org/*} <ide> url.sub "download.savannah.gnu.org", "download-mirror.savannah.gnu.org" <del> when %r{.*www.apache.org/dyn/closer.lua\?path=.*} <add> when %r{.*www\.apache\.org/dyn/closer\.lua\?path=.*} <ide> url.sub "www.apache.org/dyn/closer.lua?path=", "archive.apache.org/dist/" <del> when %r{.*mirrors.ocf.berkeley.edu/debian.*} <add> when %r{.*mirrors\.ocf\.berkeley\.edu/debian.*} <ide> url.sub "mirrors.ocf.berkeley.edu/debian", "mirrorservice.org/sites/ftp.debian.org/debian" <ide> end <ide> end
1
Ruby
Ruby
drop an unused hash; change slang to special
6893c23f48d2707714240a1ae2a410a0661aa3a5
<ide><path>actionmailer/test/mailers/base_mailer.rb <ide> def email_with_translations <ide> def without_mail_call <ide> end <ide> <del> def with_nil_as_return_value(hash = {}) <add> def with_nil_as_return_value <ide> mail(:template_name => "welcome") <ide> nil <ide> end <ide><path>actionpack/lib/action_dispatch/http/cache.rb <ide> def etag=(etag) <ide> LAST_MODIFIED = "Last-Modified".freeze <ide> ETAG = "ETag".freeze <ide> CACHE_CONTROL = "Cache-Control".freeze <del> SPESHUL_KEYS = %w[extras no-cache max-age public must-revalidate] <add> SPECIAL_KEYS = %w[extras no-cache max-age public must-revalidate] <ide> <ide> def cache_control_segments <ide> if cache_control = self[CACHE_CONTROL] <ide> def cache_control_headers <ide> cache_control_segments.each do |segment| <ide> directive, argument = segment.split('=', 2) <ide> <del> if SPESHUL_KEYS.include? directive <add> if SPECIAL_KEYS.include? directive <ide> key = directive.tr('-', '_') <ide> cache_control[key.to_sym] = argument || true <ide> else
2
Javascript
Javascript
add node_test_no_internet to the doc builder
914d800a23f1c7877770d62bd4061957c402c8ca
<ide><path>tools/doc/versions.js <ide> const getUrl = (url) => { <ide> }); <ide> }; <ide> <add>const kNoInternet = !!process.env.NODE_TEST_NO_INTERNET; <add> <ide> module.exports = { <ide> async versions() { <ide> if (_versions) { <ide> module.exports = { <ide> const url = <ide> 'https://raw.githubusercontent.com/nodejs/node/master/CHANGELOG.md'; <ide> let changelog; <del> try { <del> changelog = await getUrl(url); <del> } catch (e) { <del> // Fail if this is a release build, otherwise fallback to local files. <del> if (isRelease()) { <del> throw e; <del> } else { <del> const file = path.join(srcRoot, 'CHANGELOG.md'); <del> console.warn(`Unable to retrieve ${url}. Falling back to ${file}.`); <del> changelog = readFileSync(file, { encoding: 'utf8' }); <add> const file = path.join(srcRoot, 'CHANGELOG.md'); <add> if (kNoInternet) { <add> changelog = readFileSync(file, { encoding: 'utf8' }); <add> } else { <add> try { <add> changelog = await getUrl(url); <add> } catch (e) { <add> // Fail if this is a release build, otherwise fallback to local files. <add> if (isRelease()) { <add> throw e; <add> } else { <add> console.warn(`Unable to retrieve ${url}. Falling back to ${file}.`); <add> changelog = readFileSync(file, { encoding: 'utf8' }); <add> } <ide> } <ide> } <ide> const ltsRE = /Long Term Support/i;
1
PHP
PHP
valueretriever
31d720672ef9698af14ed3c06a1716e61e47425b
<ide><path>src/Illuminate/Support/Collection.php <ide> protected function valueRetriever($value) <ide> { <ide> return function($item) use ($value) <ide> { <del> return is_object($item) ? $item->{$value} : array_get($item, $value); <add> return data_get($item, $value); <ide> }; <ide> } <ide> <ide><path>tests/Support/SupportCollectionTest.php <ide> public function testGroupByAttribute() <ide> <ide> public function testGettingSumFromCollection() <ide> { <del> $c = new Collection(array((object) array('foo' => 50), (object) array('foo' => 50))); <del> $this->assertEquals(100, $c->sum('foo')); <add> $c = new Collection(array((object) array('foo' => 50), (object) array('foo' => 50))); <add> $this->assertEquals(100, $c->sum('foo')); <ide> <del> $c = new Collection(array((object) array('foo' => 50), (object) array('foo' => 50))); <del> $this->assertEquals(100, $c->sum(function($i) { return $i->foo; })); <add> $c = new Collection(array((object) array('foo' => 50), (object) array('foo' => 50))); <add> $this->assertEquals(100, $c->sum(function($i) { return $i->foo; })); <ide> } <ide> <ide> public function testGettingSumFromEmptyCollection() <ide> { <del> $c = new Collection(); <del> $this->assertEquals(0, $c->sum('foo')); <add> $c = new Collection(); <add> $this->assertEquals(0, $c->sum('foo')); <add> } <add> <add> public function testValueRetrieverAcceptsDotNotation() <add> { <add> $c = new Collection(array( <add> (object) array('id' => 1, 'foo' => array('bar' => 'B')), (object) array('id' => 2, 'foo' => array('bar' => 'A')) <add> )); <add> <add> $c = $c->sortBy('foo.bar'); <add> $this->assertEquals(array(2, 1), $c->lists('id')); <ide> } <ide> <ide> }
2
Python
Python
move parse_once to quarantine
ff7232761497985720387c4288439ac1dce2ee77
<ide><path>tests/utils/test_dag_processing.py <ide> from unittest import mock <ide> from unittest.mock import MagicMock, PropertyMock <ide> <add>import pytest <add> <ide> from airflow.configuration import conf <ide> from airflow.jobs.local_task_job import LocalTaskJob as LJ <ide> from airflow.jobs.scheduler_job import DagFileProcessorProcess <ide> class path, thus when reloading logging module the airflow.processor_manager <ide> <ide> self.assertFalse(os.path.isfile(log_file_loc)) <ide> <add> @pytest.mark.quarantined <ide> def test_parse_once(self): <ide> test_dag_path = os.path.join(TEST_DAG_FOLDER, 'test_scheduler_dags.py') <ide> async_mode = 'sqlite' not in conf.get('core', 'sql_alchemy_conn')
1
Javascript
Javascript
use proxy logger in test worker
de7798c7539a0a4a946239a1d4b822a3cf1070fc
<ide><path>client/src/client/workers/test-evaluator.js <ide> import '@babel/polyfill'; <ide> <ide> const oldLog = self.console.log.bind(self.console); <ide> self.console.log = function proxyConsole(...args) { <del> self.__logs = [...self.__logs, ...args]; <add> self.postMessage({ type: 'LOG', data: String(args) }); <ide> return oldLog(...args); <ide> }; <ide> <ide> onmessage = async e => { <del> self.__logs = []; <ide> const { script: __test, code } = e.data; <ide> /* eslint-disable no-unused-vars */ <ide> const assert = chai.assert; <ide> onmessage = async e => { <ide> if (typeof testResult === 'function') { <ide> await testResult(() => code); <ide> } <del> self.postMessage({ pass: true, logs: self.__logs.map(String) }); <add> self.postMessage({ pass: true }); <ide> } catch (err) { <ide> self.postMessage({ <ide> err: { <ide> message: err.message, <ide> stack: err.stack <del> }, <del> logs: self.__logs.map(String) <add> } <ide> }); <ide> if (!(err instanceof chai.AssertionError)) { <ide> console.error(err); <ide><path>client/src/templates/Challenges/redux/execute-challenge-saga.js <ide> function* ExecuteChallengeSaga() { <ide> } <ide> } <ide> <add>function* logToConsole(channel) { <add> yield takeEvery(channel, function*(args) { <add> yield put(updateLogs(args)); <add> }); <add>} <add> <ide> function* ExecuteJSChallengeSaga() { <ide> const files = yield select(challengeFilesSelector); <ide> const { code, solution } = yield call(buildJSFromFiles, files); <ide> <add> const consoleProxy = yield channel(); <add> yield fork(logToConsole, consoleProxy); <add> const log = args => consoleProxy.put(args); <add> testWorker.on('LOG', log); <add> <ide> const testResults = yield call(executeTests, { <ide> testRunner: testWorker, <ide> code, <ide> solution <ide> }); <add> <add> testWorker.remove('LOG', log); <add> consoleProxy.close(); <ide> return testResults; <ide> } <ide> <ide> function createTestFrame(state, ctx, proxyLogger) { <ide> }).then(() => console.log('Frame ready')); <ide> } <ide> <del>function* logToConsole(channel) { <del> yield takeEvery(channel, function*(args) { <del> yield put(updateLogs(args)); <del> }); <del>} <del> <ide> function* ExecuteDOMChallengeSaga() { <ide> const state = yield select(); <ide> const ctx = yield call(buildFromFiles, state); <ide> function* executeTests({ testRunner, code = '', solution = '' }) { <ide> for (const { text, testString } of tests) { <ide> const newTest = { text, testString }; <ide> try { <del> const { pass, err, logs = [] } = yield call( <add> const { pass, err } = yield call( <ide> testRunner.execute, <ide> { script: solution + '\n' + testString, code }, <ide> testTimeout <ide> ); <del> for (const log of logs) { <del> yield put(updateLogs(log)); <del> } <ide> if (pass) { <ide> newTest.pass = true; <ide> } else { <ide><path>client/src/templates/Challenges/utils/worker-executor.js <ide> export default class WorkerExecutor { <ide> constructor(workerName) { <ide> this.workerName = workerName; <ide> this.worker = null; <add> this.observers = {}; <ide> <ide> this.execute = this.execute.bind(this); <ide> this.killWorker = this.killWorker.bind(this); <ide> export default class WorkerExecutor { <ide> <ide> // Handle result <ide> worker.onmessage = e => { <add> if (e.data && e.data.type) { <add> const observers = this.observers[e.data.type] || []; <add> for (const observer of observers) { <add> observer(e.data.data); <add> } <add> return; <add> } <ide> clearTimeout(timeoutId); <ide> resolve(e.data); <ide> }; <ide> export default class WorkerExecutor { <ide> }; <ide> }); <ide> } <add> <add> on(type, callback) { <add> const observers = this.observers[type] || []; <add> observers.push(callback); <add> this.observers[type] = observers; <add> } <add> <add> remove(type, callback) { <add> const observers = this.observers[type] || []; <add> const index = observers.indexOf(callback); <add> if (index !== -1) { <add> observers.splice(index, 1); <add> } <add> } <ide> }
3
Text
Text
remove statement about client private keys
b2edcfee46097fe8e0510a455b97d5c6d0cac5ec
<ide><path>doc/api/tls.md <ide> const tls = require('tls'); <ide> ## TLS/SSL concepts <ide> <ide> The TLS/SSL is a public/private key infrastructure (PKI). For most common <del>cases, each client and server must have a _private key_. <add>cases, each server must have a _private key_. <ide> <ide> Private keys can be generated in multiple ways. The example below illustrates <ide> use of the OpenSSL command-line interface to generate a 2048-bit RSA private
1
Javascript
Javascript
restore optin behavior for builds
8791920183f9f13a7be1d513652b9c96d29648c7
<ide><path>build/tasks/build.js <ide> module.exports = function( grunt ) { <ide> startFile: "src/intro.js", <ide> endFile: "src/outro.js" <ide> }, <add> rawText: {}, <ide> onBuildWrite: convert <ide> }; <ide> <ide> module.exports = function( grunt ) { <ide> var flag, index, <ide> done = this.async(), <ide> flags = this.flags, <add> optIn = flags[ "*" ], <ide> name = this.data.dest, <ide> minimum = this.data.minimum, <ide> removeWith = this.data.removeWith, <ide> module.exports = function( grunt ) { <ide> // *:*:-css all except css and dependents (explicit > implicit) <ide> // *:*:-css:+effects same (excludes effects because explicit include is trumped by explicit exclude of dependency) <ide> // *:+effects none except effects and its dependencies (explicit include trumps implicit exclude of dependency) <add> delete flags[ "*" ]; <ide> for ( flag in flags ) { <del> if ( flag !== "*" ) { <del> excluder( flag ); <del> } <add> excluder( flag ); <ide> } <ide> <ide> // Handle Sizzle exclusion <ide> // Replace with selector-native <ide> if ( (index = excluded.indexOf( "sizzle" )) > -1 ) { <del> config.rawText = { <del> selector: "define(['./selector-native']);" <del> }; <add> config.rawText.selector = "define(['./selector-native']);"; <ide> excluded.splice( index, 1 ); <ide> } <ide> <ide> module.exports = function( grunt ) { <ide> grunt.file.write( name, compiled ); <ide> }; <ide> <add> // Turn off opt-in if necessary <add> if ( !optIn ) { <add> // Overwrite the default inclusions with the explicit ones provided <add> config.rawText.jquery = "define([" + (included.length ? included.join(",") : "") + "]);"; <add> } <add> <ide> // Trace dependencies and concatenate files <ide> requirejs.optimize( config, function( response ) { <ide> grunt.verbose.writeln( response );
1
Text
Text
alphabetize migration guide
e39970d494edf5f503072e0b0038b46465233868
<ide><path>docs/getting-started/v3-migration.md <ide> Chart.js 3.0 introduces a number of breaking changes. Chart.js 2.0 was released <ide> <ide> ### Interactions <ide> <del>* `options.onClick` is now limited to the chart area <del>* `{mode: 'single'}` was replaced with `{mode: 'nearest', intersect: true}` <ide> * `{mode: 'label'}` was replaced with `{mode: 'index'}` <add>* `{mode: 'single'}` was replaced with `{mode: 'nearest', intersect: true}` <ide> * `modes['X-axis']` was replaced with `{mode: 'index', intersect: false}` <add>* `options.onClick` is now limited to the chart area <ide> <ide> ### Customizability <ide> <ide> * `custom` attribute of elements was removed. Please use scriptable options <del>* The `zeroLine*` options of axes were removed. Use scriptable scale options instead. <ide> * The `hover` property of scriptable options `context` object was renamed to `active` to align it with the datalabels plugin. <add>* The `zeroLine*` options of axes were removed. Use scriptable scale options instead. <ide> <ide> ### Options <ide> <del>* The dataset option `tension` was renamed to `lineTension` <ide> * `scales.[x/y]Axes` arrays were removed. Scales are now configured directly to `options.scales` object with the object key being the scale Id. <ide> * `scales.[x/y]Axes.barPercentage` was moved to dataset option `barPercentage` <ide> * `scales.[x/y]Axes.barThickness` was moved to dataset option `barThickness` <ide> * `scales.[x/y]Axes.categoryPercentage` was moved to dataset option `categoryPercentage` <del>* `scales.[x/y]Axes.minBarLength` was moved to dataset option `minBarLength` <ide> * `scales.[x/y]Axes.maxBarThickness` was moved to dataset option `maxBarThickness` <add>* `scales.[x/y]Axes.minBarLength` was moved to dataset option `minBarLength` <ide> * `scales.[x/y]Axes.ticks.beginAtZero` was renamed to `scales[id].beginAtZero` <ide> * `scales.[x/y]Axes.ticks.max` was renamed to `scales[id].max` <ide> * `scales.[x/y]Axes.ticks.min` was renamed to `scales[id].min` <ide> Chart.js 3.0 introduces a number of breaking changes. Chart.js 2.0 was released <ide> * `scales.[x/y]Axes.time.format` was renamed to `scales[id].time.parser` <ide> * `scales.[x/y]Axes.time.max` was renamed to `scales[id].max` <ide> * `scales.[x/y]Axes.time.min` was renamed to `scales[id].min` <add>* The dataset option `tension` was renamed to `lineTension` <ide> <ide> ### Animations <ide> <ide> Animation system was completely rewritten in Chart.js v3. Each property can now <ide> <ide> ### Removed <ide> <add>* `Chart.chart.chart` <add>* `Chart.Controller` <add>* `Chart.types` <add>* `DatasetController.addElementAndReset` <add>* `DatasetController.createMetaData` <add>* `DatasetController.createMetaDataset` <add>* `Element.getArea` <add>* `Element.height` <add>* `Element.initialize` <add>* `Element.inLabelRange` <ide> * `helpers.addEvent` <ide> * `helpers.aliasPixel` <ide> * `helpers.configMerge` <ide> * `helpers.indexOf` <ide> * `helpers.lineTo` <del>* `helpers.min` <ide> * `helpers.max` <add>* `helpers.min` <ide> * `helpers.nextItem` <ide> * `helpers.numberOfLabelLines` <ide> * `helpers.previousItem` <ide> * `helpers.removeEvent` <ide> * `helpers.roundedRect` <ide> * `helpers.scaleMerge` <ide> * `helpers.where` <del>* `Chart.Controller` <del>* `Chart.chart.chart` <del>* `Chart.types` <del>* `DatasetController.addElementAndReset` <del>* `DatasetController.createMetaData` <del>* `DatasetController.createMetaDataset` <del>* `Element.getArea` <del>* `Element.height` <del>* `Element.initialize` <del>* `Element.inLabelRange` <ide> * `IPlugin.afterScaleUpdate`. Use `afterLayout` instead <ide> * `Line.calculatePointY` <ide> * `Scale.getRightValue` <add>* `Scale.handleDirectionalChanges` is now private <ide> * `Scale.mergeTicksOptions` <ide> * `Scale.ticksAsNumbers` <del>* `Scale.handleDirectionalChanges` is now private <ide> * `Scale.tickValues` is now private <ide> * The tooltip item's `x` and `y` attributes were removed. Use `datasetIndex` and `index` to get the element and any corresponding data from it <ide> <ide> Animation system was completely rewritten in Chart.js v3. Each property can now <ide> <ide> ### Renamed <ide> <add>* `Chart.Animation.animationObject` was renamed to `Chart.Animation` <add>* `Chart.Animation.chartInstance` was renamed to `Chart.Animation.chart` <add>* `DatasetController.updateElement` was renamed to `DatasetController.updateElements` <add>* `helpers._decimalPlaces` was renamed to `helpers.math._decimalPlaces` <add>* `helpers.almostEquals` was renamed to `helpers.math.almostEquals` <add>* `helpers.almostWhole` was renamed to `helpers.math.almostWhole` <add>* `helpers.callCallback` was renamed to `helpers.callback` <ide> * `helpers.clear` was renamed to `helpers.canvas.clear` <add>* `helpers.distanceBetweenPoints` was renamed to `helpers.math.distanceBetweenPoints` <ide> * `helpers.drawRoundedRectangle` was renamed to `helpers.canvas.roundedRect` <del>* `helpers.callCallback` was renamed to `helpers.callback` <del>* `helpers.getValueOrDefault` was renamed to `helpers.valueOrDefault` <add>* `helpers.getAngleFromPoint` was renamed to `helpers.math.getAngleFromPoint` <add>* `helpers.getMaximumHeight` was renamed to `helpers.dom.getMaximumHeight` <add>* `helpers.getMaximumWidth` was renamed to `helpers.dom.getMaximumWidth` <add>* `helpers.getRelativePosition` was renamed to `helpers.dom.getRelativePosition` <add>* `helpers.getStyle` was renamed to `helpers.dom.getStyle` <ide> * `helpers.getValueAtIndexOrDefault` was renamed to `helpers.valueAtIndexOrDefault` <add>* `helpers.getValueOrDefault` was renamed to `helpers.valueOrDefault` <ide> * `helpers.easingEffects` was renamed to `helpers.easing.effects` <ide> * `helpers.log10` was renamed to `helpers.math.log10` <del>* `helpers.almostEquals` was renamed to `helpers.math.almostEquals` <del>* `helpers.almostWhole` was renamed to `helpers.math.almostWhole` <del>* `helpers.distanceBetweenPoints` was renamed to `helpers.math.distanceBetweenPoints` <ide> * `helpers.isNumber` was renamed to `helpers.math.isNumber` <ide> * `helpers.sign` was renamed to `helpers.math.sign` <add>* `helpers.retinaScale` was renamed to `helpers.dom.retinaScale` <add>* `helpers.splineCurve` was renamed to `helpers.curve.splineCurve` <add>* `helpers.splineCurveMonotone` was renamed to `helpers.curve.splineCurveMonotone` <ide> * `helpers.toDegrees` was renamed to `helpers.math.toDegrees` <ide> * `helpers.toRadians` was renamed to `helpers.math.toRadians` <del>* `helpers.getAngleFromPoint` was renamed to `helpers.math.getAngleFromPoint` <del>* `helpers.splineCurveMonotone` was renamed to `helpers.curve.splineCurveMonotone` <del>* `helpers.splineCurve` was renamed to `helpers.curve.splineCurve` <del>* `helpers.retinaScale` was renamed to `helpers.dom.retinaScale` <del>* `helpers.getMaximumWidth` was renamed to `helpers.dom.getMaximumWidth` <del>* `helpers.getMaximumHeight` was renamed to `helpers.dom.getMaximumHeight` <del>* `helpers.getRelativePosition` was renamed to `helpers.dom.getRelativePosition` <del>* `helpers.getStyle` was renamed to `helpers.dom.getStyle` <del>* `Chart.Animation.animationObject` was renamed to `Chart.Animation` <del>* `Chart.Animation.chartInstance` was renamed to `Chart.Animation.chart` <del>* `DatasetController.updateElement` was renamed to `DatasetController.updateElements` <ide> * `Scale.calculateTickRotation` was renamed to `Scale.calculateLabelRotation` <ide> * `TimeScale.getLabelCapacity` was renamed to `TimeScale._getLabelCapacity` <del>* `TimeScale.tickFormatFunction` was renamed to `TimeScale._tickFormatFunction` <ide> * `TimeScale.getPixelForOffset` was renamed to `TimeScale._getPixelForOffset` <add>* `TimeScale.tickFormatFunction` was renamed to `TimeScale._tickFormatFunction` <ide> * `Tooltip.options.legendColorBackgroupd` was renamed to `Tooltip.options.multiKeyBackground` <ide> <ide> #### Renamed private APIs <ide> Animation system was completely rewritten in Chart.js v3. Each property can now <ide> <ide> ##### Ticks <ide> <del>* When the `autoSkip` option is enabled, `Scale.ticks` now contains only the non-skipped ticks instead of all ticks. <del>* `Scale.ticks` now contains objects instead of strings <del>* `Scale.buildTicks` is now expected to return tick objects <ide> * `Scale.afterBuildTicks` now has no parameters like the other callbacks <add>* `Scale.buildTicks` is now expected to return tick objects <ide> * `Scale.convertTicksToLabels` was renamed to `generateTickLabels`. It is now expected to set the label property on the ticks given as input <add>* `Scale.ticks` now contains objects instead of strings <add>* When the `autoSkip` option is enabled, `Scale.ticks` now contains only the non-skipped ticks instead of all ticks. <ide> <ide> ##### Time Scale <ide>
1
Python
Python
add missing classmethod decorators
1da782cb28dc9bb030e8f09b78ea14a81324c3d6
<ide><path>src/transformers/models/auto/auto_factory.py <ide> def __init__(self, *args, **kwargs): <ide> f"`{self.__class__.__name__}.from_config(config)` methods." <ide> ) <ide> <add> @classmethod <ide> def from_config(cls, config, **kwargs): <ide> if type(config) in cls._model_mapping.keys(): <ide> model_class = _get_model_class(config, cls._model_mapping) <ide> def from_config(cls, config, **kwargs): <ide> f"Model type should be one of {', '.join(c.__name__ for c in cls._model_mapping.keys())}." <ide> ) <ide> <add> @classmethod <ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): <ide> config = kwargs.pop("config", None) <ide> kwargs["_from_auto"] = True
1
Ruby
Ruby
remove dummy method
4f476d70661ff6b108f5c5e3175ee2db8d55927b
<ide><path>Library/Homebrew/test/test_formula.rb <ide> def test_factory <ide> require 'formula' <ide> class #{Formulary.class_s(name)} < Formula <ide> url 'foo-1.0' <del> def initialize(*args) <del> super <del> end <ide> end <ide> } <ide> end
1
Python
Python
remove old recordtype definition
58ee25b5d8f6bf35743c2d5e4f4441fc5f241d04
<ide><path>libcloud/dns/types.py <ide> class Provider(object): <ide> GANDI = 'gandi' <ide> <ide> <del>class RecordType(object): <del> """ <del> DNS record type. <del> """ <del> A = 0 <del> AAAA = 1 <del> MX = 2 <del> NS = 3 <del> CNAME = 4 <del> DNAME = 5 <del> TXT = 6 <del> PTR = 7 <del> SOA = 8 <del> SPF = 9 <del> SRV = 10 <del> PTR = 11 <del> NAPTR = 12 <del> REDIRECT = 13 <del> GEO = 14 <del> URL = 15 <del> WKS = 16 <del> LOC = 17 <del> <ide> class RecordType(object): <ide> """ <ide> DNS record type.
1
Text
Text
update catalan acknowledgements for v3.2
6763cbfdc03ed801576c99a5d35623cf55925e22
<ide><path>website/docs/usage/v3-2.md <ide> their contributions! <ide> <ide> - All Universal Dependencies training data has been updated to v2.8. <ide> - The Catalan data, tokenizer and lemmatizer have been updated, thanks to Carlos <del> Rodriguez and the Barcelona Supercomputing Center! <add> Rodriguez, Carme Armentano and the Barcelona Supercomputing Center! <ide> - The transformer pipelines are trained using spacy-transformers v1.1, with <ide> improved IO and more options for <ide> [model config and output](/api/architectures#TransformerModel).
1
PHP
PHP
add missing tests imports.
da8aff4338753feda04a9ca794168e0dd7de94e4
<ide><path>tests/Bus/BusBatchTest.php <ide> use Mockery as m; <ide> use PHPUnit\Framework\TestCase; <ide> use RuntimeException; <add>use stdClass; <ide> <ide> class BusBatchTest extends TestCase <ide> { <ide><path>tests/Database/DatabaseMigrationMigrateCommandTest.php <ide> use Illuminate\Foundation\Application; <ide> use Mockery as m; <ide> use PHPUnit\Framework\TestCase; <add>use stdClass; <ide> use Symfony\Component\Console\Input\ArrayInput; <ide> use Symfony\Component\Console\Output\NullOutput; <ide> <ide><path>tests/Integration/Events/ListenerTest.php <ide> <ide> namespace Illuminate\Tests\Integration\Events; <ide> <add>use Illuminate\Database\DatabaseTransactionsManager; <ide> use Illuminate\Support\Facades\Event; <ide> use Mockery as m; <ide> use Orchestra\Testbench\TestCase; <ide><path>tests/Integration/Http/ResourceTest.php <ide> <ide> use Illuminate\Foundation\Http\Middleware\ValidatePostSize; <ide> use Illuminate\Http\Exceptions\PostTooLargeException; <add>use Illuminate\Http\Request; <ide> use Illuminate\Http\Resources\ConditionallyLoadsAttributes; <ide> use Illuminate\Http\Resources\Json\JsonResource; <ide> use Illuminate\Http\Resources\MergeValue; <ide><path>tests/Testing/Concerns/TestDatabasesTest.php <ide> <ide> namespace Illuminate\Tests\Testing\Concerns; <ide> <add>use Illuminate\Config\Repository as Config; <ide> use Illuminate\Container\Container; <ide> use Illuminate\Support\Facades\DB; <ide> use Illuminate\Testing\Concerns\TestDatabases;
5
Ruby
Ruby
use separate sets for procs and symbols
aca48deda0f7bbb9831291dbf47ed3c8e4ae2b9c
<ide><path>Library/Homebrew/build_environment.rb <ide> class BuildEnvironment <ide> def initialize(*settings) <ide> @settings = Set.new(settings) <add> @procs = Set.new <ide> end <ide> <ide> def <<(o) <del> @settings << o <add> case o <add> when Proc then @procs << o <add> else @settings << o <add> end <ide> self <ide> end <ide> <ide> def userpaths? <ide> end <ide> <ide> def modify_build_environment(context=nil) <del> p = @settings.find { |s| Proc === s } <del> ENV.instance_exec(context, &p) unless p.nil? <add> @procs.each { |p| ENV.instance_exec(context, &p) } <ide> end <ide> <ide> def _dump(*) <del> @settings.dup.reject { |s| Proc === s }.join(":") <add> @settings.to_a.join(":") <ide> end <ide> <ide> def self._load(s) <ide><path>Library/Homebrew/test/test_build_environment.rb <ide> def test_userpaths? <ide> end <ide> <ide> def test_modify_build_environment <del> @env << Proc.new { 1 } <del> assert_equal 1, @env.modify_build_environment <add> @env << Proc.new { raise StandardError } <add> assert_raises(StandardError) do <add> @env.modify_build_environment <add> end <ide> end <ide> <ide> def test_marshal
2
Javascript
Javascript
add isolate version of test-child-process-fork
4428b70cbaf94d0af4e18dd727facd3a6b7ec272
<ide><path>lib/child_process.js <ide> exports.fork = function(modulePath, args, options) { <ide> args = args ? args.slice(0) : []; <ide> args.unshift(modulePath); <ide> <add> if (options.thread) { <add> if (!process.features.isolates) { <add> throw new Error('node compiled without isolate support'); <add> } <add> } <add> <ide> if (options.stdinStream) { <ide> throw new Error('stdinStream not allowed for fork()'); <ide> } <ide><path>test/simple/test-child-process-fork.js <ide> var common = require('../common'); <ide> var fork = require('child_process').fork; <ide> var args = ['foo', 'bar']; <ide> <del>var n = fork(common.fixturesDir + '/child-process-spawn-node.js', args); <add>var options = { <add> thread: process.TEST_ISOLATE ? true : false <add>}; <add> <add>var n = fork(common.fixturesDir + '/child-process-spawn-node.js', <add> args, <add> options); <ide> assert.deepEqual(args, ['foo', 'bar']); <ide> <ide> var messageCount = 0; <ide><path>test/simple/test-isolates2.js <add>// Skip this test if Node is not compiled with isolates support. <add>if (!process.features.isolates) return; <add> <add>var assert = require('assert'); <add> <add>// This is the same test as test-child-process-fork except it uses isolates <add>// instead of processes. process.TEST_ISOLATE is a ghetto method of passing <add>// some information into the other test. <add>process.TEST_ISOLATE = true; <add>require('./test-child-process-fork'); <add> <add>var numThreads = process.binding('isolates').count(); <add>assert.ok(numThreads > 1);
3
PHP
PHP
fix whitespace error in validation utility
4b2825431901b3bdd7409df8f956f26fba998800
<ide><path>lib/Cake/Utility/Validation.php <ide> public static function date($check, $format = 'ymd', $regex = null) { <ide> $separator . '((1[6-9]|[2-9]\\d)\\d{2})$%'; <ide> <ide> $regex['my'] = '%^(' . $month . $separator . $year . ')$%'; <del> $regex['ym'] = '%^(' . $year . $separator . $month . ')$%'; <add> $regex['ym'] = '%^(' . $year . $separator . $month . ')$%'; <ide> $regex['y'] = '%^(' . $fourDigitYear . ')$%'; <ide> <ide> $format = (is_array($format)) ? array_values($format) : array($format);
1
Python
Python
add head_mask and decoder_head_mask to tf led
e7381c4596828e5d9fa7974df14f011ed95890c1
<ide><path>src/transformers/models/led/modeling_tf_led.py <ide> def call( <ide> ( <ide> hidden_states, <ide> attention_mask, <add> layer_head_mask, <ide> is_index_masked, <ide> is_index_global_attn, <ide> is_global_attn, <ide> def call( <ide> attn_probs, <ide> ) <ide> <add> if layer_head_mask is not None: <add> tf.debugging.assert_equal( <add> shape_list(layer_head_mask), <add> [self.num_heads], <add> message=f"Head mask for a single layer should be of size {(self.num_heads)}, but is {shape_list(layer_head_mask)}", <add> ) <add> attn_probs = tf.reshape(layer_head_mask, (1, 1, -1, 1)) * attn_probs <add> <ide> # apply dropout <ide> attn_probs = self.dropout(attn_probs, training=training) <ide> value_vectors = tf.reshape(value_vectors, (batch_size, seq_len, self.num_heads, self.head_dim)) <ide> def call( <ide> attn_output=attn_output, <ide> hidden_states=hidden_states, <ide> max_num_global_attn_indices=max_num_global_attn_indices, <add> layer_head_mask=layer_head_mask, <ide> is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero, <ide> is_index_global_attn_nonzero=is_index_global_attn_nonzero, <ide> is_local_index_no_global_attn_nonzero=is_local_index_no_global_attn_nonzero, <ide> def _compute_global_attn_output_from_hidden( <ide> attn_output, <ide> hidden_states, <ide> max_num_global_attn_indices, <add> layer_head_mask, <ide> is_local_index_global_attn_nonzero, <ide> is_index_global_attn_nonzero, <ide> is_local_index_no_global_attn_nonzero, <ide> def _compute_global_attn_output_from_hidden( <ide> # compute global attn probs <ide> global_attn_probs_float = tf.nn.softmax(global_attn_scores, axis=-1) <ide> <add> # apply layer head maskin <add> if layer_head_mask is not None: <add> tf.debugging.assert_equal( <add> shape_list(layer_head_mask), <add> [self.num_heads], <add> message=f"Head mask for a single layer should be of size {(self.num_heads)}, but is {shape_list(layer_head_mask)}", <add> ) <add> global_attn_probs_float = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape( <add> global_attn_probs_float, (batch_size, self.num_heads, max_num_global_attn_indices, seq_len) <add> ) <add> global_attn_probs_float = tf.reshape( <add> global_attn_probs_float, (batch_size * self.num_heads, max_num_global_attn_indices, seq_len) <add> ) <add> <ide> # dropout <ide> global_attn_probs = self.global_dropout(global_attn_probs_float, training=training) <ide> <ide> def call(self, inputs, training=False): <ide> ( <ide> hidden_states, <ide> attention_mask, <add> layer_head_mask, <ide> is_index_masked, <ide> is_index_global_attn, <ide> is_global_attn, <ide> ) = inputs <ide> <ide> self_outputs = self.longformer_self_attn( <del> [hidden_states, attention_mask, is_index_masked, is_index_global_attn, is_global_attn], <add> [hidden_states, attention_mask, layer_head_mask, is_index_masked, is_index_global_attn, is_global_attn], <ide> training=training, <ide> ) <ide> <ide> def call( <ide> key_value_states: Optional[tf.Tensor] = None, <ide> past_key_value: Optional[Tuple[Tuple[tf.Tensor]]] = None, <ide> attention_mask: Optional[tf.Tensor] = None, <add> layer_head_mask: Optional[tf.Tensor] = None, <ide> training=False, <ide> ) -> Tuple[tf.Tensor, Optional[tf.Tensor]]: <ide> """Input shape: Batch x Time x Channel""" <ide> def call( <ide> <ide> attn_weights = tf.nn.softmax(attn_weights, axis=-1) <ide> <add> if layer_head_mask is not None: <add> tf.debugging.assert_equal( <add> shape_list(layer_head_mask), <add> [self.num_heads], <add> message=f"Head mask for a single layer should be of size {(self.num_heads)}, but is {shape_list(layer_head_mask)}", <add> ) <add> attn_weights = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape( <add> attn_weights, (bsz, self.num_heads, tgt_len, src_len) <add> ) <add> attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len)) <add> <ide> attn_probs = self.dropout(attn_weights, training=training) <ide> <ide> attn_output = tf.matmul(attn_probs, value_states) <ide> def call( <ide> self, <ide> hidden_states: tf.Tensor, <ide> attention_mask: tf.Tensor, <add> layer_head_mask: tf.Tensor, <ide> is_index_masked: tf.Tensor, <ide> is_index_global_attn: tf.Tensor, <ide> is_global_attn: bool, <ide> def call( <ide> hidden_states (:obj:`tf.Tensor`): input to the layer of shape `(seq_len, batch, embed_dim)` <ide> attention_mask (:obj:`tf.Tensor`): attention mask of size <ide> `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. <add> layer_head_mask (:obj:`tf.Tensor`): mask for attention heads in a given layer of size <add> `(config.encoder_attention_heads,)`. <ide> """ <ide> residual = hidden_states <ide> layer_outputs = self.self_attn( <del> [hidden_states, attention_mask, is_index_masked, is_index_global_attn, is_global_attn], <add> [hidden_states, attention_mask, layer_head_mask, is_index_masked, is_index_global_attn, is_global_attn], <ide> training=training, <ide> ) <ide> <ide> def call( <ide> attention_mask: Optional[tf.Tensor] = None, <ide> encoder_hidden_states: Optional[tf.Tensor] = None, <ide> encoder_attention_mask: Optional[tf.Tensor] = None, <add> layer_head_mask: Optional[tf.Tensor] = None, <add> encoder_layer_head_mask: Optional[tf.Tensor] = None, <ide> past_key_value: Optional[Tuple[tf.Tensor]] = None, <ide> training=False, <ide> ) -> Tuple[tf.Tensor, tf.Tensor, Tuple[Tuple[tf.Tensor]]]: <ide> def call( <ide> encoder_hidden_states (:obj:`tf.Tensor`): cross attention input to the layer of shape `(seq_len, batch, embed_dim)` <ide> encoder_attention_mask (:obj:`tf.Tensor`): encoder attention mask of size <ide> `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. <add> layer_head_mask (:obj:`tf.Tensor`): mask for attention heads in a given layer of size <add> `(config.encoder_attention_heads,)`. <add> encoder_layer_head_mask (:obj:`tf.Tensor`): mask for encoder attention heads in a given layer of <add> size `(config.encoder_attention_heads,)`. <ide> past_key_value (:obj:`Tuple(tf.Tensor)`): cached past key and value projection states <ide> """ <ide> residual = hidden_states <ide> def call( <ide> hidden_states=hidden_states, <ide> past_key_value=self_attn_past_key_value, <ide> attention_mask=attention_mask, <add> layer_head_mask=layer_head_mask, <ide> ) <ide> hidden_states = self.dropout(hidden_states, training=training) <ide> hidden_states = residual + hidden_states <ide> def call( <ide> hidden_states=hidden_states, <ide> key_value_states=encoder_hidden_states, <ide> attention_mask=encoder_attention_mask, <add> layer_head_mask=encoder_layer_head_mask, <ide> past_key_value=cross_attn_past_key_value, <ide> ) <ide> hidden_states = self.dropout(hidden_states, training=training) <ide> class TFLEDSeq2SeqLMOutput(ModelOutput): <ide> shifting the input_ids right, following the paper. <ide> decoder_attention_mask (:obj:`tf.Tensor` of shape :obj:`(batch_size, target_sequence_length)`, `optional`): <ide> will be made by default and ignore pad tokens. It is not recommended to set this for most use cases. <add> head_mask (:obj:`tf.Tensor` of shape :obj:`(encoder_layers, encoder_attention_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <add> decoder_head_mask (:obj:`tf.Tensor` of shape :obj:`(decoder_layers, decoder_attention_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the head is **masked**. <add> <ide> encoder_outputs (:obj:`tf.FloatTensor`, `optional`): <ide> hidden states at the output of the last layer of the encoder. Used in the cross-attention of the decoder. <ide> of shape :obj:`(batch_size, sequence_length, hidden_size)` is a sequence of <ide> def call( <ide> inputs_embeds=None, <ide> attention_mask=None, <ide> global_attention_mask=None, <add> head_mask=None, <ide> output_attentions=None, <ide> output_hidden_states=None, <ide> return_dict=None, <ide> def call( <ide> - 0 for tokens that are **masked**. <ide> <ide> `What are attention masks? <../glossary.html#attention-mask>`__ <add> head_mask (:obj:`tf.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <ide> inputs_embeds (:obj:`tf.Tensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`): <ide> Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded <ide> representation. This is useful if you want more control over how to convert :obj:`input_ids` indices <ide> def call( <ide> config=self.config, <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <add> head_mask=head_mask, <ide> global_attention_mask=global_attention_mask, <ide> inputs_embeds=inputs_embeds, <ide> output_attentions=output_attentions, <ide> def call( <ide> encoder_states = () if inputs["output_hidden_states"] else None <ide> all_attentions = all_global_attentions = () if inputs["output_attentions"] else None <ide> <add> # check if head_mask has a correct number of layers specified if desired <add> if inputs["head_mask"] is not None: <add> tf.debugging.assert_equal( <add> shape_list(inputs["head_mask"])[0], <add> len(self.layers), <add> message=f"The head_mask should be specified for {len(self.layers)} layers, but it is for {shape_list(inputs['head_mask'])[0]}.", <add> ) <ide> # encoder layers <del> for encoder_layer in self.layers: <add> for idx, encoder_layer in enumerate(self.layers): <ide> <ide> if inputs["output_hidden_states"]: <ide> hidden_states_to_add = self.compute_hidden_states(hidden_states, padding_len) <ide> def call( <ide> layer_outputs = encoder_layer( <ide> hidden_states=hidden_states, <ide> attention_mask=inputs["attention_mask"], <add> layer_head_mask=inputs["head_mask"][idx] if inputs["head_mask"] is not None else None, <ide> is_index_masked=is_index_masked, <ide> is_index_global_attn=is_index_global_attn, <ide> is_global_attn=is_global_attn, <ide> def call( <ide> attention_mask=None, <ide> encoder_hidden_states=None, <ide> encoder_attention_mask=None, <add> head_mask=None, <add> encoder_head_mask=None, <ide> past_key_values=None, <ide> use_cache=None, <ide> output_attentions=None, <ide> def call( <ide> - 1 for tokens that are **not masked**, <ide> - 0 for tokens that are **masked**. <ide> `What are attention masks? <../glossary.html#attention-mask>`__ <add> head_mask (:obj:`tf.Tensor` of shape :obj:`(decoder_layers, decoder_attention_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <add> encoder_head_mask (:obj:`tf.Tensor` of shape :obj:`(encoder_layers, encoder_attention_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules in encoder to avoid performing cross-attention <add> on hidden heads. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <ide> past_key_values (:obj:`Tuple[Tuple[tf.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <ide> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <ide> decoding. If :obj:`past_key_values` are used, the user can optionally input only the last <ide> def call( <ide> attention_mask=attention_mask, <ide> encoder_hidden_states=encoder_hidden_states, <ide> encoder_attention_mask=encoder_attention_mask, <add> head_mask=head_mask, <add> encoder_head_mask=encoder_head_mask, <ide> inputs_embeds=inputs_embeds, <ide> past_key_values=past_key_values, <ide> use_cache=use_cache, <ide> def call( <ide> all_hidden_states = () <ide> all_self_attns = () <ide> present_key_values = () <add> <add> # check if head_mask has a correct number of layers specified if desired <add> if inputs["head_mask"] is not None: <add> tf.debugging.assert_equal( <add> shape_list(inputs["head_mask"])[0], <add> len(self.layers), <add> message=f"The head_mask should be specified for {len(self.layers)} layers, but it is for {shape_list(inputs['head_mask'])[0]}.", <add> ) <ide> for idx, decoder_layer in enumerate(self.layers): <ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) <ide> if inputs["output_hidden_states"]: <ide> def call( <ide> attention_mask=combined_attention_mask, <ide> encoder_hidden_states=inputs["encoder_hidden_states"], <ide> encoder_attention_mask=inputs["encoder_attention_mask"], <add> layer_head_mask=inputs["head_mask"][idx] if inputs["head_mask"] is not None else None, <add> encoder_layer_head_mask=inputs["encoder_head_mask"][idx] <add> if inputs["encoder_head_mask"] is not None <add> else None, <ide> past_key_value=past_key_value, <ide> ) <ide> <ide> def call( <ide> attention_mask=None, <ide> decoder_input_ids=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> encoder_outputs: Optional[Union[Tuple, TFLEDEncoderBaseModelOutput]] = None, <ide> global_attention_mask=None, <ide> past_key_values=None, <ide> def call( <ide> attention_mask=attention_mask, <ide> decoder_input_ids=decoder_input_ids, <ide> decoder_attention_mask=decoder_attention_mask, <add> head_mask=head_mask, <add> decoder_head_mask=decoder_head_mask, <ide> encoder_outputs=encoder_outputs, <ide> global_attention_mask=global_attention_mask, <ide> past_key_values=past_key_values, <ide> def call( <ide> input_ids=inputs["input_ids"], <ide> attention_mask=inputs["attention_mask"], <ide> global_attention_mask=inputs["global_attention_mask"], <add> head_mask=inputs["head_mask"], <ide> inputs_embeds=inputs["inputs_embeds"], <ide> output_attentions=inputs["output_attentions"], <ide> output_hidden_states=inputs["output_hidden_states"], <ide> def call( <ide> attention_mask=inputs["decoder_attention_mask"], <ide> encoder_hidden_states=inputs["encoder_outputs"][0], <ide> encoder_attention_mask=inputs["attention_mask"], <add> head_mask=inputs["decoder_head_mask"], <add> encoder_head_mask=inputs["head_mask"], <ide> past_key_values=inputs["past_key_values"], <ide> inputs_embeds=inputs["decoder_inputs_embeds"], <ide> use_cache=inputs["use_cache"], <ide> def call( <ide> attention_mask=None, <ide> decoder_input_ids=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> encoder_outputs: Optional[Union[Tuple, TFLEDEncoderBaseModelOutput]] = None, <ide> global_attention_mask=None, <ide> past_key_values=None, <ide> def call( <ide> attention_mask=attention_mask, <ide> decoder_input_ids=decoder_input_ids, <ide> decoder_attention_mask=decoder_attention_mask, <add> head_mask=head_mask, <add> decoder_head_mask=decoder_head_mask, <ide> encoder_outputs=encoder_outputs, <ide> global_attention_mask=global_attention_mask, <ide> past_key_values=past_key_values, <ide> def call( <ide> decoder_attention_mask=inputs["decoder_attention_mask"], <ide> encoder_outputs=inputs["encoder_outputs"], <ide> global_attention_mask=inputs["global_attention_mask"], <add> head_mask=inputs["head_mask"], <add> decoder_head_mask=inputs["decoder_head_mask"], <ide> past_key_values=inputs["past_key_values"], <ide> inputs_embeds=inputs["inputs_embeds"], <ide> decoder_inputs_embeds=inputs["decoder_inputs_embeds"], <ide> def call( <ide> attention_mask=None, <ide> decoder_input_ids=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> encoder_outputs: Optional[TFLEDEncoderBaseModelOutput] = None, <ide> global_attention_mask=None, <ide> past_key_values=None, <ide> def call( <ide> attention_mask=attention_mask, <ide> decoder_input_ids=decoder_input_ids, <ide> decoder_attention_mask=decoder_attention_mask, <add> head_mask=head_mask, <add> decoder_head_mask=decoder_head_mask, <ide> encoder_outputs=encoder_outputs, <ide> global_attention_mask=global_attention_mask, <ide> past_key_values=past_key_values, <ide> def call( <ide> decoder_attention_mask=inputs["decoder_attention_mask"], <ide> encoder_outputs=inputs["encoder_outputs"], <ide> global_attention_mask=inputs["global_attention_mask"], <add> head_mask=inputs["head_mask"], <add> decoder_head_mask=inputs["decoder_head_mask"], <ide> past_key_values=inputs["past_key_values"], <ide> inputs_embeds=inputs["inputs_embeds"], <ide> decoder_inputs_embeds=inputs["decoder_inputs_embeds"], <ide><path>src/transformers/models/longformer/modeling_tf_longformer.py <ide> def call( <ide> ( <ide> hidden_states, <ide> attention_mask, <add> layer_head_mask, <ide> is_index_masked, <ide> is_index_global_attn, <ide> is_global_attn, <ide> def call( <ide> attn_probs, <ide> ) <ide> <add> if layer_head_mask is not None: <add> tf.debugging.assert_equal( <add> shape_list(layer_head_mask), <add> [self.num_heads], <add> message=f"Head mask for a single layer should be of size {(self.num_heads)}, but is {shape_list(layer_head_mask)}", <add> ) <add> attn_probs = tf.reshape(layer_head_mask, (1, 1, -1, 1)) * attn_probs <add> <ide> # apply dropout <ide> attn_probs = self.dropout(attn_probs, training=training) <ide> value_vectors = tf.reshape(value_vectors, (batch_size, seq_len, self.num_heads, self.head_dim)) <ide> def call( <ide> attn_output=attn_output, <ide> hidden_states=hidden_states, <ide> max_num_global_attn_indices=max_num_global_attn_indices, <add> layer_head_mask=layer_head_mask, <ide> is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero, <ide> is_index_global_attn_nonzero=is_index_global_attn_nonzero, <ide> is_local_index_no_global_attn_nonzero=is_local_index_no_global_attn_nonzero, <ide> def _compute_global_attn_output_from_hidden( <ide> attn_output, <ide> hidden_states, <ide> max_num_global_attn_indices, <add> layer_head_mask, <ide> is_local_index_global_attn_nonzero, <ide> is_index_global_attn_nonzero, <ide> is_local_index_no_global_attn_nonzero, <ide> def _compute_global_attn_output_from_hidden( <ide> # compute global attn probs <ide> global_attn_probs_float = tf.nn.softmax(global_attn_scores, axis=-1) <ide> <add> # apply layer head maskin <add> if layer_head_mask is not None: <add> tf.debugging.assert_equal( <add> shape_list(layer_head_mask), <add> [self.num_heads], <add> message=f"Head mask for a single layer should be of size {(self.num_heads)}, but is {shape_list(layer_head_mask)}", <add> ) <add> global_attn_probs_float = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape( <add> global_attn_probs_float, (batch_size, self.num_heads, max_num_global_attn_indices, seq_len) <add> ) <add> global_attn_probs_float = tf.reshape( <add> global_attn_probs_float, (batch_size * self.num_heads, max_num_global_attn_indices, seq_len) <add> ) <add> <ide> # dropout <ide> global_attn_probs = self.global_dropout(global_attn_probs_float, training=training) <ide> <ide> def call(self, inputs, training=False): <ide> ( <ide> hidden_states, <ide> attention_mask, <add> layer_head_mask, <ide> is_index_masked, <ide> is_index_global_attn, <ide> is_global_attn, <ide> ) = inputs <ide> <ide> self_outputs = self.self_attention( <del> [hidden_states, attention_mask, is_index_masked, is_index_global_attn, is_global_attn], <add> [hidden_states, attention_mask, layer_head_mask, is_index_masked, is_index_global_attn, is_global_attn], <ide> training=training, <ide> ) <ide> attention_output = self.dense_output(self_outputs[0], hidden_states, training=training) <ide> def call(self, inputs, training=False): <ide> ( <ide> hidden_states, <ide> attention_mask, <add> layer_head_mask, <ide> is_index_masked, <ide> is_index_global_attn, <ide> is_global_attn, <ide> ) = inputs <ide> <ide> attention_outputs = self.attention( <del> [hidden_states, attention_mask, is_index_masked, is_index_global_attn, is_global_attn], <add> [hidden_states, attention_mask, layer_head_mask, is_index_masked, is_index_global_attn, is_global_attn], <ide> training=training, <ide> ) <ide> attention_output = attention_outputs[0] <ide> def call( <ide> all_hidden_states = () if output_hidden_states else None <ide> all_attentions = all_global_attentions = () if output_attentions else None <ide> <del> for i, layer_module in enumerate(self.layer): <add> for idx, layer_module in enumerate(self.layer): <ide> if output_hidden_states: <ide> hidden_states_to_add = hidden_states[:, :-padding_len] if padding_len > 0 else hidden_states <ide> all_hidden_states = all_hidden_states + (hidden_states_to_add,) <ide> def call( <ide> [ <ide> hidden_states, <ide> attention_mask, <add> head_mask[idx] if head_mask is not None else None, <ide> is_index_masked, <ide> is_index_global_attn, <ide> is_global_attn, <ide> def call( <ide> self, <ide> input_ids=None, <ide> attention_mask=None, <add> head_mask=None, <ide> global_attention_mask=None, <ide> token_type_ids=None, <ide> position_ids=None, <ide> def call( <ide> config=self.config, <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <add> head_mask=head_mask, <ide> global_attention_mask=global_attention_mask, <ide> token_type_ids=token_type_ids, <ide> position_ids=position_ids, <ide> def call( <ide> encoder_outputs = self.encoder( <ide> embedding_output, <ide> attention_mask=extended_attention_mask, <add> head_mask=head_mask, <ide> padding_len=padding_len, <ide> is_index_masked=is_index_masked, <ide> is_index_global_attn=is_index_global_attn, <ide> def serving(self, inputs): <ide> - 0 for tokens that are **masked**. <ide> <ide> `What are attention masks? <../glossary.html#attention-mask>`__ <add> head_mask (:obj:`tf.Tensor` of shape :obj:`(encoder_layers, encoder_attention_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <ide> global_attention_mask (:obj:`tf.Tensor` of shape :obj:`({0})`, `optional`): <ide> Mask to decide the attention given on each token, local attention or global attention. Tokens with global <ide> attention attends to all other tokens, and all other tokens attend to them. This is important for <ide> def call( <ide> self, <ide> input_ids=None, <ide> attention_mask=None, <add> head_mask=None, <ide> global_attention_mask=None, <ide> token_type_ids=None, <ide> position_ids=None, <ide> def call( <ide> config=self.config, <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <add> head_mask=head_mask, <ide> global_attention_mask=global_attention_mask, <ide> token_type_ids=token_type_ids, <ide> position_ids=position_ids, <ide> def call( <ide> outputs = self.longformer( <ide> input_ids=inputs["input_ids"], <ide> attention_mask=inputs["attention_mask"], <add> head_mask=inputs["head_mask"], <ide> global_attention_mask=inputs["global_attention_mask"], <ide> token_type_ids=inputs["token_type_ids"], <ide> position_ids=inputs["position_ids"], <ide> def call( <ide> self, <ide> input_ids=None, <ide> attention_mask=None, <add> head_mask=None, <ide> global_attention_mask=None, <ide> token_type_ids=None, <ide> position_ids=None, <ide> def call( <ide> config=self.config, <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <add> head_mask=head_mask, <ide> global_attention_mask=global_attention_mask, <ide> token_type_ids=token_type_ids, <ide> position_ids=position_ids, <ide> def call( <ide> outputs = self.longformer( <ide> input_ids=inputs["input_ids"], <ide> attention_mask=inputs["attention_mask"], <add> head_mask=inputs["head_mask"], <ide> global_attention_mask=inputs["global_attention_mask"], <ide> token_type_ids=inputs["token_type_ids"], <ide> position_ids=inputs["position_ids"], <ide> def call( <ide> self, <ide> input_ids=None, <ide> attention_mask=None, <add> head_mask=None, <ide> global_attention_mask=None, <ide> token_type_ids=None, <ide> position_ids=None, <ide> def call( <ide> config=self.config, <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <add> head_mask=head_mask, <ide> global_attention_mask=global_attention_mask, <ide> token_type_ids=token_type_ids, <ide> position_ids=position_ids, <ide> def call( <ide> outputs = self.longformer( <ide> input_ids=inputs["input_ids"], <ide> attention_mask=inputs["attention_mask"], <add> head_mask=inputs["head_mask"], <ide> global_attention_mask=inputs["global_attention_mask"], <ide> token_type_ids=inputs["token_type_ids"], <ide> position_ids=inputs["position_ids"], <ide> def call( <ide> self, <ide> input_ids=None, <ide> attention_mask=None, <add> head_mask=None, <ide> token_type_ids=None, <ide> position_ids=None, <ide> global_attention_mask=None, <ide> def call( <ide> config=self.config, <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <add> head_mask=head_mask, <ide> global_attention_mask=global_attention_mask, <ide> token_type_ids=token_type_ids, <ide> position_ids=position_ids, <ide> def call( <ide> outputs = self.longformer( <ide> input_ids=inputs["input_ids"], <ide> attention_mask=inputs["attention_mask"], <add> head_mask=inputs["head_mask"], <ide> global_attention_mask=inputs["global_attention_mask"], <ide> token_type_ids=inputs["token_type_ids"], <ide> position_ids=inputs["position_ids"], <ide> def call( <ide> self, <ide> input_ids=None, <ide> attention_mask=None, <add> head_mask=None, <ide> token_type_ids=None, <ide> position_ids=None, <ide> global_attention_mask=None, <ide> def call( <ide> config=self.config, <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <add> head_mask=head_mask, <ide> global_attention_mask=global_attention_mask, <ide> token_type_ids=token_type_ids, <ide> position_ids=position_ids, <ide> def call( <ide> position_ids=flat_position_ids, <ide> token_type_ids=flat_token_type_ids, <ide> attention_mask=flat_attention_mask, <add> head_mask=head_mask, <ide> global_attention_mask=flat_global_attention_mask, <ide> inputs_embeds=flat_inputs_embeds, <ide> output_attentions=output_attentions, <ide> def call( <ide> self, <ide> input_ids=None, <ide> attention_mask=None, <add> head_mask=None, <ide> token_type_ids=None, <ide> position_ids=None, <ide> global_attention_mask=None, <ide> def call( <ide> config=self.config, <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <add> head_mask=head_mask, <ide> global_attention_mask=global_attention_mask, <ide> token_type_ids=token_type_ids, <ide> position_ids=position_ids, <ide> def call( <ide> outputs = self.longformer( <ide> input_ids=inputs["input_ids"], <ide> attention_mask=inputs["attention_mask"], <add> head_mask=inputs["head_mask"], <ide> global_attention_mask=inputs["global_attention_mask"], <ide> token_type_ids=inputs["token_type_ids"], <ide> position_ids=inputs["position_ids"], <ide><path>tests/test_modeling_tf_led.py <ide> def prepare_led_inputs_dict( <ide> decoder_input_ids, <ide> attention_mask=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> ): <ide> if attention_mask is None: <ide> attention_mask = tf.cast(tf.math.not_equal(input_ids, config.pad_token_id), tf.int8) <ide> def prepare_led_inputs_dict( <ide> ], <ide> axis=-1, <ide> ) <add> if head_mask is None: <add> head_mask = tf.ones((config.encoder_layers, config.encoder_attention_heads)) <add> if decoder_head_mask is None: <add> decoder_head_mask = tf.ones((config.decoder_layers, config.decoder_attention_heads)) <ide> return { <ide> "input_ids": input_ids, <ide> "attention_mask": attention_mask, <ide> "decoder_input_ids": decoder_input_ids, <ide> "decoder_attention_mask": decoder_attention_mask, <add> "head_mask": head_mask, <add> "decoder_head_mask": decoder_head_mask, <ide> } <ide> <ide> <ide> class TFLEDModelTest(TFModelTesterMixin, unittest.TestCase): <ide> all_generative_model_classes = (TFLEDForConditionalGeneration,) if is_tf_available() else () <ide> is_encoder_decoder = True <ide> test_pruning = False <del> test_head_masking = False <ide> <ide> def setUp(self): <ide> self.model_tester = TFLEDModelTester(self) <ide><path>tests/test_modeling_tf_longformer.py <ide> class TFLongformerModelTest(TFModelTesterMixin, unittest.TestCase): <ide> if is_tf_available() <ide> else () <ide> ) <del> test_head_masking = False <ide> <ide> def setUp(self): <ide> self.model_tester = TFLongformerModelTester(self) <ide> def test_layer_local_attn(self): <ide> attention_mask = tf.where(tf.range(4)[None, :, None, None] > 1, -10000.0, attention_mask[:, :, None, None]) <ide> is_index_masked = tf.math.less(attention_mask[:, :, 0, 0], 0) <ide> <add> layer_head_mask = None <add> <ide> output_hidden_states = layer( <del> [hidden_states, attention_mask, is_index_masked, is_index_global_attn, is_global_attn] <add> [hidden_states, attention_mask, layer_head_mask, is_index_masked, is_index_global_attn, is_global_attn] <ide> )[0] <ide> <ide> expected_slice = tf.convert_to_tensor( <ide> def test_layer_global_attn(self): <ide> is_index_global_attn = tf.math.greater(attention_mask[:, :, 0, 0], 0) <ide> is_global_attn = tf.math.reduce_any(is_index_global_attn) <ide> <add> layer_head_mask = None <add> <ide> output_hidden_states = layer( <del> [hidden_states, -tf.math.abs(attention_mask), is_index_masked, is_index_global_attn, is_global_attn] <add> [ <add> hidden_states, <add> -tf.math.abs(attention_mask), <add> layer_head_mask, <add> is_index_masked, <add> is_index_global_attn, <add> is_global_attn, <add> ] <ide> )[0] <ide> <ide> self.assertTrue(output_hidden_states.shape, (2, 4, 8)) <ide> def test_layer_attn_probs(self): <ide> is_index_global_attn = tf.math.greater(attention_mask[:, :, 0, 0], 0) <ide> is_global_attn = tf.math.reduce_any(is_index_global_attn) <ide> <add> layer_head_mask = None <add> <ide> output_hidden_states, local_attentions, global_attentions = layer( <del> [hidden_states, -tf.math.abs(attention_mask), is_index_masked, is_index_global_attn, is_global_attn] <add> [ <add> hidden_states, <add> -tf.math.abs(attention_mask), <add> layer_head_mask, <add> is_index_masked, <add> is_index_global_attn, <add> is_global_attn, <add> ] <ide> ) <ide> <ide> self.assertEqual(local_attentions.shape, (2, 4, 2, 8))
4
Javascript
Javascript
fix permanent deopt
d081548858ae2c89e22c6e9a231644fba08e008e
<ide><path>lib/net.js <ide> Socket.prototype.connect = function() { <ide> // TODO(joyeecheung): use destructuring when V8 is fast enough <ide> normalized = normalizeArgs(args); <ide> } <del> const options = normalized[0]; <del> const cb = normalized[1]; <add> var options = normalized[0]; <add> var cb = normalized[1]; <ide> <ide> if (this.write !== Socket.prototype.write) <ide> this.write = Socket.prototype.write;
1
Ruby
Ruby
catch more examples from example_formula
2abd3298f9520b25550b4f5b27884452b4ddec13
<ide><path>Library/Homebrew/cmd/audit.rb <ide> def audit_line(line, lineno) <ide> if line =~ /# PLEASE REMOVE/ <ide> problem "Please remove default template comments" <ide> end <add> if line =~ /# Documentation:/ <add> problem "Please remove default template comments" <add> end <ide> if line =~ /# if this fails, try separate make\/make install steps/ <ide> problem "Please remove default template comments" <ide> end <add> if line =~ /# The url of the archive/ <add> problem "Please remove default template comments" <add> end <add> if line =~ /## Naming --/ <add> problem "Please remove default template comments" <add> end <ide> if line =~ /# if your formula requires any X11\/XQuartz components/ <ide> problem "Please remove default template comments" <ide> end
1
Go
Go
use increment operator
16e850fe3ea42f5103c9a11f3db17d11dc4f6ada
<ide><path>api/server/server.go <ide> func ServeFd(addr string, handle http.Handler) error { <ide> }() <ide> } <ide> <del> for i := 0; i < len(ls); i += 1 { <add> for i := 0; i < len(ls); i++ { <ide> err := <-chErrors <ide> if err != nil { <ide> return err <ide> func ServeApi(job *engine.Job) engine.Status { <ide> }() <ide> } <ide> <del> for i := 0; i < len(protoAddrs); i += 1 { <add> for i := 0; i < len(protoAddrs); i++ { <ide> err := <-chErrors <ide> if err != nil { <ide> return job.Error(err) <ide><path>daemon/graphdriver/devmapper/deviceset.go <ide> func (devices *DeviceSet) waitRemove(devname string) error { <ide> log.Debugf("[deviceset %s] waitRemove(%s)", devices.devicePrefix, devname) <ide> defer log.Debugf("[deviceset %s] waitRemove(%s) END", devices.devicePrefix, devname) <ide> i := 0 <del> for ; i < 1000; i += 1 { <add> for ; i < 1000; i++ { <ide> devinfo, err := getInfo(devname) <ide> if err != nil { <ide> // If there is an error we assume the device doesn't exist. <ide> func (devices *DeviceSet) waitRemove(devname string) error { <ide> // or b) the 10 second timeout expires. <ide> func (devices *DeviceSet) waitClose(info *DevInfo) error { <ide> i := 0 <del> for ; i < 1000; i += 1 { <add> for ; i < 1000; i++ { <ide> devinfo, err := getInfo(info.Name()) <ide> if err != nil { <ide> return err <ide><path>pkg/httputils/resumablerequestreader.go <ide> func (r *resumableRequestReader) Read(p []byte) (n int, err error) { <ide> } <ide> if err != nil && r.failures+1 != r.maxFailures { <ide> r.cleanUpResponse() <del> r.failures += 1 <add> r.failures++ <ide> time.Sleep(5 * time.Duration(r.failures) * time.Second) <ide> return 0, nil <ide> } else if err != nil {
3
PHP
PHP
apply fixes from styleci
44958f04b0c3eacd8ebc8b19602511438f7fbbec
<ide><path>src/Illuminate/Mail/Mailer.php <ide> <ide> namespace Illuminate\Mail; <ide> <del>use Closure; <ide> use Swift_Mailer; <ide> use Swift_Message; <ide> use Illuminate\Support\Arr; <ide> protected function setGlobalTo($message) <ide> public function queue($view, array $data = [], $callback = null, $queue = null) <ide> { <ide> if (! $view instanceof MailableContract) { <del> throw new InvalidArgumentException("Only mailables may be queued."); <add> throw new InvalidArgumentException('Only mailables may be queued.'); <ide> } <ide> <ide> return $view->queue($this->queue); <ide> public function queueOn($queue, $view, array $data, $callback) <ide> public function later($delay, $view, array $data = [], $callback = null, $queue = null) <ide> { <ide> if (! $view instanceof MailableContract) { <del> throw new InvalidArgumentException("Only mailables may be queued."); <add> throw new InvalidArgumentException('Only mailables may be queued.'); <ide> } <ide> <ide> return $view->later($delay, $this->queue); <ide><path>src/Illuminate/Mail/Transport/MailgunTransport.php <ide> namespace Illuminate\Mail\Transport; <ide> <ide> use Swift_Mime_Message; <del>use GuzzleHttp\Post\PostFile; <ide> use GuzzleHttp\ClientInterface; <ide> <ide> class MailgunTransport extends Transport <ide> protected function payload(Swift_Mime_Message $message) <ide> { <ide> return [ <ide> 'auth' => [ <del> 'api' => $this->key <add> 'api' => $this->key, <ide> ], <ide> 'multipart' => [ <ide> [ <ide> protected function payload(Swift_Mime_Message $message) <ide> [ <ide> 'name' => 'message', <ide> 'contents' => $message->toString(), <del> 'filename' => 'message.mime' <add> 'filename' => 'message.mime', <ide> ], <ide> ], <ide> ];
2
Text
Text
add changelog for rake routes default fix
6d9ad0dd921e3368b64910c5aeebb880bc8c41a3
<ide><path>actionpack/CHANGELOG.md <add>* Fix rake routes not showing the right format when <add> nesting multiple routes. <add> <add> See #18373. <add> <add> *Ravil Bayramgalin* <add> <ide> * Add ability to override default form builder for a controller. <ide> <ide> class AdminController < ApplicationController
1
Text
Text
add import to example in api-guide/parsers
4249245123f2bae425363292de689bd291d0573b
<ide><path>docs/api-guide/parsers.md <ide> Or, if you're using the `@api_view` decorator with function based views. <ide> <ide> from rest_framework.decorators import api_view <ide> from rest_framework.decorators import parser_classes <add> from rest_framework.parsers import JSONParser <ide> <ide> @api_view(['POST']) <ide> @parser_classes((JSONParser,))
1
Javascript
Javascript
remove debug statement
0689793ef81b546d225d198ff2183d95bc22af07
<ide><path>controllers/challenges.js <ide> var highestChallengeNumber = 53; <ide> <ide> exports.returnChallenge = function(req, res, next) { <ide> var challengeNumber = parseInt(req.params.challengeNumber) || 0; <del> debug(challengeNumber); <ide> if (challengeNumber > highestChallengeNumber) { <ide> req.flash('errors', { <ide> msg: "It looks like you've either completed all the challenges we have available or requested a challenge we don't have."
1
Go
Go
fix typo in overlay log message
01688ba25352a6627fb9054f9180ee12bdb1b0c2
<ide><path>libnetwork/drivers/overlay/ov_network.go <ide> func setDefaultVlan() { <ide> data := []byte{'0', '\n'} <ide> <ide> if err = ioutil.WriteFile(path, data, 0644); err != nil { <del> logrus.Errorf("endbling default vlan on bridge %s failed %v", brName, err) <add> logrus.Errorf("enabling default vlan on bridge %s failed %v", brName, err) <ide> os.Exit(1) <ide> } <ide> os.Exit(0)
1
Python
Python
update conv1d input_shape description
b9a74813081303399e8fce0f9f5f37f6a8343b03
<ide><path>keras/layers/convolutional.py <ide> class Conv1D(_Conv): <ide> it is applied to the outputs as well. <ide> <ide> When using this layer as the first layer in a model, <del> provide an `input_shape` argument <del> (tuple of integers or `None`, e.g. <del> `(10, 128)` for sequences of 10 vectors of 128-dimensional vectors, <del> or `(None, 128)` for variable-length sequences of 128-dimensional vectors. <add> provide an `input_shape` argument (tuple of integers or `None`, does not <add> include the batch axis), e.g. `input_shape=(10, 128)` for time series <add> sequences of 10 time steps with 128 features per step in <add> `data_format="channels_last"`, or `(None, 128)` for variable-length <add> sequences with 128 features per step. <ide> <ide> # Arguments <ide> filters: Integer, the dimensionality of the output space <ide> class Conv2D(_Conv): <ide> <ide> When using this layer as the first layer in a model, <ide> provide the keyword argument `input_shape` <del> (tuple of integers, does not include the sample axis), <add> (tuple of integers, does not include the batch axis), <ide> e.g. `input_shape=(128, 128, 3)` for 128x128 RGB pictures <ide> in `data_format="channels_last"`. <ide> <ide> class Conv3D(_Conv): <ide> <ide> When using this layer as the first layer in a model, <ide> provide the keyword argument `input_shape` <del> (tuple of integers, does not include the sample axis), <add> (tuple of integers, does not include the batch axis), <ide> e.g. `input_shape=(128, 128, 128, 1)` for 128x128x128 volumes <ide> with a single channel, <ide> in `data_format="channels_last"`. <ide> class Conv2DTranspose(Conv2D): <ide> <ide> When using this layer as the first layer in a model, <ide> provide the keyword argument `input_shape` <del> (tuple of integers, does not include the sample axis), <add> (tuple of integers, does not include the batch axis), <ide> e.g. `input_shape=(128, 128, 3)` for 128x128 RGB pictures <ide> in `data_format="channels_last"`. <ide> <ide> class Conv3DTranspose(Conv3D): <ide> <ide> When using this layer as the first layer in a model, <ide> provide the keyword argument `input_shape` <del> (tuple of integers, does not include the sample axis), <add> (tuple of integers, does not include the batch axis), <ide> e.g. `input_shape=(128, 128, 128, 3)` for a 128x128x128 volume with 3 channels <ide> if `data_format="channels_last"`. <ide>
1
Javascript
Javascript
add support for oncancel and onclose event
d8450845fe735b407133b1b3aa6a87e7c45679d5
<ide><path>src/renderers/dom/shared/ReactBrowserEventEmitter.js <ide> var topEventMapping = { <ide> topAnimationIteration: getVendorPrefixedEventName('animationiteration') || 'animationiteration', <ide> topAnimationStart: getVendorPrefixedEventName('animationstart') || 'animationstart', <ide> topBlur: 'blur', <add> topCancel: 'cancel', <ide> topCanPlay: 'canplay', <ide> topCanPlayThrough: 'canplaythrough', <ide> topChange: 'change', <ide> topClick: 'click', <add> topClose: 'close', <ide> topCompositionEnd: 'compositionend', <ide> topCompositionStart: 'compositionstart', <ide> topCompositionUpdate: 'compositionupdate', <ide> var ReactBrowserEventEmitter = Object.assign({}, ReactEventEmitterMixin, { <ide> // to make sure blur and focus event listeners are only attached once <ide> isListening.topBlur = true; <ide> isListening.topFocus = true; <add> } else if (dependency === 'topCancel') { <add> if (isEventSupported('cancel', true)) { <add> ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( <add> 'topCancel', <add> 'cancel', <add> mountAt <add> ); <add> } <add> isListening.topCancel = true; <add> } else if (dependency === 'topClose') { <add> if (isEventSupported('close', true)) { <add> ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( <add> 'topClose', <add> 'close', <add> mountAt <add> ); <add> } <add> isListening.topClose = true; <ide> } else if (topEventMapping.hasOwnProperty(dependency)) { <ide> ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( <ide> dependency, <ide><path>src/renderers/dom/shared/eventPlugins/SimpleEventPlugin.js <ide> var topLevelEventsToDispatchConfig: {[key: TopLevelTypes]: DispatchConfig} = {}; <ide> 'animationIteration', <ide> 'animationStart', <ide> 'blur', <add> 'cancel', <ide> 'canPlay', <ide> 'canPlayThrough', <ide> 'click', <add> 'close', <ide> 'contextMenu', <ide> 'copy', <ide> 'cut', <ide> var SimpleEventPlugin: PluginModule<MouseEvent> = { <ide> var EventConstructor; <ide> switch (topLevelType) { <ide> case 'topAbort': <add> case 'topCancel': <ide> case 'topCanPlay': <ide> case 'topCanPlayThrough': <add> case 'topClose': <ide> case 'topDurationChange': <ide> case 'topEmptied': <ide> case 'topEncrypted': <ide><path>src/renderers/shared/shared/event/EventConstants.js <ide> var topLevelTypes = { <ide> topAnimationIteration: null, <ide> topAnimationStart: null, <ide> topBlur: null, <add> topCancel: null, <ide> topCanPlay: null, <ide> topCanPlayThrough: null, <ide> topChange: null, <ide> topClick: null, <add> topClose: null, <ide> topCompositionEnd: null, <ide> topCompositionStart: null, <ide> topCompositionUpdate: null,
3
Javascript
Javascript
remove three. prefix from vector3
c24eed3903ba6841eedb1ac3976e2ed21cc26297
<ide><path>src/materials/MeshDistanceMaterial.js <ide> import { Material } from './Material'; <add>import { Vector3 } from '../math/Vector3.js'; <ide> <ide> /** <ide> * @author WestLangley / http://github.com/WestLangley <ide> function MeshDistanceMaterial( parameters ) { <ide> <ide> this.type = 'MeshDistanceMaterial'; <ide> <del> this.referencePosition = new THREE.Vector3(); <add> this.referencePosition = new Vector3(); <ide> this.nearDistance = 1; <ide> this.farDistance = 1000; <ide>
1
PHP
PHP
move extension parsing
3849dcef9a7288741ae9f13af098d656b65d0ec9
<ide><path>lib/Cake/Routing/Route/Route.php <ide> class Route { <ide> 'server' => 'server_name' <ide> ); <ide> <add>/** <add> * List of connected extensions for this route. <add> * <add> * @var array <add> */ <add> protected $_extensions = array(); <add> <ide> /** <ide> * Constructor for a Route <ide> * <del> * Using $options['_name'] a specific name can be given to a route. <del> * Otherwise a route name will be generated. <add> * ### Options <add> * <add> * - `_name` - By using $options['_name'] a specific name can be <add> * given to a route. Otherwise a route name will be generated. <add> * - `_ext` - Defines the extensions used for this route. <add> * - `pass` - Copies the listed parameters into params['pass']. <ide> * <ide> * @param string $template Template string with parameter placeholders <ide> * @param array $defaults Array of defaults for the route. <ide> public function __construct($template, $defaults = array(), $options = array()) <ide> if (isset($this->options['_name'])) { <ide> $this->_name = $this->options['_name']; <ide> } <add> if (isset($this->options['_ext'])) { <add> $this->_extensions = $this->options['_ext']; <add> } <ide> } <ide> <ide> /** <ide> public function parse($url) { <ide> if (!$this->compiled()) { <ide> $this->compile(); <ide> } <add> list($url, $ext) = $this->_parseExtension($url); <add> <ide> if (!preg_match($this->_compiledRoute, $url, $route)) { <ide> return false; <ide> } <ide> public function parse($url) { <ide> unset($route['_trailing_']); <ide> } <ide> <add> if ($ext && empty($route['_ext'])) { <add> $route['_ext'] = $ext; <add> } <add> <ide> // restructure 'pass' key route params <ide> if (isset($this->options['pass'])) { <ide> $j = count($this->options['pass']); <ide> public function parse($url) { <ide> return $route; <ide> } <ide> <add>/** <add> * Removes the extension if the $url contains a known extension. <add> * If there are no known extensions all extensions are supported. <add> * <add> * @param string $url The url to parse. <add> * @return array containing url, extension <add> */ <add> protected function _parseExtension($url) { <add> if (empty($this->_extensions)) { <add> return array($url, null); <add> } <add> preg_match('/\.([0-9a-z]*)$/', $url, $match); <add> if (empty($match[1])) { <add> return array($url, null); <add> } <add> $ext = strtolower($match[1]); <add> $len = strlen($match[1]); <add> foreach ($this->_extensions as $name) { <add> if (strtolower($name) === $ext) { <add> $url = substr($url, 0, ($len + 1) * -1); <add> return array($url, $ext); <add> } <add> } <add> return array($url, null); <add> } <add> <ide> /** <ide> * Parse passed parameters into a list of passed args. <ide> * <ide><path>lib/Cake/Routing/Router.php <ide> public static function resourceMap($resourceMap = null) { <ide> /** <ide> * Connects a new Route in the router. <ide> * <del> * Routes are a way of connecting request urls to objects in your application. At their core routes <del> * are a set or regular expressions that are used to match requests to destinations. <add> * Routes are a way of connecting request urls to objects in your application. <add> * At their core routes are a set or regular expressions that are used to <add> * match requests to destinations. <ide> * <ide> * Examples: <ide> * <ide> * `Router::connect('/:controller/:action/*');` <ide> * <del> * The first parameter will be used as a controller name while the second is used as the action name. <del> * the '/*' syntax makes this route greedy in that it will match requests like `/posts/index` as well as requests <add> * The first parameter will be used as a controller name while the second is <add> * used as the action name. The '/*' syntax makes this route greedy in that <add> * it will match requests like `/posts/index` as well as requests <ide> * like `/posts/edit/1/foo/bar`. <ide> * <ide> * `Router::connect('/home-page', array('controller' => 'pages', 'action' => 'display', 'home'));` <ide> * <del> * The above shows the use of route parameter defaults. And providing routing parameters for a static route. <add> * The above shows the use of route parameter defaults. And providing routing <add> * parameters for a static route. <ide> * <ide> * {{{ <ide> * Router::connect( <ide> public static function resourceMap($resourceMap = null) { <ide> * ); <ide> * }}} <ide> * <del> * Shows connecting a route with custom route parameters as well as providing patterns for those parameters. <del> * Patterns for routing parameters do not need capturing groups, as one will be added for each route params. <add> * Shows connecting a route with custom route parameters as well as <add> * providing patterns for those parameters. Patterns for routing parameters <add> * do not need capturing groups, as one will be added for each route params. <ide> * <del> * $options offers several 'special' keys that have special meaning in the $options array. <add> * $options offers several 'special' keys that have special meaning <add> * in the $options array. <ide> * <del> * - `pass` is used to define which of the routed parameters should be shifted into the pass array. Adding a <del> * parameter to pass will remove it from the regular route array. Ex. `'pass' => array('slug')` <del> * - `routeClass` is used to extend and change how individual routes parse requests and handle reverse routing, <del> * via a custom routing class. Ex. `'routeClass' => 'SlugRoute'` <del> * - `_name` Used to define a specific name for routes. This can be used to optimize reverse routing lookups. <del> * If undefined a name will be generated for each connected route. <add> * - `pass` is used to define which of the routed parameters should be shifted <add> * into the pass array. Adding a parameter to pass will remove it from the <add> * regular route array. Ex. `'pass' => array('slug')`. <add> * - `routeClass` is used to extend and change how individual routes parse requests <add> * and handle reverse routing, via a custom routing class. <add> * Ex. `'routeClass' => 'SlugRoute'` <add> * - `_name` Used to define a specific name for routes. This can be used to optimize <add> * reverse routing lookups. If undefined a name will be generated for each <add> * connected route. <ide> * <ide> * @param string $route A string describing the template of the route <ide> * @param array $defaults An array describing the default route parameters. These parameters will be used by default <ide> public static function connect($route, $defaults = array(), $options = array()) <ide> if (empty($options['action'])) { <ide> $defaults += array('action' => 'index'); <ide> } <add> if (empty($options['_ext'])) { <add> $options['_ext'] = self::$_validExtensions; <add> } <ide> $routeClass = static::$_routeClass; <ide> if (isset($options['routeClass'])) { <ide> $routeClass = static::_validateRouteClass($options['routeClass']); <ide> public static function parse($url) { <ide> $url = substr($url, 0, strpos($url, '?')); <ide> } <ide> <add><<<<<<< HEAD <ide> extract(static::_parseExtension($url)); <ide> <ide> $out = static::$_routes->parse($url); <add>======= <add> $out = self::$_routes->parse($url); <add>>>>>>>> Move extension parsing. <ide> <ide> if (isset($out['prefix'])) { <ide> $out['action'] = $out['prefix'] . '_' . $out['action']; <ide> } <ide> <del> if (!empty($ext) && !isset($out['ext'])) { <del> $out['ext'] = $ext; <del> } <ide> return $out; <ide> } <ide> <ide> /** <add><<<<<<< HEAD <ide> * Parses a file extension out of a URL, if Router::parseExtensions() is enabled. <ide> * <ide> * @param string $url <ide> protected static function _parseExtension($url) { <ide> } <ide> <ide> /** <add>======= <add>>>>>>>> Move extension parsing. <ide> * Set the route collection object Router should use. <ide> * <ide> * @param Cake\Routing\RouteCollection $routes <ide> public static function normalize($url = '/') { <ide> * Instructs the router to parse out file extensions from the URL. For example, <ide> * http://example.com/posts.rss would yield an file extension of "rss". <ide> * The file extension itself is made available in the controller as <del> * `$this->params['ext']`, and is used by the RequestHandler component to <add> * `$this->params['_ext']`, and is used by the RequestHandler component to <ide> * automatically switch to alternate layouts and templates, and load helpers <ide> * corresponding to the given content, i.e. RssHelper. Switching layouts and helpers <ide> * requires that the chosen extension has a defined mime type in `Cake\Network\Response` <ide><path>lib/Cake/Test/TestCase/Routing/Route/RouteTest.php <ide> public function testBasicRouteCompiling() { <ide> $this->assertRegExp($result, '/test_plugin/posts/edit/5/name:value/nick:name'); <ide> } <ide> <add>/** <add> * Test parsing routes with extensions. <add> * <add> * @return void <add> */ <add> public function testRouteParsingWithExtensions() { <add> $route = new Route( <add> '/:controller/:action/*', <add> array(), <add> array('_ext' => array('json', 'xml')) <add> ); <add> <add> $result = $route->parse('/posts/index'); <add> $this->assertFalse(isset($result['_ext'])); <add> <add> $result = $route->parse('/posts/index.pdf'); <add> $this->assertFalse(isset($result['_ext'])); <add> <add> $result = $route->parse('/posts/index.json'); <add> $this->assertEquals('json', $result['_ext']); <add> <add> $result = $route->parse('/posts/index.xml'); <add> $this->assertEquals('xml', $result['_ext']); <add> } <add> <ide> /** <ide> * test that route parameters that overlap don't cause errors. <ide> * <ide><path>lib/Cake/Test/TestCase/Routing/RouterTest.php <ide> public function testUrlGenerationWithAdminPrefix() { <ide> 'plugin' => null, <ide> 'prefix' => 'admin', <ide> 'admin' => true, <del> 'ext' => 'html' <add> '_ext' => 'html' <ide> )); <ide> $request->base = ''; <ide> $request->here = '/admin/registrations/index'; <ide> public function testUrlGenerationWithExtensions() { <ide> Router::connect('/:controller/:action'); <ide> Router::parse('/'); <ide> <del> $result = Router::url(array('plugin' => null, 'controller' => 'articles', 'action' => 'add', 'id' => null, 'ext' => 'json')); <add> $result = Router::url(array('plugin' => null, 'controller' => 'articles', 'action' => 'add', 'id' => null, '_ext' => 'json')); <ide> $expected = '/articles/add.json'; <ide> $this->assertEquals($expected, $result); <ide> <del> $result = Router::url(array('plugin' => null, 'controller' => 'articles', 'action' => 'add', 'ext' => 'json')); <add> $result = Router::url(array('plugin' => null, 'controller' => 'articles', 'action' => 'add', '_ext' => 'json')); <ide> $expected = '/articles/add.json'; <ide> $this->assertEquals($expected, $result); <ide> <del> $result = Router::url(array('plugin' => null, 'controller' => 'articles', 'action' => 'index', 'id' => null, 'ext' => 'json')); <add> $result = Router::url(array('plugin' => null, 'controller' => 'articles', 'action' => 'index', 'id' => null, '_ext' => 'json')); <ide> $expected = '/articles.json'; <ide> $this->assertEquals($expected, $result); <ide> <ide> public function testSetExtensions() { <ide> * @return void <ide> */ <ide> public function testExtensionParsing() { <add> /* <ide> Router::parseExtensions(); <ide> require CAKE . 'Config' . DS . 'routes.php'; <ide> <ide> $result = Router::parse('/posts.rss'); <del> $expected = array('plugin' => null, 'controller' => 'posts', 'action' => 'index', 'ext' => 'rss', 'pass' => array()); <add> $expected = array( <add> 'plugin' => null, <add> 'controller' => 'posts', <add> 'action' => 'index', <add> '_ext' => 'rss', <add> 'pass' => array() <add> ); <ide> $this->assertEquals($expected, $result); <ide> <ide> $result = Router::parse('/posts/view/1.rss'); <del> $expected = array('plugin' => null, 'controller' => 'posts', 'action' => 'view', 'pass' => array('1'), 'ext' => 'rss'); <add> $expected = array( <add> 'plugin' => null, <add> 'controller' => 'posts', <add> 'action' => 'view', <add> 'pass' => array('1'), <add> '_ext' => 'rss' <add> ); <ide> $this->assertEquals($expected, $result); <ide> <ide> $result = Router::parse('/posts/view/1.rss?query=test'); <ide> $this->assertEquals($expected, $result); <ide> <ide> $result = Router::parse('/posts/view/1.atom'); <del> $expected['ext'] = 'atom'; <add> $expected['_ext'] = 'atom'; <ide> $this->assertEquals($expected, $result); <del> <add> */ <ide> Router::reload(); <add> Router::parseExtensions('rss', 'xml'); <add> <ide> require CAKE . 'Config' . DS . 'routes.php'; <ide> <del> Router::parseExtensions('rss', 'xml'); <ide> <ide> $result = Router::parse('/posts.xml'); <del> $expected = array('plugin' => null, 'controller' => 'posts', 'action' => 'index', 'ext' => 'xml', 'pass' => array()); <add> $expected = array( <add> 'plugin' => null, <add> 'controller' => 'posts', <add> 'action' => 'index', <add> '_ext' => 'xml', <add> 'pass' => array() <add> ); <ide> $this->assertEquals($expected, $result); <ide> <ide> $result = Router::parse('/posts.atom?hello=goodbye'); <del> $expected = array('plugin' => null, 'controller' => 'posts.atom', 'action' => 'index', 'pass' => array()); <add> $expected = array( <add> 'plugin' => null, <add> 'controller' => 'posts.atom', <add> 'action' => 'index', <add> 'pass' => array() <add> ); <ide> $this->assertEquals($expected, $result); <ide> <ide> Router::reload(); <del> Router::connect('/controller/action', array('controller' => 'controller', 'action' => 'action', 'ext' => 'rss')); <add> Router::connect('/controller/action', array('controller' => 'controller', 'action' => 'action', '_ext' => 'rss')); <ide> $result = Router::parse('/controller/action'); <del> $expected = array('controller' => 'controller', 'action' => 'action', 'plugin' => null, 'ext' => 'rss', 'pass' => array()); <add> $expected = array( <add> 'controller' => 'controller', <add> 'action' => 'action', <add> 'plugin' => null, <add> '_ext' => 'rss', <add> 'pass' => array() <add> ); <ide> $this->assertEquals($expected, $result); <ide> <ide> Router::reload(); <ide> Router::parseExtensions('rss'); <del> Router::connect('/controller/action', array('controller' => 'controller', 'action' => 'action', 'ext' => 'rss')); <add> Router::connect('/controller/action', array('controller' => 'controller', 'action' => 'action', '_ext' => 'rss')); <ide> $result = Router::parse('/controller/action'); <del> $expected = array('controller' => 'controller', 'action' => 'action', 'plugin' => null, 'ext' => 'rss', 'pass' => array()); <add> $expected = array( <add> 'controller' => 'controller', <add> 'action' => 'action', <add> 'plugin' => null, <add> '_ext' => 'rss', <add> 'pass' => array() <add> ); <ide> $this->assertEquals($expected, $result); <ide> } <ide>
4
Javascript
Javascript
add rfc 232 mocha mixin blueprint
95cb1d274c1cda6f9ee2e68d99a03dfe7b0449f6
<ide><path>blueprints/mixin-test/mocha-rfc-232-files/__root__/__testType__/__name__-test.js <add>import { expect } from 'chai'; <add>import { describe, it } from 'mocha'; <add>import EmberObject from '@ember/object'; <add>import <%= classifiedModuleName %>Mixin from '<%= dasherizedPackageName %>/mixins/<%= dasherizedModuleName %>'; <add> <add>describe('<%= friendlyTestName %>', function() { <add> // Replace this with your real tests. <add> it('works', function() { <add> let <%= classifiedModuleName %>Object = EmberObject.extend(<%= classifiedModuleName %>Mixin); <add> let subject = <%= classifiedModuleName %>Object.create(); <add> expect(subject).to.be.ok; <add> }); <add>}); <ide><path>node-tests/blueprints/mixin-test-test.js <ide> describe('Blueprint: mixin-test', function() { <ide> }); <ide> }); <ide> }); <add> <add> describe('with ember-mocha@0.14.0', function() { <add> beforeEach(function() { <add> modifyPackages([ <add> { name: 'ember-cli-qunit', delete: true }, <add> { name: 'ember-mocha', dev: true }, <add> ]); <add> generateFakePackageManifest('ember-mocha', '0.14.0'); <add> }); <add> <add> it('mixin-test foo', function() { <add> return emberGenerateDestroy(['mixin-test', 'foo'], _file => { <add> expect(_file('tests/unit/mixins/foo-test.js')).to.equal( <add> fixture('mixin-test/mocha-rfc232.js') <add> ); <add> }); <add> }); <add> }); <ide> }); <ide> <ide> describe('in app - module unification', function() { <ide><path>node-tests/fixtures/mixin-test/mocha-rfc232.js <add>import { expect } from 'chai'; <add>import { describe, it } from 'mocha'; <add>import EmberObject from '@ember/object'; <add>import FooMixin from 'my-app/mixins/foo'; <add> <add>describe('Unit | Mixin | foo', function() { <add> // Replace this with your real tests. <add> it('works', function() { <add> let FooObject = EmberObject.extend(FooMixin); <add> let subject = FooObject.create(); <add> expect(subject).to.be.ok; <add> }); <add>});
3
Ruby
Ruby
use request.body io and rewind, if possible
3957d44fd10c683518562f22d8b73f1b1c3d455d
<ide><path>actionpack/lib/action_dispatch/middleware/params_parser.rb <ide> def parse_formatted_parameters(env) <ide> when Proc <ide> strategy.call(request.raw_post) <ide> when :xml_simple, :xml_node <del> (Hash.from_xml(request.raw_post) || {}).with_indifferent_access <add> data = Hash.from_xml(request.body) || {} <add> request.body.rewind if request.body.respond_to?(:rewind) <add> data.with_indifferent_access <ide> when :yaml <ide> YAML.load(request.raw_post) <ide> when :json <del> data = ActiveSupport::JSON.decode(request.raw_post) <add> data = ActiveSupport::JSON.decode(request.body) <add> request.body.rewind if request.body.respond_to?(:rewind) <ide> data = {:_json => data} unless data.is_a?(Hash) <ide> data.with_indifferent_access <ide> else <ide> def logger <ide> defined?(Rails.logger) ? Rails.logger : Logger.new($stderr) <ide> end <ide> end <del>end <ide>\ No newline at end of file <add>end
1
Ruby
Ruby
drop array allocations on `html_safe`
783858c8e150eb0f98d7e5d893e492ee08998662
<ide><path>activesupport/lib/active_support/core_ext/string/output_safety.rb <ide> def safe_concat(value) <ide> original_concat(value) <ide> end <ide> <del> def initialize(*) <add> def initialize(str = '') <ide> @html_safe = true <ide> super <ide> end
1
Go
Go
remove redundant sync.once
350fadbdd4acaa40e5c0f92189db42b430dd755d
<ide><path>rootless/rootless.go <ide> package rootless // import "github.com/docker/docker/rootless" <ide> import ( <ide> "os" <ide> "path/filepath" <del> "sync" <ide> <ide> "github.com/pkg/errors" <ide> "github.com/rootless-containers/rootlesskit/pkg/api/client" <ide> ) <ide> <del>const ( <del> // RootlessKitDockerProxyBinary is the binary name of rootlesskit-docker-proxy <del> RootlessKitDockerProxyBinary = "rootlesskit-docker-proxy" <del>) <del> <del>var ( <del> runningWithRootlessKit bool <del> runningWithRootlessKitOnce sync.Once <del>) <add>// RootlessKitDockerProxyBinary is the binary name of rootlesskit-docker-proxy <add>const RootlessKitDockerProxyBinary = "rootlesskit-docker-proxy" <ide> <ide> // RunningWithRootlessKit returns true if running under RootlessKit namespaces. <ide> func RunningWithRootlessKit() bool { <del> runningWithRootlessKitOnce.Do(func() { <del> u := os.Getenv("ROOTLESSKIT_STATE_DIR") <del> runningWithRootlessKit = u != "" <del> }) <del> return runningWithRootlessKit <add> return os.Getenv("ROOTLESSKIT_STATE_DIR") != "" <ide> } <ide> <ide> // GetRootlessKitClient returns RootlessKit client
1
PHP
PHP
remove pointless @package tag
e73b45464856b36b9f7801b8808c15a712221ca0
<ide><path>lib/Cake/Model/Datasource/Database/Type/DateTimeType.php <ide> * <ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * @link http://cakephp.org CakePHP(tm) Project <del> * @package Cake.Model <ide> * @since CakePHP(tm) v 3.0.0 <ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <ide> */
1
PHP
PHP
add tests for save() and multiple locales
83abced287feba5e94551a82657b9143fe82cecd
<ide><path>lib/Cake/Test/Case/Model/Behavior/TranslateBehaviorTest.php <ide> public function testSaveCreate() { <ide> $this->assertEquals($expected, $result); <ide> } <ide> <add>/** <add> * test save multiple locales method <add> * <add> * @return void <add> */ <add> public function testSaveMultipleLocales() { <add> $this->loadFixtures('Translate', 'TranslatedItem'); <add> <add> $TestModel = new TranslatedItem(); <add> $data = array( <add> 'slug' => 'fourth_translated', <add> 'title' => array( <add> 'eng' => 'Title #4', <add> 'spa' => 'Leyenda #4', <add> ), <add> 'content' => array( <add> 'eng' => 'Content #4', <add> 'spa' => 'Contenido #4', <add> ), <add> 'translated_article_id' => 1, <add> ); <add> $TestModel->create(); <add> $TestModel->save($data); <add> <add> $translations = array('title' => 'Title', 'content' => 'Content'); <add> $TestModel->bindTranslation($translations, false); <add> $TestModel->locale = array('eng', 'spa'); <add> $result = $TestModel->read(); <add> <add> $this->assertCount(2, $result['Title']); <add> $this->assertEquals($result['Title'][0]['locale'], 'eng'); <add> $this->assertEquals($result['Title'][0]['content'], 'Title #4'); <add> $this->assertEquals($result['Title'][1]['locale'], 'spa'); <add> $this->assertEquals($result['Title'][1]['content'], 'Leyenda #4'); <add> <add> $this->assertCount(2, $result['Content']); <add> } <add> <ide> /** <ide> * testSaveAssociatedCreate method <ide> *
1
Text
Text
add link on logo to readme
71704fbc96ae1cd06aff1aec12421c3f4620d806
<ide><path>README.md <ide> <p align="center"> <del> <img alt="Node.js" src="https://nodejs.org/static/images/logo-light.svg" width="400"/> <add> <a href="https://nodejs.org/"> <add> <img alt="Node.js" src="https://nodejs.org/static/images/logo-light.svg" width="400"/> <add> </a> <ide> </p> <ide> <p align="center"> <ide> <a title="Gitter" href="https://gitter.im/nodejs/node?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge"><img src="https://badges.gitter.im/Join%20Chat.svg"></a>
1
Ruby
Ruby
use opt_prefix when available
e07a587f42abcf107866f0937643b1a261adf185
<ide><path>Library/Homebrew/cmd/--prefix.rb <ide> def __prefix <ide> if ARGV.named.empty? <ide> puts HOMEBREW_PREFIX <ide> else <del> puts ARGV.resolved_formulae.map(&:installed_prefix) <add> puts ARGV.resolved_formulae.map { |f| <add> f.opt_prefix.exist? ? f.opt_prefix : f.installed_prefix <add> } <ide> end <ide> end <ide> end
1
Ruby
Ruby
add missing root mkpath
d78dc014d14bf2619d3ae3e985373aff393e67e0
<ide><path>Library/Homebrew/github_packages.rb <ide> def upload_bottle(user, token, skopeo, formula_full_name, bottle_hash, keep_old: <ide> <ide> root = Pathname("#{formula_name}--#{version_rebuild}") <ide> FileUtils.rm_rf root <add> root.mkpath <ide> <ide> if keep_old <ide> download(user, token, skopeo, image_uri, root, dry_run: dry_run)
1
Python
Python
show more task info
6b1ef78d21e1a6c13018b5b7a589f48bc451515a
<ide><path>celery/events/cursesmon.py <ide> def draw(self): <ide> except KeyError: <ide> pass <ide> else: <del> info = selection.info(['args', 'kwargs', <del> 'result', 'runtime', 'eta']) <add> info = selection.info() <ide> if 'runtime' in info: <ide> info['runtime'] = '%.2fs' % info['runtime'] <ide> if 'result' in info: <ide><path>celery/events/state.py <ide> class Task(Element): <ide> <ide> #: meth:`info` displays these fields by default. <ide> _info_fields = ('args', 'kwargs', 'retries', 'result', <del> 'eta', 'runtime', 'expires', 'exception') <add> 'eta', 'runtime', 'expires', 'exception', <add> 'exchange', 'routing_key') <ide> <ide> #: Default values. <ide> _defaults = dict(uuid=None, name=None, state=states.PENDING, <ide> class Task(Element): <ide> revoked=False, args=None, kwargs=None, eta=None, <ide> expires=None, retries=None, worker=None, result=None, <ide> exception=None, timestamp=None, runtime=None, <del> traceback=None) <add> traceback=None, exchange=None, routing_key=None) <ide> <ide> def __init__(self, **fields): <ide> super(Task, self).__init__(**dict(self._defaults, **fields)) <ide> def on_unknown_event(self, type, timestamp=None, **fields): <ide> <ide> def info(self, fields=None, extra=[]): <ide> """Information about this task suitable for on-screen display.""" <del> if fields is None: <del> fields = self._info_fields <del> return dict((key, getattr(self, key, None)) <del> for key in list(fields) + list(extra) <del> if getattr(self, key, None) is not None) <add> fields = self._info_fields if fields is None else fields <add> <add> def _keys(): <add> for key in list(fields) + list(extra): <add> value = getattr(self, key, None) <add> if value is not None: <add> yield key, value <add> <add> return dict(_keys()) <ide> <ide> def __repr__(self): <ide> return '<Task: %s(%s) %s>' % (self.name, self.uuid, self.state)
2