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 |
|---|---|---|---|---|---|
Ruby | Ruby | remove unnecessary lasgn | 2a5218dacc4bc6ef574279d5ddf069c33b8b3802 | <ide><path>Library/Homebrew/build.rb
<ide> def detect_stdlibs
<ide> # of software installs an executable that links against libstdc++
<ide> # and dylibs against libc++, libc++-only dependencies can safely
<ide> # link against it.
<del> stdlibs = keg.detect_cxx_stdlibs :skip_executables => true
<add> keg.detect_cxx_stdlibs(:skip_executables => true)
<ide> end
<ide>
<ide> def fixopt f | 1 |
Javascript | Javascript | allow circular references | d3aafd02efd3a403d646a3044adcf14e63a88d32 | <ide><path>lib/assert.js
<ide> assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
<ide> }
<ide> };
<ide>
<del>function _deepEqual(actual, expected, strict) {
<add>function _deepEqual(actual, expected, strict, memos) {
<ide> // 7.1. All identical values are equivalent, as determined by ===.
<ide> if (actual === expected) {
<ide> return true;
<ide> function _deepEqual(actual, expected, strict) {
<ide> // corresponding key, and an identical 'prototype' property. Note: this
<ide> // accounts for both named and indexed properties on Arrays.
<ide> } else {
<del> return objEquiv(actual, expected, strict);
<add> memos = memos || {actual: [], expected: []};
<add>
<add> const actualIndex = memos.actual.indexOf(actual);
<add> if (actualIndex !== -1) {
<add> if (actualIndex === memos.expected.indexOf(expected)) {
<add> return true;
<add> }
<add> }
<add>
<add> memos.actual.push(actual);
<add> memos.expected.push(expected);
<add>
<add> return objEquiv(actual, expected, strict, memos);
<ide> }
<ide> }
<ide>
<ide> function isArguments(object) {
<ide> return Object.prototype.toString.call(object) == '[object Arguments]';
<ide> }
<ide>
<del>function objEquiv(a, b, strict) {
<add>function objEquiv(a, b, strict, actualVisitedObjects) {
<ide> if (a === null || a === undefined || b === null || b === undefined)
<ide> return false;
<ide> // if one is a primitive, the other must be same
<ide> function objEquiv(a, b, strict) {
<ide> //~~~possibly expensive deep test
<ide> for (i = ka.length - 1; i >= 0; i--) {
<ide> key = ka[i];
<del> if (!_deepEqual(a[key], b[key], strict)) return false;
<add> if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
<add> return false;
<ide> }
<ide> return true;
<ide> }
<ide><path>test/parallel/test-assert.js
<ide> try {
<ide>
<ide> assert.ok(threw);
<ide>
<del>// GH-207. Make sure deepEqual doesn't loop forever on circular refs
<del>var b = {};
<del>b.b = b;
<add>// https://github.com/nodejs/node/issues/6416
<add>// Make sure circular refs don't throw.
<add>{
<add> const b = {};
<add> b.b = b;
<ide>
<del>var c = {};
<del>c.b = c;
<add> const c = {};
<add> c.b = c;
<ide>
<del>var gotError = false;
<del>try {
<del> assert.deepEqual(b, c);
<del>} catch (e) {
<del> gotError = true;
<del>}
<add> a.doesNotThrow(makeBlock(a.deepEqual, b, c));
<add> a.doesNotThrow(makeBlock(a.deepStrictEqual, b, c));
<ide>
<add> const d = {};
<add> d.a = 1;
<add> d.b = d;
<add>
<add> const e = {};
<add> e.a = 1;
<add> e.b = e.a;
<add>
<add> a.throws(makeBlock(a.deepEqual, d, e), /AssertionError/);
<add> a.throws(makeBlock(a.deepStrictEqual, d, e), /AssertionError/);
<add>}
<ide> // GH-7178. Ensure reflexivity of deepEqual with `arguments` objects.
<ide> var args = (function() { return arguments; })();
<ide> a.throws(makeBlock(a.deepEqual, [], args));
<ide> a.throws(makeBlock(a.deepEqual, args, []));
<del>assert.ok(gotError);
<ide>
<ide>
<ide> var circular = {y: 1}; | 2 |
Javascript | Javascript | improve tab completion coverage | 68e6673224365120f50286169148539c7043efd8 | <ide><path>test/parallel/test-readline-tab-complete.js
<ide> common.skipIfDumbTerminal();
<ide> const width = getStringWidth(char) - 1;
<ide>
<ide> class FakeInput extends EventEmitter {
<del> columns = ((width + 1) * 10 + (lineBreak ? 0 : 10)) * 3
<add> columns = ((width + 1) * 10 + (lineBreak ? 0 : 10)) * 3
<ide>
<del> write = common.mustCall((data) => {
<del> output += data;
<del> }, 6)
<add> write = common.mustCall((data) => {
<add> output += data;
<add> }, 6)
<ide>
<del> resume() {}
<del> pause() {}
<del> end() {}
<add> resume() {}
<add> pause() {}
<add> end() {}
<ide> }
<ide>
<ide> const fi = new FakeInput();
<ide> const rli = new readline.Interface({
<ide> input: fi,
<ide> output: fi,
<ide> terminal: true,
<del> completer: completer
<add> completer: common.mustCallAtLeast(completer),
<ide> });
<ide>
<ide> const last = '\r\nFirst group\r\n\r\n' +
<ide> common.skipIfDumbTerminal();
<ide> rli.close();
<ide> });
<ide> });
<add>
<add>{
<add> let output = '';
<add> class FakeInput extends EventEmitter {
<add> columns = 80
<add>
<add> write = common.mustCall((data) => {
<add> output += data;
<add> }, 1)
<add>
<add> resume() {}
<add> pause() {}
<add> end() {}
<add> }
<add>
<add> const fi = new FakeInput();
<add> const rli = new readline.Interface({
<add> input: fi,
<add> output: fi,
<add> terminal: true,
<add> completer:
<add> common.mustCallAtLeast((_, cb) => cb(new Error('message'))),
<add> });
<add>
<add> rli.on('line', common.mustNotCall());
<add> fi.emit('data', '\t');
<add> queueMicrotask(() => {
<add> assert.match(output, /^Tab completion error: Error: message/);
<add> output = '';
<add> });
<add> rli.close();
<add>} | 1 |
Go | Go | remove job from `docker top` | 3e096cb9c9e9d708df7982be5694daaa62bb4849 | <ide><path>api/client/top.go
<ide> package client
<ide>
<ide> import (
<add> "encoding/json"
<ide> "fmt"
<ide> "net/url"
<ide> "strings"
<ide> "text/tabwriter"
<ide>
<del> "github.com/docker/docker/engine"
<add> "github.com/docker/docker/api/types"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> )
<ide>
<ide> func (cli *DockerCli) CmdTop(args ...string) error {
<ide> if err != nil {
<ide> return err
<ide> }
<del> var procs engine.Env
<del> if err := procs.Decode(stream); err != nil {
<add>
<add> procList := types.ContainerProcessList{}
<add> err = json.NewDecoder(stream).Decode(&procList)
<add> if err != nil {
<ide> return err
<ide> }
<add>
<ide> w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
<del> fmt.Fprintln(w, strings.Join(procs.GetList("Titles"), "\t"))
<del> processes := [][]string{}
<del> if err := procs.GetJson("Processes", &processes); err != nil {
<del> return err
<del> }
<del> for _, proc := range processes {
<add> fmt.Fprintln(w, strings.Join(procList.Titles, "\t"))
<add>
<add> for _, proc := range procList.Processes {
<ide> fmt.Fprintln(w, strings.Join(proc, "\t"))
<ide> }
<ide> w.Flush()
<ide><path>api/server/server.go
<ide> func getContainersTop(eng *engine.Engine, version version.Version, w http.Respon
<ide> if version.LessThan("1.4") {
<ide> return fmt.Errorf("top was improved a lot since 1.3, Please upgrade your docker client.")
<ide> }
<add>
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<add>
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide>
<del> job := eng.Job("top", vars["name"], r.Form.Get("ps_args"))
<del> streamJSON(job, w, false)
<del> return job.Run()
<add> procList, err := getDaemon(eng).ContainerTop(vars["name"], r.Form.Get("ps_args"))
<add> if err != nil {
<add> return err
<add> }
<add>
<add> return writeJSON(w, http.StatusOK, procList)
<ide> }
<ide>
<ide> func getContainersJSON(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide><path>api/types/types.go
<ide> type Container struct {
<ide> type CopyConfig struct {
<ide> Resource string
<ide> }
<add>
<add>// GET "/containers/{name:.*}/top"
<add>type ContainerProcessList struct {
<add> Processes [][]string
<add> Titles []string
<add>}
<ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) Install(eng *engine.Engine) error {
<ide> "restart": daemon.ContainerRestart,
<ide> "start": daemon.ContainerStart,
<ide> "stop": daemon.ContainerStop,
<del> "top": daemon.ContainerTop,
<ide> "wait": daemon.ContainerWait,
<ide> "execCreate": daemon.ContainerExecCreate,
<ide> "execStart": daemon.ContainerExecStart,
<ide><path>daemon/top.go
<ide> import (
<ide> "strconv"
<ide> "strings"
<ide>
<del> "github.com/docker/docker/engine"
<add> "github.com/docker/docker/api/types"
<ide> )
<ide>
<del>func (daemon *Daemon) ContainerTop(job *engine.Job) error {
<del> if len(job.Args) != 1 && len(job.Args) != 2 {
<del> return fmt.Errorf("Not enough arguments. Usage: %s CONTAINER [PS_ARGS]\n", job.Name)
<del> }
<del> var (
<del> name = job.Args[0]
<add>func (daemon *Daemon) ContainerTop(name string, psArgs string) (*types.ContainerProcessList, error) {
<add> if psArgs == "" {
<ide> psArgs = "-ef"
<del> )
<del>
<del> if len(job.Args) == 2 && job.Args[1] != "" {
<del> psArgs = job.Args[1]
<ide> }
<ide>
<ide> container, err := daemon.Get(name)
<ide> if err != nil {
<del> return err
<add> return nil, err
<ide> }
<add>
<ide> if !container.IsRunning() {
<del> return fmt.Errorf("Container %s is not running", name)
<add> return nil, fmt.Errorf("Container %s is not running", name)
<ide> }
<add>
<ide> pids, err := daemon.ExecutionDriver().GetPidsForContainer(container.ID)
<ide> if err != nil {
<del> return err
<add> return nil, err
<ide> }
<add>
<ide> output, err := exec.Command("ps", strings.Split(psArgs, " ")...).Output()
<ide> if err != nil {
<del> return fmt.Errorf("Error running ps: %s", err)
<add> return nil, fmt.Errorf("Error running ps: %s", err)
<ide> }
<ide>
<add> procList := &types.ContainerProcessList{}
<add>
<ide> lines := strings.Split(string(output), "\n")
<del> header := strings.Fields(lines[0])
<del> out := &engine.Env{}
<del> out.SetList("Titles", header)
<add> procList.Titles = strings.Fields(lines[0])
<ide>
<ide> pidIndex := -1
<del> for i, name := range header {
<add> for i, name := range procList.Titles {
<ide> if name == "PID" {
<ide> pidIndex = i
<ide> }
<ide> }
<ide> if pidIndex == -1 {
<del> return fmt.Errorf("Couldn't find PID field in ps output")
<add> return nil, fmt.Errorf("Couldn't find PID field in ps output")
<ide> }
<ide>
<del> processes := [][]string{}
<ide> for _, line := range lines[1:] {
<ide> if len(line) == 0 {
<ide> continue
<ide> }
<ide> fields := strings.Fields(line)
<ide> p, err := strconv.Atoi(fields[pidIndex])
<ide> if err != nil {
<del> return fmt.Errorf("Unexpected pid '%s': %s", fields[pidIndex], err)
<add> return nil, fmt.Errorf("Unexpected pid '%s': %s", fields[pidIndex], err)
<ide> }
<ide>
<ide> for _, pid := range pids {
<ide> if pid == p {
<ide> // Make sure number of fields equals number of header titles
<ide> // merging "overhanging" fields
<del> process := fields[:len(header)-1]
<del> process = append(process, strings.Join(fields[len(header)-1:], " "))
<del> processes = append(processes, process)
<add> process := fields[:len(procList.Titles)-1]
<add> process = append(process, strings.Join(fields[len(procList.Titles)-1:], " "))
<add> procList.Processes = append(procList.Processes, process)
<ide> }
<ide> }
<ide> }
<del> out.SetJson("Processes", processes)
<del> out.WriteTo(job.Stdout)
<del> return nil
<add> return procList, nil
<ide> } | 5 |
Mixed | Ruby | add relation#find_or_create_by and friends | eb72e62c3042c0df989d951b1d12291395ebdb8e | <ide><path>activerecord/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<add>* Add `find_or_create_by`, `find_or_create_by!` and
<add> `find_or_initialize_by` methods to `Relation`.
<add>
<add> These are similar to the `first_or_create` family of methods, but
<add> the behaviour when a record is created is slightly different:
<add>
<add> User.where(first_name: 'Penélope').first_or_create
<add>
<add> will execute:
<add>
<add> User.where(first_name: 'Penélope').create
<add>
<add> Causing all the `create` callbacks to execute within the context of
<add> the scope. This could affect queries that occur within callbacks.
<add>
<add> User.find_or_create_by(first_name: 'Penélope')
<add>
<add> will execute:
<add>
<add> User.create(first_name: 'Penélope')
<add>
<add> Which obviously does not affect the scoping of queries within
<add> callbacks.
<add>
<add> The `find_or_create_by` version also reads better, frankly. But note
<add> that it does not allow attributes to be specified for the `create`
<add> that are not included in the `find_by`.
<add>
<add> *Jon Leighton*
<add>
<ide> * Fix bug with presence validation of associations. Would incorrectly add duplicated errors
<ide> when the association was blank. Bug introduced in 1fab518c6a75dac5773654646eb724a59741bc13.
<ide>
<ide> * `find_or_initialize_by_...` can be rewritten using
<ide> `where(...).first_or_initialize`
<ide> * `find_or_create_by_...` can be rewritten using
<del> `where(...).first_or_create`
<add> `find_or_create_by(...)` or where(...).first_or_create`
<ide> * `find_or_create_by_...!` can be rewritten using
<del> `where(...).first_or_create!`
<add> `find_or_create_by!(...) or `where(...).first_or_create!`
<ide>
<ide> The implementation of the deprecated dynamic finders has been moved
<ide> to the `activerecord-deprecated_finders` gem. See below for details.
<ide><path>activerecord/lib/active_record/querying.rb
<ide> module ActiveRecord
<ide> module Querying
<ide> delegate :find, :take, :take!, :first, :first!, :last, :last!, :exists?, :any?, :many?, :to => :all
<ide> delegate :first_or_create, :first_or_create!, :first_or_initialize, :to => :all
<add> delegate :find_or_create_by, :find_or_create_by!, :find_or_initialize_by, :to => :all
<ide> delegate :find_by, :find_by!, :to => :all
<ide> delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, :to => :all
<ide> delegate :find_each, :find_in_batches, :to => :all
<ide><path>activerecord/lib/active_record/relation.rb
<ide> def create!(*args, &block)
<ide> #
<ide> # Expects arguments in the same format as +Base.create+.
<ide> #
<add> # Note that the <tt>create</tt> will execute within the context of this scope, and that may for example
<add> # affect the result of queries within callbacks. If you don't want this, use the <tt>find_or_create_by</tt>
<add> # method.
<add> #
<ide> # ==== Examples
<ide> # # Find the first user named Penélope or create a new one.
<ide> # User.where(:first_name => 'Penélope').first_or_create
<ide> def first_or_initialize(attributes = nil, &block)
<ide> first || new(attributes, &block)
<ide> end
<ide>
<add> # Finds the first record with the given attributes, or creates it if one does not exist.
<add> #
<add> # See also <tt>first_or_create</tt>.
<add> #
<add> # ==== Examples
<add> # # Find the first user named Penélope or create a new one.
<add> # User.find_or_create_by(first_name: 'Penélope')
<add> # # => <User id: 1, first_name: 'Penélope', last_name: nil>
<add> def find_or_create_by(attributes, &block)
<add> find_by(attributes) || create(attributes, &block)
<add> end
<add>
<add> # Like <tt>find_or_create_by</tt>, but calls <tt>create!</tt> so an exception is raised if the created record is invalid.
<add> def find_or_create_by!(attributes, &block)
<add> find_by(attributes) || create!(attributes, &block)
<add> end
<add>
<add> # Like <tt>find_or_create_by</tt>, but calls <tt>new</tt> instead of <tt>create</tt>.
<add> def find_or_initialize_by(attributes, &block)
<add> find_by(attributes) || new(attributes, &block)
<add> end
<add>
<ide> # Runs EXPLAIN on the query or queries triggered by this relation and
<ide> # returns the result as a string. The string is formatted imitating the
<ide> # ones printed by the database shell.
<ide><path>activerecord/test/cases/relations_test.rb
<ide> def test_first_or_initialize_with_block
<ide> assert_equal 'parrot', parrot.name
<ide> end
<ide>
<add> def test_find_or_create_by
<add> assert_nil Bird.find_by(name: 'bob')
<add>
<add> bird = Bird.find_or_create_by(name: 'bob')
<add> assert bird.persisted?
<add>
<add> assert_equal bird, Bird.find_or_create_by(name: 'bob')
<add> end
<add>
<add> def test_find_or_create_by!
<add> assert_raises(ActiveRecord::RecordInvalid) { Bird.find_or_create_by!(color: 'green') }
<add> end
<add>
<add> def test_find_or_initialize_by
<add> assert_nil Bird.find_by(name: 'bob')
<add>
<add> bird = Bird.find_or_initialize_by(name: 'bob')
<add> assert bird.new_record?
<add> bird.save!
<add>
<add> assert_equal bird, Bird.find_or_initialize_by(name: 'bob')
<add> end
<add>
<ide> def test_explicit_create_scope
<ide> hens = Bird.where(:name => 'hen')
<ide> assert_equal 'hen', hens.new.name
<ide><path>guides/source/active_record_querying.md
<ide> WARNING: Up to and including Rails 3.1, when the number of arguments passed to a
<ide> Find or build a new object
<ide> --------------------------
<ide>
<del>It's common that you need to find a record or create it if it doesn't exist. You can do that with the `first_or_create` and `first_or_create!` methods.
<add>It's common that you need to find a record or create it if it doesn't exist. You can do that with the `find_or_create_by` and `find_or_create_by!` methods.
<ide>
<del>### `first_or_create`
<add>### `find_or_create_by` and `first_or_create`
<ide>
<del>The `first_or_create` method checks whether `first` returns `nil` or not. If it does return `nil`, then `create` is called. This is very powerful when coupled with the `where` method. Let's see an example.
<add>The `find_or_create_by` method checks whether a record with the attributes exists. If it doesn't, then `create` is called. Let's see an example.
<ide>
<del>Suppose you want to find a client named 'Andy', and if there's none, create one and additionally set his `locked` attribute to false. You can do so by running:
<add>Suppose you want to find a client named 'Andy', and if there's none, create one. You can do so by running:
<ide>
<ide> ```ruby
<del>Client.where(:first_name => 'Andy').first_or_create(:locked => false)
<del># => #<Client id: 1, first_name: "Andy", orders_count: 0, locked: false, created_at: "2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27">
<add>Client.find_or_create_by(first_name: 'Andy')
<add># => #<Client id: 1, first_name: "Andy", orders_count: 0, locked: true, created_at: "2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27">
<ide> ```
<ide>
<ide> The SQL generated by this method looks like this:
<ide>
<ide> ```sql
<ide> SELECT * FROM clients WHERE (clients.first_name = 'Andy') LIMIT 1
<ide> BEGIN
<del>INSERT INTO clients (created_at, first_name, locked, orders_count, updated_at) VALUES ('2011-08-30 05:22:57', 'Andy', 0, NULL, '2011-08-30 05:22:57')
<add>INSERT INTO clients (created_at, first_name, locked, orders_count, updated_at) VALUES ('2011-08-30 05:22:57', 'Andy', 1, NULL, '2011-08-30 05:22:57')
<ide> COMMIT
<ide> ```
<ide>
<del>`first_or_create` returns either the record that already exists or the new record. In our case, we didn't already have a client named Andy so the record is created and returned.
<add>`find_or_create_by` returns either the record that already exists or the new record. In our case, we didn't already have a client named Andy so the record is created and returned.
<ide>
<ide> The new record might not be saved to the database; that depends on whether validations passed or not (just like `create`).
<ide>
<del>It's also worth noting that `first_or_create` takes into account the arguments of the `where` method. In the example above we didn't explicitly pass a `:first_name => 'Andy'` argument to `first_or_create`. However, that was used when creating the new record because it was already passed before to the `where` method.
<add>Suppose we want to set the 'locked' attribute to true, if we're
<add>creating a new record, but we don't want to include it in the query. So
<add>we want to find the client named "Andy", or if that client doesn't
<add>exist, create a client named "Andy" which is not locked.
<ide>
<del>You can do the same with the `find_or_create_by` method:
<add>We can achive this in two ways. The first is passing a block to the
<add>`find_or_create_by` method:
<ide>
<ide> ```ruby
<del>Client.find_or_create_by_first_name(:first_name => "Andy", :locked => false)
<add>Client.find_or_create_by(first_name: 'Andy') do |c|
<add> c.locked = false
<add>end
<add>```
<add>
<add>The block will only be executed if the client is being created. The
<add>second time we run this code, the block will be ignored.
<add>
<add>The second way is using the `first_or_create` method:
<add>
<add>```ruby
<add>Client.where(first_name: 'Andy').first_or_create(locked: false)
<ide> ```
<ide>
<del>This method still works, but it's encouraged to use `first_or_create` because it's more explicit on which arguments are used to _find_ the record and which are used to _create_, resulting in less confusion overall.
<add>In this version, we are building a scope to search for Andy, and getting
<add>the first record if it existed, or else creating it with `locked:
<add>false`.
<ide>
<del>### `first_or_create!`
<add>Note that these two are slightly different. In the second version, the
<add>scope that we build will affect any other queries that may happens while
<add>creating the record. For example, if we had a callback that ran
<add>another query, that would execute within the `Client.where(first_name:
<add>'Andy')` scope.
<ide>
<del>You can also use `first_or_create!` to raise an exception if the new record is invalid. Validations are not covered on this guide, but let's assume for a moment that you temporarily add
<add>### `find_or_create_by!` and `first_or_create!`
<add>
<add>You can also use `find_or_create_by!` to raise an exception if the new record is invalid. Validations are not covered on this guide, but let's assume for a moment that you temporarily add
<ide>
<ide> ```ruby
<ide> validates :orders_count, :presence => true
<ide> validates :orders_count, :presence => true
<ide> to your `Client` model. If you try to create a new `Client` without passing an `orders_count`, the record will be invalid and an exception will be raised:
<ide>
<ide> ```ruby
<del>Client.where(:first_name => 'Andy').first_or_create!(:locked => false)
<add>Client.find_or_create_by!(first_name: 'Andy')
<ide> # => ActiveRecord::RecordInvalid: Validation failed: Orders count can't be blank
<ide> ```
<ide>
<del>As with `first_or_create` there is a `find_or_create_by!` method but the `first_or_create!` method is preferred for clarity.
<add>There is also a `first_or_create!` method which does a similar thing for
<add>`first_or_create`.
<ide>
<del>### `first_or_initialize`
<add>### `find_or_initialize_by` and `first_or_initialize`
<ide>
<del>The `first_or_initialize` method will work just like `first_or_create` but it will not call `create` but `new`. This means that a new model instance will be created in memory but won't be saved to the database. Continuing with the `first_or_create` example, we now want the client named 'Nick':
<add>The `find_or_initialize_by` method will work just like
<add>`find_or_create_by` but it will call `new` instead of `create`. This
<add>means that a new model instance will be created in memory but won't be
<add>saved to the database. Continuing with the `find_or_create_by` example, we
<add>now want the client named 'Nick':
<ide>
<ide> ```ruby
<del>nick = Client.where(:first_name => 'Nick').first_or_initialize(:locked => false)
<del># => <Client id: nil, first_name: "Nick", orders_count: 0, locked: false, created_at: "2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27">
<add>nick = Client.find_or_initialize_by(first_name: 'Nick')
<add># => <Client id: nil, first_name: "Nick", orders_count: 0, locked: true, created_at: "2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27">
<ide>
<ide> nick.persisted?
<ide> # => false
<ide> nick.save
<ide> # => true
<ide> ```
<ide>
<add>There is also a `first_or_initialize` method which does a similar thing
<add>for `first_or_create`.
<add>
<ide> Finding by SQL
<ide> --------------
<ide> | 5 |
Mixed | Javascript | remove watcher state errors for fs.watch | 301f6cc553bd73cfa345ae7de6ee81655efc57d0 | <ide><path>doc/api/errors.md
<ide> falsy value.
<ide> An invalid symlink type was passed to the [`fs.symlink()`][] or
<ide> [`fs.symlinkSync()`][] methods.
<ide>
<del><a id="ERR_FS_WATCHER_ALREADY_STARTED"></a>
<del>### ERR_FS_WATCHER_ALREADY_STARTED
<del>
<del>An attempt was made to start a watcher returned by `fs.watch()` that has
<del>already been started.
<del>
<del><a id="ERR_FS_WATCHER_NOT_STARTED"></a>
<del>### ERR_FS_WATCHER_NOT_STARTED
<del>
<del>An attempt was made to initiate operations on a watcher returned by
<del>`fs.watch()` that has not yet been started.
<del>
<ide> <a id="ERR_HTTP_HEADERS_SENT"></a>
<ide> ### ERR_HTTP_HEADERS_SENT
<ide>
<ide><path>lib/fs.js
<ide> const fs = exports;
<ide> const { Buffer } = require('buffer');
<ide> const errors = require('internal/errors');
<ide> const {
<del> ERR_FS_WATCHER_ALREADY_STARTED,
<del> ERR_FS_WATCHER_NOT_STARTED,
<ide> ERR_INVALID_ARG_TYPE,
<ide> ERR_INVALID_CALLBACK,
<ide> ERR_OUT_OF_RANGE
<ide> util.inherits(FSWatcher, EventEmitter);
<ide>
<ide> // FIXME(joyeecheung): this method is not documented.
<ide> // At the moment if filename is undefined, we
<del>// 1. Throw an Error from C++ land if it's the first time .start() is called
<del>// 2. Return silently from C++ land if .start() has already been called
<add>// 1. Throw an Error if it's the first time .start() is called
<add>// 2. Return silently if .start() has already been called
<ide> // on a valid filename and the wrap has been initialized
<add>// This method is a noop if the watcher has already been started.
<ide> FSWatcher.prototype.start = function(filename,
<ide> persistent,
<ide> recursive,
<ide> encoding) {
<ide> lazyAssert()(this._handle instanceof FSEvent, 'handle must be a FSEvent');
<ide> if (this._handle.initialized) {
<del> throw new ERR_FS_WATCHER_ALREADY_STARTED();
<add> return;
<ide> }
<ide>
<ide> filename = getPathFromURL(filename);
<ide> validatePath(filename, 'filename');
<ide>
<del> var err = this._handle.start(pathModule.toNamespacedPath(filename),
<del> persistent,
<del> recursive,
<del> encoding);
<add> const err = this._handle.start(pathModule.toNamespacedPath(filename),
<add> persistent,
<add> recursive,
<add> encoding);
<ide> if (err) {
<ide> const error = errors.uvException({
<ide> errno: err,
<ide> FSWatcher.prototype.start = function(filename,
<ide> }
<ide> };
<ide>
<add>// This method is a noop if the watcher has not been started.
<ide> FSWatcher.prototype.close = function() {
<ide> lazyAssert()(this._handle instanceof FSEvent, 'handle must be a FSEvent');
<ide> if (!this._handle.initialized) {
<del> throw new ERR_FS_WATCHER_NOT_STARTED();
<add> return;
<ide> }
<ide> this._handle.close();
<ide> };
<ide><path>lib/internal/errors.js
<ide> E('ERR_FALSY_VALUE_REJECTION', 'Promise was rejected with falsy value', Error);
<ide> E('ERR_FS_INVALID_SYMLINK_TYPE',
<ide> 'Symlink type must be one of "dir", "file", or "junction". Received "%s"',
<ide> Error); // Switch to TypeError. The current implementation does not seem right
<del>E('ERR_FS_WATCHER_ALREADY_STARTED',
<del> 'The watcher has already been started', Error);
<del>E('ERR_FS_WATCHER_NOT_STARTED',
<del> 'The watcher has not been started', Error);
<ide> E('ERR_HTTP2_ALTSVC_INVALID_ORIGIN',
<ide> 'HTTP/2 ALTSVC frames require a valid origin', TypeError);
<ide> E('ERR_HTTP2_ALTSVC_LENGTH',
<ide><path>test/parallel/test-fs-watch.js
<ide> for (const testCase of cases) {
<ide> assert.strictEqual(eventType, 'change');
<ide> assert.strictEqual(argFilename, testCase.fileName);
<ide>
<del> common.expectsError(() => watcher.start(), {
<del> code: 'ERR_FS_WATCHER_ALREADY_STARTED',
<del> message: 'The watcher has already been started'
<del> });
<add> watcher.start(); // starting a started watcher should be a noop
<ide> // end of test case
<ide> watcher.close();
<del> common.expectsError(() => watcher.close(), {
<del> code: 'ERR_FS_WATCHER_NOT_STARTED',
<del> message: 'The watcher has not been started'
<del> });
<add> watcher.close(); // closing a closed watcher should be a noop
<ide> }));
<ide>
<ide> // long content so it's actually flushed. toUpperCase so there's real change. | 4 |
PHP | PHP | fix method order | 7bac330c68a5ad23f24918d310fd55722d5f1d00 | <ide><path>src/Illuminate/Pagination/Paginator.php
<ide> public function __construct(Factory $factory, array $items, $total, $perPage = n
<ide> if (is_null($perPage))
<ide> {
<ide> $this->perPage = (int) $total;
<del> $this->items = array_slice($items, 0, $this->perPage);
<ide> $this->hasMore = count($items) > $this->perPage;
<add> $this->items = array_slice($items, 0, $this->perPage);
<ide> }
<ide> else
<ide> { | 1 |
Text | Text | improve the doc of the 'information' event | 0a5a762a16224479003dd44b7855b236fc481de9 | <ide><path>doc/api/http.md
<ide> the client should send the request body.
<ide> added: v10.0.0
<ide> -->
<ide>
<del>Emitted when the server sends a 1xx response (excluding 101 Upgrade). This
<del>event is emitted with a callback containing an object with a status code.
<add>* `info` {Object}
<add> * `statusCode` {integer}
<add>
<add>Emitted when the server sends a 1xx response (excluding 101 Upgrade). The
<add>listeners of this event will receive an object containing the status code.
<ide>
<ide> ```js
<ide> const http = require('http');
<ide> const options = {
<ide> const req = http.request(options);
<ide> req.end();
<ide>
<del>req.on('information', (res) => {
<del> console.log(`Got information prior to main response: ${res.statusCode}`);
<add>req.on('information', (info) => {
<add> console.log(`Got information prior to main response: ${info.statusCode}`);
<ide> });
<ide> ```
<ide> | 1 |
Text | Text | update build badge | dcee2eac68e0c1b4061c94c69e920ed2d42f42f2 | <ide><path>README.md
<del># The Algorithms - Python <!-- [](https://travis-ci.org/TheAlgorithms/Python) -->
<add># The Algorithms - Python
<ide> [](https://www.paypal.me/TheAlgorithms/100)
<del>[](https://travis-ci.org/TheAlgorithms/Python)
<add>[](https://travis-ci.com/TheAlgorithms/Python)
<ide> [](https://lgtm.com/projects/g/TheAlgorithms/Python/alerts)
<ide> [](https://gitter.im/TheAlgorithms)
<ide> [](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md) | 1 |
Text | Text | add a note about breaking changes | d07fb284628076518ee15e2240b3eea1456e56ca | <ide><path>docs/developers/contributing.md
<ide> New contributions to the library are welcome, but we ask that you please follow
<ide> - Check that your code will pass tests, `gulp test` will run tests for you.
<ide> - Keep pull requests concise, and document new functionality in the relevant `.md` file.
<ide> - Consider whether your changes are useful for all users, or if creating a Chart.js [plugin](plugins.md) would be more appropriate.
<add>- Avoid breaking changes unless there is an upcoming major release, which are infrequent. We encourage people to write plugins for most new advanced features, so care a lot about backwards compatibility.
<ide>
<ide> # Joining the project
<ide> | 1 |
Text | Text | add lost params for including stetho | 5daf1cfa6d773ed51e08510230abd0d2ce7506ca | <ide><path>docs/Debugging.md
<ide> The debugger will receive a list of all project roots, separated by a space. For
<ide> 2. In ```android/app/src/main/java/com/{yourAppName}/MainApplication.java```, add the following imports:
<ide>
<ide> ```java
<add> import android.os.Bundle;
<ide> import com.facebook.react.modules.network.ReactCookieJarContainer;
<ide> import com.facebook.stetho.Stetho;
<ide> import okhttp3.OkHttpClient;
<ide> The debugger will receive a list of all project roots, separated by a space. For
<ide>
<ide> 3. In ```android/app/src/main/java/com/{yourAppName}/MainApplication.java``` add the function:
<ide> ```java
<del> public void onCreate() {
<del> super.onCreate();
<add> public void onCreate(Bundle savedInstanceState) {
<add> super.onCreate(savedInstanceState);
<ide> Stetho.initializeWithDefaults(this);
<ide> OkHttpClient client = new OkHttpClient.Builder()
<ide> .connectTimeout(0, TimeUnit.MILLISECONDS) | 1 |
Javascript | Javascript | throw check in test-zlib-write-after-close | 817b28b4e4cc35aa6c3e5ad3be37aafc0b539d45 | <ide><path>test/parallel/test-zlib-write-after-close.js
<ide> const zlib = require('zlib');
<ide> zlib.gzip('hello', common.mustCall(function(err, out) {
<ide> const unzip = zlib.createGunzip();
<ide> unzip.close(common.mustCall(function() {}));
<del> assert.throws(function() {
<del> unzip.write(out);
<del> });
<add> assert.throws(() => unzip.write(out), /^Error: zlib binding closed$/);
<ide> })); | 1 |
Go | Go | fix panic on error looking up volume driver | 5baf8a411899b1aa39f921df8debfd925491be68 | <ide><path>volume/store/store.go
<ide> func (s *VolumeStore) Remove(v volume.Volume) error {
<ide>
<ide> vd, err := volumedrivers.GetDriver(v.DriverName())
<ide> if err != nil {
<del> return &OpErr{Err: err, Name: vd.Name(), Op: "remove"}
<add> return &OpErr{Err: err, Name: v.DriverName(), Op: "remove"}
<ide> }
<ide>
<ide> logrus.Debugf("Removing volume reference: driver %s, name %s", v.DriverName(), name) | 1 |
Python | Python | remove unused import | c8282437a7f75f9c3af7a1b2ad57297be41863ff | <ide><path>keras/applications/imagenet_utils.py
<del>import numpy as np
<ide> import json
<ide>
<ide> from ..utils.data_utils import get_file | 1 |
Text | Text | remove dependancy status badge | e98767ecee543048d448f1476673eee5840510e8 | <ide><path>README.md
<ide> # Atom
<ide>
<ide> [](https://dev.azure.com/github/Atom/_build/latest?definitionId=32&branchName=master)
<del>[](https://david-dm.org/atom/atom)
<ide>
<ide> Atom is a hackable text editor for the 21st century, built on [Electron](https://github.com/electron/electron), and based on everything we love about our favorite editors. We designed it to be deeply customizable, but still approachable using the default configuration.
<ide> | 1 |
Text | Text | add npm info to getting started doc | b87106c1817d380576fbd6fc1ae1e7928d38b6ba | <ide><path>docs/00-Getting-Started.md
<ide> You can also grab Chart.js using bower:
<ide> bower install Chart.js --save
<ide> ```
<ide>
<add>or NPM:
<add>
<add>```bash
<add>npm install chart.js --save
<add>```
<add>
<ide> Also, Chart.js is available from CDN:
<ide>
<ide> https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js | 1 |
Text | Text | add docs about nextruntime for custom webpack | d1db7141ba029acbafcec3684e469611c59b43ad | <ide><path>docs/api-reference/next.config.js/custom-webpack-config.md
<ide> The second argument to the `webpack` function is an object with the following pr
<ide> - `buildId`: `String` - The build id, used as a unique identifier between builds
<ide> - `dev`: `Boolean` - Indicates if the compilation will be done in development
<ide> - `isServer`: `Boolean` - It's `true` for server-side compilation, and `false` for client-side compilation
<add>- `nextRuntime`: `String` - The target runtime for server-side compilation; either `"edge"` or `"nodejs"`
<ide> - `defaultLoaders`: `Object` - Default loaders used internally by Next.js:
<ide> - `babel`: `Object` - Default `babel-loader` configuration
<ide> | 1 |
Python | Python | add test for ticket #324 | 1ce64f75d452492caa9bffbb36d4b3711c3e4e23 | <ide><path>numpy/core/tests/test_regression.py
<ide> def check_object_array_assign(self, level=rlevel):
<ide> x.flat[2] = (1,2,3)
<ide> assert_equal(x.flat[2],(1,2,3))
<ide>
<add> def check_ndmin_float64(self, level=rlevel):
<add> """Ticket #324"""
<add> x = N.array([1,2,3],dtype=N.float64)
<add> assert_equal(N.array(x,dtype=N.float32,ndmin=2).ndim,2)
<add> assert_equal(N.array(x,dtype=N.float64,ndmin=2).ndim,2)
<add>
<ide> if __name__ == "__main__":
<ide> NumpyTest().run() | 1 |
PHP | PHP | use a get wrapper to avoid null issues | f9bae5b1f50c13f19fd273c6a6dfeeb134525b79 | <ide><path>src/Mailer/Transport/SmtpTransport.php
<ide> public function __destruct()
<ide> */
<ide> public function __wakeup()
<ide> {
<del> /** @psalm-suppress PossiblyNullPropertyAssignmentValue */
<ide> $this->_socket = null;
<ide> }
<ide>
<ide> public function connected(): bool
<ide> */
<ide> public function disconnect(): void
<ide> {
<del> if ($this->connected()) {
<del> $this->_disconnect();
<add> if (!$this->connected()) {
<add> return;
<ide> }
<add>
<add> $this->_disconnect();
<ide> }
<ide>
<ide> /**
<ide> protected function _bufferResponseLines(array $responseLines): void
<ide> protected function _connect(): void
<ide> {
<ide> $this->_generateSocket();
<del> if (!$this->_socket->connect()) {
<add> if (!$this->_socket()->connect()) {
<ide> throw new SocketException('Unable to connect to SMTP server.');
<ide> }
<ide> $this->_smtpSend(null, '220');
<ide> protected function _connect(): void
<ide> $this->_smtpSend("EHLO {$host}", '250');
<ide> if ($config['tls']) {
<ide> $this->_smtpSend('STARTTLS', '220');
<del> $this->_socket->enableCrypto('tls');
<add> $this->_socket()->enableCrypto('tls');
<ide> $this->_smtpSend("EHLO {$host}", '250');
<ide> }
<ide> } catch (SocketException $e) {
<ide> protected function _sendData(Message $message): void
<ide> protected function _disconnect(): void
<ide> {
<ide> $this->_smtpSend('QUIT', false);
<del> $this->_socket->disconnect();
<add> $this->_socket()->disconnect();
<ide> }
<ide>
<ide> /**
<ide> protected function _smtpSend(?string $data, $checkCode = '250'): ?string
<ide> $this->_lastResponse = [];
<ide>
<ide> if ($data !== null) {
<del> $this->_socket->write($data . "\r\n");
<add> $this->_socket()->write($data . "\r\n");
<ide> }
<ide>
<ide> $timeout = $this->_config['timeout'];
<ide> protected function _smtpSend(?string $data, $checkCode = '250'): ?string
<ide> $response = '';
<ide> $startTime = time();
<ide> while (substr($response, -2) !== "\r\n" && ((time() - $startTime) < $timeout)) {
<del> $bytes = $this->_socket->read();
<add> $bytes = $this->_socket()->read();
<ide> if ($bytes === null) {
<ide> break;
<ide> }
<ide> protected function _smtpSend(?string $data, $checkCode = '250'): ?string
<ide>
<ide> return null;
<ide> }
<add>
<add> /**
<add> * @return \Cake\Network\Socket
<add> * @throws \RuntimeException If socket is not set.
<add> */
<add> protected function _socket(): Socket
<add> {
<add> if ($this->_socket === null) {
<add> throw new \RuntimeException('Socket is null, but must be set.');
<add> }
<add>
<add> return $this->_socket;
<add> }
<ide> } | 1 |
Go | Go | add netns strategy | f52b2fdcbb29258c5b492fdb2479d473fcb42ca0 | <ide><path>pkg/libcontainer/network/netns.go
<add>package network
<add>
<add>import (
<add> "fmt"
<add> "os"
<add> "syscall"
<add>
<add> "github.com/dotcloud/docker/pkg/libcontainer"
<add> "github.com/dotcloud/docker/pkg/system"
<add>)
<add>
<add>// crosbymichael: could make a network strategy that instead of returning veth pair names it returns a pid to an existing network namespace
<add>type NetNS struct {
<add>}
<add>
<add>func (v *NetNS) Create(n *libcontainer.Network, nspid int, context libcontainer.Context) error {
<add> nsname, exists := n.Context["nsname"]
<add>
<add> if !exists {
<add> return fmt.Errorf("nspath does not exist in network context")
<add> }
<add>
<add> context["nspath"] = fmt.Sprintf("/var/run/netns/%s", nsname)
<add> return nil
<add>}
<add>
<add>func (v *NetNS) Initialize(config *libcontainer.Network, context libcontainer.Context) error {
<add> nspath, exists := context["nspath"]
<add> if !exists {
<add> return fmt.Errorf("nspath does not exist in network context")
<add> }
<add>
<add> f, err := os.OpenFile(nspath, os.O_RDONLY, 0)
<add> if err != nil {
<add> return fmt.Errorf("failed get network namespace fd: %v", err)
<add> }
<add>
<add> if err := system.Setns(f.Fd(), syscall.CLONE_NEWNET); err != nil {
<add> return fmt.Errorf("failed to setns current network namespace: %v", err)
<add> }
<add> return nil
<add>}
<ide><path>pkg/libcontainer/network/strategy.go
<ide> package network
<ide>
<ide> import (
<ide> "errors"
<add>
<ide> "github.com/dotcloud/docker/pkg/libcontainer"
<ide> )
<ide>
<ide> var (
<ide> var strategies = map[string]NetworkStrategy{
<ide> "veth": &Veth{},
<ide> "loopback": &Loopback{},
<add> "netns": &NetNS{},
<ide> }
<ide>
<ide> // NetworkStrategy represents a specific network configuration for | 2 |
Javascript | Javascript | allow "section/" links pointing to "section/index" | 238094310694f0755e6089bf92c36d0ff55fe626 | <ide><path>docs/spec/ngdocSpec.js
<ide> describe('ngdoc', function(){
<ide> expect(doc.convertUrlToAbsolute('angular.widget')).toEqual('section/angular.widget');
<ide> });
<ide>
<add> it('should change id to index if not specified', function() {
<add> expect(doc.convertUrlToAbsolute('guide/')).toEqual('guide/index');
<add> });
<ide> });
<ide>
<ide> describe('sorting', function(){
<ide><path>docs/src/ngdoc.js
<ide> Doc.prototype = {
<ide> * @returns {string} Absolute url
<ide> */
<ide> convertUrlToAbsolute: function(url) {
<add> if (url.substr(-1) == '/') return url + 'index';
<ide> if (url.match(/\//)) return url;
<del>
<del> // remove this after
<ide> return this.section + '/' + url;
<ide> },
<ide> | 2 |
Java | Java | eliminate windowuntil from stringdecoder | d55210551612e7ded3a068818ebc76a1e151bab3 | <ide><path>spring-core/src/main/java/org/springframework/core/codec/StringDecoder.java
<ide>
<ide> import org.springframework.core.ResolvableType;
<ide> import org.springframework.core.io.buffer.DataBuffer;
<add>import org.springframework.core.io.buffer.DataBufferLimitException;
<ide> import org.springframework.core.io.buffer.DataBufferUtils;
<ide> import org.springframework.core.io.buffer.DataBufferWrapper;
<ide> import org.springframework.core.io.buffer.DefaultDataBufferFactory;
<ide> public Flux<String> decode(Publisher<DataBuffer> input, ResolvableType elementTy
<ide> Flux<DataBuffer> inputFlux = Flux.defer(() -> {
<ide> DataBufferUtils.Matcher matcher = DataBufferUtils.matcher(delimiterBytes);
<ide>
<del> Flux<DataBuffer> buffers = Flux.from(input)
<del> .concatMapIterable(buffer -> endFrameAfterDelimiter(buffer, matcher));
<add> @SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
<add> LimitChecker limiter = new LimitChecker(getMaxInMemorySize());
<ide>
<del> Flux<List<DataBuffer>> delimitedBuffers;
<del> if (getMaxInMemorySize() != -1) {
<del> delimitedBuffers = buffers
<del> .windowUntil(buffer -> buffer instanceof EndFrameBuffer)
<del> .concatMap(window -> window.collect(
<del> () -> new LimitedDataBufferList(getMaxInMemorySize()),
<del> LimitedDataBufferList::add));
<del> }
<del> else {
<del> delimitedBuffers = buffers.bufferUntil(buffer -> buffer instanceof EndFrameBuffer);
<del> }
<del>
<del> return delimitedBuffers
<add> return Flux.from(input)
<add> .concatMapIterable(buffer -> endFrameAfterDelimiter(buffer, matcher))
<add> .doOnNext(limiter)
<add> .bufferUntil(buffer -> buffer instanceof EndFrameBuffer)
<ide> .map(list -> joinAndStrip(list, this.stripDelimiter))
<ide> .doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release);
<ide> });
<ide> private static DataBuffer joinAndStrip(List<DataBuffer> dataBuffers, boolean str
<ide> DataBuffer lastBuffer = dataBuffers.get(lastIdx);
<ide> if (lastBuffer instanceof EndFrameBuffer) {
<ide> matchingDelimiter = ((EndFrameBuffer) lastBuffer).delimiter();
<del> dataBuffers = dataBuffers.subList(0, lastIdx);
<add> dataBuffers.remove(lastIdx);
<ide> }
<ide>
<ide> DataBuffer result = dataBuffers.get(0).factory().join(dataBuffers);
<ide> public byte[] delimiter() {
<ide> }
<ide>
<ide>
<del> private class ConcatMapIterableDiscardWorkaroundCache implements Consumer<DataBuffer>, Runnable {
<add> private static class LimitChecker implements Consumer<DataBuffer> {
<ide>
<del> private final List<DataBuffer> buffers = new ArrayList<>();
<add> @SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
<add> private final LimitedDataBufferList list;
<ide>
<ide>
<del> public List<DataBuffer> addAll(List<DataBuffer> buffersToAdd) {
<del> this.buffers.addAll(buffersToAdd);
<del> return buffersToAdd;
<del> }
<del>
<del> @Override
<del> public void accept(DataBuffer dataBuffer) {
<del> this.buffers.remove(dataBuffer);
<add> LimitChecker(int maxInMemorySize) {
<add> this.list = new LimitedDataBufferList(maxInMemorySize);
<ide> }
<ide>
<ide> @Override
<del> public void run() {
<del> this.buffers.forEach(buffer -> {
<del> try {
<del> DataBufferUtils.release(buffer);
<del> }
<del> catch (Throwable ex) {
<del> // Keep going..
<del> }
<del> });
<add> public void accept(DataBuffer buffer) {
<add> if (buffer instanceof EndFrameBuffer) {
<add> this.list.clear();
<add> }
<add> try {
<add> this.list.add(buffer);
<add> }
<add> catch (DataBufferLimitException ex) {
<add> DataBufferUtils.release(buffer);
<add> throw ex;
<add> }
<ide> }
<ide> }
<ide>
<ide><path>spring-core/src/main/java/org/springframework/core/io/buffer/DataBufferUtils.java
<ide> public static Mono<DataBuffer> join(Publisher<? extends DataBuffer> buffers, int
<ide> return (Mono<DataBuffer>) buffers;
<ide> }
<ide>
<del> // TODO: Drop doOnDiscard(LimitedDataBufferList.class, ...) (reactor-core#1924)
<del>
<ide> return Flux.from(buffers)
<ide> .collect(() -> new LimitedDataBufferList(maxByteCount), LimitedDataBufferList::add)
<ide> .filter(list -> !list.isEmpty())
<ide> .map(list -> list.get(0).factory().join(list))
<del> .doOnDiscard(LimitedDataBufferList.class, LimitedDataBufferList::releaseAndClear)
<ide> .doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release);
<ide> }
<ide>
<ide><path>spring-core/src/test/java/org/springframework/core/codec/StringDecoderTests.java
<ide> public void decode() {
<ide> // TODO: temporarily replace testDecodeAll with explicit decode/cancel/empty
<ide> // see https://github.com/reactor/reactor-core/issues/2041
<ide>
<del> testDecode(input, TYPE, step -> step.expectNext(u, e, o).verifyComplete(), null, null);
<del> testDecodeCancel(input, TYPE, null, null);
<del> testDecodeEmpty(TYPE, null, null);
<add>// testDecode(input, TYPE, step -> step.expectNext(u, e, o).verifyComplete(), null, null);
<add>// testDecodeCancel(input, TYPE, null, null);
<add>// testDecodeEmpty(TYPE, null, null);
<ide>
<del> // testDecodeAll(input, TYPE, step -> step.expectNext(u, e, o).verifyComplete(), null, null);
<add> testDecodeAll(input, TYPE, step -> step.expectNext(u, e, o).verifyComplete(), null, null);
<ide> }
<ide>
<ide> @Test | 3 |
Python | Python | fix some docstring typos | b15219689f57ac41b3b7f79708c457cc9693fa5d | <ide><path>celery/task/base.py
<ide> class TaskType(type):
<ide> Automatically registers the task in the task registry, except
<ide> if the ``abstract`` attribute is set.
<ide>
<del> If no ``name`` attribute is provieded, the name is automatically
<add> If no ``name`` attribute is provided, the name is automatically
<ide> set to the name of the module it was defined in, and the class name.
<ide>
<ide> """
<ide> def __new__(cls, name, bases, attrs):
<ide> super_new = super(TaskType, cls).__new__
<ide> task_module = attrs["__module__"]
<ide>
<del> # Abstract class, remove the abstract attribute so the
<add> # Abstract class, remove the abstract attribute so
<ide> # any class inheriting from this won't be abstract by default.
<ide> if attrs.pop("abstract", None):
<ide> return super_new(cls, name, bases, attrs) | 1 |
Javascript | Javascript | remove useless hasownproperty checks | 69521477a1f77c8c149c166c5c6b77a93bb3a009 | <ide><path>src/core/core.element.js
<ide> module.exports = function(Chart) {
<ide>
<ide> helpers.each(this._model, function(value, key) {
<ide>
<del> if (key[0] === '_' || !this._model.hasOwnProperty(key)) {
<add> if (key[0] === '_') {
<ide> // Only non-underscored properties
<ide> }
<ide>
<ide><path>src/core/core.helpers.js
<ide> module.exports = function(Chart) {
<ide> helpers.clone = function(obj) {
<ide> var objClone = {};
<ide> helpers.each(obj, function(value, key) {
<del> if (obj.hasOwnProperty(key)) {
<del> if (helpers.isArray(value)) {
<del> objClone[key] = value.slice(0);
<del> } else if (typeof value === 'object' && value !== null) {
<del> objClone[key] = helpers.clone(value);
<del> } else {
<del> objClone[key] = value;
<del> }
<add> if (helpers.isArray(value)) {
<add> objClone[key] = value.slice(0);
<add> } else if (typeof value === 'object' && value !== null) {
<add> objClone[key] = helpers.clone(value);
<add> } else {
<add> objClone[key] = value;
<ide> }
<ide> });
<ide> return objClone;
<ide> module.exports = function(Chart) {
<ide> }
<ide> helpers.each(additionalArgs, function(extensionObject) {
<ide> helpers.each(extensionObject, function(value, key) {
<del> if (extensionObject.hasOwnProperty(key)) {
<del> base[key] = value;
<del> }
<add> base[key] = value;
<ide> });
<ide> });
<ide> return base;
<ide> module.exports = function(Chart) {
<ide> var base = helpers.clone(_base);
<ide> helpers.each(Array.prototype.slice.call(arguments, 1), function(extension) {
<ide> helpers.each(extension, function(value, key) {
<del> if (extension.hasOwnProperty(key)) {
<del> if (key === 'scales') {
<del> // Scale config merging is complex. Add out own function here for that
<del> base[key] = helpers.scaleMerge(base.hasOwnProperty(key) ? base[key] : {}, value);
<del>
<del> } else if (key === 'scale') {
<del> // Used in polar area & radar charts since there is only one scale
<del> base[key] = helpers.configMerge(base.hasOwnProperty(key) ? base[key] : {}, Chart.scaleService.getScaleDefaults(value.type), value);
<del> } else if (base.hasOwnProperty(key) && helpers.isArray(base[key]) && helpers.isArray(value)) {
<del> // In this case we have an array of objects replacing another array. Rather than doing a strict replace,
<del> // merge. This allows easy scale option merging
<del> var baseArray = base[key];
<del>
<del> helpers.each(value, function(valueObj, index) {
<del>
<del> if (index < baseArray.length) {
<del> if (typeof baseArray[index] === 'object' && baseArray[index] !== null && typeof valueObj === 'object' && valueObj !== null) {
<del> // Two objects are coming together. Do a merge of them.
<del> baseArray[index] = helpers.configMerge(baseArray[index], valueObj);
<del> } else {
<del> // Just overwrite in this case since there is nothing to merge
<del> baseArray[index] = valueObj;
<del> }
<add> if (key === 'scales') {
<add> // Scale config merging is complex. Add out own function here for that
<add> base[key] = helpers.scaleMerge(base.hasOwnProperty(key) ? base[key] : {}, value);
<add>
<add> } else if (key === 'scale') {
<add> // Used in polar area & radar charts since there is only one scale
<add> base[key] = helpers.configMerge(base.hasOwnProperty(key) ? base[key] : {}, Chart.scaleService.getScaleDefaults(value.type), value);
<add> } else if (base.hasOwnProperty(key) && helpers.isArray(base[key]) && helpers.isArray(value)) {
<add> // In this case we have an array of objects replacing another array. Rather than doing a strict replace,
<add> // merge. This allows easy scale option merging
<add> var baseArray = base[key];
<add>
<add> helpers.each(value, function(valueObj, index) {
<add>
<add> if (index < baseArray.length) {
<add> if (typeof baseArray[index] === 'object' && baseArray[index] !== null && typeof valueObj === 'object' && valueObj !== null) {
<add> // Two objects are coming together. Do a merge of them.
<add> baseArray[index] = helpers.configMerge(baseArray[index], valueObj);
<ide> } else {
<del> baseArray.push(valueObj); // nothing to merge
<add> // Just overwrite in this case since there is nothing to merge
<add> baseArray[index] = valueObj;
<ide> }
<del> });
<add> } else {
<add> baseArray.push(valueObj); // nothing to merge
<add> }
<add> });
<ide>
<del> } else if (base.hasOwnProperty(key) && typeof base[key] === "object" && base[key] !== null && typeof value === "object") {
<del> // If we are overwriting an object with an object, do a merge of the properties.
<del> base[key] = helpers.configMerge(base[key], value);
<add> } else if (base.hasOwnProperty(key) && typeof base[key] === "object" && base[key] !== null && typeof value === "object") {
<add> // If we are overwriting an object with an object, do a merge of the properties.
<add> base[key] = helpers.configMerge(base[key], value);
<ide>
<del> } else {
<del> // can just overwrite the value in this case
<del> base[key] = value;
<del> }
<add> } else {
<add> // can just overwrite the value in this case
<add> base[key] = value;
<ide> }
<ide> });
<ide> });
<ide> module.exports = function(Chart) {
<ide> var base = helpers.clone(_base);
<ide>
<ide> helpers.each(extension, function(value, key) {
<del> if (extension.hasOwnProperty(key)) {
<del> if (key === 'xAxes' || key === 'yAxes') {
<del> // These properties are arrays of items
<del> if (base.hasOwnProperty(key)) {
<del> helpers.each(value, function(valueObj, index) {
<del> var axisType = helpers.getValueOrDefault(valueObj.type, key === 'xAxes' ? 'category' : 'linear');
<del> var axisDefaults = Chart.scaleService.getScaleDefaults(axisType);
<del> if (index >= base[key].length || !base[key][index].type) {
<del> base[key].push(helpers.configMerge(axisDefaults, valueObj));
<del> } else if (valueObj.type && valueObj.type !== base[key][index].type) {
<del> // Type changed. Bring in the new defaults before we bring in valueObj so that valueObj can override the correct scale defaults
<del> base[key][index] = helpers.configMerge(base[key][index], axisDefaults, valueObj);
<del> } else {
<del> // Type is the same
<del> base[key][index] = helpers.configMerge(base[key][index], valueObj);
<del> }
<del> });
<del> } else {
<del> base[key] = [];
<del> helpers.each(value, function(valueObj) {
<del> var axisType = helpers.getValueOrDefault(valueObj.type, key === 'xAxes' ? 'category' : 'linear');
<del> base[key].push(helpers.configMerge(Chart.scaleService.getScaleDefaults(axisType), valueObj));
<del> });
<del> }
<del> } else if (base.hasOwnProperty(key) && typeof base[key] === "object" && base[key] !== null && typeof value === "object") {
<del> // If we are overwriting an object with an object, do a merge of the properties.
<del> base[key] = helpers.configMerge(base[key], value);
<del>
<add> if (key === 'xAxes' || key === 'yAxes') {
<add> // These properties are arrays of items
<add> if (base.hasOwnProperty(key)) {
<add> helpers.each(value, function(valueObj, index) {
<add> var axisType = helpers.getValueOrDefault(valueObj.type, key === 'xAxes' ? 'category' : 'linear');
<add> var axisDefaults = Chart.scaleService.getScaleDefaults(axisType);
<add> if (index >= base[key].length || !base[key][index].type) {
<add> base[key].push(helpers.configMerge(axisDefaults, valueObj));
<add> } else if (valueObj.type && valueObj.type !== base[key][index].type) {
<add> // Type changed. Bring in the new defaults before we bring in valueObj so that valueObj can override the correct scale defaults
<add> base[key][index] = helpers.configMerge(base[key][index], axisDefaults, valueObj);
<add> } else {
<add> // Type is the same
<add> base[key][index] = helpers.configMerge(base[key][index], valueObj);
<add> }
<add> });
<ide> } else {
<del> // can just overwrite the value in this case
<del> base[key] = value;
<add> base[key] = [];
<add> helpers.each(value, function(valueObj) {
<add> var axisType = helpers.getValueOrDefault(valueObj.type, key === 'xAxes' ? 'category' : 'linear');
<add> base[key].push(helpers.configMerge(Chart.scaleService.getScaleDefaults(axisType), valueObj));
<add> });
<ide> }
<add> } else if (base.hasOwnProperty(key) && typeof base[key] === "object" && base[key] !== null && typeof value === "object") {
<add> // If we are overwriting an object with an object, do a merge of the properties.
<add> base[key] = helpers.configMerge(base[key], value);
<add>
<add> } else {
<add> // can just overwrite the value in this case
<add> base[key] = value;
<ide> }
<ide> });
<ide> | 2 |
Python | Python | remove dead code in tests | 40255ab00207f343d5e913c616c20f0f79504bfe | <ide><path>transformers/tests/modeling_tf_common_test.py
<ide> def test_attention_outputs(self):
<ide> self.model_tester.seq_length,
<ide> self.model_tester.key_len if hasattr(self.model_tester, 'key_len') else self.model_tester.seq_length])
<ide>
<del> def test_headmasking(self):
<del> pass
<del> # config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<del>
<del> # config.output_attentions = True
<del> # config.output_hidden_states = True
<del> # configs_no_init = _config_zero_init(config) # To be sure we have no Nan
<del> # for model_class in self.all_model_classes:
<del> # model = model_class(config=configs_no_init)
<del> # model.eval()
<del>
<del> # # Prepare head_mask
<del> # # Set require_grad after having prepared the tensor to avoid error (leaf variable has been moved into the graph interior)
<del> # head_mask = torch.ones(self.model_tester.num_hidden_layers, self.model_tester.num_attention_heads)
<del> # head_mask[0, 0] = 0
<del> # head_mask[-1, :-1] = 0
<del> # head_mask.requires_grad_(requires_grad=True)
<del> # inputs = inputs_dict.copy()
<del> # inputs['head_mask'] = head_mask
<del>
<del> # outputs = model(**inputs)
<del>
<del> # # Test that we can get a gradient back for importance score computation
<del> # output = sum(t.sum() for t in outputs[0])
<del> # output = output.sum()
<del> # output.backward()
<del> # multihead_outputs = head_mask.grad
<del>
<del> # attentions = outputs[-1]
<del> # hidden_states = outputs[-2]
<del>
<del> # # Remove Nan
<del>
<del> # self.assertIsNotNone(multihead_outputs)
<del> # self.assertEqual(len(multihead_outputs), self.model_tester.num_hidden_layers)
<del> # self.assertAlmostEqual(
<del> # attentions[0][..., 0, :, :].flatten().sum().item(), 0.0)
<del> # self.assertNotEqual(
<del> # attentions[0][..., -1, :, :].flatten().sum().item(), 0.0)
<del> # self.assertNotEqual(
<del> # attentions[1][..., 0, :, :].flatten().sum().item(), 0.0)
<del> # self.assertAlmostEqual(
<del> # attentions[-1][..., -2, :, :].flatten().sum().item(), 0.0)
<del> # self.assertNotEqual(
<del> # attentions[-1][..., -1, :, :].flatten().sum().item(), 0.0)
<del>
<del>
<del> def test_head_pruning(self):
<del> pass
<del> # if not self.test_pruning:
<del> # return
<del>
<del> # config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<del>
<del> # for model_class in self.all_model_classes:
<del> # config.output_attentions = True
<del> # config.output_hidden_states = False
<del> # model = model_class(config=config)
<del> # model.eval()
<del> # heads_to_prune = {0: list(range(1, self.model_tester.num_attention_heads)),
<del> # -1: [0]}
<del> # model.prune_heads(heads_to_prune)
<del> # outputs = model(**inputs_dict)
<del>
<del> # attentions = outputs[-1]
<del>
<del> # self.assertEqual(
<del> # attentions[0].shape[-3], 1)
<del> # self.assertEqual(
<del> # attentions[1].shape[-3], self.model_tester.num_attention_heads)
<del> # self.assertEqual(
<del> # attentions[-1].shape[-3], self.model_tester.num_attention_heads - 1)
<del>
<del>
<ide> def test_hidden_states_output(self):
<ide> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<ide>
<ide> def test_hidden_states_output(self):
<ide> list(hidden_states[0].shape[-2:]),
<ide> [self.model_tester.seq_length, self.model_tester.hidden_size])
<ide>
<del>
<del> def test_resize_tokens_embeddings(self):
<del> pass
<del> # original_config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<del> # if not self.test_resize_embeddings:
<del> # return
<del>
<del> # for model_class in self.all_model_classes:
<del> # config = copy.deepcopy(original_config)
<del> # model = model_class(config)
<del>
<del> # model_vocab_size = config.vocab_size
<del> # # Retrieve the embeddings and clone theme
<del> # model_embed = model.resize_token_embeddings(model_vocab_size)
<del> # cloned_embeddings = model_embed.weight.clone()
<del>
<del> # # Check that resizing the token embeddings with a larger vocab size increases the model's vocab size
<del> # model_embed = model.resize_token_embeddings(model_vocab_size + 10)
<del> # self.assertEqual(model.config.vocab_size, model_vocab_size + 10)
<del> # # Check that it actually resizes the embeddings matrix
<del> # self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] + 10)
<del>
<del> # # Check that resizing the token embeddings with a smaller vocab size decreases the model's vocab size
<del> # model_embed = model.resize_token_embeddings(model_vocab_size - 15)
<del> # self.assertEqual(model.config.vocab_size, model_vocab_size - 15)
<del> # # Check that it actually resizes the embeddings matrix
<del> # self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] - 15)
<del>
<del> # # Check that adding and removing tokens has not modified the first part of the embedding matrix.
<del> # models_equal = True
<del> # for p1, p2 in zip(cloned_embeddings, model_embed.weight):
<del> # if p1.data.ne(p2.data).sum() > 0:
<del> # models_equal = False
<del>
<del> # self.assertTrue(models_equal)
<del>
<del>
<ide> def test_model_common_attributes(self):
<ide> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<ide>
<ide> def test_model_common_attributes(self):
<ide> x = model.get_output_embeddings()
<ide> assert x is None or isinstance(x, tf.keras.layers.Layer)
<ide>
<del>
<del> def test_tie_model_weights(self):
<del> pass
<del> # config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<del>
<del> # def check_same_values(layer_1, layer_2):
<del> # equal = True
<del> # for p1, p2 in zip(layer_1.weight, layer_2.weight):
<del> # if p1.data.ne(p2.data).sum() > 0:
<del> # equal = False
<del> # return equal
<del>
<del> # for model_class in self.all_model_classes:
<del> # if not hasattr(model_class, 'tie_weights'):
<del> # continue
<del>
<del> # config.torchscript = True
<del> # model_not_tied = model_class(config)
<del> # params_not_tied = list(model_not_tied.parameters())
<del>
<del> # config_tied = copy.deepcopy(config)
<del> # config_tied.torchscript = False
<del> # model_tied = model_class(config_tied)
<del> # params_tied = list(model_tied.parameters())
<del>
<del> # # Check that the embedding layer and decoding layer are the same in size and in value
<del> # self.assertGreater(len(params_not_tied), len(params_tied))
<del>
<del> # # Check that after resize they remain tied.
<del> # model_tied.resize_token_embeddings(config.vocab_size + 10)
<del> # params_tied_2 = list(model_tied.parameters())
<del> # self.assertGreater(len(params_not_tied), len(params_tied))
<del> # self.assertEqual(len(params_tied_2), len(params_tied))
<del>
<ide> def test_determinism(self):
<ide> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<ide>
<ide> def ids_tensor(shape, vocab_size, rng=None, name=None, dtype=None):
<ide> return output
<ide>
<ide>
<del>class TFModelUtilsTest(unittest.TestCase):
<del> @pytest.mark.skipif('tensorflow' not in sys.modules, reason="requires TensorFlow")
<del> def test_model_from_pretrained(self):
<del> pass
<del> # logging.basicConfig(level=logging.INFO)
<del> # for model_name in list(BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<del> # config = BertConfig.from_pretrained(model_name)
<del> # self.assertIsNotNone(config)
<del> # self.assertIsInstance(config, PretrainedConfig)
<del>
<del> # model = BertModel.from_pretrained(model_name)
<del> # model, loading_info = BertModel.from_pretrained(model_name, output_loading_info=True)
<del> # self.assertIsNotNone(model)
<del> # self.assertIsInstance(model, PreTrainedModel)
<del> # for value in loading_info.values():
<del> # self.assertEqual(len(value), 0)
<del>
<del> # config = BertConfig.from_pretrained(model_name, output_attentions=True, output_hidden_states=True)
<del> # model = BertModel.from_pretrained(model_name, output_attentions=True, output_hidden_states=True)
<del> # self.assertEqual(model.config.output_attentions, True)
<del> # self.assertEqual(model.config.output_hidden_states, True)
<del> # self.assertEqual(model.config, config)
<del>
<del>
<ide> if __name__ == "__main__":
<ide> unittest.main() | 1 |
Ruby | Ruby | clarify the need to run command twice | 2af9c080799c25a0bb4f6f6b8d2685b6c0e47299 | <ide><path>railties/test/commands/dev_cache_test.rb
<ide> def teardown
<ide>
<ide> test 'dev:cache deletes file and outputs message' do
<ide> Dir.chdir(app_path) do
<del> output = `rails dev:cache`
<del> output = `rails dev:cache`
<add> `rails dev:cache` # Create caching file.
<add> output = `rails dev:cache` # Delete caching file.
<ide> assert_not File.exist?('tmp/caching-dev.txt')
<ide> assert_match(%r{Development mode is no longer being cached}, output)
<ide> end | 1 |
PHP | PHP | fix cs error | 8802e1fd42b3a4d1cb5e57e365039434ce483fde | <ide><path>tests/TestCase/Mailer/EmailTest.php
<ide> use Cake\Log\Log;
<ide> use Cake\Mailer\Email;
<ide> use Cake\Mailer\Transport\DebugTransport;
<del>use Cake\Mailer\TransportFactory;
<ide> use Cake\TestSuite\TestCase;
<ide> use Exception;
<ide> use SimpleXmlElement; | 1 |
Go | Go | remove unused requireschema2 | 85fddc0081339ea12e6c7bd71f702aa737f589b2 | <ide><path>distribution/config.go
<ide> type Config struct {
<ide> // ReferenceStore manages tags. This value is optional, when excluded
<ide> // content will not be tagged.
<ide> ReferenceStore refstore.Store
<del> // RequireSchema2 ensures that only schema2 manifests are used.
<del> RequireSchema2 bool
<ide> }
<ide>
<ide> // ImagePullConfig stores pull configuration.
<ide><path>distribution/pull_v2.go
<ide> func (p *puller) pullTag(ctx context.Context, ref reference.Named, platform *spe
<ide>
<ide> switch v := manifest.(type) {
<ide> case *schema1.SignedManifest:
<del> if p.config.RequireSchema2 {
<del> return false, fmt.Errorf("invalid manifest: not schema2")
<del> }
<del>
<ide> // give registries time to upgrade to schema2 and only warn if we know a registry has been upgraded long time ago
<ide> // TODO: condition to be removed
<ide> if reference.Domain(ref) == "docker.io" {
<ide><path>distribution/push_v2.go
<ide> func (p *pusher) pushTag(ctx context.Context, ref reference.NamedTagged, id dige
<ide>
<ide> putOptions := []distribution.ManifestServiceOption{distribution.WithTag(ref.Tag())}
<ide> if _, err = manSvc.Put(ctx, manifest, putOptions...); err != nil {
<del> if runtime.GOOS == "windows" || p.config.RequireSchema2 {
<add> if runtime.GOOS == "windows" {
<ide> logrus.Warnf("failed to upload schema2 manifest: %v", err)
<ide> return err
<ide> } | 3 |
PHP | PHP | fix typo that was causing tests to fail | 7ab598656d07646323cc942aba4a5e49c28479d3 | <ide><path>lib/Cake/Network/Email/SmtpTransport.php
<ide> protected function _connect() {
<ide> $this->_socket->enableCrypto('tls');
<ide> $this->_smtpSend("EHLO {$host}", '250');
<ide> }
<del> } catch (Errpr\SocketException $e) {
<add> } catch (Error\SocketException $e) {
<ide> if ($this->_config['tls']) {
<ide> throw new Error\SocketException(__d('cake_dev', 'SMTP server did not accept the connection or trying to connect to non TLS SMTP server using TLS.'));
<ide> } | 1 |
Python | Python | add vision_encoder_decoder to models/__init__.py | 840fc8dbca9cfcfaaa6a2f7333294c7b740ed775 | <ide><path>src/transformers/models/__init__.py
<ide> t5,
<ide> tapas,
<ide> transfo_xl,
<add> vision_encoder_decoder,
<ide> visual_bert,
<ide> vit,
<ide> wav2vec2,
<ide><path>utils/check_repo.py
<ide> def get_model_modules():
<ide> "modeling_tf_pytorch_utils",
<ide> "modeling_tf_utils",
<ide> "modeling_tf_transfo_xl_utilities",
<add> "modeling_vision_encoder_decoder",
<ide> ]
<ide> modules = []
<ide> for model in dir(transformers.models): | 2 |
Javascript | Javascript | fix app crash caused by textinput | 53d18c83c8de220d3da5f30271a2e9a0765b8df2 | <ide><path>Libraries/Components/TextInput/TextInput.js
<ide> var TextInput = React.createClass({
<ide> this.props.onChange && this.props.onChange(event);
<ide> this.props.onChangeText && this.props.onChangeText(text);
<ide>
<add> if (!this.refs.input) {
<add> // calling `this.props.onChange` or `this.props.onChangeText`
<add> // may clean up the input itself. Exits here.
<add> return;
<add> }
<add>
<ide> // This is necessary in case native updates the text and JS decides
<ide> // that the update should be ignored and we should stick with the value
<ide> // that we have in JS. | 1 |
PHP | PHP | use self and static | ce821c04a0fe042892629217701307253626cf72 | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public function touchOwners()
<ide> {
<ide> $this->$relation()->touch();
<ide>
<del> if ($this->$relation instanceof Model)
<add> if ($this->$relation instanceof self)
<ide> {
<ide> $this->$relation->touchOwners();
<ide> }
<ide><path>src/Illuminate/Database/Query/Builder.php
<ide> public function selectSub($query, $as)
<ide> $callback($query = $this->newQuery());
<ide> }
<ide>
<del> if ($query instanceof Builder)
<add> if ($query instanceof self)
<ide> {
<ide> $bindings = $query->getBindings();
<ide>
<ide> public function truncate()
<ide> */
<ide> public function newQuery()
<ide> {
<del> return new Builder($this->connection, $this->grammar, $this->processor);
<add> return new static($this->connection, $this->grammar, $this->processor);
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Support/Collection.php
<ide> public function __toString()
<ide> */
<ide> protected function getArrayableItems($items)
<ide> {
<del> if ($items instanceof Collection)
<add> if ($items instanceof self)
<ide> {
<ide> $items = $items->all();
<ide> } | 3 |
Python | Python | add a high max for mlperf tests so they are green. | 2533c6978e9b57d8d8dfd6f11bcedcdd73d2f15d | <ide><path>official/recommendation/ncf_keras_benchmark.py
<ide> def _run_and_report_benchmark_mlperf_like(self):
<ide> Note: MLPerf like tests are not tuned to hit a specific hr@10 value, but
<ide> we want it recorded.
<ide> """
<del> self._run_and_report_benchmark(hr_at_10_min=0.61)
<add> self._run_and_report_benchmark(hr_at_10_min=0.61, hr_at_10_max=0.65)
<ide>
<ide> def _run_and_report_benchmark(self, hr_at_10_min=0.630, hr_at_10_max=0.640):
<ide> """Run test and report results. | 1 |
Text | Text | use function form of this.setstate | 5de58ad98d5047e6a00e9a298fcf2f01f83e5da6 | <ide><path>curriculum/challenges/english/03-front-end-libraries/react/bind-this-to-a-class-method.english.md
<ide> One common way is to explicitly bind <code>this</code> in the constructor so <co
<ide>
<ide> ## Instructions
<ide> <section id='instructions'>
<del>The code editor has a component with a <code>state</code> that keeps track of an item count. It also has a method which allows you to increment this item count. However, the method doesn't work because it's using the <code>this</code> keyword that is undefined. Fix it by explicitly binding <code>this</code> to the <code>addItem()</code> method in the component's constructor.
<del>Next, add a click handler to the <code>button</code> element in the render method. It should trigger the <code>addItem()</code> method when the button receives a click event. Remember that the method you pass to the <code>onClick</code> handler needs curly braces because it should be interpreted directly as JavaScript.
<del>Once you complete the above steps you should be able to click the button and see the item count increment in the HTML.
<add>The code editor has a component with a <code>state</code> that keeps track of the text. It also has a method which allows you to set the text to <code>"You clicked!"</code>. However, the method doesn't work because it's using the <code>this</code> keyword that is undefined. Fix it by explicitly binding <code>this</code> to the <code>handleClick()</code> method in the component's constructor.
<add>Next, add a click handler to the <code>button</code> element in the render method. It should trigger the <code>handleClick()</code> method when the button receives a click event. Remember that the method you pass to the <code>onClick</code> handler needs curly braces because it should be interpreted directly as JavaScript.
<add>Once you complete the above steps you should be able to click the button and see <code>You clicked!</code>.
<ide> </section>
<ide>
<ide> ## Tests
<ide> Once you complete the above steps you should be able to click the button and see
<ide> tests:
<ide> - text: <code>MyComponent</code> should return a <code>div</code> element which wraps two elements, a button and an <code>h1</code> element, in that order.
<ide> testString: assert(Enzyme.mount(React.createElement(MyComponent)).find('div').length === 1 && Enzyme.mount(React.createElement(MyComponent)).find('div').childAt(0).type() === 'button' && Enzyme.mount(React.createElement(MyComponent)).find('div').childAt(1).type() === 'h1');
<del> - text: 'The state of <code>MyComponent</code> should initialize with the key value pair <code>{ itemCount: 0 }</code>.'
<del> testString: 'assert(Enzyme.mount(React.createElement(MyComponent)).state(''itemCount'') === 0);'
<del> - text: Clicking the <code>button</code> element should run the <code>addItem</code> method and increment the state <code>itemCount</code> by <code>1</code>.
<del> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ itemCount: 0 }); return waitForIt(() => mockedComponent.state(''itemCount'')); }; const second = () => { mockedComponent.find(''button'').simulate(''click''); return waitForIt(() => mockedComponent.state(''itemCount'')); }; const firstValue = await first(); const secondValue = await second(); assert(firstValue === 0 && secondValue === 1); };'
<add> - text: 'The state of <code>MyComponent</code> should initialize with the key value pair <code>{ text: "Hello" }</code>.'
<add> testString: 'assert(Enzyme.mount(React.createElement(MyComponent)).state(''text'') === ''Hello'');'
<add> - text: Clicking the <code>button</code> element should run the <code>handleClick</code> method and set the state <code>text</code> to <code>"You clicked!"</code>.
<add> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ text: ''Hello'' }); return waitForIt(() => mockedComponent.state(''text'')); }; const second = () => { mockedComponent.find(''button'').simulate(''click''); return waitForIt(() => mockedComponent.state(''text'')); }; const firstValue = await first(); const secondValue = await second(); assert(firstValue === ''Hello'' && secondValue === ''You clicked!''); };'
<ide>
<ide> ```
<ide>
<ide> class MyComponent extends React.Component {
<ide> constructor(props) {
<ide> super(props);
<ide> this.state = {
<del> itemCount: 0
<add> text: "Hello"
<ide> };
<ide> // change code below this line
<ide>
<ide> // change code above this line
<ide> }
<del> addItem() {
<add> handleClick() {
<ide> this.setState({
<del> itemCount: this.state.itemCount + 1
<add> text: "You clicked!"
<ide> });
<ide> }
<ide> render() {
<ide> class MyComponent extends React.Component {
<ide> { /* change code below this line */ }
<ide> <button>Click Me</button>
<ide> { /* change code above this line */ }
<del> <h1>Current Item Count: {this.state.itemCount}</h1>
<add> <h1>{this.state.text}</h1>
<ide> </div>
<ide> );
<ide> }
<ide> class MyComponent extends React.Component {
<ide> constructor(props) {
<ide> super(props);
<ide> this.state = {
<del> itemCount: 0
<add> text: "Hello"
<ide> };
<del> this.addItem = this.addItem.bind(this);
<add> this.handleClick = this.handleClick.bind(this);
<ide> }
<del> addItem() {
<add> handleClick() {
<ide> this.setState({
<del> itemCount: this.state.itemCount + 1
<add> text: "You clicked!"
<ide> });
<ide> }
<ide> render() {
<ide> return (
<ide> <div>
<del> <button onClick = {this.addItem}>Click Me</button>
<del> <h1>Current Item Count: {this.state.itemCount}</h1>
<add> <button onClick = {this.handleClick}>Click Me</button>
<add> <h1>{this.state.text}</h1>
<ide> </div>
<ide> );
<ide> }
<ide><path>curriculum/challenges/english/03-front-end-libraries/react/use--for-a-more-concise-conditional.english.md
<ide> class MyComponent extends React.Component {
<ide> this.toggleDisplay = this.toggleDisplay.bind(this);
<ide> }
<ide> toggleDisplay() {
<del> this.setState({
<del> display: !this.state.display
<del> });
<add> this.setState(state => ({
<add> display: !state.display
<add> }));
<ide> }
<ide> render() {
<ide> // change code below this line
<ide> class MyComponent extends React.Component {
<ide> this.toggleDisplay = this.toggleDisplay.bind(this);
<ide> }
<ide> toggleDisplay() {
<del> this.setState({
<del> display: !this.state.display
<del> });
<add> this.setState(state => ({
<add> display: !state.display
<add> }));
<ide> }
<ide> render() {
<ide> // change code below this line
<ide><path>curriculum/challenges/english/03-front-end-libraries/react/use-a-ternary-expression-for-conditional-rendering.english.md
<ide> class CheckUserAge extends React.Component {
<ide> });
<ide> }
<ide> submit() {
<del> this.setState({
<del> userAge: this.state.input
<del> });
<add> this.setState(state => ({
<add> userAge: state.input
<add> }));
<ide> }
<ide> render() {
<ide> const buttonOne = <button onClick={this.submit}>Submit</button>;
<ide> class CheckUserAge extends React.Component {
<ide> });
<ide> }
<ide> submit() {
<del> this.setState({
<del> userAge: this.state.input
<del> });
<add> this.setState(state => ({
<add> userAge: state.input
<add> }));
<ide> }
<ide> render() {
<ide> const buttonOne = <button onClick={this.submit}>Submit</button>;
<ide><path>curriculum/challenges/english/03-front-end-libraries/react/use-state-to-toggle-an-element.english.md
<ide> forumTopicId: 301421
<ide>
<ide> ## Description
<ide> <section id='description'>
<del>You can use <code>state</code> in React applications in more complex ways than what you've seen so far. One example is to monitor the status of a value, then render the UI conditionally based on this value. There are several different ways to accomplish this, and the code editor shows one method.
<add>Sometimes you might need to know the previous state when updating the state. However, state updates may be asynchronous - this means React may batch multiple <code>setState()</code> calls into a single update. This means you can't rely on the previous value of <code>this.state</code> or <code>this.props</code> when calculating the next value. So, you should not use code like this:
<add>
<add>```js
<add>this.setState({
<add> counter: this.state.counter + this.props.increment
<add>});
<add>```
<add>
<add>Instead, you should pass <code>setState</code> a function that allows you to access state and props. Using a function with <code>setState</code> guarantees you are working with the most current values of state and props. This means that the above should be rewritten as:
<add>
<add>```js
<add>this.setState((state, props) => ({
<add> counter: state.counter + props.increment
<add>}));
<add>```
<add>
<add>You can also use a form without `props` if you need only the `state`:
<add>
<add>```js
<add>this.setState(state => ({
<add> counter: state.counter + 1
<add>}));
<add>```
<add>
<add>Note that you have to wrap the object literal in parentheses, otherwise JavaScript thinks it's a block of code.
<ide> </section>
<ide>
<ide> ## Instructions
<ide> <section id='instructions'>
<ide> <code>MyComponent</code> has a <code>visibility</code> property which is initialized to <code>false</code>. The render method returns one view if the value of <code>visibility</code> is true, and a different view if it is false.
<del>Currently, there is no way of updating the <code>visibility</code> property in the component's <code>state</code>. The value should toggle back and forth between true and false. There is a click handler on the button which triggers a class method called <code>toggleVisibility()</code>. Define this method so the <code>state</code> of <code>visibility</code> toggles to the opposite value when the method is called. If <code>visibility</code> is <code>false</code>, the method sets it to <code>true</code>, and vice versa.
<add>Currently, there is no way of updating the <code>visibility</code> property in the component's <code>state</code>. The value should toggle back and forth between true and false. There is a click handler on the button which triggers a class method called <code>toggleVisibility()</code>. Pass a function to <code>setState</code> to define this method so that the <code>state</code> of <code>visibility</code> toggles to the opposite value when the method is called. If <code>visibility</code> is <code>false</code>, the method sets it to <code>true</code>, and vice versa.
<ide> Finally, click the button to see the conditional rendering of the component based on its <code>state</code>.
<ide> <strong>Hint:</strong> Don't forget to bind the <code>this</code> keyword to the method in the constructor!
<ide> </section>
<ide> tests:
<ide> testString: assert.strictEqual(Enzyme.mount(React.createElement(MyComponent)).state('visibility'), false);
<ide> - text: Clicking the button element should toggle the <code>visibility</code> property in state between <code>true</code> and <code>false</code>.
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ visibility: false }); return waitForIt(() => mockedComponent.state(''visibility'')); }; const second = () => { mockedComponent.find(''button'').simulate(''click''); return waitForIt(() => mockedComponent.state(''visibility'')); }; const third = () => { mockedComponent.find(''button'').simulate(''click''); return waitForIt(() => mockedComponent.state(''visibility'')); }; const firstValue = await first(); const secondValue = await second(); const thirdValue = await third(); assert(!firstValue && secondValue && !thirdValue); }; '
<add> - text: An anonymous function should be passed to <code>setState</code>.
<add> testString: const paramRegex = '[a-zA-Z$_]\\w*(,[a-zA-Z$_]\\w*)?'; const noSpaces = code.replace(/\s/g, ''); assert(new RegExp('this\\.setState\\((function\\(' + paramRegex + '\\){|([a-zA-Z$_]\\w*|\\(' + paramRegex + '\\))=>)').test(noSpaces));
<add> - text: <code>this</code> should not be used inside <code>setState</code>
<add> testString: assert(!/this\.setState\([^}]*this/.test(code));
<ide>
<ide> ```
<ide>
<ide> class MyComponent extends React.Component {
<ide> this.toggleVisibility = this.toggleVisibility.bind(this);
<ide> }
<ide> toggleVisibility() {
<del> this.setState({
<del> visibility: !this.state.visibility
<del> });
<add> this.setState(state => ({
<add> visibility: !state.visibility
<add> }));
<ide> }
<ide> render() {
<ide> if (this.state.visibility) {
<ide><path>curriculum/challenges/english/03-front-end-libraries/react/write-a-simple-counter.english.md
<ide> class Counter extends React.Component {
<ide> });
<ide> }
<ide> increment() {
<del> this.setState({
<del> count: this.state.count + 1
<del> });
<add> this.setState(state => ({
<add> count: state.count + 1
<add> }));
<ide> }
<ide> decrement() {
<del> this.setState({
<del> count: this.state.count - 1
<del> });
<add> this.setState(state => ({
<add> count: state.count - 1
<add> }));
<ide> }
<ide> render() {
<ide> return ( | 5 |
Text | Text | remove redundant table of contents for n-api | d3abb60b050858af6d5dff7fdd67cf94c76936b8 | <ide><path>doc/api/n-api.md
<ide> properties:
<ide> using `napi_get_last_error_info`. More information can be found in the error
<ide> handling section [Error Handling][].
<ide>
<del>The documentation for N-API is structured as follows:
<del>
<del>* [Basic N-API Data Types][]
<del>* [Error Handling][]
<del>* [Object Lifetime Management][]
<del>* [Module Registration][]
<del>* [Working with JavaScript Values][]
<del>* [Working with JavaScript Values - Abstract Operations][]
<del>* [Working with JavaScript Properties][]
<del>* [Working with JavaScript Functions][]
<del>* [Object Wrap][]
<del>* [Simple Asynchronous Operations][]
<del>* [Custom Asynchronous Operations][]
<del>* [Promises][]
<del>* [Script Execution][]
<del>
<ide> The N-API is a C API that ensures ABI stability across Node.js versions
<ide> and different compiler levels. However, we also understand that a C++
<ide> API can be easier to use in many cases. To support these cases we expect
<ide> NAPI_EXTERN napi_status napi_get_uv_event_loop(napi_env env,
<ide> - `[in] env`: The environment that the API is invoked under.
<ide> - `[out] loop`: The current libuv loop instance.
<ide>
<del>[Promises]: #n_api_promises
<del>[Simple Asynchronous Operations]: #n_api_simple_asynchronous_operations
<del>[Custom Asynchronous Operations]: #n_api_custom_asynchronous_operations
<del>[Basic N-API Data Types]: #n_api_basic_n_api_data_types
<ide> [ECMAScript Language Specification]: https://tc39.github.io/ecma262/
<ide> [Error Handling]: #n_api_error_handling
<del>[Module Registration]: #n_api_module_registration
<ide> [Native Abstractions for Node.js]: https://github.com/nodejs/nan
<ide> [Object Lifetime Management]: #n_api_object_lifetime_management
<ide> [Object Wrap]: #n_api_object_wrap
<del>[Script Execution]: #n_api_script_execution
<ide> [Section 6.1.4]: https://tc39.github.io/ecma262/#sec-ecmascript-language-types-string-type
<ide> [Section 6.1.6]: https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type
<ide> [Section 6.1.7.1]: https://tc39.github.io/ecma262/#table-2 | 1 |
Python | Python | fix libcloud connection class | 366310b2694bbbbb306998eadfa12c05e561c005 | <ide><path>libcloud/utils/loggingconnection.py
<ide> from pipes import quote as pquote
<ide> from xml.dom.minidom import parseString
<ide>
<del>import sys
<ide> import os
<ide>
<ide> from libcloud.common.base import (LibcloudConnection,
<del> HTTPResponse,
<ide> HttpLibResponseProxy)
<del>from libcloud.utils.py3 import httplib
<del>from libcloud.utils.py3 import PY3
<del>from libcloud.utils.py3 import StringIO
<ide> from libcloud.utils.py3 import u
<del>from libcloud.utils.py3 import b
<del>
<ide>
<ide> from libcloud.utils.misc import lowercase_keys
<ide> from libcloud.utils.compression import decompress_data
<ide> def _log_response(self, r):
<ide> ht += "%s: %s\r\n" % (h[0].title(), h[1])
<ide> ht += "\r\n"
<ide>
<del> # this is evil. laugh with me. ha arharhrhahahaha
<del> class fakesock(object):
<del> def __init__(self, s):
<del> self.s = s
<del>
<del> def makefile(self, *args, **kwargs):
<del> if PY3:
<del> from io import BytesIO
<del> cls = BytesIO
<del> else:
<del> cls = StringIO
<del>
<del> return cls(b(self.s))
<del> rr = r
<ide> headers = lowercase_keys(dict(r.getheaders()))
<ide>
<ide> encoding = headers.get('content-encoding', None)
<ide> def makefile(self, *args, **kwargs):
<ide> pretty_print = os.environ.get('LIBCLOUD_DEBUG_PRETTY_PRINT_RESPONSE',
<ide> False)
<ide>
<del> if r.chunked:
<del> ht += "%x\r\n" % (len(body))
<del> ht += body.decode('utf-8')
<del> ht += "\r\n0\r\n"
<del> else:
<del> if pretty_print and content_type == 'application/json':
<del> try:
<del> body = json.loads(body.decode('utf-8'))
<del> body = json.dumps(body, sort_keys=True, indent=4)
<del> except:
<del> # Invalid JSON or server is lying about content-type
<del> pass
<del> elif pretty_print and content_type == 'text/xml':
<del> try:
<del> elem = parseString(body.decode('utf-8'))
<del> body = elem.toprettyxml()
<del> except Exception:
<del> # Invalid XML
<del> pass
<del>
<del> ht += u(body)
<del>
<del> if sys.version_info >= (2, 6) and sys.version_info < (2, 7):
<del> cls = HTTPResponse
<del> else:
<del> cls = httplib.HTTPResponse
<add> if pretty_print and content_type == 'application/json':
<add> try:
<add> body = json.loads(body.decode('utf-8'))
<add> body = json.dumps(body, sort_keys=True, indent=4)
<add> except:
<add> # Invalid JSON or server is lying about content-type
<add> pass
<add> elif pretty_print and content_type == 'text/xml':
<add> try:
<add> elem = parseString(body.decode('utf-8'))
<add> body = elem.toprettyxml()
<add> except Exception:
<add> # Invalid XML
<add> pass
<add>
<add> ht += u(body)
<ide>
<del> rr = cls(sock=fakesock(ht), method=r._method,
<del> debuglevel=r.debuglevel)
<del> rr.begin()
<ide> rv += ht
<ide> rv += ("\n# -------- end %d:%d response ----------\n"
<ide> % (id(self), id(r)))
<ide>
<del> rr._original_data = body
<del> return (rr, rv)
<add> return rv
<ide>
<ide> def _log_curl(self, method, url, body, headers):
<ide> cmd = ["curl"]
<ide> def _log_curl(self, method, url, body, headers):
<ide> return " ".join(cmd)
<ide>
<ide> def getresponse(self):
<del> r = HttpLibResponseProxy(LibcloudConnection.getresponse(self))
<add> original_response = LibcloudConnection.getresponse(self)
<ide> if self.log is not None:
<del> r, rv = self._log_response(r)
<add> rv = self._log_response(HttpLibResponseProxy(original_response))
<ide> self.log.write(rv + "\n")
<ide> self.log.flush()
<del> return r
<add> return original_response
<ide>
<ide> def request(self, method, url, body=None, headers=None):
<ide> headers.update({'X-LC-Request-ID': str(id(self))}) | 1 |
Javascript | Javascript | remove unneeded `--expose-internals` | 556de23dfbc829903f97b0a253ae71c1414fab13 | <ide><path>test/wpt/test-timers.js
<ide> 'use strict';
<ide>
<del>// Flags: --expose-internals
<del>
<ide> require('../common');
<ide> const { WPTRunner } = require('../common/wpt');
<ide> | 1 |
Python | Python | obtain sentence for each mention | 4392c01b7bfb22e435249128ac15c196c5b50bd1 | <ide><path>examples/pipeline/wiki_entity_linking/run_el.py
<ide> def is_dev(file_name):
<ide> return file_name.endswith("3.txt")
<ide>
<ide>
<del>def evaluate(predictions, golds, to_print=True):
<add>def evaluate(predictions, golds, to_print=True, times_hundred=True):
<ide> if len(predictions) != len(golds):
<ide> raise ValueError("predictions and gold entities should have the same length")
<ide>
<ide> def evaluate(predictions, golds, to_print=True):
<ide> print("fp", fp)
<ide> print("fn", fn)
<ide>
<del> precision = 100 * tp / (tp + fp + 0.0000001)
<del> recall = 100 * tp / (tp + fn + 0.0000001)
<add> precision = tp / (tp + fp + 0.0000001)
<add> recall = tp / (tp + fn + 0.0000001)
<add> if times_hundred:
<add> precision = precision*100
<add> recall = recall*100
<ide> fscore = 2 * recall * precision / (recall + precision + 0.0000001)
<ide>
<ide> accuracy = corrects / (corrects + incorrects)
<ide><path>examples/pipeline/wiki_entity_linking/train_el.py
<ide> from thinc.misc import Residual
<ide> from thinc.misc import LayerNorm as LN
<ide>
<add>from spacy.matcher import PhraseMatcher
<ide> from spacy.tokens import Doc
<ide>
<ide> """ TODO: this code needs to be implemented in pipes.pyx"""
<ide>
<ide>
<ide> class EL_Model:
<ide>
<add> PRINT_INSPECT = False
<ide> PRINT_TRAIN = False
<ide> EPS = 0.0000000005
<ide> CUTOFF = 0.5
<ide>
<ide> BATCH_SIZE = 5
<ide>
<del> INPUT_DIM = 300
<add> DOC_CUTOFF = 300 # number of characters from the doc context
<add> INPUT_DIM = 300 # dimension of pre-trained vectors
<add>
<ide> HIDDEN_1_WIDTH = 32 # 10
<ide> HIDDEN_2_WIDTH = 32 # 6
<ide> DESC_WIDTH = 64 # 4
<ide> def train_model(self, training_dir, entity_descr_output, trainlimit=None, devlim
<ide> # raise errors instead of runtime warnings in case of int/float overflow
<ide> np.seterr(all='raise')
<ide>
<del> train_ent, train_gold, train_desc, train_article, train_texts = self._get_training_data(training_dir,
<del> entity_descr_output,
<del> False,
<del> trainlimit,
<del> to_print=False)
<add> train_ent, train_gold, train_desc, train_art, train_art_texts, train_sent, train_sent_texts = \
<add> self._get_training_data(training_dir, entity_descr_output, False, trainlimit, to_print=False)
<add>
<add> # inspect data
<add> if self.PRINT_INSPECT:
<add> for entity in train_ent:
<add> print("entity", entity)
<add> print("gold", train_gold[entity])
<add> print("desc", train_desc[entity])
<add> print("sentence ID", train_sent[entity])
<add> print("sentence text", train_sent_texts[train_sent[entity]])
<add> print("article ID", train_art[entity])
<add> print("article text", train_art_texts[train_art[entity]])
<add> print()
<ide>
<ide> train_pos_entities = [k for k,v in train_gold.items() if v]
<ide> train_neg_entities = [k for k,v in train_gold.items() if not v]
<ide>
<ide> train_pos_count = len(train_pos_entities)
<ide> train_neg_count = len(train_neg_entities)
<ide>
<add> if to_print:
<add> print()
<add> print("Upsampling, original training instances pos/neg:", train_pos_count, train_neg_count)
<add>
<ide> # upsample positives to 50-50 distribution
<ide> while train_pos_count < train_neg_count:
<ide> train_ent.append(random.choice(train_pos_entities))
<ide> def train_model(self, training_dir, entity_descr_output, trainlimit=None, devlim
<ide>
<ide> shuffle(train_ent)
<ide>
<del> dev_ent, dev_gold, dev_desc, dev_article, dev_texts = self._get_training_data(training_dir,
<del> entity_descr_output,
<del> True,
<del> devlimit,
<del> to_print=False)
<add> dev_ent, dev_gold, dev_desc, dev_art, dev_art_texts, dev_sent, dev_sent_texts = \
<add> self._get_training_data(training_dir, entity_descr_output, True, devlimit, to_print=False)
<ide> shuffle(dev_ent)
<ide>
<ide> dev_pos_count = len([g for g in dev_gold.values() if g])
<ide> dev_neg_count = len([g for g in dev_gold.values() if not g])
<ide>
<ide> self._begin_training()
<ide>
<del> print()
<del> self._test_dev(dev_ent, dev_gold, dev_desc, dev_article, dev_texts, print_string="dev_random", calc_random=True)
<del> print()
<del> self._test_dev(dev_ent, dev_gold, dev_desc, dev_article, dev_texts, print_string="dev_pre", avg=True)
<del>
<ide> if to_print:
<ide> print()
<del> print("Training on", len(train_ent), "entities in", len(train_texts), "articles")
<del> print("Training instances pos/neg", train_pos_count, train_neg_count)
<add> print("Training on", len(train_ent), "entities in", len(train_art_texts), "articles")
<add> print("Training instances pos/neg:", train_pos_count, train_neg_count)
<ide> print()
<del> print("Dev test on", len(dev_ent), "entities in", len(dev_texts), "articles")
<del> print("Dev instances pos/neg", dev_pos_count, dev_neg_count)
<add> print("Dev test on", len(dev_ent), "entities in", len(dev_art_texts), "articles")
<add> print("Dev instances pos/neg:", dev_pos_count, dev_neg_count)
<ide> print()
<ide> print(" CUTOFF", self.CUTOFF)
<add> print(" DOC_CUTOFF", self.DOC_CUTOFF)
<ide> print(" INPUT_DIM", self.INPUT_DIM)
<ide> print(" HIDDEN_1_WIDTH", self.HIDDEN_1_WIDTH)
<ide> print(" DESC_WIDTH", self.DESC_WIDTH)
<ide> def train_model(self, training_dir, entity_descr_output, trainlimit=None, devlim
<ide> print(" DROP", self.DROP)
<ide> print()
<ide>
<add> self._test_dev(dev_ent, dev_gold, dev_desc, dev_art, dev_art_texts, print_string="dev_random", calc_random=True)
<add> self._test_dev(dev_ent, dev_gold, dev_desc, dev_art, dev_art_texts, print_string="dev_pre", avg=True)
<add> print()
<add>
<ide> start = 0
<ide> stop = min(self.BATCH_SIZE, len(train_ent))
<ide> processed = 0
<ide> def train_model(self, training_dir, entity_descr_output, trainlimit=None, devlim
<ide>
<ide> golds = [train_gold[e] for e in next_batch]
<ide> descs = [train_desc[e] for e in next_batch]
<del> articles = [train_texts[train_article[e]] for e in next_batch]
<add> articles = [train_art_texts[train_art[e]] for e in next_batch]
<ide>
<ide> self.update(entities=next_batch, golds=golds, descs=descs, texts=articles)
<del> self._test_dev(dev_ent, dev_gold, dev_desc, dev_article, dev_texts, print_string="dev_inter", avg=True)
<add> self._test_dev(dev_ent, dev_gold, dev_desc, dev_art, dev_art_texts, print_string="dev_inter", avg=True)
<ide>
<ide> processed += len(next_batch)
<ide>
<ide> def _test_dev(self, entities, gold_by_entity, desc_by_entity, article_by_entity,
<ide> predictions = self._predict(entities=entities, article_docs=article_docs, desc_docs=desc_docs, avg=avg)
<ide>
<ide> # TODO: combine with prior probability
<del> p, r, f, acc = run_el.evaluate(predictions, golds, to_print=False)
<add> p, r, f, acc = run_el.evaluate(predictions, golds, to_print=False, times_hundred=False)
<ide> loss, gradient = self.get_loss(self.model.ops.asarray(predictions), self.model.ops.asarray(golds))
<ide>
<ide> print("p/r/F/acc/loss", print_string, round(p, 1), round(r, 1), round(f, 1), round(acc, 2), round(loss, 5))
<ide> def _get_training_data(self, training_dir, entity_descr_output, dev, limit, to_p
<ide> collect_incorrect=True)
<ide>
<ide> local_vectors = list() # TODO: local vectors
<del> text_by_article = dict()
<add>
<add> entities = set()
<ide> gold_by_entity = dict()
<ide> desc_by_entity = dict()
<ide> article_by_entity = dict()
<del> entities = list()
<add> text_by_article = dict()
<add> sentence_by_entity = dict()
<add> text_by_sentence = dict()
<ide>
<ide> cnt = 0
<del> next_entity_nr = 0
<add> next_entity_nr = 1
<add> next_sent_nr = 1
<ide> files = listdir(training_dir)
<ide> shuffle(files)
<ide> for f in files:
<ide> def _get_training_data(self, training_dir, entity_descr_output, dev, limit, to_p
<ide> if cnt % 500 == 0 and to_print:
<ide> print(datetime.datetime.now(), "processed", cnt, "files in the training dataset")
<ide> cnt += 1
<del> if article_id not in text_by_article:
<del> with open(os.path.join(training_dir, f), mode="r", encoding='utf8') as file:
<del> text = file.read()
<del> text_by_article[article_id] = text
<add>
<add> # parse the article text
<add> with open(os.path.join(training_dir, f), mode="r", encoding='utf8') as file:
<add> text = file.read()
<add> article_doc = self.nlp(text)
<add> truncated_text = text[0:min(self.DOC_CUTOFF, len(text))]
<add> text_by_article[article_id] = truncated_text
<add>
<add> # process all positive and negative entities, collect all relevant mentions in this article
<add> article_terms = set()
<add> entities_by_mention = dict()
<ide>
<ide> for mention, entity_pos in correct_entries[article_id].items():
<ide> descr = id_to_descr.get(entity_pos)
<ide> if descr:
<del> entities.append(next_entity_nr)
<del> gold_by_entity[next_entity_nr] = 1
<del> desc_by_entity[next_entity_nr] = descr
<del> article_by_entity[next_entity_nr] = article_id
<add> entity = "E_" + str(next_entity_nr) + "_" + article_id + "_" + mention
<ide> next_entity_nr += 1
<add> gold_by_entity[entity] = 1
<add> desc_by_entity[entity] = descr
<add> article_terms.add(mention)
<add> mention_entities = entities_by_mention.get(mention, set())
<add> mention_entities.add(entity)
<add> entities_by_mention[mention] = mention_entities
<ide>
<ide> for mention, entity_negs in incorrect_entries[article_id].items():
<ide> for entity_neg in entity_negs:
<ide> descr = id_to_descr.get(entity_neg)
<ide> if descr:
<del> entities.append(next_entity_nr)
<del> gold_by_entity[next_entity_nr] = 0
<del> desc_by_entity[next_entity_nr] = descr
<del> article_by_entity[next_entity_nr] = article_id
<add> entity = "E_" + str(next_entity_nr) + "_" + article_id + "_" + mention
<ide> next_entity_nr += 1
<add> gold_by_entity[entity] = 0
<add> desc_by_entity[entity] = descr
<add> article_terms.add(mention)
<add> mention_entities = entities_by_mention.get(mention, set())
<add> mention_entities.add(entity)
<add> entities_by_mention[mention] = mention_entities
<add>
<add> # find all matches in the doc for the mentions
<add> # TODO: fix this - doesn't look like all entities are found
<add> matcher = PhraseMatcher(self.nlp.vocab)
<add> patterns = list(self.nlp.tokenizer.pipe(article_terms))
<add>
<add> matcher.add("TerminologyList", None, *patterns)
<add> matches = matcher(article_doc)
<add>
<add> # store sentences
<add> sentence_to_id = dict()
<add> for match_id, start, end in matches:
<add> span = article_doc[start:end]
<add> sent_text = span.sent
<add> sent_nr = sentence_to_id.get(sent_text, None)
<add> if sent_nr is None:
<add> sent_nr = "S_" + str(next_sent_nr) + article_id
<add> next_sent_nr += 1
<add> text_by_sentence[sent_nr] = sent_text
<add> sentence_to_id[sent_text] = sent_nr
<add> mention_entities = entities_by_mention[span.text]
<add> for entity in mention_entities:
<add> entities.add(entity)
<add> sentence_by_entity[entity] = sent_nr
<add> article_by_entity[entity] = article_id
<add>
<add> # remove entities that didn't have all data
<add> gold_by_entity = {k: v for k, v in gold_by_entity.items() if k in entities}
<add> desc_by_entity = {k: v for k, v in desc_by_entity.items() if k in entities}
<add>
<add> article_by_entity = {k: v for k, v in article_by_entity.items() if k in entities}
<add> text_by_article = {k: v for k, v in text_by_article.items() if k in article_by_entity.values()}
<add>
<add> sentence_by_entity = {k: v for k, v in sentence_by_entity.items() if k in entities}
<add> text_by_sentence = {k: v for k, v in text_by_sentence.items() if k in sentence_by_entity.values()}
<ide>
<ide> if to_print:
<ide> print()
<ide> print("Processed", cnt, "training articles, dev=" + str(dev))
<ide> print()
<del> return entities, gold_by_entity, desc_by_entity, article_by_entity, text_by_article
<add> return list(entities), gold_by_entity, desc_by_entity, article_by_entity, text_by_article, sentence_by_entity, text_by_sentence
<ide>
<ide><path>examples/pipeline/wiki_entity_linking/wiki_nel_pipeline.py
<ide> print("STEP 6: training", datetime.datetime.now())
<ide> my_nlp = spacy.load('en_core_web_md')
<ide> trainer = EL_Model(kb=my_kb, nlp=my_nlp)
<del> trainer.train_model(training_dir=TRAINING_DIR, entity_descr_output=ENTITY_DESCR, trainlimit=400, devlimit=50)
<add> trainer.train_model(training_dir=TRAINING_DIR, entity_descr_output=ENTITY_DESCR, trainlimit=100, devlimit=20)
<ide> print()
<ide>
<ide> # STEP 7: apply the EL algorithm on the dev dataset | 3 |
Javascript | Javascript | pass options to scrollintoview | 044e6ba9cd217a079d99a2274b3bf5f5e6d70875 | <ide><path>src/devtools/views/Element.js
<ide> export default function ElementView({ index, style }: Props) {
<ide> const component = useRef(null);
<ide> useEffect(() => {
<ide> if (isSelected && component.current !== null) {
<del> component.current.scrollIntoView();
<add> component.current.scrollIntoView({
<add> behavior: 'smooth',
<add> block: 'center',
<add> inline: 'center',
<add> });
<ide> }
<ide> }, [isSelected]);
<ide> | 1 |
PHP | PHP | fix tests under testsuite namespace | 5182d862348f90e781857404e52e0be1d52e9849 | <ide><path>src/Controller/Component/RequestHandlerComponent.php
<ide> public function implementedEvents()
<ide> return [
<ide> 'Controller.startup' => 'startup',
<ide> 'Controller.beforeRender' => 'beforeRender',
<del> 'Controller.beforeRedirect' => 'beforeRedirect',
<ide> ];
<ide> }
<ide>
<ide><path>tests/TestCase/TestSuite/CookieEncryptedUsingControllerTest.php
<del><?php
<del>/**
<del> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<del> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> * @link https://cakephp.org CakePHP Project
<del> * @since 3.1.6
<del> * @license https://opensource.org/licenses/mit-license.php MIT License
<del> */
<del>namespace Cake\Test\TestCase\Controller;
<del>
<del>use Cake\Routing\DispatcherFactory;
<del>use Cake\Routing\Router;
<del>use Cake\TestSuite\IntegrationTestCase;
<del>use Cake\Utility\Security;
<del>
<del>/**
<del> * CookieEncryptedUsingControllerTest class
<del> */
<del>class CookieEncryptedUsingControllerTest extends IntegrationTestCase
<del>{
<del> /**
<del> * reset environment.
<del> *
<del> * @return void
<del> */
<del> public function setUp()
<del> {
<del> parent::setUp();
<del> static::setAppNamespace();
<del>
<del> Security::setSalt('abcdabcdabcdabcdabcdabcdabcdabcdabcd');
<del> Router::connect('/:controller/:action/*', [], ['routeClass' => 'InflectedRoute']);
<del> $this->useHttpServer(true);
<del> }
<del>
<del> /**
<del> * Can encrypt/decrypt the cookie value.
<del> */
<del> public function testCanEncryptAndDecryptWithAes()
<del> {
<del> $this->cookieEncrypted('NameOfCookie', 'Value of Cookie', 'aes');
<del>
<del> $this->get('/cookie_component_test/view/');
<del> $this->assertStringStartsWith('Q2FrZQ==.', $this->viewVariable('ValueFromRequest'), 'Encrypted');
<del> $this->assertEquals('Value of Cookie', $this->viewVariable('ValueFromCookieComponent'), 'Decrypted');
<del> }
<del>
<del> /**
<del> * Can encrypt/decrypt the cookie value by default.
<del> */
<del> public function testCanEncryptAndDecryptCookieValue()
<del> {
<del> $this->cookieEncrypted('NameOfCookie', 'Value of Cookie');
<del>
<del> $this->get('/cookie_component_test/view/');
<del> $this->assertStringStartsWith('Q2FrZQ==.', $this->viewVariable('ValueFromRequest'), 'Encrypted');
<del> $this->assertEquals('Value of Cookie', $this->viewVariable('ValueFromCookieComponent'), 'Decrypted');
<del> }
<del>
<del> /**
<del> * Can encrypt/decrypt even if the cookie value are array.
<del> */
<del> public function testCanEncryptAndDecryptEvenIfCookieValueIsArray()
<del> {
<del> $this->cookieEncrypted('NameOfCookie', ['Value1 of Cookie', 'Value2 of Cookie']);
<del>
<del> $this->get('/cookie_component_test/view/');
<del> $this->assertStringStartsWith('Q2FrZQ==.', $this->viewVariable('ValueFromRequest'), 'Encrypted');
<del> $this->assertEquals(
<del> ['Value1 of Cookie', 'Value2 of Cookie'],
<del> $this->viewVariable('ValueFromCookieComponent'),
<del> 'Decrypted'
<del> );
<del> }
<del>
<del> /**
<del> * Can specify the encryption key.
<del> */
<del> public function testCanSpecifyEncryptionKey()
<del> {
<del> $key = 'another salt xxxxxxxxxxxxxxxxxxx';
<del> $this->cookieEncrypted('NameOfCookie', 'Value of Cookie', 'aes', $key);
<del>
<del> $this->get('/cookie_component_test/view/' . urlencode($key));
<del> $this->assertStringStartsWith('Q2FrZQ==.', $this->viewVariable('ValueFromRequest'), 'Encrypted');
<del> $this->assertEquals('Value of Cookie', $this->viewVariable('ValueFromCookieComponent'), 'Decrypted');
<del> }
<del>
<del> /**
<del> * Can be used in Security::setSalt() as the encryption key.
<del> */
<del> public function testCanBeUsedSecuritySaltAsEncryptionKey()
<del> {
<del> $key = 'another salt xxxxxxxxxxxxxxxxxxx';
<del> Security::setSalt($key);
<del> $this->cookieEncrypted('NameOfCookie', 'Value of Cookie', 'aes');
<del>
<del> $this->get('/cookie_component_test/view/' . urlencode($key));
<del> $this->assertStringStartsWith('Q2FrZQ==.', $this->viewVariable('ValueFromRequest'), 'Encrypted');
<del> $this->assertEquals('Value of Cookie', $this->viewVariable('ValueFromCookieComponent'), 'Decrypted');
<del> }
<del>
<del> /**
<del> * Can AssertCookie even if the value is encrypted by
<del> * the CookieComponent.
<del> */
<del> public function testCanAssertCookieEncrypted()
<del> {
<del> $this->get('/cookie_component_test/set_cookie');
<del> $this->assertCookieEncrypted('abc', 'NameOfCookie');
<del> }
<del>
<del> /**
<del> * Can AssertCookie even if encrypted with the aes.
<del> */
<del> public function testCanAssertCookieEncryptedWithAes()
<del> {
<del> $this->get('/cookie_component_test/set_cookie');
<del> $this->assertCookieEncrypted('abc', 'NameOfCookie', 'aes');
<del> }
<del>
<del> /**
<del> * Can AssertCookie even if encrypted with the another
<del> * encrypted key.
<del> */
<del> public function testCanAssertCookieEncryptedWithAnotherEncryptionKey()
<del> {
<del> $key = 'another salt xxxxxxxxxxxxxxxxxxx';
<del> Security::setSalt($key);
<del> $this->get('/cookie_component_test/set_cookie');
<del> $this->assertCookieEncrypted('abc', 'NameOfCookie', 'aes', $key);
<del> }
<del>
<del> /**
<del> * Can AssertCookie even if encrypted with the aes when using PSR7 server.
<del> */
<del> public function testCanAssertCookieEncryptedWithAesWhenUsingPsr7()
<del> {
<del> $this->useHttpServer(true);
<del> $this->get('/cookie_component_test/set_cookie');
<del> $this->assertCookieEncrypted('abc', 'NameOfCookie', 'aes');
<del> }
<del>}
<ide><path>tests/TestCase/TestSuite/IntegrationTestCaseTest.php
<ide> public function testGetQueryStringHttpServer()
<ide> $this->assertResponseContains('"contentType":"text\/plain"');
<ide> $this->assertHeader('X-Middleware', 'true');
<ide>
<del> $request = $this->_controller->request;
<add> $request = $this->_controller->getRequest();
<ide> $this->assertContains('/request_action/params_pass?q=query', $request->getRequestTarget());
<ide> }
<ide>
<ide> public function testGetQueryStringSetsHere()
<ide> $this->assertResponseContains('"contentType":"text\/plain"');
<ide> $this->assertHeader('X-Middleware', 'true');
<ide>
<del> $request = $this->_controller->request;
<add> $request = $this->_controller->getRequest();
<ide> $this->assertContains('/request_action/params_pass?q=query', $request->here());
<ide> $this->assertContains('/request_action/params_pass?q=query', $request->getRequestTarget());
<ide> });
<ide><path>tests/test_app/TestApp/Controller/CookieComponentTestController.php
<del><?php
<del>/**
<del> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<del> * Copyright 2005-2011, Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> * @link https://cakephp.org CakePHP(tm) Project
<del> * @since 3.1.6
<del> * @license https://opensource.org/licenses/mit-license.php MIT License
<del> */
<del>namespace TestApp\Controller;
<del>
<del>use Cake\Controller\Controller;
<del>
<del>/**
<del> * CookieComponentTestController class
<del> */
<del>class CookieComponentTestController extends Controller
<del>{
<del> /**
<del> * @var array
<del> */
<del> public $components = [
<del> 'Cookie',
<del> ];
<del>
<del> public $autoRender = false;
<del>
<del> /**
<del> * view
<del> *
<del> * @param string|null $key Encryption key used. By defaults,
<del> * CookieComponent::_config['key'].
<del> */
<del> public function view($key = null)
<del> {
<del> if (isset($key)) {
<del> $this->Cookie->setConfig('key', $key);
<del> }
<del> $this->set('ValueFromRequest', $this->request->getCookie('NameOfCookie'));
<del> $this->set('ValueFromCookieComponent', $this->Cookie->read('NameOfCookie'));
<del> }
<del>
<del> /**
<del> * action to set a cookie
<del> *
<del> * @param string|null $key Encryption key used. By defaults,
<del> * CookieComponent::_config['key'].
<del> */
<del> public function set_cookie($key = null)
<del> {
<del> if (isset($key)) {
<del> $this->Cookie->setConfig('key', $key);
<del> }
<del> $this->Cookie->write('NameOfCookie', 'abc');
<del> }
<del>} | 4 |
Javascript | Javascript | fix timeout reset after keep-alive timeout | d71718db6aa4feb8dc10edbad1134472468e971a | <ide><path>lib/_http_server.js
<ide> function socketOnData(server, socket, parser, state, d) {
<ide> assert(!socket._paused);
<ide> debug('SERVER socketOnData %d', d.length);
<ide>
<del> if (state.keepAliveTimeoutSet) {
<del> socket.setTimeout(0);
<del> if (server.timeout) {
<del> socket.setTimeout(server.timeout);
<del> }
<del> state.keepAliveTimeoutSet = false;
<del> }
<del>
<ide> var ret = parser.execute(d);
<ide> onParserExecuteCommon(server, socket, parser, state, ret, d);
<ide> }
<ide> function socketOnError(e) {
<ide> }
<ide>
<ide> function onParserExecuteCommon(server, socket, parser, state, ret, d) {
<add> resetSocketTimeout(server, socket, state);
<add>
<ide> if (ret instanceof Error) {
<ide> debug('parse error', ret);
<ide> socketOnError.call(socket, ret);
<ide> function resOnFinish(req, res, socket, state, server) {
<ide> // new message. In this callback we setup the response object and pass it
<ide> // to the user.
<ide> function parserOnIncoming(server, socket, state, req, keepAlive) {
<add> resetSocketTimeout(server, socket, state);
<add>
<ide> state.incoming.push(req);
<ide>
<ide> // If the writable end isn't consuming, then stop reading
<ide> function parserOnIncoming(server, socket, state, req, keepAlive) {
<ide> return false; // Not a HEAD response. (Not even a response!)
<ide> }
<ide>
<add>function resetSocketTimeout(server, socket, state) {
<add> if (!state.keepAliveTimeoutSet)
<add> return;
<add>
<add> socket.setTimeout(server.timeout || 0);
<add> state.keepAliveTimeoutSet = false;
<add>}
<add>
<ide> function onSocketResume() {
<ide> // It may seem that the socket is resumed, but this is an enemy's trick to
<ide> // deceive us! `resume` is emitted asynchronously, and may be called from
<ide><path>test/parallel/test-http-server-keep-alive-timeout-slow-client-headers.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const http = require('http');
<add>const net = require('net');
<add>
<add>const server = http.createServer(common.mustCall((req, res) => {
<add> res.end();
<add>}, 2));
<add>
<add>server.keepAliveTimeout = common.platformTimeout(100);
<add>
<add>server.listen(0, common.mustCall(() => {
<add> const port = server.address().port;
<add> const socket = net.connect({ port }, common.mustCall(() => {
<add> request(common.mustCall(() => {
<add> // Make a second request on the same socket, after the keep-alive timeout
<add> // has been set on the server side.
<add> request(common.mustCall());
<add> }));
<add> }));
<add>
<add> server.on('timeout', common.mustCall(() => {
<add> socket.end();
<add> server.close();
<add> }));
<add>
<add> function request(callback) {
<add> socket.setEncoding('utf8');
<add> socket.on('data', onData);
<add> let response = '';
<add>
<add> // Simulate a client that sends headers slowly (with a period of inactivity
<add> // that is longer than the keep-alive timeout).
<add> socket.write('GET / HTTP/1.1\r\n' +
<add> `Host: localhost:${port}\r\n`);
<add> setTimeout(() => {
<add> socket.write('Connection: keep-alive\r\n' +
<add> '\r\n');
<add> }, common.platformTimeout(300));
<add>
<add> function onData(chunk) {
<add> response += chunk;
<add> if (chunk.includes('\r\n')) {
<add> socket.removeListener('data', onData);
<add> onHeaders();
<add> }
<add> }
<add>
<add> function onHeaders() {
<add> assert.ok(response.includes('HTTP/1.1 200 OK\r\n'));
<add> assert.ok(response.includes('Connection: keep-alive\r\n'));
<add> callback();
<add> }
<add> }
<add>}));
<ide><path>test/parallel/test-http-server-keep-alive-timeout-slow-server.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const http = require('http');
<add>
<add>const server = http.createServer(common.mustCall((req, res) => {
<add> if (req.url === '/first') {
<add> res.end('ok');
<add> return;
<add> }
<add> setTimeout(() => {
<add> res.end('ok');
<add> }, common.platformTimeout(500));
<add>}, 2));
<add>
<add>server.keepAliveTimeout = common.platformTimeout(200);
<add>
<add>const agent = new http.Agent({
<add> keepAlive: true,
<add> maxSockets: 1
<add>});
<add>
<add>function request(path, callback) {
<add> const port = server.address().port;
<add> const req = http.request({ agent, path, port }, common.mustCall((res) => {
<add> assert.strictEqual(res.statusCode, 200);
<add>
<add> res.setEncoding('utf8');
<add>
<add> let result = '';
<add> res.on('data', (chunk) => {
<add> result += chunk;
<add> });
<add>
<add> res.on('end', common.mustCall(() => {
<add> assert.strictEqual(result, 'ok');
<add> callback();
<add> }));
<add> }));
<add> req.end();
<add>}
<add>
<add>server.listen(0, common.mustCall(() => {
<add> request('/first', () => {
<add> request('/second', () => {
<add> server.close();
<add> });
<add> });
<add>})); | 3 |
Text | Text | fix typo in changelog for 8.8.0 | 57a716febd9fe6b4e5d39e1f7d03094019bd211e | <ide><path>doc/changelogs/CHANGELOG_V8.md
<ide> * **crypto**:
<ide> - expose ECDH class [#8188](https://github.com/nodejs/node/pull/8188)
<ide> * **http2**:
<del> - http2 is now exposed by defualt without the need for a flag [#15685](https://github.com/nodejs/node/pull/15685)
<add> - http2 is now exposed by default without the need for a flag [#15685](https://github.com/nodejs/node/pull/15685)
<ide> - a new environment varible NODE\_NO\_HTTP2 has been added to allow userland http2 to be required [#15685](https://github.com/nodejs/node/pull/15685)
<ide> - support has been added for generic `Duplex` streams [#16269](https://github.com/nodejs/node/pull/16269)
<ide> * **module**: | 1 |
Javascript | Javascript | inline cache mock for dependencygraph-test | 666706b0da142d3d13668066c1b1ef14607f681d | <ide><path>packager/react-packager/__mocks__/debug.js
<ide> */
<ide> 'use strict';
<ide>
<del>module.exports = function() {
<del> return function() {};
<del>};
<add>module.exports = () => () => {};
<ide><path>packager/react-packager/src/DependencyResolver/DependencyGraph/__tests__/DependencyGraph-test.js
<ide> jest.autoMockOff();
<ide> const Promise = require('promise');
<ide>
<ide> jest
<del> .mock('fs')
<del> .mock('../../../Cache')
<del> .mock('../../../Activity');
<add> .mock('fs');
<ide>
<del>var Cache = require('../../../Cache');
<ide> var DependencyGraph = require('../index');
<ide> var fs = require('fs');
<ide>
<ide> describe('DependencyGraph', function() {
<ide> isWatchman: () => Promise.resolve(false),
<ide> };
<ide>
<add> const Cache = jest.genMockFn();
<add> Cache.prototype.get = jest.genMockFn().mockImplementation(
<add> (filepath, field, cb) => cb(filepath)
<add> );
<add> Cache.prototype.invalidate = jest.genMockFn();
<add> Cache.prototype.end = jest.genMockFn();
<add>
<ide> defaults = {
<ide> assetExts: ['png', 'jpg'],
<ide> cache: new Cache(),
<ide><path>packager/react-packager/src/DependencyResolver/DependencyGraph/index.js
<ide> class DependencyGraph {
<ide> this._opts = {
<ide> activity: activity || defaultActivity,
<ide> roots,
<del> ignoreFilePath: ignoreFilePath || () => {},
<add> ignoreFilePath: ignoreFilePath || (() => {}),
<ide> fileWatcher,
<ide> assetRoots_DEPRECATED: assetRoots_DEPRECATED || [],
<ide> assetExts, | 3 |
Text | Text | remove description of `dependency_loading` option | 19ede1f85dc802c81ac80eed29b4e36a6b5b2286 | <ide><path>guides/source/configuring.md
<ide> application. Accepts a valid week day symbol (e.g. `:monday`).
<ide> end
<ide> ```
<ide>
<del>* `config.dependency_loading` is a flag that allows you to disable constant autoloading setting it to false. It only has effect if `config.cache_classes` is true, which it is by default in production mode.
<del>
<ide> * `config.eager_load` when true, eager loads all registered `config.eager_load_namespaces`. This includes your application, engines, Rails frameworks and any other registered namespace.
<ide>
<ide> * `config.eager_load_namespaces` registers namespaces that are eager loaded when `config.eager_load` is true. All namespaces in the list must respond to the `eager_load!` method. | 1 |
Javascript | Javascript | remove outdated comment | 727ef10fdfd3c3710248f1567f291d925a589b64 | <ide><path>src/renderers/webgl/WebGLLights.js
<ide> function WebGLLights( extensions, capabilities ) {
<ide>
<ide> const uniforms = cache.get( light );
<ide>
<del> // (a) intensity is the total visible light emitted
<del> //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
<del>
<del> // (b) intensity is the brightness of the light
<ide> uniforms.color.copy( color ).multiplyScalar( intensity );
<ide>
<ide> uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 ); | 1 |
Python | Python | use six.text_type for hyperlink names | b1b47036d756475faad8e03f7eb2f3f93aac2107 | <ide><path>rest_framework/relations.py
<ide> def get_url(self, obj, view_name, request, format):
<ide> return self.reverse(view_name, kwargs=kwargs, request=request, format=format)
<ide>
<ide> def get_name(self, obj):
<del> return str(obj)
<add> return six.text_type(obj)
<ide>
<ide> def to_internal_value(self, data):
<ide> request = self.context.get('request', None) | 1 |
Go | Go | use device/inode of the root dir, not the image | e6a73e65a23163273fa63d54b8f12530f7eef104 | <ide><path>devmapper/deviceset_devmapper.go
<ide> func (devices *DeviceSetDM) initDevmapper() error {
<ide> return err
<ide> }
<ide>
<del> // Set the device prefix from the device id and inode of the data image
<add> // Set the device prefix from the device id and inode of the docker root dir
<ide>
<del> st, err := os.Stat(data)
<add> st, err := os.Stat(devices.root)
<ide> if err != nil {
<del> return fmt.Errorf("Error looking up data image %s: %s", data, err)
<add> return fmt.Errorf("Error looking up dir %s: %s", devices.root, err)
<ide> }
<ide> sysSt := st.Sys().(*syscall.Stat_t)
<ide> // "reg-" stands for "regular file". | 1 |
Text | Text | fix layout problem in v4 changelog | 9744928cf5fae9b2a5a5c88f7aeeeb3a01220afe | <ide><path>CHANGELOG.md
<ide> release.
<ide> ----
<ide> ----
<ide>
<del>## 2016-06-23, Version 5.12.0 (Stable), @evanlucas
<del>
<del><a href="doc/changelogs/CHANGELOG_V5.md#5.12.0">Moved to doc/changelogs/CHANGELOG_V5.md#5.12.0</a>.
<del>
<del>## 2016-06-23, Version 4.4.6 'Argon' (LTS), @thealphanerd
<del>
<del><a href="doc/changelogs/CHANGELOG_V4.md#4.4.6">Moved to doc/changelogs/CHANGELOG_V4.md#4.4.6</a>.
<del>
<ide> ## 2016-05-06, Version 0.12.14 (Maintenance), @rvagg
<ide>
<ide> <a href="doc/changelogs/CHANGELOG_V012.md#0.12.14">Moved to doc/changelogs/CHANGELOG_V012.md#0.12.14</a>.
<ide><path>doc/changelogs/CHANGELOG_V4.md
<ide> will be supported actively until April 2017 and maintained until April 2018.
<ide>
<ide> <a id="4.4.6"></a>
<del>
<ide> ## 2016-06-23, Version 4.4.6 'Argon' (LTS), @thealphanerd
<ide>
<add>### Notable Changes
<add>
<ide> This is an important security release. All Node.js users should consult the security release summary at nodejs.org for details on patched vulnerabilities.
<ide>
<ide> This release is specifically related to a Buffer overflow vulnerability discovered in v8, more details can be found [in the CVE](https://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-1669) | 2 |
Javascript | Javascript | replace indexof with includes | 9564c20810d7dccaae8bb917251681051a2a1144 | <ide><path>test/async-hooks/init-hooks.js
<ide> class ActivityCollector {
<ide> const violations = [];
<ide> function v(msg) { violations.push(msg); }
<ide> for (const a of this._activities.values()) {
<del> if (types != null && types.indexOf(a.type) < 0) continue;
<add> if (types != null && !types.includes(a.type)) continue;
<ide>
<ide> if (a.init && a.init.length > 1) {
<ide> v('Activity inited twice\n' + activityString(a) +
<ide> class ActivityCollector {
<ide>
<ide> activitiesOfTypes(types) {
<ide> if (!Array.isArray(types)) types = [ types ];
<del> return this.activities.filter((x) => types.indexOf(x.type) >= 0);
<add> return this.activities.filter((x) => types.includes(x.type));
<ide> }
<ide>
<ide> get activities() {
<ide><path>test/parallel/test-repl-tab-complete.js
<ide> const warningRegEx = new RegExp(
<ide> });
<ide>
<ide> // no `biu`
<del> assert.strictEqual(data.indexOf('ele.biu'), -1);
<add> assert.strictEqual(data.includes('ele.biu'), false);
<ide> }));
<ide> });
<ide> | 2 |
Ruby | Ruby | add test showing root match in path namespace | 561d9eff0c5702c449a2a0117ad9950ad8842dc2 | <ide><path>actionpack/test/dispatch/routing_test.rb
<ide> def self.matches?(request)
<ide>
<ide> namespace :path => :api do
<ide> resource :me
<add> match '/' => 'mes#index'
<ide> end
<ide> end
<ide> end
<ide> def test_path_namespace
<ide> get '/api/me'
<ide> assert_equal 'mes#show', @response.body
<ide> assert_equal '/api/me', me_path
<add>
<add> get '/api'
<add> assert_equal 'mes#index', @response.body
<ide> end
<ide> end
<ide> | 1 |
Python | Python | create dummy connection correctly | e2a8ab10d4ce790a60920544d186e5cc97909a24 | <ide><path>libcloud/drivers/dummy.py
<ide> def __init__(self, creds):
<ide> driver=self,
<ide> extra={'foo': 'bar'}),
<ide> ]
<add> self.connection = DummyConnection(self.creds)
<ide>
<ide> def get_uuid(self, unique_field=None):
<ide> return str(uuid.uuid4()) | 1 |
Text | Text | add iterm2 introduction | 3f512e0af428f0dae78283fc9f5be89c8d8bf03e | <ide><path>client/src/pages/guide/english/terminal-commandline/macos-terminal/index.md
<ide> Use the following syntax to delete a file
<ide>
<ide> **rm _#PATH_TO_FILE_**
<ide>
<add># iTerm2
<ide>
<add>iTerm2 is an alternative to the legacy terminal in Mac OS. iTerm2 brings some new features such as:
<ide>
<add>* Split Panes
<add>* Hotkey Window
<add>* Search
<add>* Autocomplete
<add>* Paste history
<add>* Configurability
<add>* and many [more](https://www.iterm2.com/features.html)
<ide>
<del>
<add>Just download iTerm2 from the official [website](https://www.iterm2.com/downloads.html). Additional documentation can be found [here](https://www.iterm2.com/documentation.html). | 1 |
Text | Text | remove appmetrics from tierlist | 92cd72626eb3e335ba2f52cb026ea2d037d90e2b | <ide><path>doc/contributing/diagnostic-tooling-support-tiers.md
<ide> The tools are currently assigned to Tiers as follows:
<ide> | Debugger | Command line Debug Client | ? | Yes | 1 |
<ide> | Tracing | trace\_events (API) | No | Yes | 1 |
<ide> | Tracing | trace\_gc | No | Yes | 1 |
<del>| F/P/T | appmetrics | No | No | ? |
<ide> | M/T | eBPF tracing tool | No | No | ? | | 1 |
Java | Java | remove deprecated methods in spring-test-mvc | 2748f2b8eba22264408f2a05725810b58e80649d | <ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/mock/client/match/MockRestRequestMatchers.java
<ide> public static XpathRequestMatchers xpath(String expression, Map<String, String>
<ide> return new XpathRequestMatchers(expression, namespaces, args);
<ide> }
<ide>
<del>
<del> // Deprecated methods ..
<del>
<del> /**
<del> * Expect that the specified request header contains a subtring
<del> *
<del> * @deprecated in favor of {@link #header(String, Matcher...)}
<del> */
<del> public static RequestMatcher headerContains(final String header, final String substring) {
<del> Assert.notNull(header, "'header' must not be null");
<del> Assert.notNull(substring, "'substring' must not be null");
<del> return new RequestMatcher() {
<del> public void match(ClientHttpRequest request) throws AssertionError {
<del> List<String> actualHeaders = request.getHeaders().get(header);
<del> AssertionErrors.assertTrue("Expected header <" + header + "> in request", actualHeaders != null);
<del>
<del> boolean foundMatch = false;
<del> for (String headerValue : actualHeaders) {
<del> if (headerValue.contains(substring)) {
<del> foundMatch = true;
<del> break;
<del> }
<del> }
<del>
<del> AssertionErrors.assertTrue("Expected value containing <" + substring + "> in header <" + header + ">",
<del> foundMatch);
<del> }
<del> };
<del> }
<del>
<del> /**
<del> * Expect the given request body content.
<del> *
<del> * @deprecated in favor of {@link #content()} as well as {@code jsonPath(..)},
<del> * and {@code xpath(..)} methods in this class
<del> */
<del> public static RequestMatcher body(final String body) {
<del> Assert.notNull(body, "'body' must not be null");
<del> return new RequestMatcher() {
<del> public void match(ClientHttpRequest request) throws AssertionError, IOException {
<del> MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;
<del> AssertionErrors.assertEquals("Unexpected body content", body, mockRequest.getBodyAsString());
<del> }
<del> };
<del> }
<del>
<ide> }
<ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/mock/client/response/MockRestResponseCreators.java
<ide> public static DefaultResponseCreator withStatus(HttpStatus status) {
<ide> return new DefaultResponseCreator(status);
<ide> }
<ide>
<del> /**
<del> * Respond with a given body, headers, status code, and status text.
<del> *
<del> * @param body the body of the response "UTF-8" encoded
<del> * @param headers the response headers
<del> * @param statusCode the response status code
<del> * @param statusText the response status text
<del> *
<del> * @deprecated in favor of methods returning DefaultResponseCreator
<del> */
<del> public static ResponseCreator withResponse(final String body, final HttpHeaders headers,
<del> final HttpStatus statusCode, final String statusText) {
<del>
<del> return new ResponseCreator() {
<del> public MockClientHttpResponse createResponse(ClientHttpRequest request) throws IOException {
<del> MockClientHttpResponse response = new MockClientHttpResponse(body.getBytes("UTF-8"), statusCode);
<del> response.getHeaders().putAll(headers);
<del> return response;
<del> }
<del> };
<del> }
<del>
<del> /**
<del> * Respond with the given body, headers, and a status code of 200 (OK).
<del> *
<del> * @param body the body of the response "UTF-8" encoded
<del> * @param headers the response headers
<del> *
<del> * @deprecated in favor of methods 'withXyz' in this class returning DefaultResponseCreator
<del> */
<del> public static ResponseCreator withResponse(String body, HttpHeaders headers) {
<del> return withResponse(body, headers, HttpStatus.OK, "");
<del> }
<del>
<del> /**
<del> * Respond with a given body, headers, status code, and text.
<del> *
<del> * @param body a {@link Resource} containing the body of the response
<del> * @param headers the response headers
<del> * @param statusCode the response status code
<del> * @param statusText the response status text
<del> *
<del> * @deprecated in favor of methods 'withXyz' in this class returning DefaultResponseCreator
<del> */
<del> public static ResponseCreator withResponse(final Resource body, final HttpHeaders headers,
<del> final HttpStatus statusCode, String statusText) {
<del>
<del> return new ResponseCreator() {
<del> public MockClientHttpResponse createResponse(ClientHttpRequest request) throws IOException {
<del> MockClientHttpResponse response = new MockClientHttpResponse(body.getInputStream(), statusCode);
<del> response.getHeaders().putAll(headers);
<del> return response;
<del> }
<del> };
<del> }
<del>
<del> /**
<del> * Respond with the given body, headers, and a status code of 200 (OK).
<del> * @param body the body of the response
<del> * @param headers the response headers
<del> *
<del> * @deprecated in favor of methods 'withXyz' in this class returning DefaultResponseCreator
<del> */
<del> public static ResponseCreator withResponse(final Resource body, final HttpHeaders headers) {
<del> return withResponse(body, headers, HttpStatus.OK, "");
<del> }
<del>
<ide> } | 2 |
Ruby | Ruby | fix a bug with time_select and prompts | 46e2901f12e48dbe86eba416097d7546d215c790 | <ide><path>actionview/lib/action_view/helpers/date_helper.rb
<ide> def select_year
<ide> end
<ide> end
<ide>
<add> def prompt_text(prompt, type)
<add> prompt.kind_of?(String) ? prompt : I18n.translate(:"datetime.prompts.#{type}", locale: @options[:locale])
<add> end
<add>
<ide> # If the day is hidden, the day should be set to the 1st so all month and year choices are
<ide> # valid. Otherwise, February 31st or February 29th, 2011 can be selected, which are invalid.
<ide> def set_day_if_discarded
<ide> def prompt_option_tag(type, options)
<ide> I18n.translate(:"datetime.prompts.#{type}", locale: @options[:locale])
<ide> end
<ide>
<del> prompt ? content_tag("option", prompt, value: "") : ""
<add> prompt ? content_tag("option", prompt_text(prompt, type), value: "") : ""
<ide> end
<ide>
<ide> # Builds hidden input tag for date part and value.
<ide><path>actionview/test/template/date_helper_test.rb
<ide> def test_select_time_with_generic_with_css_classes
<ide> assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), include_seconds: true, with_css_classes: true)
<ide> end
<ide>
<add> def test_select_time_with_a_single_default_prompt
<add> expected = +%(<input name="date[year]" id="date_year" value="2003" type="hidden" autocomplete="off" />\n)
<add> expected << %(<input name="date[month]" id="date_month" value="8" type="hidden" autocomplete="off" />\n)
<add> expected << %(<input name="date[day]" id="date_day" value="16" type="hidden" autocomplete="off" />\n)
<add>
<add> expected << %(<select id="date_hour" name="date[hour]">\n)
<add> expected << %(<option value="">Hour</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08" selected="selected">08</option>\n<option value="09">09</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">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)
<add> expected << "</select>\n"
<add>
<add> expected << " : "
<add>
<add> expected << %(<select id="date_minute" name="date[minute]">\n)
<add> expected << %(<option value="">Choose minute</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</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">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<option value="32">32</option>\n<option value="33">33</option>\n<option value="34">34</option>\n<option value="35">35</option>\n<option value="36">36</option>\n<option value="37">37</option>\n<option value="38">38</option>\n<option value="39">39</option>\n<option value="40">40</option>\n<option value="41">41</option>\n<option value="42">42</option>\n<option value="43">43</option>\n<option value="44">44</option>\n<option value="45">45</option>\n<option value="46">46</option>\n<option value="47">47</option>\n<option value="48">48</option>\n<option value="49">49</option>\n<option value="50">50</option>\n<option value="51">51</option>\n<option value="52">52</option>\n<option value="53">53</option>\n<option value="54">54</option>\n<option value="55">55</option>\n<option value="56">56</option>\n<option value="57">57</option>\n<option value="58">58</option>\n<option value="59">59</option>\n)
<add> expected << "</select>\n"
<add>
<add> expected << " : "
<add>
<add> expected << %(<select id="date_second" name="date[second]">\n)
<add> expected << %(<option value="">Choose seconds</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</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">16</option>\n<option value="17">17</option>\n<option value="18" selected="selected">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<option value="32">32</option>\n<option value="33">33</option>\n<option value="34">34</option>\n<option value="35">35</option>\n<option value="36">36</option>\n<option value="37">37</option>\n<option value="38">38</option>\n<option value="39">39</option>\n<option value="40">40</option>\n<option value="41">41</option>\n<option value="42">42</option>\n<option value="43">43</option>\n<option value="44">44</option>\n<option value="45">45</option>\n<option value="46">46</option>\n<option value="47">47</option>\n<option value="48">48</option>\n<option value="49">49</option>\n<option value="50">50</option>\n<option value="51">51</option>\n<option value="52">52</option>\n<option value="53">53</option>\n<option value="54">54</option>\n<option value="55">55</option>\n<option value="56">56</option>\n<option value="57">57</option>\n<option value="58">58</option>\n<option value="59">59</option>\n)
<add> expected << "</select>\n"
<add>
<add> assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), include_seconds: true,
<add> prompt: { hour: true, minute: "Choose minute", second: "Choose seconds" })
<add> end
<add>
<ide> def test_select_time_with_custom_with_css_classes
<ide> expected = +%(<input name="date[year]" id="date_year" value="2003" type="hidden" autocomplete="off" />\n)
<ide> expected << %(<input name="date[month]" id="date_month" value="8" type="hidden" autocomplete="off" />\n) | 2 |
Python | Python | add generic connection type | 6d1d53b780c48297fa2e6d8e075fdaa0f0f42e22 | <ide><path>airflow/www/views.py
<ide> def _get_connection_types() -> List[Tuple[str, str]]:
<ide> ('fs', 'File (path)'),
<ide> ('mesos_framework-id', 'Mesos Framework ID'),
<ide> ('email', 'Email'),
<add> ('generic', 'Generic'),
<ide> ]
<ide> providers_manager = ProvidersManager()
<ide> for connection_type, provider_info in providers_manager.hooks.items(): | 1 |
Python | Python | apply unicode fixer | 3a5c5475b5c2043dbe6791d3a5100a45d491546e | <ide><path>doc/sphinxext/numpydoc/docscrape_sphinx.py
<ide> from __future__ import division, absolute_import, print_function
<ide>
<del>import re, inspect, textwrap, pydoc
<add>import re, inspect, textwrap, pydoc, aya
<ide> import sphinx
<ide> import collections
<ide> from .docscrape import NumpyDocString, FunctionDoc, ClassDoc
<ide>
<add>if sys.version_info[0] >= 3:
<add> sixu = lambda s: s
<add>else:
<add> sixu = lambda s: unicode(s, 'unicode_escape')
<add>
<add>
<ide> class SphinxDocString(NumpyDocString):
<ide> def __init__(self, docstring, config={}):
<ide> self.use_plots = config.get('use_plots', False)
<ide> def _str_member_list(self, name):
<ide>
<ide> if others:
<ide> maxlen_0 = max(3, max([len(x[0]) for x in others]))
<del> hdr = u"="*maxlen_0 + u" " + u"="*10
<del> fmt = u'%%%ds %%s ' % (maxlen_0,)
<add> hdr = sixu("=")*maxlen_0 + sixu(" ") + sixu("=")*10
<add> fmt = sixu('%%%ds %%s ') % (maxlen_0,)
<ide> out += ['', hdr]
<ide> for param, param_type, desc in others:
<del> desc = u" ".join(x.strip() for x in desc).strip()
<add> desc = sixu(" ").join(x.strip() for x in desc).strip()
<ide> if param_type:
<ide> desc = "(%s) %s" % (param_type, desc)
<ide> out += [fmt % (param.strip(), desc)]
<ide><path>doc/sphinxext/numpydoc/numpydoc.py
<ide> """
<ide> from __future__ import division, absolute_import, print_function
<ide>
<add>import os, sys, re, pydoc
<ide> import sphinx
<add>import inspect
<ide> import collections
<ide>
<ide> if sphinx.__version__ < '1.0.1':
<ide> raise RuntimeError("Sphinx 1.0.1 or newer is required")
<ide>
<del>import os, sys, re, pydoc
<ide> from .docscrape_sphinx import get_doc_object, SphinxDocString
<ide> from sphinx.util.compat import Directive
<del>import inspect
<add>
<add>if sys.version_info[0] >= 3:
<add> sixu = lambda s: s
<add>else:
<add> sixu = lambda s: unicode(s, 'unicode_escape')
<add>
<ide>
<ide> def mangle_docstrings(app, what, name, obj, options, lines,
<ide> reference_offset=[0]):
<ide> def mangle_docstrings(app, what, name, obj, options, lines,
<ide>
<ide> if what == 'module':
<ide> # Strip top title
<del> title_re = re.compile(u'^\\s*[#*=]{4,}\\n[a-z0-9 -]+\\n[#*=]{4,}\\s*',
<add> title_re = re.compile(sixu('^\\s*[#*=]{4,}\\n[a-z0-9 -]+\\n[#*=]{4,}\\s*'),
<ide> re.I|re.S)
<del> lines[:] = title_re.sub(u'', u"\n".join(lines)).split(u"\n")
<add> lines[:] = title_re.sub(sixu(''), sixu("\n").join(lines)).split(sixu("\n"))
<ide> else:
<del> doc = get_doc_object(obj, what, u"\n".join(lines), config=cfg)
<add> doc = get_doc_object(obj, what, sixu("\n").join(lines), config=cfg)
<ide> if sys.version_info[0] >= 3:
<ide> doc = str(doc)
<ide> else:
<ide> doc = str(doc).decode('utf-8')
<del> lines[:] = doc.split(u"\n")
<add> lines[:] = doc.split(sixu("\n"))
<ide>
<ide> if app.config.numpydoc_edit_link and hasattr(obj, '__name__') and \
<ide> obj.__name__:
<ide> if hasattr(obj, '__module__'):
<del> v = dict(full_name=u"%s.%s" % (obj.__module__, obj.__name__))
<add> v = dict(full_name=sixu("%s.%s") % (obj.__module__, obj.__name__))
<ide> else:
<ide> v = dict(full_name=obj.__name__)
<del> lines += [u'', u'.. htmlonly::', u'']
<del> lines += [u' %s' % x for x in
<add> lines += [sixu(''), sixu('.. htmlonly::'), sixu('')]
<add> lines += [sixu(' %s') % x for x in
<ide> (app.config.numpydoc_edit_link % v).split("\n")]
<ide>
<ide> # replace reference numbers so that there are no duplicates
<ide> references = []
<ide> for line in lines:
<ide> line = line.strip()
<del> m = re.match(u'^.. \\[([a-z0-9_.-])\\]', line, re.I)
<add> m = re.match(sixu('^.. \\[([a-z0-9_.-])\\]'), line, re.I)
<ide> if m:
<ide> references.append(m.group(1))
<ide>
<ide> def mangle_docstrings(app, what, name, obj, options, lines,
<ide> if references:
<ide> for i, line in enumerate(lines):
<ide> for r in references:
<del> if re.match(u'^\\d+$', r):
<del> new_r = u"R%d" % (reference_offset[0] + int(r))
<add> if re.match(sixu('^\\d+$'), r):
<add> new_r = sixu("R%d") % (reference_offset[0] + int(r))
<ide> else:
<del> new_r = u"%s%d" % (r, reference_offset[0])
<del> lines[i] = lines[i].replace(u'[%s]_' % r,
<del> u'[%s]_' % new_r)
<del> lines[i] = lines[i].replace(u'.. [%s]' % r,
<del> u'.. [%s]' % new_r)
<add> new_r = sixu("%s%d") % (r, reference_offset[0])
<add> lines[i] = lines[i].replace(sixu('[%s]_') % r,
<add> sixu('[%s]_') % new_r)
<add> lines[i] = lines[i].replace(sixu('.. [%s]') % r,
<add> sixu('.. [%s]') % new_r)
<ide>
<ide> reference_offset[0] += len(references)
<ide>
<ide> def mangle_signature(app, what, name, obj, options, sig, retann):
<ide>
<ide> doc = SphinxDocString(pydoc.getdoc(obj))
<ide> if doc['Signature']:
<del> sig = re.sub(u"^[^(]*", u"", doc['Signature'])
<del> return sig, u''
<add> sig = re.sub(sixu("^[^(]*"), sixu(""), doc['Signature'])
<add> return sig, sixu('')
<ide>
<ide> def setup(app, get_doc_object_=get_doc_object):
<ide> if not hasattr(app, 'add_config_value'):
<ide><path>doc/sphinxext/numpydoc/tests/test_docscrape.py
<ide> from numpydoc.docscrape_sphinx import SphinxDocString, SphinxClassDoc
<ide> from nose.tools import *
<ide>
<add>if sys.version_info[0] >= 3:
<add> sixu = lambda s: s
<add>else:
<add> sixu = lambda s: unicode(s, 'unicode_escape')
<add>
<add>
<ide> doc_txt = '''\
<ide> numpy.multivariate_normal(mean, cov, shape=None, spam=None)
<ide>
<ide> def test_str():
<ide>
<ide> Raises
<ide> ------
<del>RuntimeError :
<add>RuntimeError :
<ide> Some error
<ide>
<ide> Warns
<ide> -----
<del>RuntimeWarning :
<add>RuntimeWarning :
<ide> Some warning
<ide>
<ide> Warnings
<ide> def test_sphinx_str():
<ide> The drawn samples, arranged according to `shape`. If the
<ide> shape given is (m,n,...), then the shape of `out` is is
<ide> (m,n,...,N).
<del>
<add>
<ide> In other words, each entry ``out[i,j,...,:]`` is an N-dimensional
<ide> value drawn from the distribution.
<ide>
<ide> def test_sphinx_str():
<ide> **spam** : parrot
<ide>
<ide> A parrot off its mortal coil.
<del>
<add>
<ide> :Raises:
<ide>
<del> **RuntimeError** :
<add> **RuntimeError** :
<ide>
<ide> Some error
<ide>
<ide> :Warns:
<ide>
<del> **RuntimeWarning** :
<add> **RuntimeWarning** :
<ide>
<ide> Some warning
<ide>
<ide> def test_sphinx_str():
<ide> Certain warnings apply.
<ide>
<ide> .. seealso::
<del>
<add>
<ide> :obj:`some`, :obj:`other`, :obj:`funcs`
<del>
<add>
<ide> :obj:`otherfunc`
<ide> relationship
<del>
<add>
<ide> .. rubric:: Notes
<ide>
<ide> Instead of specifying the full covariance matrix, popular
<ide> def test_sphinx_str():
<ide> [True, True]
<ide> """)
<ide>
<del>
<add>
<ide> doc2 = NumpyDocString("""
<ide> Returns array of indices of the maximum values of along the given axis.
<ide>
<ide> def test_unicode():
<ide> """)
<ide> assert isinstance(doc['Summary'][0], str)
<ide> if sys.version_info[0] >= 3:
<del> assert doc['Summary'][0] == u'öäöäöäöäöåååå'
<add> assert doc['Summary'][0] == sixu('öäöäöäöäöåååå')
<ide> else:
<del> assert doc['Summary'][0] == u'öäöäöäöäöåååå'.encode('utf-8')
<add> assert doc['Summary'][0] == sixu('öäöäöäöäöåååå').encode('utf-8')
<ide>
<ide> def test_plot_examples():
<ide> cfg = dict(use_plots=True)
<ide> def test_plot_examples():
<ide> Examples
<ide> --------
<ide> .. plot::
<del>
<add>
<ide> import matplotlib.pyplot as plt
<ide> plt.plot([1,2,3],[4,5,6])
<ide> plt.show()
<ide> def test_class_members_doc():
<ide>
<ide> Methods
<ide> -------
<del> a :
<add> a :
<ide>
<del> b :
<add> b :
<ide>
<del> c :
<add> c :
<ide>
<del> .. index::
<add> .. index::
<ide>
<ide> """)
<ide>
<ide> def test_class_members_doc_sphinx():
<ide> .. rubric:: Attributes
<ide>
<ide> === ==========
<del> t (float) Current time.
<del> y (ndarray) Current variable values.
<add> t (float) Current time.
<add> y (ndarray) Current variable values.
<ide> === ==========
<ide>
<ide> .. rubric:: Methods
<ide>
<ide> === ==========
<del> a
<del> b
<del> c
<add> a
<add> b
<add> c
<ide> === ==========
<ide>
<ide> """)
<ide>
<ide> if __name__ == "__main__":
<ide> import nose
<ide> nose.run()
<del>
<ide><path>numpy/__init__.py
<ide> def pkgload(*packages, **options):
<ide> # Make these accessible from numpy name-space
<ide> # but not imported in from numpy import *
<ide> if sys.version_info[0] >= 3:
<del> from builtins import bool, int, float, complex, object, unicode, str
<add> from builtins import bool, int, float, complex, object, str
<add> unicode = str
<ide> else:
<ide> from __builtin__ import bool, int, float, complex, object, unicode, str
<ide>
<ide><path>numpy/compat/py3k.py
<ide>
<ide> __all__ = ['bytes', 'asbytes', 'isfileobj', 'getexception', 'strchar',
<ide> 'unicode', 'asunicode', 'asbytes_nested', 'asunicode_nested',
<del> 'asstr', 'open_latin1', 'long', 'basestring']
<add> 'asstr', 'open_latin1', 'long', 'basestring', 'sixu']
<ide>
<ide> import sys
<ide>
<ide> long = int
<ide> integer_types = (int,)
<ide> basestring = str
<del> bytes = bytes
<ide> unicode = str
<add> bytes = bytes
<ide>
<ide> def asunicode(s):
<ide> if isinstance(s, bytes):
<ide> def isfileobj(f):
<ide> def open_latin1(filename, mode='r'):
<ide> return open(filename, mode=mode, encoding='iso-8859-1')
<ide>
<add> def sixu(s):
<add> return s
<add>
<ide> strchar = 'U'
<ide>
<ide>
<ide> else:
<ide> bytes = str
<del> unicode = unicode
<ide> long = long
<ide> basestring = basestring
<add> unicode = unicode
<ide> integer_types = (int, long)
<ide> asbytes = str
<ide> asstr = str
<ide> def asunicode(s):
<ide> def open_latin1(filename, mode='r'):
<ide> return open(filename, mode=mode)
<ide>
<add> def sixu(s):
<add> return unicode(s, 'unicode_escape')
<add>
<ide>
<ide> def getexception():
<ide> return sys.exc_info()[1]
<ide><path>numpy/core/numerictypes.py
<ide> # we don't export these for import *, but we do want them accessible
<ide> # as numerictypes.bool, etc.
<ide> if sys.version_info[0] >= 3:
<del> from builtins import bool, int, float, complex, object, unicode, str
<add> from builtins import bool, int, float, complex, object, str
<add> unicode = str
<ide> else:
<ide> from __builtin__ import bool, int, float, complex, object, unicode, str
<ide>
<ide><path>numpy/core/tests/test_arrayprint.py
<ide> import sys
<ide> import numpy as np
<ide> from numpy.testing import *
<add>from numpy.compat import sixu
<ide>
<ide> class TestArrayRepr(object):
<ide> def test_nan_inf(self):
<ide> def test_unicode_object_array():
<ide> expected = "array(['é'], dtype=object)"
<ide> else:
<ide> expected = "array([u'\\xe9'], dtype=object)"
<del> x = np.array([u'\xe9'], dtype=object)
<add> x = np.array([sixu('\xe9')], dtype=object)
<ide> assert_equal(repr(x), expected)
<ide>
<ide>
<ide><path>numpy/core/tests/test_defchararray.py
<ide> import sys
<ide> from numpy.core.multiarray import _vec_string
<ide>
<del>from numpy.compat import asbytes, asbytes_nested
<add>from numpy.compat import asbytes, asbytes_nested, sixu
<ide>
<ide> kw_unicode_true = {'unicode': True} # make 2to3 work properly
<ide> kw_unicode_false = {'unicode': False}
<ide> def test_from_object_array(self):
<ide> ['long', '0123456789']]))
<ide>
<ide> def test_from_object_array_unicode(self):
<del> A = np.array([['abc', u'Sigma \u03a3'],
<add> A = np.array([['abc', sixu('Sigma \u03a3')],
<ide> ['long ', '0123456789']], dtype='O')
<ide> self.assertRaises(ValueError, np.char.array, (A,))
<ide> B = np.char.array(A, **kw_unicode_true)
<ide> assert_equal(B.dtype.itemsize, 10 * np.array('a', 'U').dtype.itemsize)
<del> assert_array_equal(B, [['abc', u'Sigma \u03a3'],
<add> assert_array_equal(B, [['abc', sixu('Sigma \u03a3')],
<ide> ['long', '0123456789']])
<ide>
<ide> def test_from_string_array(self):
<ide> def test_from_string_array(self):
<ide> assert_(C[0,0] == A[0,0])
<ide>
<ide> def test_from_unicode_array(self):
<del> A = np.array([['abc', u'Sigma \u03a3'],
<add> A = np.array([['abc', sixu('Sigma \u03a3')],
<ide> ['long ', '0123456789']])
<ide> assert_equal(A.dtype.type, np.unicode_)
<ide> B = np.char.array(A)
<ide> def fail():
<ide>
<ide> def test_unicode_upconvert(self):
<ide> A = np.char.array(['abc'])
<del> B = np.char.array([u'\u03a3'])
<add> B = np.char.array([sixu('\u03a3')])
<ide> assert_(issubclass((A + B).dtype.type, np.unicode_))
<ide>
<ide> def test_from_string(self):
<ide> def test_from_string(self):
<ide> assert_(issubclass(A.dtype.type, np.string_))
<ide>
<ide> def test_from_unicode(self):
<del> A = np.char.array(u'\u03a3')
<add> A = np.char.array(sixu('\u03a3'))
<ide> assert_equal(len(A), 1)
<ide> assert_equal(len(A[0]), 1)
<ide> assert_equal(A.itemsize, 4)
<ide> def setUp(self):
<ide> self.A = np.array([[' abc ', ''],
<ide> ['12345', 'MixedCase'],
<ide> ['123 \t 345 \0 ', 'UPPER']]).view(np.chararray)
<del> self.B = np.array([[u' \u03a3 ', u''],
<del> [u'12345', u'MixedCase'],
<del> [u'123 \t 345 \0 ', u'UPPER']]).view(np.chararray)
<add> self.B = np.array([[sixu(' \u03a3 '), sixu('')],
<add> [sixu('12345'), sixu('MixedCase')],
<add> [sixu('123 \t 345 \0 '), sixu('UPPER')]]).view(np.chararray)
<ide>
<ide> def test_len(self):
<ide> assert_(issubclass(np.char.str_len(self.A).dtype.type, np.integer))
<ide> def setUp(self):
<ide> ['12345', 'MixedCase'],
<ide> ['123 \t 345 \0 ', 'UPPER']],
<ide> dtype='S').view(np.chararray)
<del> self.B = np.array([[u' \u03a3 ', u''],
<del> [u'12345', u'MixedCase'],
<del> [u'123 \t 345 \0 ', u'UPPER']]).view(np.chararray)
<add> self.B = np.array([[sixu(' \u03a3 '), sixu('')],
<add> [sixu('12345'), sixu('MixedCase')],
<add> [sixu('123 \t 345 \0 '), sixu('UPPER')]]).view(np.chararray)
<ide>
<ide> def test_capitalize(self):
<ide> assert_(issubclass(self.A.capitalize().dtype.type, np.string_))
<ide> def test_capitalize(self):
<ide> ['123 \t 345 \0 ', 'Upper']]))
<ide> assert_(issubclass(self.B.capitalize().dtype.type, np.unicode_))
<ide> assert_array_equal(self.B.capitalize(), [
<del> [u' \u03c3 ', ''],
<add> [sixu(' \u03c3 '), ''],
<ide> ['12345', 'Mixedcase'],
<ide> ['123 \t 345 \0 ', 'Upper']])
<ide>
<ide> def test_decode(self):
<ide>
<ide> def test_encode(self):
<ide> B = self.B.encode('unicode_escape')
<del> assert_(B[0][0] == asbytes(r' \u03a3 '))
<add> assert_(B[0][0] == str(' \\u03a3 ').encode('latin1'))
<ide>
<ide> def test_expandtabs(self):
<ide> T = self.A.expandtabs()
<ide> def test_lower(self):
<ide> ['123 \t 345 \0 ', 'upper']]))
<ide> assert_(issubclass(self.B.lower().dtype.type, np.unicode_))
<ide> assert_array_equal(self.B.lower(), [
<del> [u' \u03c3 ', u''],
<del> [u'12345', u'mixedcase'],
<del> [u'123 \t 345 \0 ', u'upper']])
<add> [sixu(' \u03c3 '), sixu('')],
<add> [sixu('12345'), sixu('mixedcase')],
<add> [sixu('123 \t 345 \0 '), sixu('upper')]])
<ide>
<ide> def test_lstrip(self):
<ide> assert_(issubclass(self.A.lstrip().dtype.type, np.string_))
<ide> def test_lstrip(self):
<ide> ['23 \t 345 \x00', 'UPPER']]))
<ide> assert_(issubclass(self.B.lstrip().dtype.type, np.unicode_))
<ide> assert_array_equal(self.B.lstrip(), [
<del> [u'\u03a3 ', ''],
<add> [sixu('\u03a3 '), ''],
<ide> ['12345', 'MixedCase'],
<ide> ['123 \t 345 \0 ', 'UPPER']])
<ide>
<ide> def test_replace(self):
<ide>
<ide> if sys.version_info[0] < 3:
<ide> # NOTE: b'abc'.replace(b'a', 'b') is not allowed on Py3
<del> R = self.A.replace(asbytes('a'), u'\u03a3')
<add> R = self.A.replace(asbytes('a'), sixu('\u03a3'))
<ide> assert_(issubclass(R.dtype.type, np.unicode_))
<ide> assert_array_equal(R, [
<del> [u' \u03a3bc ', ''],
<del> ['12345', u'MixedC\u03a3se'],
<add> [sixu(' \u03a3bc '), ''],
<add> ['12345', sixu('MixedC\u03a3se')],
<ide> ['123 \t 345 \x00', 'UPPER']])
<ide>
<ide> def test_rjust(self):
<ide> def test_rstrip(self):
<ide> ['123 \t 345 \x00', 'UPP']]))
<ide> assert_(issubclass(self.B.rstrip().dtype.type, np.unicode_))
<ide> assert_array_equal(self.B.rstrip(), [
<del> [u' \u03a3', ''],
<add> [sixu(' \u03a3'), ''],
<ide> ['12345', 'MixedCase'],
<ide> ['123 \t 345', 'UPPER']])
<ide>
<ide> def test_strip(self):
<ide> ['23 \t 345 \x00', 'UPP']]))
<ide> assert_(issubclass(self.B.strip().dtype.type, np.unicode_))
<ide> assert_array_equal(self.B.strip(), [
<del> [u'\u03a3', ''],
<add> [sixu('\u03a3'), ''],
<ide> ['12345', 'MixedCase'],
<ide> ['123 \t 345', 'UPPER']])
<ide>
<ide> def test_swapcase(self):
<ide> ['123 \t 345 \0 ', 'upper']]))
<ide> assert_(issubclass(self.B.swapcase().dtype.type, np.unicode_))
<ide> assert_array_equal(self.B.swapcase(), [
<del> [u' \u03c3 ', u''],
<del> [u'12345', u'mIXEDcASE'],
<del> [u'123 \t 345 \0 ', u'upper']])
<add> [sixu(' \u03c3 '), sixu('')],
<add> [sixu('12345'), sixu('mIXEDcASE')],
<add> [sixu('123 \t 345 \0 '), sixu('upper')]])
<ide>
<ide> def test_title(self):
<ide> assert_(issubclass(self.A.title().dtype.type, np.string_))
<ide> def test_title(self):
<ide> ['123 \t 345 \0 ', 'Upper']]))
<ide> assert_(issubclass(self.B.title().dtype.type, np.unicode_))
<ide> assert_array_equal(self.B.title(), [
<del> [u' \u03a3 ', u''],
<del> [u'12345', u'Mixedcase'],
<del> [u'123 \t 345 \0 ', u'Upper']])
<add> [sixu(' \u03a3 '), sixu('')],
<add> [sixu('12345'), sixu('Mixedcase')],
<add> [sixu('123 \t 345 \0 '), sixu('Upper')]])
<ide>
<ide> def test_upper(self):
<ide> assert_(issubclass(self.A.upper().dtype.type, np.string_))
<ide> def test_upper(self):
<ide> ['123 \t 345 \0 ', 'UPPER']]))
<ide> assert_(issubclass(self.B.upper().dtype.type, np.unicode_))
<ide> assert_array_equal(self.B.upper(), [
<del> [u' \u03a3 ', u''],
<del> [u'12345', u'MIXEDCASE'],
<del> [u'123 \t 345 \0 ', u'UPPER']])
<add> [sixu(' \u03a3 '), sixu('')],
<add> [sixu('12345'), sixu('MIXEDCASE')],
<add> [sixu('123 \t 345 \0 '), sixu('UPPER')]])
<ide>
<ide> def test_isnumeric(self):
<ide> def fail():
<ide><path>numpy/core/tests/test_multiarray.py
<ide> import sys
<ide> import os
<ide> import warnings
<add>
<ide> import numpy as np
<ide> from nose import SkipTest
<ide> from numpy.core import *
<del>from numpy.compat import asbytes
<ide> from numpy.testing.utils import WarningManager
<del>from numpy.compat import asbytes, getexception, strchar
<add>from numpy.compat import asbytes, getexception, strchar, sixu
<ide> from test_print import in_foreign_locale
<ide> from numpy.core.multiarray_tests import (
<ide> test_neighborhood_iterator, test_neighborhood_iterator_oob,
<ide> # is an empty tuple instead of None.
<ide> # http://docs.python.org/dev/whatsnew/3.3.html#api-changes
<ide> EMPTY = ()
<del>else:
<add>else:
<ide> EMPTY = None
<ide>
<ide>
<ide> def test_mixed(self):
<ide>
<ide>
<ide> def test_unicode(self):
<del> g1 = array([u"This",u"is",u"example"])
<del> g2 = array([u"This",u"was",u"example"])
<add> g1 = array([sixu("This"),sixu("is"),sixu("example")])
<add> g2 = array([sixu("This"),sixu("was"),sixu("example")])
<ide> assert_array_equal(g1 == g2, [g1[i] == g2[i] for i in [0,1,2]])
<ide> assert_array_equal(g1 != g2, [g1[i] != g2[i] for i in [0,1,2]])
<ide> assert_array_equal(g1 <= g2, [g1[i] <= g2[i] for i in [0,1,2]])
<ide> def test_field_names(self):
<ide> raise SkipTest('non ascii unicode field indexing skipped; '
<ide> 'raises segfault on python 2.x')
<ide> else:
<del> assert_raises(ValueError, a.__setitem__, u'\u03e0', 1)
<del> assert_raises(ValueError, a.__getitem__, u'\u03e0')
<add> assert_raises(ValueError, a.__setitem__, sixu('\u03e0'), 1)
<add> assert_raises(ValueError, a.__getitem__, sixu('\u03e0'))
<ide>
<ide> def test_field_names_deprecation(self):
<ide> import warnings
<ide><path>numpy/core/tests/test_nditer.py
<ide>
<ide> import numpy as np
<ide> from numpy import array, arange, nditer, all
<del>from numpy.compat import asbytes
<add>from numpy.compat import asbytes, sixu
<ide> from numpy.testing import *
<ide>
<ide>
<ide> def test_iter_buffering_string():
<ide> assert_raises(TypeError,nditer,a,['buffered'],['readonly'],
<ide> op_dtypes='U2')
<ide> i = nditer(a, ['buffered'], ['readonly'], op_dtypes='U6')
<del> assert_equal(i[0], u'abc')
<add> assert_equal(i[0], sixu('abc'))
<ide> assert_equal(i[0].dtype, np.dtype('U6'))
<ide>
<ide> def test_iter_buffering_growinner():
<ide><path>numpy/core/tests/test_regression.py
<ide> assert_raises, assert_warns, dec
<ide> )
<ide> from numpy.testing.utils import _assert_valid_refcount, WarningManager
<del>from numpy.compat import asbytes, asunicode, asbytes_nested, long
<add>from numpy.compat import asbytes, asunicode, asbytes_nested, long, sixu
<ide>
<ide> rlevel = 1
<ide>
<ide> def test_scalar_compare(self,level=rlevel):
<ide> def test_unicode_swapping(self,level=rlevel):
<ide> """Ticket #79"""
<ide> ulen = 1
<del> ucs_value = u'\U0010FFFF'
<add> ucs_value = sixu('\U0010FFFF')
<ide> ua = np.array([[[ucs_value*ulen]*2]*3]*4, dtype='U%s' % ulen)
<ide> ua2 = ua.newbyteorder()
<ide>
<ide> def test_unaligned_unicode_access(self, level=rlevel) :
<ide> for i in range(1,9) :
<ide> msg = 'unicode offset: %d chars'%i
<ide> t = np.dtype([('a','S%d'%i),('b','U2')])
<del> x = np.array([(asbytes('a'),u'b')], dtype=t)
<add> x = np.array([(asbytes('a'),sixu('b'))], dtype=t)
<ide> if sys.version_info[0] >= 3:
<ide> assert_equal(str(x), "[(b'a', 'b')]", err_msg=msg)
<ide> else:
<ide> def test_object_array_to_fixed_string(self):
<ide>
<ide> def test_unicode_to_string_cast(self):
<ide> """Ticket #1240."""
<del> a = np.array([[u'abc', u'\u03a3'], [u'asdf', u'erw']], dtype='U')
<add> a = np.array(
<add> [ [sixu('abc'), sixu('\u03a3')],
<add> [sixu('asdf'), sixu('erw')]
<add> ], dtype='U')
<ide> def fail():
<ide> b = np.array(a, 'S4')
<ide> self.assertRaises(UnicodeEncodeError, fail)
<ide>
<ide> def test_mixed_string_unicode_array_creation(self):
<del> a = np.array(['1234', u'123'])
<add> a = np.array(['1234', sixu('123')])
<ide> assert_(a.itemsize == 16)
<del> a = np.array([u'123', '1234'])
<add> a = np.array([sixu('123'), '1234'])
<ide> assert_(a.itemsize == 16)
<del> a = np.array(['1234', u'123', '12345'])
<add> a = np.array(['1234', sixu('123'), '12345'])
<ide> assert_(a.itemsize == 20)
<del> a = np.array([u'123', '1234', u'12345'])
<add> a = np.array([sixu('123'), '1234', sixu('12345')])
<ide> assert_(a.itemsize == 20)
<del> a = np.array([u'123', '1234', u'1234'])
<add> a = np.array([sixu('123'), '1234', sixu('1234')])
<ide> assert_(a.itemsize == 16)
<ide>
<ide> def test_misaligned_objects_segfault(self):
<ide> def test_string_truncation_ucs2(self):
<ide> if sys.version_info[0] >= 3:
<ide> a = np.array(['abcd'])
<ide> else:
<del> a = np.array([u'abcd'])
<add> a = np.array([sixu('abcd')])
<ide> assert_equal(a.dtype.itemsize, 16)
<ide>
<ide> def test_unique_stable(self):
<ide><path>numpy/core/tests/test_unicode.py
<ide>
<ide> from numpy.testing import *
<ide> from numpy.core import *
<del>from numpy.compat import asbytes
<add>from numpy.compat import asbytes, sixu
<ide>
<ide> # Guess the UCS length for this python interpreter
<ide> if sys.version_info[:2] >= (3, 3):
<ide> def buffer_length(arr):
<ide> else:
<ide> return prod(v.shape) * v.itemsize
<ide> else:
<del> if len(buffer(u'u')) == 4:
<add> if len(buffer(sixu('u'))) == 4:
<ide> ucs4 = True
<ide> else:
<ide> ucs4 = False
<ide> def buffer_length(arr):
<ide> # In both cases below we need to make sure that the byte swapped value (as
<ide> # UCS4) is still a valid unicode:
<ide> # Value that can be represented in UCS2 interpreters
<del>ucs2_value = u'\u0900'
<add>ucs2_value = sixu('\u0900')
<ide> # Value that cannot be represented in UCS2 interpreters (but can in UCS4)
<del>ucs4_value = u'\U00100900'
<add>ucs4_value = sixu('\U00100900')
<ide>
<ide>
<ide> ############################################################
<ide> def content_check(self, ua, ua_scalar, nbytes):
<ide> # Check the length of the data buffer
<ide> self.assertTrue(buffer_length(ua) == nbytes)
<ide> # Small check that data in array element is ok
<del> self.assertTrue(ua_scalar == u'')
<add> self.assertTrue(ua_scalar == sixu(''))
<ide> # Encode to ascii and double check
<ide> self.assertTrue(ua_scalar.encode('ascii') == asbytes(''))
<ide> # Check buffer lengths for scalars
<ide><path>numpy/lib/_iotools.py
<ide> from numpy.compat import asbytes, bytes, asbytes_nested, long, basestring
<ide>
<ide> if sys.version_info[0] >= 3:
<del> from builtins import bool, int, float, complex, object, unicode, str
<add> from builtins import bool, int, float, complex, object, str
<add> unicode = str
<ide> else:
<ide> from __builtin__ import bool, int, float, complex, object, unicode, str
<ide>
<ide><path>numpy/lib/npyio.py
<ide> from ._datasource import DataSource
<ide> from ._compiled_base import packbits, unpackbits
<ide>
<del>from ._iotools import LineSplitter, NameValidator, StringConverter, \
<del> ConverterError, ConverterLockError, ConversionWarning, \
<del> _is_string_like, has_nested_fields, flatten_dtype, \
<del> easy_dtype, _bytes_to_name
<add>from ._iotools import (
<add> LineSplitter, NameValidator, StringConverter,
<add> ConverterError, ConverterLockError, ConversionWarning,
<add> _is_string_like, has_nested_fields, flatten_dtype,
<add> easy_dtype, _bytes_to_name
<add> )
<add>
<add>from numpy.compat import (
<add> asbytes, asstr, asbytes_nested, bytes, basestring, unicode
<add> )
<ide>
<del>from numpy.compat import asbytes, asstr, asbytes_nested, bytes, basestring
<ide> from io import BytesIO
<ide>
<ide> if sys.version_info[0] >= 3:
<ide><path>numpy/lib/tests/test_regression.py
<ide> from __future__ import division, absolute_import, print_function
<ide>
<ide> import sys
<add>
<add>import numpy as np
<ide> from numpy.testing import *
<ide> from numpy.testing.utils import _assert_valid_refcount
<del>import numpy as np
<add>from numpy.compat import unicode
<ide>
<ide> rlevel = 1
<ide>
<ide><path>numpy/ma/tests/test_regression.py
<ide> from __future__ import division, absolute_import, print_function
<ide>
<del>from numpy.testing import *
<ide> import numpy as np
<ide> import numpy.ma as ma
<add>from numpy.testing import *
<add>from numpy.compat import sixu
<ide>
<ide> rlevel = 1
<ide>
<ide> def test_masked_array_repeat(self, level=rlevel):
<ide>
<ide> def test_masked_array_repr_unicode(self):
<ide> """Ticket #1256"""
<del> repr(np.ma.array(u"Unicode"))
<add> repr(np.ma.array(sixu("Unicode")))
<ide>
<ide> def test_atleast_2d(self):
<ide> """Ticket #1559"""
<ide><path>tools/py3tool.py
<ide> 'throw',
<ide> 'tuple_params',
<ide> 'types',
<del># 'unicode',
<add> 'unicode',
<ide> 'urllib',
<ide> # 'ws_comma',
<ide> 'xrange', | 17 |
Java | Java | use assertj in annotationattributestests | 03dd45fbd62bdc158bf31098fd54cf5de3da2026 | <ide><path>spring-core/src/test/java/org/springframework/core/annotation/AnnotationAttributesTests.java
<ide> public void typeSafeAttributeAccess() {
<ide> @Test
<ide> public void unresolvableClassWithClassNotFoundException() throws Exception {
<ide> attributes.put("unresolvableClass", new ClassNotFoundException("myclass"));
<del> assertThatIllegalArgumentException().isThrownBy(() ->
<del> attributes.getClass("unresolvableClass"))
<del> .withMessageContaining("myclass");
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(() -> attributes.getClass("unresolvableClass"))
<add> .withMessageContaining("myclass")
<add> .withCauseInstanceOf(ClassNotFoundException.class);
<ide> }
<ide>
<ide> @Test
<ide> public void unresolvableClassWithLinkageError() throws Exception {
<ide> attributes.put("unresolvableClass", new LinkageError("myclass"));
<del> exception.expect(IllegalArgumentException.class);
<del> exception.expectMessage(containsString("myclass"));
<del> attributes.getClass("unresolvableClass");
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(() -> attributes.getClass("unresolvableClass"))
<add> .withMessageContaining("myclass")
<add> .withCauseInstanceOf(LinkageError.class);
<ide> }
<ide>
<ide> @Test
<ide> public void nestedAnnotations() throws Exception {
<ide>
<ide> @Test
<ide> public void getEnumWithNullAttributeName() {
<del> assertThatIllegalArgumentException().isThrownBy(() ->
<del> attributes.getEnum(null))
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(() -> attributes.getEnum(null))
<ide> .withMessageContaining("must not be null or empty");
<ide> }
<ide>
<ide> @Test
<ide> public void getEnumWithEmptyAttributeName() {
<del> assertThatIllegalArgumentException().isThrownBy(() ->
<del> attributes.getEnum(""))
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(() -> attributes.getEnum(""))
<ide> .withMessageContaining("must not be null or empty");
<ide> }
<ide>
<ide> @Test
<ide> public void getEnumWithUnknownAttributeName() {
<del> assertThatIllegalArgumentException().isThrownBy(() ->
<del> attributes.getEnum("bogus"))
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(() -> attributes.getEnum("bogus"))
<ide> .withMessageContaining("Attribute 'bogus' not found");
<ide> }
<ide>
<ide> @Test
<ide> public void getEnumWithTypeMismatch() {
<ide> attributes.put("color", "RED");
<del> assertThatIllegalArgumentException().isThrownBy(() ->
<del> attributes.getEnum("color"))
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(() -> attributes.getEnum("color"))
<ide> .withMessageContaining("Attribute 'color' is of type String, but Enum was expected");
<ide> }
<ide> | 1 |
PHP | PHP | add reply-to on config for mailer | 4f3813069fc00a595673afb4a074d18002aa1c06 | <ide><path>src/Illuminate/Mail/MailServiceProvider.php
<ide> public function register()
<ide> if (is_array($to) && isset($to['address'])) {
<ide> $mailer->alwaysTo($to['address'], $to['name']);
<ide> }
<add>
<add> $replyTo = $app['config']['mail.reply-to'];
<add>
<add> if (is_array($replyTo) && isset($replyTo['address'])) {
<add> $mailer->alwaysReplyTo($replyTo['address'], $replyTo['name']);
<add> }
<ide>
<ide> return $mailer;
<ide> });
<ide><path>src/Illuminate/Mail/Mailer.php
<ide> class Mailer implements MailerContract, MailQueueContract
<ide> * @var array
<ide> */
<ide> protected $to;
<add>
<add> /**
<add> * The global reply-to address and name.
<add> *
<add> * @var array
<add> */
<add> protected $replyTo;
<ide>
<ide> /**
<ide> * The IoC container instance.
<ide> public function alwaysTo($address, $name = null)
<ide> {
<ide> $this->to = compact('address', 'name');
<ide> }
<add>
<add> /**
<add> * Set the global reply-to address and name.
<add> *
<add> * @param string $address
<add> * @param string|null $name
<add> * @return void
<add> */
<add> public function alwaysReplyTo($address, $name = null)
<add> {
<add> $this->replyTo = compact('address', 'name');
<add> }
<ide>
<ide> /**
<ide> * Begin the process of mailing a mailable class instance.
<ide> protected function createMessage()
<ide> if (! empty($this->from['address'])) {
<ide> $message->from($this->from['address'], $this->from['name']);
<ide> }
<add>
<add> // If a global reply-to address has been specified we will set it on every message
<add> // instances so the developer does not have to repeat themselves every time
<add> // they create a new message. We will just go ahead and push the address.
<add> if (! empty($this->replyTo['address'])) {
<add> $message->replyTo($this->replyTo['address'], $this->replyTo['name']);
<add> }
<ide>
<ide> return $message;
<ide> } | 2 |
Text | Text | add £450, £400, £100 and £50 tiers | ec50f2ed89975fcdf081b9002e8645754cc92bbe | <ide><path>SUPPORTERS.md
<ide> # Kickstarter Supporters
<ide>
<ide> This file contains a list of the awesome people who gave £5 or more to
<del>[our Kickstarter](http://www.kickstarter.com/projects/homebrew/brew-test-bot).
<add>[our Kickstarter](http://www.kickstarter.com/projects/homebrew/brew-test-bot).
<ide>
<ide> This list is still incomplete as we need addresses for everyone who receives
<ide> a physical reward. Kickstarter recommends asking only when we are ready to
<ide> ship (to avoid changes of address) so we can't ask for more names/URLs
<ide> until then.
<ide>
<add>These mindblowing people supported our Kickstarter by giving us £450 or more:
<add>
<add>* [Hashrocket](http://hashrocket.com/)
<add>
<add>These spectacular people supported our Kickstarter by giving us £400 or more:
<add>
<add>* [Cargo Media](http://www.cargomedia.ch/)
<add>
<add>These amazing people supported our Kickstarter by giving us £100 or more:
<add>
<add>* [Mac Mini Vault](www.macminivault.com)
<add>* jpr
<add>* [Greg Sieranski](http://wonbyte.com)
<add>* [Stanley Stuart](http://fivetanley.com)
<add>* [Conor McDermottroe](www.mcdermottroe.com)
<add>* [Spike Grobstein](http://spike.grobste.in)
<add>* [nonfiction studios inc.](http://nonfiction.ca/)
<add>* [Dev Fu! LLC](devfu.com)
<add>* [Human Made Limited](http://hmn.md/)
<add>* [Roland Moriz](https://roland.io/)
<add>* [Rob Freiburger](http://robfreiburger.com/)
<add>* [Carter Schonwald](www.wellposed.com)
<add>* [Andy Piper](http://andypiper.co.uk)
<add>* [Moriah Trostler](http://www.televolve.com)
<add>* [Zach Kelling](http://whatit.is)
<add>* [Scott Densmore](http://scottdensmore.com)
<add>* [Adam Walz](www.adamwalz.net)
<add>* [Timo Tijhof](https://github.com/Krinkle)
<add>* [Joshua Hull](https://github.com/joshbuddy)
<add>* [Chad Catlett](http://www.chadcatlett.com/)
<add>
<add>These awesome people supported our Kickstarter by giving us £50 or more:
<add>
<add>* [Oliver Sigge](http://oliver-sigge.de)
<add>* [grahams](http://sean-graham.com/)
<add>* [Brian Ford](http://briantford.com)
<add>* Will Froning
<add>* [Florian Eckerstorfer](http://florianeckerstorfer.com)
<add>* [Leonhard Melzer](http://foomoo.de/)
<add>* [Klaus Großmann](https://github.com/iKlaus)
<add>* [monmon](https://github.com/monmon)
<add>* [nimbly](http://nimbly.be)
<add>* [cimnine](cimnine.ch)
<add>* [Greg DeAngelis](http://greg.deangel.is)
<add>* [Johan Carlquist](https://www.rymdvarel.se)
<add>* [Simon Lundström](http://soy.se)
<add>* [Samir Talwar](http://samirtalwar.com/)
<add>* [John Wu](http://www.johnwu.com)
<add>* [Jan Lehnardt](http://couchdb.apache.org)
<add>* [Adam Auden](http://bimble.net/)
<add>* [closure.jp](http://closure.jp/)
<add>* Scott S.
<add>* [Rachel Baker](http://rachelbaker.me)
<add>* Dominique Poulain
<add>* [Talks](http://tlks.me)
<add>* [Philipp Bosch](http://pb.io)
<add>* [Alexandru Badiu](http://ctrlz.ro)
<add>* [Misha Manulis](http://brewbit.com)
<add>* [MrBri](mrbri.com)
<add>* [Marc Van Olmen](http://www.marcvanolmen.com)
<add>* [Scott Gardner](scotteg.com)
<add>* [Peter JC](peterjc.dk)
<add>* [Nathan Toups](rojoroboto.com)
<add>* [Fluent Globe](fluentglobe.com)
<add>* [Dmitri Akatov](akatov.com)
<add>* [Joey Mink](http://joeymink.com)
<add>* [MentalPower](http://mentalpower.us)
<add>* [@worldofchris](http://www.worldofchris.com)
<add>* [Joël Kuijten](http://pm5544.eu)
<add>* [William Griffiths](Cwmni.com)
<add>* [Paul Howard](https://github.com/pauldhoward)
<add>* [Mårten Gustafson](http://marten.gustafson.pp.se)
<add>* [Markus Heurung](http://markusheurung.de)
<add>
<ide> These wonderful people supported our Kickstarter by giving us £10 or more:
<ide>
<ide> * [Simon Rascovsky](teleradiologia.com) | 1 |
Text | Text | improve test robustness | be4070a73dbc05eb4d4dbfef6dbdaee16e0b34a9 | <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/make-a-person.english.md
<ide> tests:
<ide>
<ide> ```js
<ide> var Person = function(firstAndLast) {
<add> // Only change code below this line
<ide> // Complete the method below and implement the others similarly
<ide> this.getFullName = function() {
<ide> return "";
<ide> bob.getFullName();
<ide>
<ide> </div>
<ide>
<add>### After Test
<add>
<add><div id='js-teardown'>
<add>
<add>```js
<add>if(bob){
<add> bob = new Person("Bob Ross");
<add>}
<add>```
<add>
<add></div>
<ide>
<ide>
<ide> </section> | 1 |
Mixed | Ruby | add allocations to template renderer subscription | e8c1be4ae7797f3ede588d2cf04a0155b4d6ce4a | <ide><path>actionpack/lib/action_controller/log_subscriber.rb
<ide> def start_processing(event)
<ide>
<ide> def process_action(event)
<ide> info do
<del> payload = event.payload
<add> payload = event.payload
<ide> additions = ActionController::Base.log_process_action(payload)
<del>
<ide> status = payload[:status]
<add>
<ide> if status.nil? && payload[:exception].present?
<ide> exception_class_name = payload[:exception].first
<ide> status = ActionDispatch::ExceptionWrapper.status_code_for_exception(exception_class_name)
<ide> end
<add>
<add> additions << "Allocations: #{event.allocations}"
<add>
<ide> message = +"Completed #{status} #{Rack::Utils::HTTP_STATUS_CODES[status]} in #{event.duration.round}ms"
<ide> message << " (#{additions.join(" | ")})" unless additions.empty?
<ide> message << "\n\n" if defined?(Rails.env) && Rails.env.development?
<ide><path>actionview/CHANGELOG.md
<add>* Add allocations to template rendering instrumentation.
<add>
<add> Adds the allocations for template and partial rendering to the server output on render.
<add>
<add> ```
<add> Rendered posts/_form.html.erb (Duration: 7.1ms | Allocations: 6004)
<add> Rendered posts/new.html.erb within layouts/application (Duration: 8.3ms | Allocations: 6654)
<add> Completed 200 OK in 858ms (Views: 848.4ms | ActiveRecord: 0.4ms | Allocations: 1539564)
<add> ```
<add>
<add> *Eileen M. Uchitelle*, *Aaron Patterson*
<add>
<ide> * Respect the `only_path` option passed to `url_for` when the options are passed in as an array
<ide>
<ide> Fixes #33237.
<ide><path>actionview/lib/action_view/log_subscriber.rb
<ide> def render_template(event)
<ide> info do
<ide> message = +" Rendered #{from_rails_root(event.payload[:identifier])}"
<ide> message << " within #{from_rails_root(event.payload[:layout])}" if event.payload[:layout]
<del> message << " (#{event.duration.round(1)}ms)"
<add> message << " (Duration: #{event.duration.round(1)}ms | Allocations: #{event.allocations})"
<ide> end
<ide> end
<ide>
<ide> def render_partial(event)
<ide> info do
<ide> message = +" Rendered #{from_rails_root(event.payload[:identifier])}"
<ide> message << " within #{from_rails_root(event.payload[:layout])}" if event.payload[:layout]
<del> message << " (#{event.duration.round(1)}ms)"
<add> message << " (Duration: #{event.duration.round(1)}ms | Allocations: #{event.allocations})"
<ide> message << " #{cache_message(event.payload)}" unless event.payload[:cache_hit].nil?
<ide> message
<ide> end
<ide> def render_collection(event)
<ide>
<ide> info do
<ide> " Rendered collection of #{from_rails_root(identifier)}" \
<del> " #{render_count(event.payload)} (#{event.duration.round(1)}ms)"
<add> " #{render_count(event.payload)} (Duration: #{event.duration.round(1)}ms | Allocations: #{event.allocations})"
<ide> end
<ide> end
<ide>
<ide><path>actionview/test/activerecord/controller_runtime_test.rb
<ide> def test_log_with_active_record
<ide> wait
<ide>
<ide> assert_equal 2, @logger.logged(:info).size
<del> assert_match(/\(Views: [\d.]+ms \| ActiveRecord: [\d.]+ms\)/, @logger.logged(:info)[1])
<add> assert_match(/\(Views: [\d.]+ms \| ActiveRecord: [\d.]+ms \| Allocations: [\d.]+\)/, @logger.logged(:info)[1])
<ide> end
<ide>
<ide> def test_runtime_reset_before_requests
<ide> def test_runtime_reset_before_requests
<ide> wait
<ide>
<ide> assert_equal 2, @logger.logged(:info).size
<del> assert_match(/\(Views: [\d.]+ms \| ActiveRecord: 0\.0ms\)/, @logger.logged(:info)[1])
<add> assert_match(/\(Views: [\d.]+ms \| ActiveRecord: [\d.]+ms \| Allocations: [\d.]+\)/, @logger.logged(:info)[1])
<ide> end
<ide>
<ide> def test_log_with_active_record_when_post
<ide> post :create
<ide> wait
<del> assert_match(/ActiveRecord: ([1-9][\d.]+)ms\)/, @logger.logged(:info)[2])
<add> assert_match(/ActiveRecord: ([1-9][\d.]+)ms \| Allocations: [\d.]+\)/, @logger.logged(:info)[2])
<ide> end
<ide>
<ide> def test_log_with_active_record_when_redirecting
<ide> get :redirect
<ide> wait
<ide> assert_equal 3, @logger.logged(:info).size
<del> assert_match(/\(ActiveRecord: [\d.]+ms\)/, @logger.logged(:info)[2])
<add> assert_match(/\(ActiveRecord: [\d.]+ms \| Allocations: [\d.]+\)/, @logger.logged(:info)[2])
<ide> end
<ide>
<ide> def test_include_time_query_time_after_rendering
<ide> get :db_after_render
<ide> wait
<ide>
<ide> assert_equal 2, @logger.logged(:info).size
<del> assert_match(/\(Views: [\d.]+ms \| ActiveRecord: ([1-9][\d.]+)ms\)/, @logger.logged(:info)[1])
<add> assert_match(/\(Views: [\d.]+ms \| ActiveRecord: ([1-9][\d.]+)ms \| Allocations: [\d.]+\)/, @logger.logged(:info)[1])
<ide> end
<ide> end
<ide><path>actionview/test/template/log_subscriber_test.rb
<ide> def test_render_uncached_outer_partial_with_inner_cached_partial_wont_mix_cache_
<ide> wait
<ide> *, cached_inner, uncached_outer = @logger.logged(:info)
<ide> assert_match(/Rendered test\/_cached_customer\.erb (.*) \[cache miss\]/, cached_inner)
<del> assert_match(/Rendered test\/_nested_cached_customer\.erb \(.*?ms\)$/, uncached_outer)
<add> assert_match(/Rendered test\/_nested_cached_customer\.erb \(Duration: .*?ms \| Allocations: .*?\)$/, uncached_outer)
<ide>
<ide> # Second render hits the cache for the _cached_customer partial. Outer template's log shouldn't be affected.
<ide> @view.render(partial: "test/nested_cached_customer", locals: { cached_customer: Customer.new("Stan") })
<ide> wait
<ide> *, cached_inner, uncached_outer = @logger.logged(:info)
<ide> assert_match(/Rendered test\/_cached_customer\.erb (.*) \[cache hit\]/, cached_inner)
<del> assert_match(/Rendered test\/_nested_cached_customer\.erb \(.*?ms\)$/, uncached_outer)
<add> assert_match(/Rendered test\/_nested_cached_customer\.erb \(Duration: .*?ms \| Allocations: .*?\)$/, uncached_outer)
<ide> end
<ide> end
<ide> | 5 |
Ruby | Ruby | rework the routing documentation | 5ead15b07597e9cdb887cfe6aa74de4a14140bb1 | <ide><path>actionpack/lib/action_dispatch/routing.rb
<ide> require 'active_support/core_ext/regexp'
<ide>
<ide> module ActionDispatch
<del> # = Routing
<del> #
<ide> # The routing module provides URL rewriting in native Ruby. It's a way to
<ide> # redirect incoming requests to controllers and actions. This replaces
<del> # mod_rewrite rules. Best of all, Rails' Routing works with any web server.
<add> # mod_rewrite rules. Best of all, Rails' \Routing works with any web server.
<ide> # Routes are defined in <tt>config/routes.rb</tt>.
<ide> #
<del> # Consider the following route, which you will find commented out at the
<del> # bottom of your generated <tt>config/routes.rb</tt>:
<del> #
<del> # match ':controller(/:action(/:id(.:format)))'
<del> #
<del> # This route states that it expects requests to consist of a
<del> # <tt>:controller</tt> followed optionally by an <tt>:action</tt> that in
<del> # turn is followed optionally by an <tt>:id</tt>, which in turn is followed
<del> # optionally by a <tt>:format</tt>
<del> #
<del> # Suppose you get an incoming request for <tt>/blog/edit/22</tt>, you'll end
<del> # up with:
<del> #
<del> # params = { :controller => 'blog',
<del> # :action => 'edit',
<del> # :id => '22'
<del> # }
<del> #
<ide> # Think of creating routes as drawing a map for your requests. The map tells
<ide> # them where to go based on some predefined pattern:
<ide> #
<ide> module ActionDispatch
<ide> #
<ide> # Other names simply map to a parameter as in the case of <tt>:id</tt>.
<ide> #
<add> # == Resources
<add> #
<add> # Resource routing allows you to quickly declare all of the common routes
<add> # for a given resourceful controller. Instead of declaring separate routes
<add> # for your +index+, +show+, +new+, +edit+, +create+, +update+ and +destroy+
<add> # actions, a resourceful route declares them in a single line of code:
<add> #
<add> # resources :photos
<add> #
<add> # Sometimes, you have a resource that clients always look up without
<add> # referencing an ID. A common example, /profile always shows the profile of
<add> # the currently logged in user. In this case, you can use a singular resource
<add> # to map /profile (rather than /profile/:id) to the show action.
<add> #
<add> # resource :profile
<add> #
<add> # It's common to have resources that are logically children of other
<add> # resources:
<add> #
<add> # resources :magazines do
<add> # resources :ads
<add> # end
<add> #
<add> # You may wish to organize groups of controllers under a namespace. Most
<add> # commonly, you might group a number of administrative controllers under
<add> # an +admin+ namespace. You would place these controllers under the
<add> # app/controllers/admin directory, and you can group them together in your
<add> # router:
<add> #
<add> # namespace "admin" do
<add> # resources :posts, :comments
<add> # end
<add> #
<ide> # == Named routes
<ide> #
<ide> # Routes can be named by passing an <tt>:as</tt> option,
<ide> module ActionDispatch
<ide> # Encoding regular expression modifiers are silently ignored. The
<ide> # match will always use the default encoding or ASCII.
<ide> #
<add> # == Default route
<add> #
<add> # Consider the following route, which you will find commented out at the
<add> # bottom of your generated <tt>config/routes.rb</tt>:
<add> #
<add> # match ':controller(/:action(/:id(.:format)))'
<add> #
<add> # This route states that it expects requests to consist of a
<add> # <tt>:controller</tt> followed optionally by an <tt>:action</tt> that in
<add> # turn is followed optionally by an <tt>:id</tt>, which in turn is followed
<add> # optionally by a <tt>:format</tt>.
<add> #
<add> # Suppose you get an incoming request for <tt>/blog/edit/22</tt>, you'll end
<add> # up with:
<add> #
<add> # params = { :controller => 'blog',
<add> # :action => 'edit',
<add> # :id => '22'
<add> # }
<add> #
<add> # By not relying on default routes, you improve the security of your
<add> # application since not all controller actions, which includes actions you
<add> # might add at a later time, are exposed by default.
<add> #
<ide> # == HTTP Methods
<ide> #
<ide> # Using the <tt>:via</tt> option when specifying a route allows you to restrict it to a specific HTTP method.
<ide> module ActionDispatch
<ide> # however if your route needs to respond to more than one HTTP method (or all methods) then using the
<ide> # <tt>:via</tt> option on <tt>match</tt> is preferable.
<ide> #
<add> # == External redirects
<add> #
<add> # You can redirect any path to another path using the redirect helper in your router:
<add> #
<add> # match "/stories" => redirect("/posts")
<add> #
<add> # == Routing to Rack Applications
<add> #
<add> # Instead of a String, like <tt>posts#index</tt>, which corresponds to the
<add> # index action in the PostsController, you can specify any Rack application
<add> # as the endpoint for a matcher:
<add> #
<add> # match "/application.js" => Sprockets
<add> #
<ide> # == Reloading routes
<ide> #
<ide> # You can reload routes if you feel you must:
<ide> module ActionDispatch
<ide> #
<ide> # == View a list of all your routes
<ide> #
<del> # Run <tt>rake routes</tt>.
<add> # rake routes
<add> #
<add> # Target specific controllers by prefixing the command with <tt>CONTROLLER=x</tt>.
<ide> #
<ide> module Routing
<ide> autoload :DeprecatedMapper, 'action_dispatch/routing/deprecated_mapper' | 1 |
Go | Go | change alias for oci-specs to match existing code | 91bd9a6642699edaa1cee76cbf712baa2ba374a1 | <ide><path>daemon/containerd/service.go
<ide> import (
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/layer"
<ide> "github.com/opencontainers/go-digest"
<del> ocispec "github.com/opencontainers/image-spec/specs-go/v1"
<add> specs "github.com/opencontainers/image-spec/specs-go/v1"
<ide> )
<ide>
<ide> // ImageService implements daemon.ImageService
<ide> func NewService(c *containerd.Client) *ImageService {
<ide>
<ide> // PullImage initiates a pull operation. image is the repository name to pull, and
<ide> // tagOrDigest may be either empty, or indicate a specific tag or digest to pull.
<del>func (cs *ImageService) PullImage(ctx context.Context, image, tagOrDigest string, platform *ocispec.Platform, metaHeaders map[string][]string, authConfig *types.AuthConfig, outStream io.Writer) error {
<add>func (cs *ImageService) PullImage(ctx context.Context, image, tagOrDigest string, platform *specs.Platform, metaHeaders map[string][]string, authConfig *types.AuthConfig, outStream io.Writer) error {
<ide> var opts []containerd.RemoteOpt
<ide> if platform != nil {
<ide> opts = append(opts, containerd.WithPlatform(platforms.Format(*platform)))
<ide> func (cs *ImageService) ImagesPrune(ctx context.Context, pruneFilters filters.Ar
<ide> // inConfig (if src is "-"), or from a URI specified in src. Progress output is
<ide> // written to outStream. Repository and tag names can optionally be given in
<ide> // the repo and tag arguments, respectively.
<del>func (cs *ImageService) ImportImage(src string, repository string, platform *ocispec.Platform, tag string, msg string, inConfig io.ReadCloser, outStream io.Writer, changes []string) error {
<add>func (cs *ImageService) ImportImage(src string, repository string, platform *specs.Platform, tag string, msg string, inConfig io.ReadCloser, outStream io.Writer, changes []string) error {
<ide> panic("not implemented")
<ide> }
<ide>
<ide> func (cs *ImageService) CommitImage(c backend.CommitConfig) (image.ID, error) {
<ide> }
<ide>
<ide> // GetImage returns an image corresponding to the image referred to by refOrID.
<del>func (cs *ImageService) GetImage(refOrID string, platform *ocispec.Platform) (retImg *image.Image, retErr error) {
<add>func (cs *ImageService) GetImage(refOrID string, platform *specs.Platform) (retImg *image.Image, retErr error) {
<ide> panic("not implemented")
<ide> }
<ide> | 1 |
Javascript | Javascript | fix spelling/grammar in test comment | c8d9957f68b4cd9891bf529a018338673e5b51ce | <ide><path>src/core/__tests__/ReactCompositeComponent-test.js
<ide> describe('ReactCompositeComponent', function() {
<ide>
<ide> it('should give context for PropType errors in nested components.', () => {
<ide> // In this test, we're making sure that if a proptype error is found in a
<del> // component, we give a smal hint as to which parent instantiated that
<del> // component as per warnings about key-usage in ReactDescriptorValidator.
<add> // component, we give a small hint as to which parent instantiated that
<add> // component as per warnings about key usage in ReactDescriptorValidator.
<ide> spyOn(console, 'warn');
<ide> var MyComp = React.createClass({
<ide> propTypes: { | 1 |
Python | Python | fix typo in training_args_tf.py | d441f8d29dedeb0b64277f5323787a891b207a9a | <ide><path>src/transformers/training_args_tf.py
<ide> class TFTrainingArguments(TrainingArguments):
<ide> If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints in
<ide> :obj:`output_dir`.
<ide> no_cuda (:obj:`bool`, `optional`, defaults to :obj:`False`):
<del> Wherher to not use CUDA even when it is available or not.
<add> Whether to not use CUDA even when it is available or not.
<ide> seed (:obj:`int`, `optional`, defaults to 42):
<ide> Random seed for initialization.
<ide> fp16 (:obj:`bool`, `optional`, defaults to :obj:`False`): | 1 |
Javascript | Javascript | use lru for encoded strings | 255385d25545796023a049df65461abdd49a61be | <ide><path>src/utils.js
<ide> // @flow
<ide>
<add>const LRU = require('lru-cache');
<add>
<ide> const FB_MODULE_RE = /^(.*) \[from (.*)\]$/;
<ide> const cachedDisplayNames: WeakMap<Function, string> = new WeakMap();
<ide>
<add>// On large trees, encoding takes significant time.
<add>// Try to reuse the already encoded strings.
<add>let encodedStringCache = new LRU({ max: 1000 });
<add>
<ide> export function getDisplayName(
<ide> type: Function,
<ide> fallbackName: string = 'Unknown'
<ide> export function utfDecodeString(array: Uint32Array): string {
<ide> }
<ide>
<ide> export function utfEncodeString(string: string): Uint32Array {
<add> let cached = encodedStringCache.get(string);
<add> if (cached !== undefined) {
<add> return cached;
<add> }
<add>
<ide> // $FlowFixMe Flow's Uint32Array.from's type definition is wrong; first argument of mapFn will be string
<del> return Uint32Array.from(string, toCodePoint);
<add> const encoded = Uint32Array.from(string, toCodePoint);
<add> encodedStringCache.set(string, encoded);
<add> return encoded;
<ide> }
<ide>
<ide> function toCodePoint(string: string) { | 1 |
Python | Python | improve quine–mccluskey algorithm | 9af2eef9b3761bf51580dedfb6fa7136ca0c5c2c | <ide><path>boolean_algebra/quine_mc_cluskey.py
<ide> from __future__ import annotations
<ide>
<add>from typing import Sequence
<add>
<ide>
<ide> def compare_string(string1: str, string2: str) -> str:
<ide> """
<ide> def compare_string(string1: str, string2: str) -> str:
<ide> >>> compare_string('0110','1101')
<ide> 'X'
<ide> """
<del> l1 = list(string1)
<del> l2 = list(string2)
<add> list1 = list(string1)
<add> list2 = list(string2)
<ide> count = 0
<del> for i in range(len(l1)):
<del> if l1[i] != l2[i]:
<add> for i in range(len(list1)):
<add> if list1[i] != list2[i]:
<ide> count += 1
<del> l1[i] = "_"
<add> list1[i] = "_"
<ide> if count > 1:
<ide> return "X"
<ide> else:
<del> return "".join(l1)
<add> return "".join(list1)
<ide>
<ide>
<ide> def check(binary: list[str]) -> list[str]:
<ide> def check(binary: list[str]) -> list[str]:
<ide> ['0.00.01.5']
<ide> """
<ide> pi = []
<del> while 1:
<add> while True:
<ide> check1 = ["$"] * len(binary)
<ide> temp = []
<ide> for i in range(len(binary)):
<ide> def check(binary: list[str]) -> list[str]:
<ide> binary = list(set(temp))
<ide>
<ide>
<del>def decimal_to_binary(no_of_variable: int, minterms: list[float]) -> list[str]:
<add>def decimal_to_binary(no_of_variable: int, minterms: Sequence[float]) -> list[str]:
<ide> """
<ide> >>> decimal_to_binary(3,[1.5])
<ide> ['0.00.01.5']
<ide> """
<ide> temp = []
<del> s = ""
<del> for m in minterms:
<add> for minterm in minterms:
<add> string = ""
<ide> for i in range(no_of_variable):
<del> s = str(m % 2) + s
<del> m //= 2
<del> temp.append(s)
<del> s = ""
<add> string = str(minterm % 2) + string
<add> minterm //= 2
<add> temp.append(string)
<ide> return temp
<ide>
<ide>
<ide> def is_for_table(string1: str, string2: str, count: int) -> bool:
<ide> >>> is_for_table('01_','001',1)
<ide> False
<ide> """
<del> l1 = list(string1)
<del> l2 = list(string2)
<add> list1 = list(string1)
<add> list2 = list(string2)
<ide> count_n = 0
<del> for i in range(len(l1)):
<del> if l1[i] != l2[i]:
<add> for i in range(len(list1)):
<add> if list1[i] != list2[i]:
<ide> count_n += 1
<del> if count_n == count:
<del> return True
<del> else:
<del> return False
<add> return count_n == count
<ide>
<ide>
<ide> def selection(chart: list[list[int]], prime_implicants: list[str]) -> list[str]:
<ide> def selection(chart: list[list[int]], prime_implicants: list[str]) -> list[str]:
<ide> for k in range(len(chart)):
<ide> chart[k][j] = 0
<ide> temp.append(prime_implicants[i])
<del> while 1:
<add> while True:
<ide> max_n = 0
<ide> rem = -1
<ide> count_n = 0 | 1 |
Python | Python | update hostvirtual docstring | 1fca5254f629d4c027e7aa7a5c12b99d6a9ee728 | <ide><path>libcloud/compute/drivers/hostvirtual.py
<ide> def destroy_node(self, node):
<ide> return bool(result)
<ide>
<ide> def ex_stop_node(self, node):
<add> """
<add> Stop a node.
<add>
<add> @param node: Node which should be used
<add> @type node: L{Node}
<add>
<add> @rtype: C{bool}
<add> """
<ide> params = {'force': 0, 'mbpkgid': node.id}
<ide> result = self.connection.request(
<ide> API_ROOT + '/cloud/server/stop',
<ide> def ex_stop_node(self, node):
<ide> return bool(result)
<ide>
<ide> def ex_start_node(self, node):
<add> """
<add> Start a node.
<add>
<add> @param node: Node which should be used
<add> @type node: L{Node}
<add>
<add> @rtype: C{bool}
<add> """
<ide> params = {'mbpkgid': node.id}
<ide> result = self.connection.request(
<ide> API_ROOT + '/cloud/server/start', | 1 |
Ruby | Ruby | raise error when cmd is bash file | c56fff39280b6d059f72cdf999f93d705d045c10 | <ide><path>Library/Homebrew/brew.rb
<ide> class MissingEnvironmentVariables < RuntimeError; end
<ide> end
<ide> exec "brew-#{cmd}", *ARGV
<ide> else
<del> raise "command made by bash not ruby: #{cmd}" if Commands.only_bash_command_list.include?(cmd)
<del>
<ide> possible_tap = OFFICIAL_CMD_TAPS.find { |_, cmds| cmds.include?(cmd) }
<ide> possible_tap = Tap.fetch(possible_tap.first) if possible_tap
<ide>
<ide><path>Library/Homebrew/commands.rb
<ide> def rebuild_commands_completion_list
<ide> file = HOMEBREW_CACHE/"all_commands_list.txt"
<ide> file.atomic_write("#{commands(aliases: true).sort.join("\n")}\n")
<ide> end
<del>
<del> def only_bash_command_list
<del> internal_commands.reject { |cmd| valid_internal_cmd?(cmd) }
<del> end
<ide> end
<ide><path>Library/Homebrew/dev-cmd/prof.rb
<ide> def prof
<ide>
<ide> brew_rb = (HOMEBREW_LIBRARY_PATH/"brew.rb").resolved_path
<ide> FileUtils.mkdir_p "prof"
<add> cmd = args.named.first
<add> raise UsageError, "#{cmd} is a Bash command!" if Commands.path(cmd).extname == ".sh"
<ide>
<ide> if args.stackprof?
<ide> Homebrew.install_gem_setup_path! "stackprof" | 3 |
PHP | PHP | remove unused property | 8bd3875080f24080983adf5626f6441665eb9e9b | <ide><path>src/ORM/Rule/IsUnique.php
<ide> class IsUnique
<ide> */
<ide> protected $_fields;
<ide>
<del> /**
<del> * The options to use.
<del> *
<del> * @var array
<del> */
<del> protected $_options;
<del>
<ide> /**
<ide> * Constructor.
<ide> * | 1 |
Javascript | Javascript | add test case for get week number of the year | 52666299dabe4a6157d984c7a47ee3aa62911998 | <ide><path>test/moment/format.js
<ide> exports.format = {
<ide> test.equal(JSON.stringify({
<ide> date : date
<ide> }), '{"date":"2012-10-09T20:30:40.678Z"}', "should output ISO8601 on JSON.stringify");
<add> test.done();
<add> },
<add>
<add> "weeks format" : function(test) {
<add>
<add> // http://en.wikipedia.org/wiki/ISO_week_date
<add> var cases = {
<add> "2005-01-02": "2004-53",
<add> "2005-12-31": "2005-52",
<add> "2007-01-01": "2007-01",
<add> "2007-12-30": "2007-52",
<add> "2007-12-31": "2008-01",
<add> "2008-01-01": "2008-01",
<add> "2008-12-28": "2008-52",
<add> "2008-12-29": "2009-01",
<add> "2008-12-30": "2009-01",
<add> "2008-12-31": "2009-01",
<add> "2009-01-01": "2009-01",
<add> "2009-12-31": "2009-53",
<add> "2010-01-01": "2009-53",
<add> "2010-01-02": "2009-53",
<add> "2010-01-03": "2009-53",
<add> };
<add>
<add> for (var i in cases) {
<add> var iso = cases[i].split('-').pop();
<add> var the = moment(i).format('ww');
<add> test.equal(iso, the, i + ": should be " + iso + ", but " + the);
<add> }
<add>
<ide> test.done();
<ide> }
<ide> }; | 1 |
Ruby | Ruby | add shortcut test to abstract/render_test.rb | dcb8b64975832ac75d92104da3c95876e56eec66 | <ide><path>actionpack/test/abstract/render_test.rb
<ide> def default
<ide> render
<ide> end
<ide>
<add> def shortcut
<add> render "template"
<add> end
<add>
<ide> def template_name
<ide> render :_template_name => :template_name
<ide> end
<ide> def test_render_default
<ide> assert_equal "With Default", @controller.response_body
<ide> end
<ide>
<add> def test_render_template_through_shortcut
<add> @controller.process(:shortcut)
<add> assert_equal "With Template", @controller.response_body
<add> end
<add>
<ide> def test_render_template_name
<ide> @controller.process(:template_name)
<ide> assert_equal "With Template Name", @controller.response_body | 1 |
Python | Python | add tests for arc eager oracle | 53b3249e06416488241a34c5d75435ca042eea84 | <ide><path>spacy/tests/parser/test_arc_eager_oracle.py
<add>from ...vocab import Vocab
<add>from ...pipeline import DependencyParser
<add>from ...tokens import Doc
<add>from ...gold import GoldParse
<add>from ...syntax.nonproj import projectivize
<add>
<add>annot_tuples = [
<add> (0, 'When', 'WRB', 11, 'advmod', 'O'),
<add> (1, 'Walter', 'NNP', 2, 'compound', 'B-PERSON'),
<add> (2, 'Rodgers', 'NNP', 11, 'nsubj', 'L-PERSON'),
<add> (3, ',', ',', 2, 'punct', 'O'),
<add> (4, 'our', 'PRP$', 6, 'poss', 'O'),
<add> (5, 'embedded', 'VBN', 6, 'amod', 'O'),
<add> (6, 'reporter', 'NN', 2, 'appos', 'O'),
<add> (7, 'with', 'IN', 6, 'prep', 'O'),
<add> (8, 'the', 'DT', 10, 'det', 'B-ORG'),
<add> (9, '3rd', 'NNP', 10, 'compound', 'I-ORG'),
<add> (10, 'Cavalry', 'NNP', 7, 'pobj', 'L-ORG'),
<add> (11, 'says', 'VBZ', 44, 'advcl', 'O'),
<add> (12, 'three', 'CD', 13, 'nummod', 'U-CARDINAL'),
<add> (13, 'battalions', 'NNS', 16, 'nsubj', 'O'),
<add> (14, 'of', 'IN', 13, 'prep', 'O'),
<add> (15, 'troops', 'NNS', 14, 'pobj', 'O'),
<add> (16, 'are', 'VBP', 11, 'ccomp', 'O'),
<add> (17, 'on', 'IN', 16, 'prep', 'O'),
<add> (18, 'the', 'DT', 19, 'det', 'O'),
<add> (19, 'ground', 'NN', 17, 'pobj', 'O'),
<add> (20, ',', ',', 17, 'punct', 'O'),
<add> (21, 'inside', 'IN', 17, 'prep', 'O'),
<add> (22, 'Baghdad', 'NNP', 21, 'pobj', 'U-GPE'),
<add> (23, 'itself', 'PRP', 22, 'appos', 'O'),
<add> (24, ',', ',', 16, 'punct', 'O'),
<add> (25, 'have', 'VBP', 26, 'aux', 'O'),
<add> (26, 'taken', 'VBN', 16, 'dep', 'O'),
<add> (27, 'up', 'RP', 26, 'prt', 'O'),
<add> (28, 'positions', 'NNS', 26, 'dobj', 'O'),
<add> (29, 'they', 'PRP', 31, 'nsubj', 'O'),
<add> (30, "'re", 'VBP', 31, 'aux', 'O'),
<add> (31, 'going', 'VBG', 26, 'parataxis', 'O'),
<add> (32, 'to', 'TO', 33, 'aux', 'O'),
<add> (33, 'spend', 'VB', 31, 'xcomp', 'O'),
<add> (34, 'the', 'DT', 35, 'det', 'B-TIME'),
<add> (35, 'night', 'NN', 33, 'dobj', 'L-TIME'),
<add> (36, 'there', 'RB', 33, 'advmod', 'O'),
<add> (37, 'presumably', 'RB', 33, 'advmod', 'O'),
<add> (38, ',', ',', 44, 'punct', 'O'),
<add> (39, 'how', 'WRB', 40, 'advmod', 'O'),
<add> (40, 'many', 'JJ', 41, 'amod', 'O'),
<add> (41, 'soldiers', 'NNS', 44, 'pobj', 'O'),
<add> (42, 'are', 'VBP', 44, 'aux', 'O'),
<add> (43, 'we', 'PRP', 44, 'nsubj', 'O'),
<add> (44, 'talking', 'VBG', 44, 'ROOT', 'O'),
<add> (45, 'about', 'IN', 44, 'prep', 'O'),
<add> (46, 'right', 'RB', 47, 'advmod', 'O'),
<add> (47, 'now', 'RB', 44, 'advmod', 'O'),
<add> (48, '?', '.', 44, 'punct', 'O')]
<add>
<add>def test_get_oracle_actions():
<add> doc = Doc(Vocab(), words=[t[1] for t in annot_tuples])
<add> parser = DependencyParser(doc.vocab)
<add> parser.moves.add_action(0, '')
<add> parser.moves.add_action(1, '')
<add> parser.moves.add_action(1, '')
<add> parser.moves.add_action(4, 'ROOT')
<add> for i, (id_, word, tag, head, dep, ent) in enumerate(annot_tuples):
<add> if head > i:
<add> parser.moves.add_action(2, dep)
<add> elif head < i:
<add> parser.moves.add_action(3, dep)
<add> ids, words, tags, heads, deps, ents = zip(*annot_tuples)
<add> heads, deps = projectivize(heads, deps)
<add> gold = GoldParse(doc, words=words, tags=tags, heads=heads, deps=deps)
<add> parser.moves.preprocess_gold(gold)
<add> actions = parser.moves.get_oracle_sequence(doc, gold) | 1 |
PHP | PHP | update server.php email address | 6f055a9b473ddd164fff688b551c78d3334cfe32 | <ide><path>server.php
<ide> * Laravel - A PHP Framework For Web Artisans
<ide> *
<ide> * @package Laravel
<del> * @author Taylor Otwell <taylorotwell@gmail.com>
<add> * @author Taylor Otwell <taylor@laravel.com>
<ide> */
<ide>
<ide> $uri = urldecode( | 1 |
Go | Go | fix bug in ipsec key rotation | bc6a60dae563ec3c8842b26d1f30081ceb6a1171 | <ide><path>libnetwork/drivers/overlay/encryption.go
<ide> func updateNodeKey(lIP, rIP net.IP, idxs []*spi, curKeys []*key, newIdx, priIdx,
<ide>
<ide> if delIdx != -1 {
<ide> // -rSA0
<del> programSA(rIP, lIP, spis[delIdx], nil, reverse, false)
<add> programSA(lIP, rIP, spis[delIdx], nil, reverse, false)
<ide> }
<ide>
<ide> if newIdx > -1 { | 1 |
Ruby | Ruby | handle corrupt checkouts | da2efa46aaf4600e5c4e1fbfa83f0973dbac55e3 | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def cached_location
<ide> @co
<ide> end
<ide>
<add> def repo_valid?
<add> @co.join(".svn").directory?
<add> end
<add>
<ide> def fetch
<ide> @url.sub!(/^svn\+/, '') if @url =~ %r[^svn\+http://]
<ide> ohai "Checking out #{@url}"
<add>
<add> if @co.exist? and not repo_valid?
<add> puts "Removing invalid SVN repo from cache"
<add> @co.rmtree
<add> end
<add>
<ide> if @spec == :revision
<ide> fetch_repo @co, @url, @ref
<ide> elsif @spec == :revisions
<ide> def fetch_repo target, url, revision=nil, ignore_externals=false
<ide> # Use "svn up" when the repository already exists locally.
<ide> # This saves on bandwidth and will have a similar effect to verifying the
<ide> # cache as it will make any changes to get the right revision.
<del> svncommand = target.exist? ? 'up' : 'checkout'
<add> svncommand = target.directory? ? 'up' : 'checkout'
<ide> args = [@@svn, svncommand]
<ide> # SVN shipped with XCode 3.1.4 can't force a checkout.
<ide> args << '--force' unless MacOS.version == :leopard and @@svn == '/usr/bin/svn'
<del> args << url if !target.exist?
<add> args << url unless target.directory?
<ide> args << target
<ide> args << '-r' << revision if revision
<ide> args << '--ignore-externals' if ignore_externals
<ide> def fetch_repo target, url, revision=nil, ignore_externals=false
<ide> # Use "svn up" when the repository already exists locally.
<ide> # This saves on bandwidth and will have a similar effect to verifying the
<ide> # cache as it will make any changes to get the right revision.
<del> svncommand = target.exist? ? 'up' : 'checkout'
<add> svncommand = target.directory? ? 'up' : 'checkout'
<ide> args = [@@svn, svncommand, '--non-interactive', '--trust-server-cert', '--force']
<del> args << url if !target.exist?
<add> args << url unless target.directory?
<ide> args << target
<ide> args << '-r' << revision if revision
<ide> args << '--ignore-externals' if ignore_externals | 1 |
Java | Java | add support for view manager commands in fabric | 3ac914478d9636e7fffe29751e916ac16f311652 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java
<ide> import com.facebook.react.modules.fabric.ReactFabric;
<ide> import com.facebook.react.uimanager.DisplayMetricsHolder;
<ide> import com.facebook.react.uimanager.UIImplementationProvider;
<del>import com.facebook.react.uimanager.UIManagerModule;
<add>import com.facebook.react.uimanager.UIManagerHelper;
<ide> import com.facebook.react.uimanager.ViewManager;
<ide> import com.facebook.react.views.imagehelper.ResourceDrawableIdHelper;
<ide> import com.facebook.soloader.SoLoader;
<ide> private void attachRootViewToInstance(
<ide> CatalystInstance catalystInstance) {
<ide> Log.d(ReactConstants.TAG, "ReactInstanceManager.attachRootViewToInstance()");
<ide> Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "attachRootViewToInstance");
<del> UIManager uiManagerModule = rootView.isFabric() ? catalystInstance.getJSIModule(UIManager.class) : catalystInstance.getNativeModule(UIManagerModule.class);
<add> UIManager uiManagerModule = UIManagerHelper.getUIManager(mCurrentReactContext, rootView.isFabric());
<ide> final int rootTag = uiManagerModule.addRootView(rootView);
<ide> rootView.setRootViewTag(rootTag);
<ide> rootView.invokeJSEntryPoint();
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java
<ide> import com.facebook.react.uimanager.JSTouchDispatcher;
<ide> import com.facebook.react.uimanager.PixelUtil;
<ide> import com.facebook.react.uimanager.RootView;
<add>import com.facebook.react.uimanager.UIManagerHelper;
<ide> import com.facebook.react.uimanager.UIManagerModule;
<ide> import com.facebook.react.uimanager.common.MeasureSpecProvider;
<ide> import com.facebook.react.uimanager.common.SizeMonitoringFrameLayout;
<ide> private void updateRootLayoutSpecs(final int widthMeasureSpec, final int heightM
<ide> new GuardedRunnable(reactApplicationContext) {
<ide> @Override
<ide> public void runGuarded() {
<del> reactApplicationContext
<del> .getCatalystInstance()
<del> .getNativeModule(UIManagerModule.class)
<del> .updateRootLayoutSpecs(getRootViewTag(), widthMeasureSpec, heightMeasureSpec);
<add> UIManagerHelper
<add> .getUIManager(reactApplicationContext, isFabric())
<add> .updateRootLayoutSpecs(getRootViewTag(), widthMeasureSpec, heightMeasureSpec);
<ide> }
<ide> });
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/UIManager.java
<ide> import com.facebook.react.uimanager.common.MeasureSpecProvider;
<ide> import com.facebook.react.uimanager.common.SizeMonitoringFrameLayout;
<ide>
<add>import javax.annotation.Nullable;
<add>
<ide> public interface UIManager extends JSIModule {
<ide>
<ide> /**
<ide> * Registers a new root view.
<ide> */
<ide> <T extends SizeMonitoringFrameLayout & MeasureSpecProvider> int addRootView(final T rootView);
<ide>
<add> /**
<add> * Updates the layout specs of the RootShadowNode based on the Measure specs received by
<add> * parameters.
<add> */
<add> void updateRootLayoutSpecs(int rootTag, int widthMeasureSpec, int heightMeasureSpec);
<add>
<add> /**
<add> * Dispatches the commandId received by parameter to the view associated with the reactTag.
<add> * The command will be processed in the UIThread.
<add> *
<add> * @param reactTag {@link int} that identifies the view that will receive this command
<add> * @param commandId {@link int} command id
<add> * @param commandArgs {@link ReadableArray} parameters associated with the command
<add> */
<add> void dispatchViewManagerCommand(int reactTag, int commandId, @Nullable ReadableArray commandArgs);
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java
<ide> import com.facebook.infer.annotation.Assertions;
<ide> import com.facebook.react.bridge.GuardedRunnable;
<ide> import com.facebook.react.bridge.ReactApplicationContext;
<add>import com.facebook.react.bridge.ReadableArray;
<ide> import com.facebook.react.bridge.ReadableMap;
<ide> import com.facebook.react.bridge.ReadableNativeMap;
<ide> import com.facebook.react.bridge.UIManager;
<ide> import com.facebook.react.uimanager.common.MeasureSpecProvider;
<ide> import com.facebook.react.uimanager.common.SizeMonitoringFrameLayout;
<ide> import java.util.ArrayList;
<add>import java.util.HashSet;
<ide> import java.util.LinkedList;
<ide> import java.util.List;
<add>import java.util.Set;
<ide> import javax.annotation.Nullable;
<ide>
<ide> /**
<ide> public synchronized void completeRoot(int rootTag, @Nullable List<ReactShadowNod
<ide> }
<ide> }
<ide>
<add> @Deprecated
<add> public void dispatchViewManagerCommand(int reactTag, int commandId, @Nullable ReadableArray commandArgs) {
<add> mUIViewOperationQueue.enqueueDispatchCommand(reactTag, commandId, commandArgs);
<add> }
<add>
<ide> private void notifyOnBeforeLayoutRecursive(ReactShadowNode node) {
<ide> if (!node.hasUpdates()) {
<ide> return;
<ide> public void onSizeChanged(final int width, final int height, int oldW, int oldH)
<ide> return rootTag;
<ide> }
<ide>
<add> @Override
<add> public void updateRootLayoutSpecs(int rootViewTag, int widthMeasureSpec, int heightMeasureSpec) {
<add> ReactShadowNode rootNode = mRootShadowNodeRegistry.getNode(rootViewTag);
<add> if (rootNode == null) {
<add> Log.w(ReactConstants.TAG, "Tried to update non-existent root tag: " + rootViewTag);
<add> return;
<add> }
<add> updateRootView(rootNode, widthMeasureSpec, heightMeasureSpec);
<add> }
<add>
<ide> /**
<ide> * Updates the root view size and re-render the RN surface.
<ide> *
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIImplementation.java
<ide> public void clearJSResponder() {
<ide> mOperationsQueue.enqueueClearJSResponder();
<ide> }
<ide>
<del> public void dispatchViewManagerCommand(int reactTag, int commandId, ReadableArray commandArgs) {
<add> public void dispatchViewManagerCommand(int reactTag, int commandId, @Nullable ReadableArray commandArgs) {
<ide> assertViewExists(reactTag, "dispatchViewManagerCommand");
<ide> mOperationsQueue.enqueueDispatchCommand(reactTag, commandId, commandArgs);
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerHelper.java
<add>package com.facebook.react.uimanager;
<add>
<add>import static com.facebook.react.uimanager.common.ViewType.FABRIC;
<add>import static com.facebook.react.uimanager.common.ViewUtil.getViewType;
<add>
<add>import com.facebook.react.bridge.CatalystInstance;
<add>import com.facebook.react.bridge.ReactContext;
<add>import com.facebook.react.bridge.UIManager;
<add>
<add>/**
<add> * Helper class for {@link UIManager}.
<add> */
<add>public class UIManagerHelper {
<add>
<add> /**
<add> * @return a {@link UIManager} that can handle the react tag received by parameter.
<add> */
<add> public static UIManager getUIManager(ReactContext context, int reactTag) {
<add> return getUIManager(context, getViewType(reactTag) == FABRIC);
<add> }
<add>
<add> /**
<add> * @return a {@link UIManager} that can handle the react tag received by parameter.
<add> */
<add> public static UIManager getUIManager(ReactContext context, boolean isFabric) {
<add> CatalystInstance catalystInstance = context.getCatalystInstance();
<add> return isFabric ?
<add> catalystInstance.getJSIModule(UIManager.class) :
<add> catalystInstance.getNativeModule(UIManagerModule.class);
<add> }
<add>
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModule.java
<ide> import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_UI_MANAGER_MODULE_CONSTANTS_END;
<ide> import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_UI_MANAGER_MODULE_CONSTANTS_START;
<ide>
<add>import static com.facebook.react.uimanager.common.ViewType.FABRIC;
<add>import static com.facebook.react.uimanager.common.ViewType.PAPER;
<add>
<ide> import android.content.ComponentCallbacks2;
<ide> import android.content.res.Configuration;
<ide> import android.content.Context;
<ide> import com.facebook.react.module.annotations.ReactModule;
<ide> import com.facebook.react.uimanager.common.MeasureSpecProvider;
<ide> import com.facebook.react.uimanager.common.SizeMonitoringFrameLayout;
<add>import com.facebook.react.uimanager.common.ViewUtil;
<ide> import com.facebook.react.uimanager.debug.NotThreadSafeViewHierarchyUpdateDebugListener;
<ide> import com.facebook.react.uimanager.events.EventDispatcher;
<ide> import com.facebook.systrace.Systrace;
<ide> public void clearJSResponder() {
<ide> mUIImplementation.clearJSResponder();
<ide> }
<ide>
<add> @Override
<ide> @ReactMethod
<del> public void dispatchViewManagerCommand(int reactTag, int commandId, ReadableArray commandArgs) {
<del> mUIImplementation.dispatchViewManagerCommand(reactTag, commandId, commandArgs);
<add> public void dispatchViewManagerCommand(int reactTag, int commandId, @Nullable ReadableArray commandArgs) {
<add> //TODO: this is a temporary approach to support ViewManagerCommands in Fabric until
<add> // the dispatchViewManagerCommand() method is supported by Fabric JS API.
<add> if (ViewUtil.getViewType(reactTag) == FABRIC) {
<add> UIManagerHelper.getUIManager(getReactApplicationContext(), true)
<add> .dispatchViewManagerCommand(reactTag, commandId, commandArgs);
<add> } else {
<add> mUIImplementation.dispatchViewManagerCommand(reactTag, commandId, commandArgs);
<add> }
<ide> }
<ide>
<ide> @ReactMethod
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIViewOperationQueue.java
<ide> public void enqueueClearJSResponder() {
<ide> public void enqueueDispatchCommand(
<ide> int reactTag,
<ide> int commandId,
<del> ReadableArray commandArgs) {
<add> @Nullable ReadableArray commandArgs) {
<ide> mOperations.add(new DispatchCommandOperation(reactTag, commandId, commandArgs));
<ide> }
<ide> | 8 |
PHP | PHP | fix coding standards | eadc3a75e564ac0d12e29e0d5d3c86193f986266 | <ide><path>lib/Cake/Console/Command/AclShell.php
<ide> public function view() {
<ide> $this->hr();
<ide>
<ide> $stack = array();
<del> $last = null;
<add> $last = null;
<ide>
<ide> foreach ($nodes as $n) {
<ide> $stack[] = $n;
<ide><path>lib/Cake/Console/Command/ApiShell.php
<ide> public function getOptionParser() {
<ide> * @return void
<ide> */
<ide> public function help() {
<del> $head = "Usage: cake api [<type>] <className> [-m <method>]\n";
<add> $head = "Usage: cake api [<type>] <className> [-m <method>]\n";
<ide> $head .= "-----------------------------------------------\n";
<ide> $head .= "Parameters:\n\n";
<ide>
<ide><path>lib/Cake/Console/Command/Task/ExtractTask.php
<ide> protected function _writeFiles() {
<ide> * @return string Translation template header
<ide> */
<ide> protected function _writeHeader() {
<del> $output = "# LANGUAGE translation of CakePHP Application\n";
<add> $output = "# LANGUAGE translation of CakePHP Application\n";
<ide> $output .= "# Copyright YEAR NAME <EMAIL@ADDRESS>\n";
<ide> $output .= "#\n";
<ide> $output .= "#, fuzzy\n";
<ide><path>lib/Cake/Console/Command/Task/ViewTask.php
<ide> protected function _interactive() {
<ide> $this->Controller->connection = $this->connection;
<ide> $this->controllerName = $this->Controller->getName();
<ide>
<del> $prompt = __d('cake_console', "Would you like bake to build your views interactively?\nWarning: Choosing no will overwrite %s views if it exist.", $this->controllerName);
<add> $prompt = __d('cake_console', "Would you like bake to build your views interactively?\nWarning: Choosing no will overwrite %s views if it exist.", $this->controllerName);
<ide> $interactive = $this->in($prompt, array('y', 'n'), 'n');
<ide>
<ide> if (strtolower($interactive) == 'n') {
<ide><path>lib/Cake/Controller/Component/Acl/PhpAcl.php
<ide> public function access($aro, $aco, $action, $type = 'deny') {
<ide>
<ide> foreach ($aco as $i => $node) {
<ide> if (!isset($tree[$node])) {
<del> $tree[$node] = array(
<add> $tree[$node] = array(
<ide> 'children' => array(),
<ide> );
<ide> }
<ide> public function addRole(array $aro) {
<ide> * @param array $alias alias from => to (e.g. Role/13 -> Role/editor)
<ide> * @return void
<ide> */
<del> public function addAlias(array $alias) {
<add> public function addAlias(array $alias) {
<ide> $this->aliases = array_merge($this->aliases, $alias);
<ide> }
<ide>
<ide><path>lib/Cake/Controller/Component/EmailComponent.php
<ide> protected function _formatAddresses($addresses) {
<ide> * @return string Stripped value
<ide> */
<ide> protected function _strip($value, $message = false) {
<del> $search = '%0a|%0d|Content-(?:Type|Transfer-Encoding)\:';
<add> $search = '%0a|%0d|Content-(?:Type|Transfer-Encoding)\:';
<ide> $search .= '|charset\=|mime-version\:|multipart/mixed|(?:[^a-z]to|b?cc)\:.*';
<ide>
<ide> if ($message !== true) {
<ide><path>lib/Cake/Controller/Controller.php
<ide> protected function _isPrivateAction(ReflectionMethod $method, CakeRequest $reque
<ide> $privateAction = (
<ide> $method->name[0] === '_' ||
<ide> !$method->isPublic() ||
<del> !in_array($method->name, $this->methods)
<add> !in_array($method->name, $this->methods)
<ide> );
<ide> $prefixes = Router::prefixes();
<ide>
<ide><path>lib/Cake/Event/CakeEventListener.php
<ide> *
<ide> * @package Cake.Event
<ide> */
<del>interface CakeEventListener {
<add>interface CakeEventListener {
<ide>
<ide> /**
<ide> * Returns a list of events this object is implementing. When the class is registered
<ide><path>lib/Cake/Model/Datasource/Database/Postgres.php
<ide> public function fields(Model $model, $alias = null, $fields = array(), $quote =
<ide> $fields[$i] = $prepend . $this->name($build[0]) . '.' . $this->name($build[1]) . ' AS ' . $this->name($build[0] . '__' . $build[1]);
<ide> }
<ide> } else {
<del> $fields[$i] = preg_replace_callback('/\(([\s\.\w]+)\)/', array(&$this, '_quoteFunctionField'), $fields[$i]);
<add> $fields[$i] = preg_replace_callback('/\(([\s\.\w]+)\)/', array(&$this, '_quoteFunctionField'), $fields[$i]);
<ide> }
<ide> $result[] = $fields[$i];
<ide> }
<ide><path>lib/Cake/Model/Datasource/Database/Sqlserver.php
<ide> public function fields(Model $model, $alias = null, $fields = array(), $quote =
<ide>
<ide> if (strpos($fields[$i], '.') === false) {
<ide> $this->_fieldMappings[$alias . '__' . $fields[$i]] = $alias . '.' . $fields[$i];
<del> $fieldName = $this->name($alias . '.' . $fields[$i]);
<add> $fieldName = $this->name($alias . '.' . $fields[$i]);
<ide> $fieldAlias = $this->name($alias . '__' . $fields[$i]);
<ide> } else {
<ide> $build = explode('.', $fields[$i]);
<ide><path>lib/Cake/Network/Http/HttpSocketResponse.php
<ide> protected function _decodeChunkedBody($body) {
<ide> $chunkLength = hexdec($hexLength);
<ide> $chunk = substr($body, 0, $chunkLength);
<ide> if (!empty($chunkExtensionName)) {
<del> // @todo See if there are popular chunk extensions we should implement
<add> // @todo See if there are popular chunk extensions we should implement
<ide> }
<ide> $decodedBody .= $chunk;
<ide> if ($chunkLength !== 0) {
<ide><path>lib/Cake/Routing/Router.php
<ide> class Router {
<ide> array('action' => 'index', 'method' => 'GET', 'id' => false),
<ide> array('action' => 'view', 'method' => 'GET', 'id' => true),
<ide> array('action' => 'add', 'method' => 'POST', 'id' => false),
<del> array('action' => 'edit', 'method' => 'PUT', 'id' => true),
<add> array('action' => 'edit', 'method' => 'PUT', 'id' => true),
<ide> array('action' => 'delete', 'method' => 'DELETE', 'id' => true),
<del> array('action' => 'edit', 'method' => 'POST', 'id' => true)
<add> array('action' => 'edit', 'method' => 'POST', 'id' => true)
<ide> );
<ide>
<ide> /**
<ide><path>lib/Cake/Test/Case/Console/ShellDispatcherTest.php
<ide> public function testShiftArgs() {
<ide> $this->assertEquals('a', $Dispatcher->shiftArgs());
<ide> $this->assertSame($Dispatcher->args, array('b' => 'c', 'd'));
<ide>
<del> $Dispatcher->args = array(0 => 'a', 2 => 'b', 30 => 'c');
<add> $Dispatcher->args = array(0 => 'a', 2 => 'b', 30 => 'c');
<ide> $this->assertEquals('a', $Dispatcher->shiftArgs());
<ide> $this->assertSame($Dispatcher->args, array(0 => 'b', 1 => 'c'));
<ide>
<ide><path>lib/Cake/Test/Case/Controller/Component/EmailComponentTest.php
<ide> public function testContentStripping() {
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $content = '<p>Some HTML content with an <a href="mailto:test@example.com">email link</a>';
<del> $result = $this->Controller->EmailTest->strip($content, true);
<add> $result = $this->Controller->EmailTest->strip($content, true);
<ide> $expected = $content;
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $content = '<p>Some HTML content with an ';
<add> $content = '<p>Some HTML content with an ';
<ide> $content .= '<a href="mailto:test@example.com,test2@example.com">email link</a>';
<del> $result = $this->Controller->EmailTest->strip($content, true);
<add> $result = $this->Controller->EmailTest->strip($content, true);
<ide> $expected = $content;
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide><path>lib/Cake/Test/Case/Core/AppTest.php
<ide> public function testCore() {
<ide> * @return void
<ide> */
<ide> public function testListObjects() {
<del> $result = App::objects('class', CAKE . 'Routing', false);
<add> $result = App::objects('class', CAKE . 'Routing', false);
<ide> $this->assertTrue(in_array('Dispatcher', $result));
<ide> $this->assertTrue(in_array('Router', $result));
<ide>
<ide><path>lib/Cake/Test/Case/I18n/MultibyteTest.php
<ide> public function testUtf8() {
<ide> 7716, 7718, 7720, 7722, 7724, 7726, 7728, 7730, 7732, 7734, 7736, 7738, 7740, 7742, 7744, 7746, 7748, 7750,
<ide> 7752, 7754, 7756, 7758, 7760, 7762, 7764, 7766, 7768, 7770, 7772, 7774, 7776, 7778, 7780, 7782, 7784, 7786,
<ide> 7788, 7790, 7792, 7794, 7796, 7798, 7800, 7802, 7804, 7806, 7808, 7810, 7812, 7814, 7816, 7818, 7820, 7822,
<del> 7824, 7826, 7828, 7830, 7831, 7832, 7833, 7834, 7840, 7842, 7844, 7846, 7848, 7850, 7852, 7854, 7856,
<add> 7824, 7826, 7828, 7830, 7831, 7832, 7833, 7834, 7840, 7842, 7844, 7846, 7848, 7850, 7852, 7854, 7856,
<ide> 7858, 7860, 7862, 7864, 7866, 7868, 7870, 7872, 7874, 7876, 7878, 7880, 7882, 7884, 7886, 7888, 7890, 7892,
<del> 7894, 7896, 7898, 7900, 7902, 7904, 7906, 7908, 7910, 7912, 7914, 7916, 7918, 7920, 7922, 7924, 7926, 7928);
<add> 7894, 7896, 7898, 7900, 7902, 7904, 7906, 7908, 7910, 7912, 7914, 7916, 7918, 7920, 7922, 7924, 7926, 7928);
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $string = 'ḁḃḅḇḉḋḍḏḑḓḕḗḙḛḝḟḡḣḥḧḩḫḭḯḱḳḵḷḹḻḽḿṁṃṅṇṉṋṍṏṑṓṕṗṙṛṝṟṡṣṥṧṩṫṭṯṱṳṵṷṹṻṽṿẁẃẅẇẉẋẍẏẑẓẕẖẗẘẙẚạảấầẩẫậắằẳẵặẹẻẽếềểễệỉịọỏốồổỗộớờởỡợụủứừửữựỳỵỷỹ';
<ide> public function testAscii() {
<ide> 7716, 7718, 7720, 7722, 7724, 7726, 7728, 7730, 7732, 7734, 7736, 7738, 7740, 7742, 7744, 7746, 7748, 7750,
<ide> 7752, 7754, 7756, 7758, 7760, 7762, 7764, 7766, 7768, 7770, 7772, 7774, 7776, 7778, 7780, 7782, 7784, 7786,
<ide> 7788, 7790, 7792, 7794, 7796, 7798, 7800, 7802, 7804, 7806, 7808, 7810, 7812, 7814, 7816, 7818, 7820, 7822,
<del> 7824, 7826, 7828, 7830, 7831, 7832, 7833, 7834, 7840, 7842, 7844, 7846, 7848, 7850, 7852, 7854, 7856,
<add> 7824, 7826, 7828, 7830, 7831, 7832, 7833, 7834, 7840, 7842, 7844, 7846, 7848, 7850, 7852, 7854, 7856,
<ide> 7858, 7860, 7862, 7864, 7866, 7868, 7870, 7872, 7874, 7876, 7878, 7880, 7882, 7884, 7886, 7888, 7890, 7892,
<del> 7894, 7896, 7898, 7900, 7902, 7904, 7906, 7908, 7910, 7912, 7914, 7916, 7918, 7920, 7922, 7924, 7926, 7928);
<add> 7894, 7896, 7898, 7900, 7902, 7904, 7906, 7908, 7910, 7912, 7914, 7916, 7918, 7920, 7922, 7924, 7926, 7928);
<ide> $result = Multibyte::ascii($input);
<ide> $expected = 'ḀḂḄḆḈḊḌḎḐḒḔḖḘḚḜḞḠḢḤḦḨḪḬḮḰḲḴḶḸḺḼḾṀṂṄṆṈṊṌṎṐṒṔṖṘṚṜṞṠṢṤṦṨṪṬṮṰṲṴṶṸṺṼṾẀẂẄẆẈẊẌẎẐẒẔẖẗẘẙẚẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼẾỀỂỄỆỈỊỌỎỐỒỔỖỘỚỜỞỠỢỤỦỨỪỬỮỰỲỴỶỸ';
<ide> $this->assertEquals($expected, $result);
<ide><path>lib/Cake/Test/Case/Model/Datasource/Database/MysqlTest.php
<ide> public function testBuildColumn2() {
<ide> 'type' => 'timestamp',
<ide> 'default' => 'current_timestamp',
<ide> 'null' => false,
<del> );
<add> );
<ide> $result = $this->Dbo->buildColumn($data);
<ide> $expected = '`created` timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL';
<ide> $this->assertEquals($expected, $result);
<ide><path>lib/Cake/Test/Case/Model/ModelIntegrationTest.php
<ide> public function testGetAssociated() {
<ide>
<ide> $assocTypes = array('hasMany', 'hasOne', 'belongsTo', 'hasAndBelongsToMany');
<ide> foreach ($assocTypes as $type) {
<del> $this->assertEquals($Article->getAssociated($type), array_keys($Article->{$type}));
<add> $this->assertEquals($Article->getAssociated($type), array_keys($Article->{$type}));
<ide> }
<ide>
<ide> $Article->bindModel(array('hasMany' => array('Category')));
<ide><path>lib/Cake/Test/Case/Model/ModelReadTest.php
<ide> public function testOldQuery() {
<ide> $this->loadFixtures('Article', 'User', 'Tag', 'ArticlesTag', 'Comment', 'Attachment');
<ide> $Article = new Article();
<ide>
<del> $query = 'SELECT title FROM ';
<add> $query = 'SELECT title FROM ';
<ide> $query .= $this->db->fullTableName('articles');
<ide> $query .= ' WHERE ' . $this->db->fullTableName('articles') . '.id IN (1,2)';
<ide>
<ide> $results = $Article->query($query);
<ide> $this->assertTrue(is_array($results));
<ide> $this->assertEquals(2, count($results));
<ide>
<del> $query = 'SELECT title, body FROM ';
<add> $query = 'SELECT title, body FROM ';
<ide> $query .= $this->db->fullTableName('articles');
<ide> $query .= ' WHERE ' . $this->db->fullTableName('articles') . '.id = 1';
<ide>
<ide> $results = $Article->query($query, false);
<ide> $this->assertFalse($this->db->getQueryCache($query));
<ide> $this->assertTrue(is_array($results));
<ide>
<del> $query = 'SELECT title, id FROM ';
<add> $query = 'SELECT title, id FROM ';
<ide> $query .= $this->db->fullTableName('articles');
<ide> $query .= ' WHERE ' . $this->db->fullTableName('articles');
<ide> $query .= '.published = ' . $this->db->value('Y');
<ide> public function testPreparedQuery() {
<ide> $result = $this->db->getQueryCache($query, $params);
<ide> $this->assertFalse(empty($result));
<ide>
<del> $query = 'SELECT id, created FROM ';
<add> $query = 'SELECT id, created FROM ';
<ide> $query .= $this->db->fullTableName('articles');
<ide> $query .= ' WHERE ' . $this->db->fullTableName('articles') . '.title = ?';
<ide>
<ide> public function testPreparedQuery() {
<ide> $result = $this->db->getQueryCache($query, $params);
<ide> $this->assertTrue(empty($result));
<ide>
<del> $query = 'SELECT title FROM ';
<add> $query = 'SELECT title FROM ';
<ide> $query .= $this->db->fullTableName('articles');
<ide> $query .= ' WHERE ' . $this->db->fullTableName('articles') . '.title LIKE ?';
<ide>
<ide> public function testPreparedQuery() {
<ide> );
<ide>
<ide> //related to ticket #5035
<del> $query = 'SELECT title FROM ';
<add> $query = 'SELECT title FROM ';
<ide> $query .= $this->db->fullTableName('articles') . ' WHERE title = ? AND published = ?';
<ide> $params = array('First? Article', 'Y');
<ide> $Article->query($query, $params);
<ide> public function testParameterMismatch() {
<ide> $this->loadFixtures('Article', 'User', 'Tag', 'ArticlesTag');
<ide> $Article = new Article();
<ide>
<del> $query = 'SELECT * FROM ' . $this->db->fullTableName('articles');
<add> $query = 'SELECT * FROM ' . $this->db->fullTableName('articles');
<ide> $query .= ' WHERE ' . $this->db->fullTableName('articles');
<ide> $query .= '.published = ? AND ' . $this->db->fullTableName('articles') . '.user_id = ?';
<ide> $params = array('Y');
<ide><path>lib/Cake/Test/Case/Model/ModelWriteTest.php
<ide> public function testFindAllForeignKey() {
<ide> 'ProductUpdateAll' => array(
<ide> 'id' => 1,
<ide> 'name' => 'product one',
<del> 'groupcode' => 120,
<del> 'group_id' => 1),
<add> 'groupcode' => 120,
<add> 'group_id' => 1),
<ide> 'Group' => array(
<ide> 'id' => 1,
<ide> 'name' => 'group one',
<ide> public function testFindAllForeignKey() {
<ide> 'ProductUpdateAll' => array(
<ide> 'id' => 2,
<ide> 'name' => 'product two',
<del> 'groupcode' => 120,
<add> 'groupcode' => 120,
<ide> 'group_id' => 1),
<ide> 'Group' => array(
<ide> 'id' => 1,
<ide> public function testUpdateAllWithJoins() {
<ide> '0' => array(
<ide> 'ProductUpdateAll' => array(
<ide> 'id' => 1,
<del> 'name' => 'new product',
<del> 'groupcode' => 120,
<del> 'group_id' => 1),
<add> 'name' => 'new product',
<add> 'groupcode' => 120,
<add> 'group_id' => 1),
<ide> 'Group' => array(
<ide> 'id' => 1,
<ide> 'name' => 'group one',
<ide> public function testUpdateAllWithJoins() {
<ide> '1' => array(
<ide> 'ProductUpdateAll' => array(
<ide> 'id' => 2,
<del> 'name' => 'new product',
<del> 'groupcode' => 120,
<del> 'group_id' => 1),
<add> 'name' => 'new product',
<add> 'groupcode' => 120,
<add> 'group_id' => 1),
<ide> 'Group' => array(
<ide> 'id' => 1,
<ide> 'name' => 'group one',
<ide> public function testUpdateAllWithoutForeignKey() {
<ide> '0' => array(
<ide> 'ProductUpdateAll' => array(
<ide> 'id' => 1,
<del> 'name' => 'new product',
<del> 'groupcode' => 120,
<del> 'group_id' => 1),
<add> 'name' => 'new product',
<add> 'groupcode' => 120,
<add> 'group_id' => 1),
<ide> 'Group' => array(
<ide> 'id' => 1,
<ide> 'name' => 'group one',
<ide> public function testUpdateAllWithoutForeignKey() {
<ide> '1' => array(
<ide> 'ProductUpdateAll' => array(
<ide> 'id' => 2,
<del> 'name' => 'new product',
<del> 'groupcode' => 120,
<del> 'group_id' => 1),
<add> 'name' => 'new product',
<add> 'groupcode' => 120,
<add> 'group_id' => 1),
<ide> 'Group' => array(
<ide> 'id' => 1,
<ide> 'name' => 'group one',
<ide><path>lib/Cake/Test/Case/Model/Validator/CakeValidationSetTest.php
<ide> *
<ide> * @package Cake.Test.Case.Model.Validator
<ide> */
<del>class CakeValidationSetTest extends CakeTestCase {
<add>class CakeValidationSetTest extends CakeTestCase {
<ide>
<ide> /**
<ide> * testValidate method
<ide><path>lib/Cake/Test/Case/Network/CakeRequestTest.php
<ide> public static function environmentGenerator() {
<ide> return array(
<ide> array(
<ide> 'IIS - No rewrite base path',
<del> array(
<add> array(
<ide> 'App' => array(
<ide> 'base' => false,
<ide> 'baseUrl' => '/index.php',
<ide><path>lib/Cake/Test/Case/Network/Email/CakeEmailTest.php
<ide> public function testCharsetsCompatible() {
<ide> $newStyleEmail = $this->_getEmailByNewStyleCharset('iso-2022-jp', null);
<ide> $newStyleHeaders = $newStyleEmail->getHeaders($checkHeaders);
<ide>
<del> $this->assertSame($oldStyleHeaders['From'], $newStyleHeaders['From']);
<del> $this->assertSame($oldStyleHeaders['To'], $newStyleHeaders['To']);
<del> $this->assertSame($oldStyleHeaders['Cc'], $newStyleHeaders['Cc']);
<add> $this->assertSame($oldStyleHeaders['From'], $newStyleHeaders['From']);
<add> $this->assertSame($oldStyleHeaders['To'], $newStyleHeaders['To']);
<add> $this->assertSame($oldStyleHeaders['Cc'], $newStyleHeaders['Cc']);
<ide> $this->assertSame($oldStyleHeaders['Subject'], $newStyleHeaders['Subject']);
<ide>
<ide> // Header Charset : UTF-8
<ide> public function testCharsetsCompatible() {
<ide> $newStyleEmail = $this->_getEmailByNewStyleCharset('iso-2022-jp', 'utf-8');
<ide> $newStyleHeaders = $newStyleEmail->getHeaders($checkHeaders);
<ide>
<del> $this->assertSame($oldStyleHeaders['From'], $newStyleHeaders['From']);
<del> $this->assertSame($oldStyleHeaders['To'], $newStyleHeaders['To']);
<del> $this->assertSame($oldStyleHeaders['Cc'], $newStyleHeaders['Cc']);
<add> $this->assertSame($oldStyleHeaders['From'], $newStyleHeaders['From']);
<add> $this->assertSame($oldStyleHeaders['To'], $newStyleHeaders['To']);
<add> $this->assertSame($oldStyleHeaders['Cc'], $newStyleHeaders['Cc']);
<ide> $this->assertSame($oldStyleHeaders['Subject'], $newStyleHeaders['Subject']);
<ide>
<ide> // Header Charset : ISO-2022-JP
<ide> public function testCharsetsCompatible() {
<ide> $newStyleEmail = $this->_getEmailByNewStyleCharset('utf-8', 'iso-2022-jp');
<ide> $newStyleHeaders = $newStyleEmail->getHeaders($checkHeaders);
<ide>
<del> $this->assertSame($oldStyleHeaders['From'], $newStyleHeaders['From']);
<del> $this->assertSame($oldStyleHeaders['To'], $newStyleHeaders['To']);
<del> $this->assertSame($oldStyleHeaders['Cc'], $newStyleHeaders['Cc']);
<add> $this->assertSame($oldStyleHeaders['From'], $newStyleHeaders['From']);
<add> $this->assertSame($oldStyleHeaders['To'], $newStyleHeaders['To']);
<add> $this->assertSame($oldStyleHeaders['Cc'], $newStyleHeaders['Cc']);
<ide> $this->assertSame($oldStyleHeaders['Subject'], $newStyleHeaders['Subject']);
<ide> }
<ide>
<ide><path>lib/Cake/Test/Case/Network/Http/HttpSocketTest.php
<ide> public function testConstruct() {
<ide> $baseConfig = $this->Socket->config;
<ide> $this->Socket->expects($this->never())->method('connect');
<ide> $this->Socket->__construct(array('host' => 'foo-bar'));
<del> $baseConfig['host'] = 'foo-bar';
<add> $baseConfig['host'] = 'foo-bar';
<ide> $baseConfig['protocol'] = getprotobyname($baseConfig['protocol']);
<ide> $this->assertEquals($this->Socket->config, $baseConfig);
<ide>
<ide><path>lib/Cake/Test/Case/Routing/Route/PluginShortRouteTest.php
<ide> *
<ide> * @package Cake.Test.Case.Routing.Route
<ide> */
<del>class PluginShortRouteTest extends CakeTestCase {
<add>class PluginShortRouteTest extends CakeTestCase {
<ide>
<ide> /**
<ide> * setUp method
<ide><path>lib/Cake/Test/Case/Routing/Route/RedirectRouteTest.php
<ide> *
<ide> * @package Cake.Test.Case.Routing.Route
<ide> */
<del>class RedirectRouteTest extends CakeTestCase {
<add>class RedirectRouteTest extends CakeTestCase {
<ide>
<ide> /**
<ide> * setUp method
<ide><path>lib/Cake/Test/Case/Routing/RouterTest.php
<ide> public function testResourceMap() {
<ide> array('action' => 'index', 'method' => 'GET', 'id' => false),
<ide> array('action' => 'view', 'method' => 'GET', 'id' => true),
<ide> array('action' => 'add', 'method' => 'POST', 'id' => false),
<del> array('action' => 'edit', 'method' => 'PUT', 'id' => true),
<add> array('action' => 'edit', 'method' => 'PUT', 'id' => true),
<ide> array('action' => 'delete', 'method' => 'DELETE', 'id' => true),
<del> array('action' => 'edit', 'method' => 'POST', 'id' => true)
<add> array('action' => 'edit', 'method' => 'POST', 'id' => true)
<ide> );
<ide> $this->assertEquals($default, $expected);
<ide>
<ide> $custom = array(
<ide> array('action' => 'index', 'method' => 'GET', 'id' => false),
<ide> array('action' => 'view', 'method' => 'GET', 'id' => true),
<ide> array('action' => 'add', 'method' => 'POST', 'id' => false),
<del> array('action' => 'edit', 'method' => 'PUT', 'id' => true),
<add> array('action' => 'edit', 'method' => 'PUT', 'id' => true),
<ide> array('action' => 'delete', 'method' => 'DELETE', 'id' => true),
<del> array('action' => 'update', 'method' => 'POST', 'id' => true)
<add> array('action' => 'update', 'method' => 'POST', 'id' => true)
<ide> );
<ide> Router::resourceMap($custom);
<ide> $this->assertEquals(Router::resourceMap(), $custom);
<ide><path>lib/Cake/Test/Case/TestSuite/CakeTestCaseTest.php
<ide> public function testAssertTextNotContains() {
<ide> * @return void
<ide> */
<ide> public function testGetMockForModel() {
<del>
<ide> $Post = $this->getMockForModel('Post');
<ide>
<ide> $this->assertInstanceOf('Post', $Post);
<ide> public function testGetMockForModel() {
<ide> * @return void
<ide> */
<ide> public function testGetMockForModelWithPlugin() {
<del>
<ide> $TestPluginComment = $this->getMockForModel('TestPlugin.TestPluginComment');
<ide>
<ide> $result = ClassRegistry::init('TestPlugin.TestPluginComment');
<ide><path>lib/Cake/Test/Case/TestSuite/CakeTestFixtureTest.php
<ide> class CakeTestFixtureTestFixture extends CakeTestFixture {
<ide> * @var array
<ide> */
<ide> public $fields = array(
<del> 'id' => array('type' => 'integer', 'key' => 'primary'),
<add> 'id' => array('type' => 'integer', 'key' => 'primary'),
<ide> 'name' => array('type' => 'string', 'length' => '255'),
<ide> 'created' => array('type' => 'datetime')
<ide> );
<ide> class StringsTestFixture extends CakeTestFixture {
<ide> * @var array
<ide> */
<ide> public $fields = array(
<del> 'id' => array('type' => 'integer', 'key' => 'primary'),
<add> 'id' => array('type' => 'integer', 'key' => 'primary'),
<ide> 'name' => array('type' => 'string', 'length' => '255'),
<ide> 'email' => array('type' => 'string', 'length' => '255'),
<ide> 'age' => array('type' => 'integer', 'default' => 10)
<ide><path>lib/Cake/Test/Case/Utility/DebuggerTest.php
<ide> public function testOutput() {
<ide> 'a' => array(
<ide> 'href' => "javascript:void(0);",
<ide> 'onclick' => "preg:/document\.getElementById\('cakeErr[a-z0-9]+\-trace'\)\.style\.display = " .
<del> "\(document\.getElementById\('cakeErr[a-z0-9]+\-trace'\)\.style\.display == 'none'" .
<del> " \? '' \: 'none'\);/"
<add> "\(document\.getElementById\('cakeErr[a-z0-9]+\-trace'\)\.style\.display == 'none'" .
<add> " \? '' \: 'none'\);/"
<ide> ),
<ide> 'b' => array(), 'Notice', '/b', ' (8)',
<ide> ));
<ide> public function testChangeOutputFormats() {
<ide>
<ide> Debugger::output('xml', array(
<ide> 'error' => '<error><code>{:code}</code><file>{:file}</file><line>{:line}</line>' .
<del> '{:description}</error>',
<add> '{:description}</error>',
<ide> 'context' => "<context>{:context}</context>",
<ide> 'trace' => "<stack>{:trace}</stack>",
<ide> ));
<ide> public function testAddFormat() {
<ide>
<ide> Debugger::addFormat('js', array(
<ide> 'traceLine' => '{:reference} - <a href="txmt://open?url=file://{:file}' .
<del> '&line={:line}">{:path}</a>, line {:line}'
<add> '&line={:line}">{:path}</a>, line {:line}'
<ide> ));
<ide> Debugger::outputAs('js');
<ide>
<ide> public function testAddFormat() {
<ide>
<ide> Debugger::addFormat('xml', array(
<ide> 'error' => '<error><code>{:code}</code><file>{:file}</file><line>{:line}</line>' .
<del> '{:description}</error>',
<add> '{:description}</error>',
<ide> ));
<ide> Debugger::outputAs('xml');
<ide>
<ide><path>lib/Cake/Test/Case/Utility/SetTest.php
<ide> public function testExtractWithNonZeroArrays() {
<ide>
<ide> $nonSequential = array(
<ide> 'User' => array(
<del> 0 => array('id' => 1),
<del> 2 => array('id' => 2),
<del> 6 => array('id' => 3),
<del> 9 => array('id' => 4),
<del> 3 => array('id' => 5),
<add> 0 => array('id' => 1),
<add> 2 => array('id' => 2),
<add> 6 => array('id' => 3),
<add> 9 => array('id' => 4),
<add> 3 => array('id' => 5),
<ide> ),
<ide> );
<ide>
<ide> $nonZero = array(
<ide> 'User' => array(
<del> 2 => array('id' => 1),
<del> 4 => array('id' => 2),
<del> 6 => array('id' => 3),
<del> 9 => array('id' => 4),
<del> 3 => array('id' => 5),
<add> 2 => array('id' => 1),
<add> 4 => array('id' => 2),
<add> 6 => array('id' => 3),
<add> 9 => array('id' => 4),
<add> 3 => array('id' => 5),
<ide> ),
<ide> );
<ide>
<ide> public function testRemove() {
<ide>
<ide> $result = Set::remove($a, 'files');
<ide> $expected = array(
<del> 'pages' => array('name' => 'page')
<add> 'pages' => array('name' => 'page')
<ide> );
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide><path>lib/Cake/Test/Case/View/Helper/FormHelperTest.php
<ide> public function testFormSecurityMultipleFields() {
<ide> $this->Form->request['_Token'] = array('key' => $key);
<ide> $result = $this->Form->secure($fields);
<ide>
<del> $hash = '51e3b55a6edd82020b3f29c9ae200e14bbeb7ee5%3AModel.0.hidden%7CModel.0.valid';
<add> $hash = '51e3b55a6edd82020b3f29c9ae200e14bbeb7ee5%3AModel.0.hidden%7CModel.0.valid';
<ide> $hash .= '%7CModel.1.hidden%7CModel.1.valid';
<ide>
<ide> $expected = array(
<ide><path>lib/Cake/Test/Case/View/Helper/HtmlHelperTest.php
<ide> public function testLink() {
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $result = $this->Html->link($this->Html->image('../favicon.ico'), '#', array('escape' => false));
<del> $expected = array(
<del> 'a' => array('href' => '#'),
<add> $expected = array(
<add> 'a' => array('href' => '#'),
<ide> 'img' => array('src' => 'img/../favicon.ico', 'alt' => ''),
<ide> '/a'
<ide> );
<ide> public function testCrumbListBootstrapStyle() {
<ide> array('ul' => array('class' => 'breadcrumb')),
<ide> '<li',
<ide> array('a' => array('class' => 'home', 'href' => '/')), 'Home', '/a',
<del> array('span' =>array('class' => 'divider')), '-', '/span',
<add> array('span' => array('class' => 'divider')), '-', '/span',
<ide> '/li',
<ide> '<li',
<ide> array('a' => array('href' => '/lib')), 'Library', '/a',
<ide> public function testCrumbListBootstrapStyle() {
<ide>
<ide> /**
<ide> * Test GetCrumbList using style of Zurb Foundation.
<del> *
<add> *
<ide> * @return void
<ide> */
<ide> public function testCrumbListZurbStyle() {
<ide> $this->Html->addCrumb('Home', '#');
<ide> $this->Html->addCrumb('Features', '#');
<del> $this->Html->addCrumb('Gene Splicing', '#');
<del> $this->Html->addCrumb('Home', '#');
<add> $this->Html->addCrumb('Gene Splicing', '#');
<add> $this->Html->addCrumb('Home', '#');
<ide> $result = $this->Html->getCrumbList(
<ide> array('class' => 'breadcrumbs', 'firstClass' => false, 'lastClass' => 'current')
<ide> );
<ide><path>lib/Cake/Test/Case/View/Helper/PaginatorHelperTest.php
<ide> public function testSortLinksUsingDotNotation() {
<ide> Router::reload();
<ide> Router::parse('/');
<ide> Router::setRequestInfo(array(
<del> array('plugin' => null, 'controller' => 'accounts', 'action' => 'index', 'pass' => array(), 'form' => array(), 'url' => array('url' => 'accounts/', 'mod_rewrite' => 'true'), 'bare' => 0),
<add> array('plugin' => null, 'controller' => 'accounts', 'action' => 'index', 'pass' => array(), 'form' => array(), 'url' => array('url' => 'accounts/', 'mod_rewrite' => 'true'), 'bare' => 0),
<ide> array('base' => '/officespace', 'here' => '/officespace/accounts/', 'webroot' => '/officespace/')
<ide> ));
<ide>
<ide><path>lib/Cake/Test/Case/View/Helper/RssHelperTest.php
<ide> public function testElementNamespaceWithoutPrefix() {
<ide>
<ide> public function testElementNamespaceWithPrefix() {
<ide> $item = array(
<del> 'title' => 'Title',
<add> 'title' => 'Title',
<ide> 'dc:creator' => 'Alex',
<ide> 'xy:description' => 'descriptive words'
<ide> );
<ide><path>lib/Cake/Test/Fixture/AcoFixture.php
<ide> class AcoFixture extends CakeTestFixture {
<ide> * @var array
<ide> */
<ide> public $records = array(
<del> array('parent_id' => null, 'model' => null, 'foreign_key' => null, 'alias' => 'ROOT', 'lft' => 1, 'rght' => 24),
<del> array('parent_id' => 1, 'model' => null, 'foreign_key' => null, 'alias' => 'Controller1', 'lft' => 2, 'rght' => 9),
<del> array('parent_id' => 2, 'model' => null, 'foreign_key' => null, 'alias' => 'action1', 'lft' => 3, 'rght' => 6),
<del> array('parent_id' => 3, 'model' => null, 'foreign_key' => null, 'alias' => 'record1', 'lft' => 4, 'rght' => 5),
<del> array('parent_id' => 2, 'model' => null, 'foreign_key' => null, 'alias' => 'action2', 'lft' => 7, 'rght' => 8),
<add> array('parent_id' => null, 'model' => null, 'foreign_key' => null, 'alias' => 'ROOT', 'lft' => 1, 'rght' => 24),
<add> array('parent_id' => 1, 'model' => null, 'foreign_key' => null, 'alias' => 'Controller1', 'lft' => 2, 'rght' => 9),
<add> array('parent_id' => 2, 'model' => null, 'foreign_key' => null, 'alias' => 'action1', 'lft' => 3, 'rght' => 6),
<add> array('parent_id' => 3, 'model' => null, 'foreign_key' => null, 'alias' => 'record1', 'lft' => 4, 'rght' => 5),
<add> array('parent_id' => 2, 'model' => null, 'foreign_key' => null, 'alias' => 'action2', 'lft' => 7, 'rght' => 8),
<ide> array('parent_id' => 1, 'model' => null, 'foreign_key' => null, 'alias' => 'Controller2', 'lft' => 10, 'rght' => 17),
<ide> array('parent_id' => 6, 'model' => null, 'foreign_key' => null, 'alias' => 'action1', 'lft' => 11, 'rght' => 14),
<ide> array('parent_id' => 7, 'model' => null, 'foreign_key' => null, 'alias' => 'record1', 'lft' => 12, 'rght' => 13),
<ide><path>lib/Cake/Test/Fixture/AcoTwoFixture.php
<ide> class AcoTwoFixture extends CakeTestFixture {
<ide> * @var array
<ide> */
<ide> public $records = array(
<del> array('parent_id' => null, 'model' => null, 'foreign_key' => null, 'alias' => 'ROOT', 'lft' => 1, 'rght' => 20),
<del> array('parent_id' => 1, 'model' => null, 'foreign_key' => null, 'alias' => 'tpsReports','lft' => 2, 'rght' => 9),
<del> array('parent_id' => 2, 'model' => null, 'foreign_key' => null, 'alias' => 'view', 'lft' => 3, 'rght' => 6),
<del> array('parent_id' => 3, 'model' => null, 'foreign_key' => null, 'alias' => 'current', 'lft' => 4, 'rght' => 5),
<del> array('parent_id' => 2, 'model' => null, 'foreign_key' => null, 'alias' => 'update', 'lft' => 7, 'rght' => 8),
<add> array('parent_id' => null, 'model' => null, 'foreign_key' => null, 'alias' => 'ROOT', 'lft' => 1, 'rght' => 20),
<add> array('parent_id' => 1, 'model' => null, 'foreign_key' => null, 'alias' => 'tpsReports','lft' => 2, 'rght' => 9),
<add> array('parent_id' => 2, 'model' => null, 'foreign_key' => null, 'alias' => 'view', 'lft' => 3, 'rght' => 6),
<add> array('parent_id' => 3, 'model' => null, 'foreign_key' => null, 'alias' => 'current', 'lft' => 4, 'rght' => 5),
<add> array('parent_id' => 2, 'model' => null, 'foreign_key' => null, 'alias' => 'update', 'lft' => 7, 'rght' => 8),
<ide> array('parent_id' => 1, 'model' => null, 'foreign_key' => null, 'alias' => 'printers', 'lft' => 10, 'rght' => 19),
<ide> array('parent_id' => 6, 'model' => null, 'foreign_key' => null, 'alias' => 'print', 'lft' => 11, 'rght' => 14),
<ide> array('parent_id' => 7, 'model' => null, 'foreign_key' => null, 'alias' => 'lettersize','lft' => 12, 'rght' => 13),
<ide><path>lib/Cake/Test/Fixture/AdFixture.php
<ide> class AdFixture extends CakeTestFixture {
<ide> * @var array
<ide> */
<ide> public $records = array(
<del> array('parent_id' => null, 'lft' => 1, 'rght' => 2, 'campaign_id' => 1, 'name' => 'Nordover'),
<del> array('parent_id' => null, 'lft' => 3, 'rght' => 4, 'campaign_id' => 1, 'name' => 'Statbergen'),
<del> array('parent_id' => null, 'lft' => 5, 'rght' => 6, 'campaign_id' => 1, 'name' => 'Feroy'),
<del> array('parent_id' => null, 'lft' => 7, 'rght' => 12, 'campaign_id' => 2, 'name' => 'Newcastle'),
<del> array('parent_id' => null, 'lft' => 8, 'rght' => 9, 'campaign_id' => 2, 'name' => 'Dublin'),
<add> array('parent_id' => null, 'lft' => 1, 'rght' => 2, 'campaign_id' => 1, 'name' => 'Nordover'),
<add> array('parent_id' => null, 'lft' => 3, 'rght' => 4, 'campaign_id' => 1, 'name' => 'Statbergen'),
<add> array('parent_id' => null, 'lft' => 5, 'rght' => 6, 'campaign_id' => 1, 'name' => 'Feroy'),
<add> array('parent_id' => null, 'lft' => 7, 'rght' => 12, 'campaign_id' => 2, 'name' => 'Newcastle'),
<add> array('parent_id' => null, 'lft' => 8, 'rght' => 9, 'campaign_id' => 2, 'name' => 'Dublin'),
<ide> array('parent_id' => null, 'lft' => 10, 'rght' => 11, 'campaign_id' => 2, 'name' => 'Alborg'),
<ide> array('parent_id' => null, 'lft' => 13, 'rght' => 14, 'campaign_id' => 3, 'name' => 'New York')
<ide> );
<ide><path>lib/Cake/Test/Fixture/AfterTreeFixture.php
<ide> class AfterTreeFixture extends CakeTestFixture {
<ide> * @var array
<ide> */
<ide> public $records = array(
<del> array('parent_id' => null, 'lft' => 1, 'rght' => 2, 'name' => 'One'),
<del> array('parent_id' => null, 'lft' => 3, 'rght' => 4, 'name' => 'Two'),
<del> array('parent_id' => null, 'lft' => 5, 'rght' => 6, 'name' => 'Three'),
<add> array('parent_id' => null, 'lft' => 1, 'rght' => 2, 'name' => 'One'),
<add> array('parent_id' => null, 'lft' => 3, 'rght' => 4, 'name' => 'Two'),
<add> array('parent_id' => null, 'lft' => 5, 'rght' => 6, 'name' => 'Three'),
<ide> array('parent_id' => null, 'lft' => 7, 'rght' => 12, 'name' => 'Four'),
<del> array('parent_id' => null, 'lft' => 8, 'rght' => 9, 'name' => 'Five'),
<add> array('parent_id' => null, 'lft' => 8, 'rght' => 9, 'name' => 'Five'),
<ide> array('parent_id' => null, 'lft' => 10, 'rght' => 11, 'name' => 'Six'),
<ide> array('parent_id' => null, 'lft' => 13, 'rght' => 14, 'name' => 'Seven')
<ide> );
<ide><path>lib/Cake/Test/Fixture/AroTwoFixture.php
<ide> class AroTwoFixture extends CakeTestFixture {
<ide> array('parent_id' => 1, 'model' => 'Group', 'foreign_key' => '1', 'alias' => 'admin', 'lft' => '2', 'rght' => '5'),
<ide> array('parent_id' => 1, 'model' => 'Group', 'foreign_key' => '2', 'alias' => 'managers', 'lft' => '6', 'rght' => '9'),
<ide> array('parent_id' => 1, 'model' => 'Group', 'foreign_key' => '3', 'alias' => 'users', 'lft' => '10', 'rght' => '19'),
<del> array('parent_id' => 2, 'model' => 'User', 'foreign_key' => '1', 'alias' => 'Bobs', 'lft' => '3', 'rght' => '4'),
<del> array('parent_id' => 3, 'model' => 'User', 'foreign_key' => '2', 'alias' => 'Lumbergh', 'lft' => '7' , 'rght' => '8'),
<del> array('parent_id' => 4, 'model' => 'User', 'foreign_key' => '3', 'alias' => 'Samir', 'lft' => '11' , 'rght' => '12'),
<del> array('parent_id' => 4, 'model' => 'User', 'foreign_key' => '4', 'alias' => 'Micheal', 'lft' => '13', 'rght' => '14'),
<del> array('parent_id' => 4, 'model' => 'User', 'foreign_key' => '5', 'alias' => 'Peter', 'lft' => '15', 'rght' => '16'),
<del> array('parent_id' => 4, 'model' => 'User', 'foreign_key' => '6', 'alias' => 'Milton', 'lft' => '17', 'rght' => '18'),
<add> array('parent_id' => 2, 'model' => 'User', 'foreign_key' => '1', 'alias' => 'Bobs', 'lft' => '3', 'rght' => '4'),
<add> array('parent_id' => 3, 'model' => 'User', 'foreign_key' => '2', 'alias' => 'Lumbergh', 'lft' => '7' , 'rght' => '8'),
<add> array('parent_id' => 4, 'model' => 'User', 'foreign_key' => '3', 'alias' => 'Samir', 'lft' => '11' , 'rght' => '12'),
<add> array('parent_id' => 4, 'model' => 'User', 'foreign_key' => '4', 'alias' => 'Micheal', 'lft' => '13', 'rght' => '14'),
<add> array('parent_id' => 4, 'model' => 'User', 'foreign_key' => '5', 'alias' => 'Peter', 'lft' => '15', 'rght' => '16'),
<add> array('parent_id' => 4, 'model' => 'User', 'foreign_key' => '6', 'alias' => 'Milton', 'lft' => '17', 'rght' => '18'),
<ide> );
<ide> }
<ide><path>lib/Cake/Test/Fixture/ArosAcoTwoFixture.php
<ide> class ArosAcoTwoFixture extends CakeTestFixture {
<ide> * @var array
<ide> */
<ide> public $records = array(
<del> array('aro_id' => '1', 'aco_id' => '1', '_create' => '-1', '_read' => '-1', '_update' => '-1', '_delete' => '-1'),
<del> array('aro_id' => '2', 'aco_id' => '1', '_create' => '0', '_read' => '1', '_update' => '1', '_delete' => '1'),
<del> array('aro_id' => '3', 'aco_id' => '2', '_create' => '0', '_read' => '1', '_update' => '0', '_delete' => '0'),
<del> array('aro_id' => '4', 'aco_id' => '2', '_create' => '1', '_read' => '1', '_update' => '0', '_delete' => '-1'),
<del> array('aro_id' => '4', 'aco_id' => '6', '_create' => '1', '_read' => '1', '_update' => '0', '_delete' => '0'),
<del> array('aro_id' => '5', 'aco_id' => '1', '_create' => '1', '_read' => '1', '_update' => '1', '_delete' => '1'),
<del> array('aro_id' => '6', 'aco_id' => '3', '_create' => '-1', '_read' => '1', '_update' => '-1', '_delete' => '-1'),
<del> array('aro_id' => '6', 'aco_id' => '4', '_create' => '-1', '_read' => '1', '_update' => '-1', '_delete' => '1'),
<del> array('aro_id' => '6', 'aco_id' => '6', '_create' => '-1', '_read' => '1', '_update' => '1', '_delete' => '-1'),
<del> array('aro_id' => '7', 'aco_id' => '2', '_create' => '-1', '_read' => '-1', '_update' => '-1', '_delete' => '-1'),
<del> array('aro_id' => '7', 'aco_id' => '7', '_create' => '1', '_read' => '1', '_update' => '1', '_delete' => '0'),
<del> array('aro_id' => '7', 'aco_id' => '8', '_create' => '1', '_read' => '1', '_update' => '1', '_delete' => '0'),
<del> array('aro_id' => '7', 'aco_id' => '9', '_create' => '1', '_read' => '1', '_update' => '1', '_delete' => '1'),
<del> array('aro_id' => '7', 'aco_id' => '10', '_create' => '0', '_read' => '0', '_update' => '0', '_delete' => '1'),
<del> array('aro_id' => '8', 'aco_id' => '10', '_create' => '1', '_read' => '1', '_update' => '1', '_delete' => '1'),
<del> array('aro_id' => '8', 'aco_id' => '2', '_create' => '-1', '_read' => '-1', '_update' => '-1', '_delete' => '-1'),
<del> array('aro_id' => '9', 'aco_id' => '4', '_create' => '1', '_read' => '1', '_update' => '1', '_delete' => '-1'),
<del> array('aro_id' => '9', 'aco_id' => '9', '_create' => '0', '_read' => '0', '_update' => '1', '_delete' => '1'),
<del> array('aro_id' => '10', 'aco_id' => '9', '_create' => '1', '_read' => '1', '_update' => '1', '_delete' => '1'),
<del> array('aro_id' => '10', 'aco_id' => '10', '_create' => '-1', '_read' => '-1', '_update' => '-1', '_delete' => '-1'),
<add> array('aro_id' => '1', 'aco_id' => '1', '_create' => '-1', '_read' => '-1', '_update' => '-1', '_delete' => '-1'),
<add> array('aro_id' => '2', 'aco_id' => '1', '_create' => '0', '_read' => '1', '_update' => '1', '_delete' => '1'),
<add> array('aro_id' => '3', 'aco_id' => '2', '_create' => '0', '_read' => '1', '_update' => '0', '_delete' => '0'),
<add> array('aro_id' => '4', 'aco_id' => '2', '_create' => '1', '_read' => '1', '_update' => '0', '_delete' => '-1'),
<add> array('aro_id' => '4', 'aco_id' => '6', '_create' => '1', '_read' => '1', '_update' => '0', '_delete' => '0'),
<add> array('aro_id' => '5', 'aco_id' => '1', '_create' => '1', '_read' => '1', '_update' => '1', '_delete' => '1'),
<add> array('aro_id' => '6', 'aco_id' => '3', '_create' => '-1', '_read' => '1', '_update' => '-1', '_delete' => '-1'),
<add> array('aro_id' => '6', 'aco_id' => '4', '_create' => '-1', '_read' => '1', '_update' => '-1', '_delete' => '1'),
<add> array('aro_id' => '6', 'aco_id' => '6', '_create' => '-1', '_read' => '1', '_update' => '1', '_delete' => '-1'),
<add> array('aro_id' => '7', 'aco_id' => '2', '_create' => '-1', '_read' => '-1', '_update' => '-1', '_delete' => '-1'),
<add> array('aro_id' => '7', 'aco_id' => '7', '_create' => '1', '_read' => '1', '_update' => '1', '_delete' => '0'),
<add> array('aro_id' => '7', 'aco_id' => '8', '_create' => '1', '_read' => '1', '_update' => '1', '_delete' => '0'),
<add> array('aro_id' => '7', 'aco_id' => '9', '_create' => '1', '_read' => '1', '_update' => '1', '_delete' => '1'),
<add> array('aro_id' => '7', 'aco_id' => '10', '_create' => '0', '_read' => '0', '_update' => '0', '_delete' => '1'),
<add> array('aro_id' => '8', 'aco_id' => '10', '_create' => '1', '_read' => '1', '_update' => '1', '_delete' => '1'),
<add> array('aro_id' => '8', 'aco_id' => '2', '_create' => '-1', '_read' => '-1', '_update' => '-1', '_delete' => '-1'),
<add> array('aro_id' => '9', 'aco_id' => '4', '_create' => '1', '_read' => '1', '_update' => '1', '_delete' => '-1'),
<add> array('aro_id' => '9', 'aco_id' => '9', '_create' => '0', '_read' => '0', '_update' => '1', '_delete' => '1'),
<add> array('aro_id' => '10', 'aco_id' => '9', '_create' => '1', '_read' => '1', '_update' => '1', '_delete' => '1'),
<add> array('aro_id' => '10', 'aco_id' => '10', '_create' => '-1', '_read' => '-1', '_update' => '-1', '_delete' => '-1'),
<ide> );
<ide> }
<ide><path>lib/Cake/Test/Fixture/AttachmentFixture.php
<ide> class AttachmentFixture extends CakeTestFixture {
<ide> * @var array
<ide> */
<ide> public $records = array(
<del> array('comment_id' => 5, 'attachment' => 'attachment.zip', 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31')
<add> array('comment_id' => 5, 'attachment' => 'attachment.zip', 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31')
<ide> );
<ide> }
<ide><path>lib/Cake/Test/Fixture/CounterCachePostFixture.php
<ide> class CounterCachePostFixture extends CakeTestFixture {
<ide> );
<ide>
<ide> public $records = array(
<del> array('id' => 1, 'title' => 'Rock and Roll', 'user_id' => 66, 'published' => false),
<del> array('id' => 2, 'title' => 'Music', 'user_id' => 66, 'published' => true),
<del> array('id' => 3, 'title' => 'Food', 'user_id' => 301, 'published' => true),
<add> array('id' => 1, 'title' => 'Rock and Roll', 'user_id' => 66, 'published' => false),
<add> array('id' => 2, 'title' => 'Music', 'user_id' => 66, 'published' => true),
<add> array('id' => 3, 'title' => 'Food', 'user_id' => 301, 'published' => true),
<ide> );
<ide> }
<ide><path>lib/Cake/Test/Fixture/CounterCachePostNonstandardPrimaryKeyFixture.php
<ide> class CounterCachePostNonstandardPrimaryKeyFixture extends CakeTestFixture {
<ide> );
<ide>
<ide> public $records = array(
<del> array('pid' => 1, 'title' => 'Rock and Roll', 'uid' => 66),
<del> array('pid' => 2, 'title' => 'Music', 'uid' => 66),
<del> array('pid' => 3, 'title' => 'Food', 'uid' => 301),
<add> array('pid' => 1, 'title' => 'Rock and Roll', 'uid' => 66),
<add> array('pid' => 2, 'title' => 'Music', 'uid' => 66),
<add> array('pid' => 3, 'title' => 'Food', 'uid' => 301),
<ide> );
<ide> }
<ide><path>lib/Cake/Test/test_app/Config/acl.php
<ide> // Roles
<ide> // -------------------------------------
<ide> $config['roles'] = array(
<del> 'Role/admin' => null,
<del> 'Role/data_acquirer' => null,
<del> 'Role/accounting' => null,
<add> 'Role/admin' => null,
<add> 'Role/data_acquirer' => null,
<add> 'Role/accounting' => null,
<ide> 'Role/database_manager' => null,
<del> 'Role/sales' => null,
<del> 'Role/data_analyst' => 'Role/data_acquirer, Role/database_manager',
<del> 'Role/reports' => 'Role/data_analyst',
<add> 'Role/sales' => null,
<add> 'Role/data_analyst' => 'Role/data_acquirer, Role/database_manager',
<add> 'Role/reports' => 'Role/data_analyst',
<ide> // allow inherited roles to be defined as an array or comma separated list
<del> 'Role/manager' => array(
<add> 'Role/manager' => array(
<ide> 'Role/accounting',
<ide> 'Role/sales',
<ide> ),
<del> 'Role/accounting_manager' => 'Role/accounting',
<add> 'Role/accounting_manager' => 'Role/accounting',
<ide> // managers
<ide> 'User/hardy' => 'Role/accounting_manager, Role/reports',
<del> 'User/stan' => 'Role/manager',
<add> 'User/stan' => 'Role/manager',
<ide> // accountants
<del> 'User/peter' => 'Role/accounting',
<del> 'User/jeff' => 'Role/accounting',
<add> 'User/peter' => 'Role/accounting',
<add> 'User/jeff' => 'Role/accounting',
<ide> // admins
<ide> 'User/jan' => 'Role/admin',
<ide> // database
<del> 'User/db_manager_1' => 'Role/database_manager',
<add> 'User/db_manager_1' => 'Role/database_manager',
<ide> 'User/db_manager_2' => 'Role/database_manager',
<ide> );
<ide>
<ide> );
<ide> $config['rules']['deny'] = array(
<ide> // accountants and sales should not delete anything
<del> '/controllers/*/delete' => array(
<add> '/controllers/*/delete' => array(
<ide> 'Role/sales',
<ide> 'Role/accounting'
<ide> ),
<del> '/controllers/db/drop' => 'User/db_manager_2',
<add> '/controllers/db/drop' => 'User/db_manager_2',
<ide> );
<ide><path>lib/Cake/TestSuite/CakeTestCase.php
<ide> public function assertTags($string, $expected, $fullDebug = false) {
<ide> }
<ide> $regex[] = array(
<ide> sprintf('%sClose %s tag', $prefix[0], substr($tags, strlen($match[0]))),
<del> sprintf('%s<[\s]*\/[\s]*%s[\s]*>[\n\r]*', $prefix[1], substr($tags, strlen($match[0]))),
<add> sprintf('%s<[\s]*\/[\s]*%s[\s]*>[\n\r]*', $prefix[1], substr($tags, strlen($match[0]))),
<ide> $i,
<ide> );
<ide> continue;
<ide> public function getMockForModel($model, $methods = array(), $config = null) {
<ide> }
<ide>
<ide> list($plugin, $name) = pluginSplit($model);
<del> $config = array_merge((array) $config, array('name' => $name));
<add> $config = array_merge((array)$config, array('name' => $name));
<ide> $mock = $this->getMock($name, $methods, array($config));
<ide> ClassRegistry::removeObject($name);
<ide> ClassRegistry::addObject($name, $mock);
<ide><path>lib/Cake/TestSuite/CakeTestSuiteCommand.php
<ide> public function run(array $argv, $exit = true) {
<ide> * @return CakeTestRunner
<ide> */
<ide> public function getRunner($loader) {
<del> return new CakeTestRunner($loader, $this->_params);
<add> return new CakeTestRunner($loader, $this->_params);
<ide> }
<ide>
<ide> /** | 47 |
Java | Java | fix punctuation in javadoc | 580b8b92f8efc95ef44bbe914cc2867838b46428 | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandler.java
<ide> *
<ide> * <p>This base class provides an {@code @ExceptionHandler} method for handling
<ide> * internal Spring MVC exceptions. This method returns a {@code ResponseEntity}
<del> * for writing to the response with a {@link HttpMessageConverter message converter}.
<add> * for writing to the response with a {@link HttpMessageConverter message converter},
<ide> * in contrast to
<ide> * {@link org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver
<ide> * DefaultHandlerExceptionResolver} which returns a | 1 |
Javascript | Javascript | remove duplicated test for eventtarget | 42ff00e4b501ecc3f182bf0c3f5ad4dd8a67f874 | <ide><path>test/parallel/test-eventtarget.js
<ide> let asyncTest = Promise.resolve();
<ide> {}, // No handleEvent function
<ide> false
<ide> ].forEach((i) => throws(() => target.addEventListener('foo', i), err(i)));
<del>
<del> [
<del> 'foo',
<del> 1,
<del> {}, // No handleEvent function
<del> false
<del> ].forEach((i) => throws(() => target.addEventListener('foo', i), err(i)));
<ide> }
<ide>
<ide> { | 1 |
Python | Python | add test for tokenization of 'i.' for danish | 8dc265ac0c2bbea683d900f64c5080a23879c9da | <ide><path>spacy/tests/lang/da/test_exceptions.py
<ide> def test_da_tokenizer_handles_exc_in_text(da_tokenizer):
<ide> tokens = da_tokenizer(text)
<ide> assert len(tokens) == 5
<ide> assert tokens[2].text == "bl.a."
<add>
<add>def test_da_tokenizer_handles_custom_base_exc(da_tokenizer):
<add> text = "Her er noget du kan kigge i."
<add> tokens = da_tokenizer(text)
<add> assert len(tokens) == 8
<add> assert tokens[6].text == "i"
<add> assert tokens[7].text == "." | 1 |
PHP | PHP | enable array_forget to unset one or many keys | 3ef0926153aaa9ab814c87977a1fbad66823dd50 | <ide><path>src/Illuminate/Http/Request.php
<ide> public function except($keys)
<ide>
<ide> $results = $this->input();
<ide>
<del> foreach ($keys as $key) array_forget($results, $key);
<add> array_forget($results, $keys);
<ide>
<ide> return $results;
<ide> }
<ide><path>src/Illuminate/Support/helpers.php
<ide> function array_flatten($array)
<ide> if ( ! function_exists('array_forget'))
<ide> {
<ide> /**
<del> * Remove an array item from a given array using "dot" notation.
<add> * Remove one or many array items from a given array using "dot" notation.
<ide> *
<del> * @param array $array
<del> * @param string $key
<add> * @param array $array
<add> * @param array|string $keys
<ide> * @return void
<ide> */
<del> function array_forget(&$array, $key)
<add> function array_forget(&$array, $keys)
<ide> {
<del> $keys = explode('.', $key);
<del>
<del> while (count($keys) > 1)
<add> foreach ((array) $keys as $key)
<ide> {
<del> $key = array_shift($keys);
<add> $parts = explode('.', $key);
<ide>
<del> if ( ! isset($array[$key]) || ! is_array($array[$key]))
<add> while (count($parts) > 1)
<ide> {
<del> return;
<add> $part = array_shift($parts);
<add>
<add> if (isset($array[$part]) && is_array($array[$part]))
<add> {
<add> $array =& $array[$part];
<add> }
<ide> }
<ide>
<del> $array =& $array[$key];
<add> unset($array[array_shift($parts)]);
<ide> }
<del>
<del> unset($array[array_shift($keys)]);
<ide> }
<ide> }
<ide>
<ide><path>tests/Support/SupportHelpersTest.php
<ide> public function testArrayForget()
<ide> array_forget($array, 'names.developer');
<ide> $this->assertFalse(isset($array['names']['developer']));
<ide> $this->assertTrue(isset($array['names']['otherDeveloper']));
<add>
<add> $array = ['names' => ['developer' => 'taylor', 'otherDeveloper' => 'dayle', 'thirdDeveloper' => 'Lucas']];
<add> array_forget($array, ['names.developer', 'names.otherDeveloper']);
<add> $this->assertFalse(isset($array['names']['developer']));
<add> $this->assertFalse(isset($array['names']['otherDeveloper']));
<add> $this->assertTrue(isset($array['names']['thirdDeveloper']));
<ide> }
<ide>
<ide> | 3 |
Python | Python | use plac annotations for arguments and add n_iter | c3b681e5fbe157ea70167da1e67c740e8339af6f | <ide><path>examples/training/train_new_entity_type.py
<ide> """
<ide> from __future__ import unicode_literals, print_function
<ide>
<add>import plac
<ide> import random
<ide> from pathlib import Path
<ide>
<ide> ]
<ide>
<ide>
<del>def main(model=None, new_model_name='animal', output_dir=None):
<del> """Set up the pipeline and entity recognizer, and train the new entity.
<del>
<del> model (unicode): Model name to start off with. If None, a blank English
<del> Language class is created.
<del> new_model_name (unicode): Name of new model to create. Will be added to the
<del> model meta and prefixed by the language code, e.g. 'en_animal'.
<del> output_dir (unicode / Path): Optional output directory. If None, no model
<del> will be saved.
<del> """
<add>@plac.annotations(
<add> model=("Model name. Defaults to blank 'en' model.", "option", "m", str),
<add> new_model_name=("New model name for model meta.", "option", "nm", str),
<add> output_dir=("Optional output directory", "option", "o", Path),
<add> n_iter=("Number of training iterations", "option", "n", int))
<add>def main(model=None, new_model_name='animal', output_dir=None, n_iter=50):
<add> """Set up the pipeline and entity recognizer, and train the new entity."""
<ide> if model is not None:
<ide> nlp = spacy.load(model) # load existing spaCy model
<ide> print("Loaded model '%s'" % model)
<ide> def main(model=None, new_model_name='animal', output_dir=None):
<ide> with nlp.disable_pipes(*other_pipes) as disabled: # only train NER
<ide> random.seed(0)
<ide> optimizer = nlp.begin_training(lambda: [])
<del> for itn in range(50):
<add> for itn in range(n_iter):
<ide> losses = {}
<ide> gold_parses = get_gold_parses(nlp.make_doc, TRAIN_DATA)
<ide> for batch in minibatch(gold_parses, size=3):
<ide> def get_gold_parses(tokenizer, train_data):
<ide>
<ide>
<ide> if __name__ == '__main__':
<del> import plac
<ide> plac.call(main) | 1 |
PHP | PHP | fix regression about other aliases to be sorted | 449a857164b4b4c08407905dfd214ba381218c27 | <ide><path>src/Controller/Component/PaginatorComponent.php
<ide> protected function _prefix(Table $object, $order, $validate = false)
<ide> }
<ide> $correctAlias = ($tableAlias === $alias);
<ide>
<del> if ($correctAlias && (!$validate || $object->hasField($field))) {
<add> if (!$correctAlias && !$validate) {
<add> $tableOrder[$alias . '.' . $field] = $value;
<add> } elseif ($correctAlias && (!$validate || $object->hasField($field))) {
<ide> $tableOrder[$tableAlias . '.' . $field] = $value;
<ide> }
<ide> }
<ide><path>tests/TestCase/Controller/Component/PaginatorComponentTest.php
<ide> public function testValidateSortWhitelistTrusted()
<ide> $this->assertEquals($expected, $result['order']);
<ide> }
<ide>
<add> /**
<add> * test that multiple fields in the whitelist are not validated and properly aliased.
<add> *
<add> * @return void
<add> */
<add> public function testValidateSortWhitelistMultiple()
<add> {
<add> $model = $this->getMock('Cake\ORM\Table');
<add> $model->expects($this->any())
<add> ->method('alias')
<add> ->will($this->returnValue('model'));
<add> $model->expects($this->never())->method('hasField');
<add>
<add> $options = [
<add> 'order' => [
<add> 'body' => 'asc',
<add> 'foo.bar' => 'asc'
<add> ],
<add> 'sortWhitelist' => ['body', 'foo.bar']
<add> ];
<add> $result = $this->Paginator->validateSort($model, $options);
<add>
<add> $expected = [
<add> 'model.body' => 'asc',
<add> 'foo.bar' => 'asc'
<add> ];
<add> $this->assertEquals($expected, $result['order']);
<add> }
<add>
<ide> /**
<ide> * test that multiple sort works.
<ide> * | 2 |
Ruby | Ruby | move custom assertion to its proper place | 3cece0b6574c496605df055a2ebf77177f5b6e7f | <ide><path>activesupport/lib/active_support/test_case.rb
<ide> def test_order
<ide> alias :assert_not_predicate :refute_predicate
<ide> alias :assert_not_respond_to :refute_respond_to
<ide> alias :assert_not_same :refute_same
<del>
<del> # Assertion that the block should not raise an exception.
<del> #
<del> # Passes if evaluated code in the yielded block raises no exception.
<del> #
<del> # assert_nothing_raised do
<del> # perform_service(param: 'no_exception')
<del> # end
<del> def assert_nothing_raised
<del> yield
<del> end
<ide> end
<ide> end
<ide><path>activesupport/lib/active_support/testing/assertions.rb
<ide> def assert_not(object, message = nil)
<ide> assert !object, message
<ide> end
<ide>
<add> # Assertion that the block should not raise an exception.
<add> #
<add> # Passes if evaluated code in the yielded block raises no exception.
<add> #
<add> # assert_nothing_raised do
<add> # perform_service(param: 'no_exception')
<add> # end
<add> def assert_nothing_raised
<add> yield
<add> end
<add>
<ide> # Test numeric difference between the return value of an expression as a
<ide> # result of what is evaluated in the yielded block.
<ide> # | 2 |
PHP | PHP | update doc comment | 593e9c67a5923d13df82067d76ae08ca9269c521 | <ide><path>src/Core/StaticConfigTrait.php
<ide> public static function configured() {
<ide> * If an array is given, the parsed dsn will be merged into this array. Note that querystring
<ide> * arguments are also parsed and set as values in the returned configuration.
<ide> *
<del> * @param array $config An array with a `dsn` key mapping to a string dsn
<add> * @param array $config An array with a `url` key mapping to a string dsn
<ide> * @return mixed null when adding configuration and an array of configuration data when reading.
<ide> */
<ide> public static function parseDsn($config) { | 1 |
Javascript | Javascript | add sourceurl comment to all compiled js files | 408202729ec842029a68a730bf2dbff532379f20 | <ide><path>src/compile-cache.js
<ide> function compileFileAtPath (compiler, filePath, extension) {
<ide> var cachePath = compiler.getCachePath(sourceCode, filePath)
<ide> var compiledCode = readCachedJavascript(cachePath)
<ide> if (compiledCode == null) {
<del> compiledCode = compiler.compile(sourceCode, filePath)
<add> compiledCode = addSourceURL(compiler.compile(sourceCode, filePath), filePath)
<ide> writeCachedJavascript(cachePath, compiledCode)
<ide> }
<ide> return compiledCode
<ide> function writeCachedJavascript (relativeCachePath, code) {
<ide> fs.writeFileSync(cachePath, code, 'utf8')
<ide> }
<ide>
<add>function addSourceURL (jsCode, filePath) {
<add> if (process.platform === 'win32')
<add> filePath = '/' + path.resolve(filePath).replace(/\\/g, '/')
<add> return jsCode + '\n' + '//# sourceURL=' + encodeURI(filePath) + '\n'
<add>}
<add>
<ide> var INLINE_SOURCE_MAP_REGEXP = /\/\/[#@]\s*sourceMappingURL=([^'"\n]+)\s*$/mg
<ide>
<ide> require('source-map-support').install({ | 1 |
Ruby | Ruby | improve the performance of string xor operation | e35e19a8b7edd355e76b7114be00dbc750453beb | <ide><path>actionpack/lib/action_controller/metal/request_forgery_protection.rb
<ide> def per_form_csrf_token(session, action_path, method)
<ide>
<ide> def xor_byte_strings(s1, s2)
<ide> s2_bytes = s2.bytes
<del> s1.bytes.map.with_index { |c1, i| c1 ^ s2_bytes[i] }.pack('c*')
<add> s1.each_byte.with_index { |c1, i| s2_bytes[i] ^= c1 }
<add> s2_bytes.pack('C*')
<ide> end
<ide>
<ide> # The form's authenticity parameter. Override to provide your own. | 1 |
Text | Text | add missing comma in docs example | 4ba768e22c56141d5488f8ee1f1d78d703b0fbfd | <ide><path>docs/api-reference/next.config.js/headers.md
<ide> module.exports = {
<ide> headers: [
<ide> {
<ide> key: 'x-hello',
<del> value: 'world'
<del> }
<del> ]
<add> value: 'world',
<add> },
<add> ],
<ide> },
<ide> {
<ide> source: '/without-basePath', // is not modified since basePath: false is set
<ide> headers: [
<ide> {
<ide> key: 'x-hello',
<del> value: 'world'
<del> }
<del> ]
<del> basePath: false
<add> value: 'world',
<add> },
<add> ],
<add> basePath: false,
<ide> },
<ide> ]
<ide> }, | 1 |
Python | Python | add a deprecation test | 5c9bd6e13ac87d961df82197bb82746d5e279f52 | <ide><path>numpy/core/tests/test_deprecations.py
<ide> def test_type_aliases(self):
<ide> self.assert_deprecated(lambda: np.long)
<ide> self.assert_deprecated(lambda: np.unicode)
<ide>
<add> # from np.core.numerictypes
<add> self.assert_deprecated(lambda: np.typeDict)
<add>
<ide>
<ide> class TestMatrixInOuter(_DeprecationTestCase):
<ide> # 2020-05-13 NumPy 1.20.0 | 1 |
Javascript | Javascript | fix the arguments order in `assert.strictequal` | 092ab7a1d39d97a3e93f8ed46d80d8ad783b2f9c | <ide><path>test/pummel/test-http-many-keep-alive-connections.js
<ide> server.listen(common.PORT, function connect() {
<ide> });
<ide>
<ide> process.on('exit', function() {
<del> assert.strictEqual(expected, responses);
<del> assert.strictEqual(expected, requests);
<add> assert.strictEqual(responses, expected);
<add> assert.strictEqual(requests, expected);
<ide> }); | 1 |
Ruby | Ruby | add regression tests for | dff86e6ea07cdddb65a683f1dc7e4b7f165e8c3e | <ide><path>activesupport/test/time_zone_test.rb
<ide> def test_parse_with_javascript_date
<ide> assert_equal Time.utc(2012, 5, 28, 7, 0, 0), twz.utc
<ide> end
<ide>
<add> def test_parse_doesnt_use_local_dst
<add> with_env_tz 'US/Eastern' do
<add> zone = ActiveSupport::TimeZone['UTC']
<add> twz = zone.parse('2013-03-10 02:00:00')
<add> assert_equal Time.utc(2013, 3, 10, 2, 0, 0), twz.time
<add> end
<add> end
<add>
<add> def test_parse_handles_dst_jump
<add> with_env_tz 'US/Eastern' do
<add> zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
<add> twz = zone.parse('2013-03-10 02:00:00')
<add> assert_equal Time.utc(2013, 3, 10, 3, 0, 0), twz.time
<add> end
<add> end
<add>
<ide> def test_utc_offset_lazy_loaded_from_tzinfo_when_not_passed_in_to_initialize
<ide> tzinfo = TZInfo::Timezone.get('America/New_York')
<ide> zone = ActiveSupport::TimeZone.create(tzinfo.name, nil, tzinfo) | 1 |
Ruby | Ruby | put backtrace_cleaner to env | fe7d4f09ef2296e45ab4a82c1556c63382856607 | <ide><path>actionpack/lib/action_dispatch/middleware/show_exceptions.rb
<ide> def rescue_action_diagnostics(env, exception)
<ide> template = ActionView::Base.new([RESCUES_TEMPLATE_PATH],
<ide> :request => Request.new(env),
<ide> :exception => exception,
<del> :application_trace => application_trace(exception),
<del> :framework_trace => framework_trace(exception),
<del> :full_trace => full_trace(exception)
<add> :application_trace => application_trace(env, exception),
<add> :framework_trace => framework_trace(env, exception),
<add> :full_trace => full_trace(env, exception)
<ide> )
<ide> file = "rescues/#{@@rescue_templates[exception.class.name]}"
<ide> body = template.render(:template => file, :layout => 'rescues/layout')
<ide> def log_error(env, exception)
<ide> ActiveSupport::Deprecation.silence do
<ide> message = "\n#{exception.class} (#{exception.message}):\n"
<ide> message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code)
<del> message << " " << application_trace(exception).join("\n ")
<add> message << " " << application_trace(env, exception).join("\n ")
<ide> logger(env).fatal("#{message}\n\n")
<ide> end
<ide> end
<ide>
<del> def application_trace(exception)
<del> clean_backtrace(exception, :silent)
<add> def application_trace(env, exception)
<add> clean_backtrace(env, exception, :silent)
<ide> end
<ide>
<del> def framework_trace(exception)
<del> clean_backtrace(exception, :noise)
<add> def framework_trace(env, exception)
<add> clean_backtrace(env, exception, :noise)
<ide> end
<ide>
<del> def full_trace(exception)
<del> clean_backtrace(exception, :all)
<add> def full_trace(env, exception)
<add> clean_backtrace(env, exception, :all)
<ide> end
<ide>
<del> def clean_backtrace(exception, *args)
<del> defined?(Rails) && Rails.respond_to?(:backtrace_cleaner) ?
<del> Rails.backtrace_cleaner.clean(exception.backtrace, *args) :
<add> def clean_backtrace(env, exception, *args)
<add> env['action_dispatch.backtrace_cleaner'] ?
<add> env['action_dispatch.backtrace_cleaner'].clean(exception.backtrace, *args) :
<ide> exception.backtrace
<ide> end
<ide>
<ide><path>actionpack/test/dispatch/show_exceptions_test.rb
<ide> def call(env)
<ide> get "/", {}, {'action_dispatch.show_exceptions' => true, 'action_dispatch.logger' => Logger.new(output)}
<ide> assert_match(/puke/, output.rewind && output.read)
<ide> end
<add>
<add> test 'uses backtrace cleaner from env' do
<add> @app = DevelopmentApp
<add> cleaner = stub(:clean => ['passed backtrace cleaner'])
<add> get "/", {}, {'action_dispatch.show_exceptions' => true, 'action_dispatch.backtrace_cleaner' => cleaner}
<add> assert_match(/passed backtrace cleaner/, body)
<add> end
<ide> end
<ide><path>railties/lib/rails/application.rb
<ide> def env_config
<ide> "action_dispatch.parameter_filter" => config.filter_parameters,
<ide> "action_dispatch.secret_token" => config.secret_token,
<ide> "action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions,
<del> "action_dispatch.logger" => Rails.logger
<add> "action_dispatch.logger" => Rails.logger,
<add> "action_dispatch.backtrace_cleaner" => Rails.backtrace_cleaner
<ide> })
<ide> end
<ide>
<ide><path>railties/test/application/configuration_test.rb
<ide> def index
<ide> make_basic_app
<ide>
<ide> assert_respond_to app, :env_config
<del> assert_equal app.env_config['action_dispatch.parameter_filter'], app.config.filter_parameters
<del> assert_equal app.env_config['action_dispatch.secret_token'], app.config.secret_token
<del> assert_equal app.env_config['action_dispatch.show_exceptions'], app.config.action_dispatch.show_exceptions
<del> assert_equal app.env_config['action_dispatch.logger'], Rails.logger
<add> assert_equal app.env_config['action_dispatch.parameter_filter'], app.config.filter_parameters
<add> assert_equal app.env_config['action_dispatch.secret_token'], app.config.secret_token
<add> assert_equal app.env_config['action_dispatch.show_exceptions'], app.config.action_dispatch.show_exceptions
<add> assert_equal app.env_config['action_dispatch.logger'], Rails.logger
<add> assert_equal app.env_config['action_dispatch.backtrace_cleaner'], Rails.backtrace_cleaner
<ide> end
<ide> end
<ide> end | 4 |
Javascript | Javascript | fix errors breaking pipe | 28e4252a005787deb2bde1f5ac2bcbc9b79ec766 | <ide><path>client/commonFramework/end.js
<ide> $(document).ready(function() {
<ide> .flatMap(code => common.detectLoops$(code))
<ide> .flatMap(
<ide> ({ err }) => err ? Observable.throw(err) : Observable.just(code)
<del> );
<add> )
<add> .flatMap(code => common.updatePreview$(code))
<add> .catch(err => Observable.just({ err }));
<ide> }
<del> return Observable.just(code);
<add> return Observable.just(code)
<add> .flatMap(code => common.updatePreview$(code))
<add> .catch(err => Observable.just({ err }));
<ide> })
<del> .flatMap(code => common.updatePreview$(code))
<del> .catch(err => Observable.just({ err }))
<ide> .subscribe(
<ide> ({ err }) => {
<ide> if (err) {
<del> return console.error(err);
<add> console.error(err);
<add> return common.updatePreview$(`
<add> <h1>${err}</h1>
<add> `).subscribe(() => {});
<ide> }
<ide> },
<ide> err => console.error(err)
<ide> $(document).ready(function() {
<ide> common.editor.setValue(common.replaceSafeTags(common.seed));
<ide> })
<ide> .flatMap(() => {
<del> return common.executeChallenge$();
<add> return common.executeChallenge$()
<add> .catch(err => Observable.just({ err }));
<ide> })
<ide> .subscribe(
<del> ({ output, original }) => {
<add> ({ err, output, original }) => {
<add> if (err) {
<add> console.error(err);
<add> return common.updateOutputDisplay('' + err);
<add> }
<ide> common.codeStorage.updateStorage(challengeName, original);
<ide> common.updateOutputDisplay('' + output);
<ide> },
<del> ({ err }) => {
<del> if (err.stack) {
<add> (err) => {
<add> if (err) {
<ide> console.error(err);
<ide> }
<ide> common.updateOutputDisplay('' + err);
<ide> $(document).ready(function() {
<ide> const solved = tests.every(test => !test.err);
<ide> return { ...rest, tests, solved };
<ide> })
<del> .catch(err => Observable.just(err));
<add> .catch(err => Observable.just({ err }));
<ide> })
<ide> .subscribe(
<ide> ({ err, solved, output, tests }) => { | 1 |
Javascript | Javascript | use property, primordials | ea866dc81b81a71f6ff4c9cb44f8953ce5b398a6 | <ide><path>lib/internal/event_target.js
<ide> const {
<ide> Set,
<ide> Symbol,
<ide> NumberIsNaN,
<add> SymbolToStringTag,
<ide> } = primordials;
<ide>
<ide> const {
<ide> class Event {
<ide> // isTrusted is special (LegacyUnforgeable)
<ide> Object.defineProperty(this, 'isTrusted', {
<ide> get() { return false; },
<del> set(ignoredValue) { return false; },
<ide> enumerable: true,
<ide> configurable: false
<ide> });
<ide> class Event {
<ide> stopPropagation() {
<ide> this.#propagationStopped = true;
<ide> }
<del>
<del> get [Symbol.toStringTag]() { return 'Event'; }
<ide> }
<ide>
<add>Object.defineProperty(Event.prototype, SymbolToStringTag, {
<add> writable: false,
<add> enumerable: false,
<add> configurable: true,
<add> value: 'Event',
<add>});
<add>
<ide> // The listeners for an EventTarget are maintained as a linked list.
<ide> // Unfortunately, the way EventTarget is defined, listeners are accounted
<ide> // using the tuple [handler,capture], and even if we don't actually make
<ide> class EventTarget {
<ide>
<ide> return `${name} ${inspect({}, opts)}`;
<ide> }
<del> get [Symbol.toStringTag]() { return 'EventTarget'; }
<ide> }
<ide>
<ide> Object.defineProperties(EventTarget.prototype, {
<ide> addEventListener: { enumerable: true },
<ide> removeEventListener: { enumerable: true },
<ide> dispatchEvent: { enumerable: true }
<ide> });
<add>Object.defineProperty(EventTarget.prototype, SymbolToStringTag, {
<add> writable: false,
<add> enumerable: false,
<add> configurable: true,
<add> value: 'EventTarget',
<add>});
<ide>
<ide> class NodeEventTarget extends EventTarget {
<ide> static defaultMaxListeners = 10; | 1 |
Javascript | Javascript | fix default value for persistent in watchfile() | 8195e0f7232fed3d6a3a2cc8464fec5e36f4433c | <ide><path>src/node.js
<ide> process.watchFile = function (filename) {
<ide> }
<ide>
<ide> if (options.persistent === undefined) options.persistent = true;
<del> if (options.interval === undefined) options.persistent = 0;
<del>
<add> if (options.interval === undefined) options.interval = 0;
<ide>
<ide> if (filename in statWatchers) {
<ide> stat = statWatchers[filename]; | 1 |
Javascript | Javascript | fix outdated urls | 66e7a4c1aa7b523f49147bff49a90ff6ffe9a1cd | <ide><path>Libraries/StyleSheet/StyleSheetTypes.js
<ide> type ____LayoutStyle_Internal = $ReadOnly<{|
<ide> /** `direction` specifies the directional flow of the user interface.
<ide> * The default is `inherit`, except for root node which will have
<ide> * value based on the current locale.
<del> * See https://facebook.github.io/yoga/docs/rtl/
<add> * See https://yogalayout.com/docs/layout-direction
<ide> * for more details.
<ide> * @platform ios
<ide> */
<ide><path>RNTester/js/examples/Image/ImageExample.js
<ide> exports.examples = [
<ide> <Image
<ide> defaultSource={require('../../assets/bunny.png')}
<ide> source={{
<del> uri: 'https://facebook.github.io/origami/public/images/birds.jpg',
<add> uri: 'https://origami.design/public/images/bird-logo.png',
<ide> }}
<ide> style={styles.base}
<ide> /> | 2 |
Javascript | Javascript | restore tree-sitter in grammar iterator | cec3b058fb72960da24b735bfbdcd4d9dc976990 | <ide><path>src/grammar-registry.js
<ide> module.exports = class GrammarRegistry {
<ide> }
<ide>
<ide> forEachGrammar(callback) {
<del> this.grammars.forEach(callback);
<add> this.getGrammars({ includeTreeSitter: true }).forEach(callback);
<ide> }
<ide>
<ide> grammarForId(languageId) { | 1 |
PHP | PHP | remove dead code | d3e96cf12e04bee156365783f96f02498cbfa173 | <ide><path>src/Illuminate/Database/Schema/Grammars/Grammar.php
<ide> public function compileForeign(Blueprint $blueprint, Fluent $command)
<ide> * Compile the blueprint's column definitions.
<ide> *
<ide> * @param \Illuminate\Database\Schema\Blueprint $blueprint
<del> * @param bool $change
<ide> * @return array
<ide> */
<del> protected function getColumns(Blueprint $blueprint, $change = false)
<add> protected function getColumns(Blueprint $blueprint)
<ide> {
<ide> $columns = array();
<ide>
<del> foreach ($change ? $blueprint->getChangedColumns() : $blueprint->getAddedColumns() as $column)
<add> foreach ($blueprint->getAddedColumns() as $column)
<ide> {
<ide> // Each of the column types have their own compiler functions which are tasked
<ide> // with turning the column definition into its SQL format for this platform | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.