content_type
stringclasses 8
values | main_lang
stringclasses 7
values | message
stringlengths 1
50
| sha
stringlengths 40
40
| patch
stringlengths 52
962k
| file_count
int64 1
300
|
|---|---|---|---|---|---|
Javascript
|
Javascript
|
remove undefined value on init cli command
|
58732a88b629b40b2d223a76fac46ecee5ae7295
|
<ide><path>local-cli/cliEntry.js
<ide> function printHelpInformation() {
<ide> let output = [
<ide> '',
<ide> chalk.bold(chalk.cyan(` react-native ${cmdName} ${this.usage()}`)),
<del> ` ${this._description}`,
<add> this._description ? ` ${this._description}` : '',
<ide> '',
<ide> ...sourceInformation,
<ide> ` ${chalk.bold('Options:')}`,
| 1
|
Text
|
Text
|
use em-dashes instead of two minuses in guides
|
8dabfbebdbdbd3b18e0e869a01602898074ef921
|
<ide><path>guides/source/action_controller_overview.md
<ide> All session stores use a cookie to store a unique ID for each session (you must
<ide>
<ide> For most stores this ID is used to look up the session data on the server, e.g. in a database table. There is one exception, and that is the default and recommended session store - the CookieStore - which stores all session data in the cookie itself (the ID is still available to you if you need it). This has the advantage of being very lightweight and it requires zero setup in a new application in order to use the session. The cookie data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it (Rails will not accept it if it has been edited).
<ide>
<del>The CookieStore can store around 4kB of data -- much less than the others -- but this is usually enough. Storing large amounts of data in the session is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error.
<add>The CookieStore can store around 4kB of data — much less than the others — but this is usually enough. Storing large amounts of data in the session is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error.
<ide>
<ide> If your user sessions don't store critical data or don't need to be around for long periods (for instance if you just use the flash for messaging), you can consider using ActionDispatch::Session::CacheStore. This will store sessions using the cache implementation you have configured for your application. The advantage of this is that you can use your existing cache infrastructure for storing sessions without requiring any additional setup or administration. The downside, of course, is that the sessions will be ephemeral and could disappear at any time.
<ide>
<ide> end
<ide> Cookies
<ide> -------
<ide>
<del>Your application can store small amounts of data on the client -- called cookies -- that will be persisted across requests and even sessions. Rails provides easy access to cookies via the `cookies` method, which -- much like the `session` -- works like a hash:
<add>Your application can store small amounts of data on the client — called cookies — that will be persisted across requests and even sessions. Rails provides easy access to cookies via the `cookies` method, which — much like the `session` — works like a hash:
<ide>
<ide> ```ruby
<ide> class CommentsController < ApplicationController
<ide><path>guides/source/asset_pipeline.md
<ide> The asset pipeline automatically evaluates ERB. This means that if you add an `e
<ide>
<ide> This writes the path to the particular asset being referenced. In this example, it would make sense to have an image in one of the asset load paths, such as `app/assets/images/image.png`, which would be referenced here. If this image is already available in `public/assets` as a fingerprinted file, then that path is referenced.
<ide>
<del>If you want to use a [data URI](http://en.wikipedia.org/wiki/Data_URI_scheme) -- a method of embedding the image data directly into the CSS file -- you can use the `asset_data_uri` helper.
<add>If you want to use a [data URI](http://en.wikipedia.org/wiki/Data_URI_scheme) — a method of embedding the image data directly into the CSS file — you can use the `asset_data_uri` helper.
<ide>
<ide> ```css
<ide> #logo { background: url(<%= asset_data_uri 'logo.png' %>) }
<ide> $('#logo').attr src: "<%= asset_path('logo.png') %>"
<ide>
<ide> ### Manifest Files and Directives
<ide>
<del>Sprockets uses manifest files to determine which assets to include and serve. These manifest files contain _directives_ -- instructions that tell Sprockets which files to require in order to build a single CSS or JavaScript file. With these directives, Sprockets loads the files specified, processes them if necessary, concatenates them into one single file and then compresses them (if `Rails.application.config.assets.compress` is true). By serving one file rather than many, the load time of pages can be greatly reduced because the browser makes fewer requests.
<add>Sprockets uses manifest files to determine which assets to include and serve. These manifest files contain _directives_ — instructions that tell Sprockets which files to require in order to build a single CSS or JavaScript file. With these directives, Sprockets loads the files specified, processes them if necessary, concatenates them into one single file and then compresses them (if `Rails.application.config.assets.compress` is true). By serving one file rather than many, the load time of pages can be greatly reduced because the browser makes fewer requests.
<ide>
<ide> For example, a new Rails application includes a default `app/assets/javascripts/application.js` file which contains the following lines:
<ide>
<ide> The file extensions used on an asset determine what preprocessing is applied. Wh
<ide>
<ide> When these files are requested, they are processed by the processors provided by the `coffee-script` and `sass` gems and then sent back to the browser as JavaScript and CSS respectively.
<ide>
<del>Additional layers of preprocessing can be requested by adding other extensions, where each extension is processed in a right-to-left manner. These should be used in the order the processing should be applied. For example, a stylesheet called `app/assets/stylesheets/projects.css.scss.erb` is first processed as ERB, then SCSS, and finally served as CSS. The same applies to a JavaScript file -- `app/assets/javascripts/projects.js.coffee.erb` is processed as ERB, then CoffeeScript, and served as JavaScript.
<add>Additional layers of preprocessing can be requested by adding other extensions, where each extension is processed in a right-to-left manner. These should be used in the order the processing should be applied. For example, a stylesheet called `app/assets/stylesheets/projects.css.scss.erb` is first processed as ERB, then SCSS, and finally served as CSS. The same applies to a JavaScript file — `app/assets/javascripts/projects.js.coffee.erb` is processed as ERB, then CoffeeScript, and served as JavaScript.
<ide>
<ide> Keep in mind that the order of these preprocessors is important. For example, if you called your JavaScript file `app/assets/javascripts/projects.js.erb.coffee` then it would be processed with the CoffeeScript interpreter first, which wouldn't understand ERB and therefore you would run into problems.
<ide>
<ide> When debug mode is off, Sprockets concatenates and runs the necessary preprocess
<ide> <script src="/assets/application.js"></script>
<ide> ```
<ide>
<del>Assets are compiled and cached on the first request after the server is started. Sprockets sets a `must-revalidate` Cache-Control HTTP header to reduce request overhead on subsequent requests -- on these the browser gets a 304 (Not Modified) response.
<add>Assets are compiled and cached on the first request after the server is started. Sprockets sets a `must-revalidate` Cache-Control HTTP header to reduce request overhead on subsequent requests — on these the browser gets a 304 (Not Modified) response.
<ide>
<ide> If any of the files in the manifest have changed between requests, the server responds with a new compiled file.
<ide>
<ide><path>guides/source/association_basics.md
<ide> end
<ide> @customer.destroy
<ide> ```
<ide>
<del>With Active Record associations, we can streamline these -- and other -- operations by declaratively telling Rails that there is a connection between the two models. Here's the revised code for setting up customers and orders:
<add>With Active Record associations, we can streamline these — and other — operations by declaratively telling Rails that there is a connection between the two models. Here's the revised code for setting up customers and orders:
<ide>
<ide> ```ruby
<ide> class Customer < ActiveRecord::Base
<ide><path>guides/source/configuring.md
<ide> These configuration methods are to be called on a `Rails::Railtie` object, such
<ide>
<ide> * `config.log_level` defines the verbosity of the Rails logger. This option defaults to `:debug` for all modes except production, where it defaults to `:info`.
<ide>
<del>* `config.log_tags` accepts a list of methods that respond to `request` object. This makes it easy to tag log lines with debug information like subdomain and request id -- both very helpful in debugging multi-user production applications.
<add>* `config.log_tags` accepts a list of methods that respond to `request` object. This makes it easy to tag log lines with debug information like subdomain and request id — both very helpful in debugging multi-user production applications.
<ide>
<ide> * `config.logger` accepts a logger conforming to the interface of Log4r or the default Ruby `Logger` class. Defaults to an instance of `ActiveSupport::BufferedLogger`, with auto flushing off in production mode.
<ide>
<ide> Below is a comprehensive list of all the initializers found in Rails in the orde
<ide>
<ide> * `initialize_cache` If `Rails.cache` isn't set yet, initializes the cache by referencing the value in `config.cache_store` and stores the outcome as `Rails.cache`. If this object responds to the `middleware` method, its middleware is inserted before `Rack::Runtime` in the middleware stack.
<ide>
<del>* `set_clear_dependencies_hook` Provides a hook for `active_record.set_dispatch_hooks` to use, which will run before this initializer. This initializer -- which runs only if `cache_classes` is set to `false` -- uses `ActionDispatch::Callbacks.after` to remove the constants which have been referenced during the request from the object space so that they will be reloaded during the following request.
<add>* `set_clear_dependencies_hook` Provides a hook for `active_record.set_dispatch_hooks` to use, which will run before this initializer. This initializer — which runs only if `cache_classes` is set to `false` — uses `ActionDispatch::Callbacks.after` to remove the constants which have been referenced during the request from the object space so that they will be reloaded during the following request.
<ide>
<ide> * `initialize_dependency_mechanism` If `config.cache_classes` is true, configures `ActiveSupport::Dependencies.mechanism` to `require` dependencies rather than `load` them.
<ide>
<ide> Below is a comprehensive list of all the initializers found in Rails in the orde
<ide> * `active_support.initialize_whiny_nils` Requires `active_support/whiny_nil` if `config.whiny_nils` is true. This file will output errors such as:
<ide>
<ide> ```
<del> Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
<add> Called id for nil, which would mistakenly be 4 — if you really wanted the id of nil, use object_id
<ide> ```
<ide>
<ide> And:
<ide> Below is a comprehensive list of all the initializers found in Rails in the orde
<ide>
<ide> * `action_view.set_configs` Sets up Action View by using the settings in `config.action_view` by `send`'ing the method names as setters to `ActionView::Base` and passing the values through.
<ide>
<del>* `action_controller.logger` Sets `ActionController::Base.logger` -- if it's not already set -- to `Rails.logger`.
<add>* `action_controller.logger` Sets `ActionController::Base.logger` — if it's not already set — to `Rails.logger`.
<ide>
<del>* `action_controller.initialize_framework_caches` Sets `ActionController::Base.cache_store` -- if it's not already set -- to `Rails.cache`.
<add>* `action_controller.initialize_framework_caches` Sets `ActionController::Base.cache_store` — if it's not already set — to `Rails.cache`.
<ide>
<ide> * `action_controller.set_configs` Sets up Action Controller by using the settings in `config.action_controller` by `send`'ing the method names as setters to `ActionController::Base` and passing the values through.
<ide>
<ide> * `action_controller.compile_config_methods` Initializes methods for the config settings specified so that they are quicker to access.
<ide>
<ide> * `active_record.initialize_timezone` Sets `ActiveRecord::Base.time_zone_aware_attributes` to true, as well as setting `ActiveRecord::Base.default_timezone` to UTC. When attributes are read from the database, they will be converted into the time zone specified by `Time.zone`.
<ide>
<del>* `active_record.logger` Sets `ActiveRecord::Base.logger` -- if it's not already set -- to `Rails.logger`.
<add>* `active_record.logger` Sets `ActiveRecord::Base.logger` — if it's not already set — to `Rails.logger`.
<ide>
<ide> * `active_record.set_configs` Sets up Active Record by using the settings in `config.active_record` by `send`'ing the method names as setters to `ActiveRecord::Base` and passing the values through.
<ide>
<ide> Below is a comprehensive list of all the initializers found in Rails in the orde
<ide>
<ide> * `active_record.set_dispatch_hooks` Resets all reloadable connections to the database if `config.cache_classes` is set to `false`.
<ide>
<del>* `action_mailer.logger` Sets `ActionMailer::Base.logger` -- if it's not already set -- to `Rails.logger`.
<add>* `action_mailer.logger` Sets `ActionMailer::Base.logger` — if it's not already set — to `Rails.logger`.
<ide>
<ide> * `action_mailer.set_configs` Sets up Action Mailer by using the settings in `config.action_mailer` by `send`'ing the method names as setters to `ActionMailer::Base` and passing the values through.
<ide>
<ide><path>guides/source/contributing_to_ruby_on_rails.md
<ide> This guide covers ways in which _you_ can become a part of the ongoing developme
<ide> * Contributing to the Ruby on Rails documentation
<ide> * Contributing to the Ruby on Rails code
<ide>
<del>Ruby on Rails is not "someone else's framework." Over the years, hundreds of people have contributed to Ruby on Rails ranging from a single character to massive architectural changes or significant documentation -- all with the goal of making Ruby on Rails better for everyone. Even if you don't feel up to writing code or documentation yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches.
<add>Ruby on Rails is not "someone else's framework." Over the years, hundreds of people have contributed to Ruby on Rails ranging from a single character to massive architectural changes or significant documentation — all with the goal of making Ruby on Rails better for everyone. Even if you don't feel up to writing code or documentation yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches.
<ide>
<ide> --------------------------------------------------------------------------------
<ide>
<ide> NOTE: Bugs in the most recent released version of Ruby on Rails are likely to ge
<ide>
<ide> If you've found a problem in Ruby on Rails which is not a security risk, do a search in GitHub under [Issues](https://github.com/rails/rails/issues) in case it was already reported. If you find no issue addressing it you can [add a new one](https://github.com/rails/rails/issues/new). (See the next section for reporting security issues).
<ide>
<del>At the minimum, your issue report needs a title and descriptive text. But that's only a minimum. You should include as much relevant information as possible. You need at least to post the code sample that has the issue. Even better is to include a unit test that shows how the expected behavior is not occurring. Your goal should be to make it easy for yourself -- and others -- to replicate the bug and figure out a fix.
<add>At the minimum, your issue report needs a title and descriptive text. But that's only a minimum. You should include as much relevant information as possible. You need at least to post the code sample that has the issue. Even better is to include a unit test that shows how the expected behavior is not occurring. Your goal should be to make it easy for yourself — and others — to replicate the bug and figure out a fix.
<ide>
<ide> Then, don't get your hopes up! Unless you have a "Code Red, Mission Critical, the World is Coming to an End" kind of bug, you're creating this issue report in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the issue report will automatically see any activity or that others will jump to fix it. Creating an issue like this is mostly to help yourself start on the path of fixing the problem and for others to confirm it with an "I'm having this problem too" comment.
<ide>
<ide> After applying their branch, test it out! Here are some things to think about:
<ide> Once you're happy that the pull request contains a good change, comment on the GitHub issue indicating your approval. Your comment should indicate that you like the change and what you like about it. Something like:
<ide>
<ide> <blockquote>
<del>I like the way you've restructured that code in generate_finder_sql -- much nicer. The tests look good too.
<add>I like the way you've restructured that code in generate_finder_sql — much nicer. The tests look good too.
<ide> </blockquote>
<ide>
<ide> If your comment simply says "+1", then odds are that other reviewers aren't going to take it too seriously. Show that you took the time to review the pull request.
<ide> Rails follows a simple set of coding style conventions.
<ide> * Use a = b and not a=b.
<ide> * Follow the conventions in the source you see used already.
<ide>
<del>The above are guidelines -- please use your best judgment in using them.
<add>The above are guidelines — please use your best judgment in using them.
<ide>
<ide> ### Updating the CHANGELOG
<ide>
<ide><path>guides/source/development_dependencies_install.md
<ide> $ sudo yum install libxml2 libxml2-devel libxslt libxslt-devel
<ide>
<ide> If you have any problems with these libraries, you should install them manually compiling the source code. Just follow the instructions at the [Red Hat/CentOS section of the Nokogiri tutorials](http://nokogiri.org/tutorials/installing_nokogiri.html#red_hat__centos) .
<ide>
<del>Also, SQLite3 and its development files for the `sqlite3-ruby` gem -- in Ubuntu you're done with just
<add>Also, SQLite3 and its development files for the `sqlite3-ruby` gem — in Ubuntu you're done with just
<ide>
<ide> ```bash
<ide> $ sudo apt-get install sqlite3 libsqlite3-dev
<ide><path>guides/source/engines.md
<ide> Run this migration using this command:
<ide> $ rake db:migrate
<ide> ```
<ide>
<del>Now with all the pieces in place, an action will take place that will associate an author -- represented by a record in the `users` table -- with a post, represented by the `blorgh_posts` table from the engine.
<add>Now with all the pieces in place, an action will take place that will associate an author — represented by a record in the `users` table — with a post, represented by the `blorgh_posts` table from the engine.
<ide>
<ide> Finally, the author's name should be displayed on the post's page. Add this code above the "Title" output inside `app/views/blorgh/posts/show.html.erb`:
<ide>
<ide> There are now no strict dependencies on what the class is, only what the API for
<ide>
<ide> Within an engine, there may come a time where you wish to use things such as initializers, internationalization or other configuration options. The great news is that these things are entirely possible because a Rails engine shares much the same functionality as a Rails application. In fact, a Rails application's functionality is actually a superset of what is provided by engines!
<ide>
<del>If you wish to use an initializer -- code that should run before the engine is loaded -- the place for it is the `config/initializers` folder. This directory's functionality is explained in the [Initializers section](http://guides.rubyonrails.org/configuring.html#initializers) of the Configuring guide, and works precisely the same way as the `config/initializers` directory inside an application. Same goes for if you want to use a standard initializer.
<add>If you wish to use an initializer — code that should run before the engine is loaded — the place for it is the `config/initializers` folder. This directory's functionality is explained in the [Initializers section](http://guides.rubyonrails.org/configuring.html#initializers) of the Configuring guide, and works precisely the same way as the `config/initializers` directory inside an application. Same goes for if you want to use a standard initializer.
<ide>
<ide> For locales, simply place the locale files in the `config/locales` directory, just like you would in an application.
<ide>
<ide> The `test` directory should be treated like a typical Rails testing environment,
<ide>
<ide> ### Functional tests
<ide>
<del>A matter worth taking into consideration when writing functional tests is that the tests are going to be running on an application -- the `test/dummy` application -- rather than your engine. This is due to the setup of the testing environment; an engine needs an application as a host for testing its main functionality, especially controllers. This means that if you were to make a typical `GET` to a controller in a controller's functional test like this:
<add>A matter worth taking into consideration when writing functional tests is that the tests are going to be running on an application — the `test/dummy` application — rather than your engine. This is due to the setup of the testing environment; an engine needs an application as a host for testing its main functionality, especially controllers. This means that if you were to make a typical `GET` to a controller in a controller's functional test like this:
<ide>
<ide> ```ruby
<ide> get :index
<ide><path>guides/source/form_helpers.md
<ide> The object yielded by `fields_for` is a form builder like the one yielded by `fo
<ide>
<ide> ### Relying on Record Identification
<ide>
<del>The Article model is directly available to users of the application, so -- following the best practices for developing with Rails -- you should declare it **a resource**:
<add>The Article model is directly available to users of the application, so — following the best practices for developing with Rails — you should declare it **a resource**:
<ide>
<ide> ```ruby
<ide> resources :articles
<ide> Here you have a list of cities whose names are presented to the user. Internally
<ide>
<ide> ### The Select and Option Tags
<ide>
<del>The most generic helper is `select_tag`, which -- as the name implies -- simply generates the `SELECT` tag that encapsulates an options string:
<add>The most generic helper is `select_tag`, which — as the name implies — simply generates the `SELECT` tag that encapsulates an options string:
<ide>
<ide> ```erb
<ide> <%= select_tag(:city_id, '<option value="1">Lisbon</option>...') %>
<ide> output:
<ide>
<ide> Whenever Rails sees that the internal value of an option being generated matches this value, it will add the `selected` attribute to that option.
<ide>
<del>TIP: The second argument to `options_for_select` must be exactly equal to the desired internal value. In particular if the value is the integer 2 you cannot pass "2" to `options_for_select` -- you must pass 2. Be aware of values extracted from the `params` hash as they are all strings.
<add>TIP: The second argument to `options_for_select` must be exactly equal to the desired internal value. In particular if the value is the integer 2 you cannot pass "2" to `options_for_select` — you must pass 2. Be aware of values extracted from the `params` hash as they are all strings.
<ide>
<ide> WARNING: when `:inlude_blank` or `:prompt:` are not present, `:include_blank` is forced true if the select attribute `required` is true, display `size` is one and `multiple` is not true.
<ide>
<ide> In most cases form controls will be tied to a specific database model and as you
<ide> <%= select(:person, :city_id, [['Lisbon', 1], ['Madrid', 2], ...]) %>
<ide> ```
<ide>
<del>Notice that the third parameter, the options array, is the same kind of argument you pass to `options_for_select`. One advantage here is that you don't have to worry about pre-selecting the correct city if the user already has one -- Rails will do this for you by reading from the `@person.city_id` attribute.
<add>Notice that the third parameter, the options array, is the same kind of argument you pass to `options_for_select`. One advantage here is that you don't have to worry about pre-selecting the correct city if the user already has one — Rails will do this for you by reading from the `@person.city_id` attribute.
<ide>
<ide> As with other helpers, if you were to use the `select` helper on a form builder scoped to the `@person` object, the syntax would be:
<ide>
<ide><path>guides/source/getting_started.md
<ide> It will look a little basic for now, but that's ok. We'll look at improving the
<ide>
<ide> ### Laying down the ground work
<ide>
<del>The first thing that you are going to need to create a new post within the application is a place to do that. A great place for that would be at `/posts/new`. If you attempt to navigate to that now -- by visiting <http://localhost:3000/posts/new> -- Rails will give you a routing error:
<add>The first thing that you are going to need to create a new post within the application is a place to do that. A great place for that would be at `/posts/new`. If you attempt to navigate to that now — by visiting <http://localhost:3000/posts/new> — Rails will give you a routing error:
<ide>
<ide> 
<ide>
<del>This is because there is nowhere inside the routes for the application -- defined inside `config/routes.rb` -- that defines this route. By default, Rails has no routes configured at all, besides the root route you defined earlier, and so you must define your routes as you need them.
<add>This is because there is nowhere inside the routes for the application — defined inside `config/routes.rb` — that defines this route. By default, Rails has no routes configured at all, besides the root route you defined earlier, and so you must define your routes as you need them.
<ide>
<ide> To do this, you're going to need to create a route inside `config/routes.rb` file, on a new line between the `do` and the `end` for the `draw` method:
<ide>
<ide> That's quite a lot of text! Let's quickly go through and understand what each pa
<ide>
<ide> The first part identifies what template is missing. In this case, it's the `posts/new` template. Rails will first look for this template. If not found, then it will attempt to load a template called `application/new`. It looks for one here because the `PostsController` inherits from `ApplicationController`.
<ide>
<del>The next part of the message contains a hash. The `:locale` key in this hash simply indicates what spoken language template should be retrieved. By default, this is the English -- or "en" -- template. The next key, `:formats` specifies the format of template to be served in response. The default format is `:html`, and so Rails is looking for an HTML template. The final key, `:handlers`, is telling us what _template handlers_ could be used to render our template. `:erb` is most commonly used for HTML templates, `:builder` is used for XML templates, and `:coffee` uses CoffeeScript to build JavaScript templates.
<add>The next part of the message contains a hash. The `:locale` key in this hash simply indicates what spoken language template should be retrieved. By default, this is the English — or "en" — template. The next key, `:formats` specifies the format of template to be served in response. The default format is `:html`, and so Rails is looking for an HTML template. The final key, `:handlers`, is telling us what _template handlers_ could be used to render our template. `:erb` is most commonly used for HTML templates, `:builder` is used for XML templates, and `:coffee` uses CoffeeScript to build JavaScript templates.
<ide>
<ide> The final part of this message tells us where Rails has looked for the templates. Templates within a basic Rails application like this are kept in a single location, but in more complex applications it could be many different paths.
<ide>
<ide> If you refresh the page now, you'll see the exact same form as in the example. B
<ide> When you call `form_for`, you pass it an identifying object for this
<ide> form. In this case, it's the symbol `:post`. This tells the `form_for`
<ide> helper what this form is for. Inside the block for this method, the
<del>`FormBuilder` object -- represented by `f` -- is used to build two labels and two text fields, one each for the title and text of a post. Finally, a call to `submit` on the `f` object will create a submit button for the form.
<add>`FormBuilder` object — represented by `f` — is used to build two labels and two text fields, one each for the title and text of a post. Finally, a call to `submit` on the `f` object will create a submit button for the form.
<ide>
<ide> There's one problem with this form though. If you inspect the HTML that is generated, by viewing the source of the page, you will see that the `action` attribute for the form is pointing at `/posts/new`. This is a problem because this route goes to the very page that you're on right at the moment, and that route should only be used to display the form for a new post.
<ide>
<ide> Let's add links to the other views as well, starting with adding this "New Post"
<ide> <%= link_to 'New post', action: :new %>
<ide> ```
<ide>
<del>This link will allow you to bring up the form that lets you create a new post. You should also add a link to this template -- `app/views/posts/new.html.erb` -- to go back to the `index` action. Do this by adding this underneath the form in this template:
<add>This link will allow you to bring up the form that lets you create a new post. You should also add a link to this template — `app/views/posts/new.html.erb` — to go back to the `index` action. Do this by adding this underneath the form in this template:
<ide>
<ide> ```erb
<ide> <%= form_for :post do |f| %>
<ide><path>guides/source/i18n.md
<ide> So, in the process of _internationalizing_ your Rails application you have to:
<ide>
<ide> In the process of _localizing_ your application you'll probably want to do the following three things:
<ide>
<del>* Replace or supplement Rails' default locale -- e.g. date and time formats, month names, Active Record model names, etc.
<del>* Abstract strings in your application into keyed dictionaries -- e.g. flash messages, static text in your views, etc.
<add>* Replace or supplement Rails' default locale — e.g. date and time formats, month names, Active Record model names, etc.
<add>* Abstract strings in your application into keyed dictionaries — e.g. flash messages, static text in your views, etc.
<ide> * Store the resulting dictionaries somewhere
<ide>
<ide> This guide will walk you through the I18n API and contains a tutorial on how to internationalize a Rails application from the start.
<ide> Internationalization is a complex problem. Natural languages differ in so many w
<ide> * providing support for English and similar languages out of the box
<ide> * making it easy to customize and extend everything for other languages
<ide>
<del>As part of this solution, **every static string in the Rails framework** -- e.g. Active Record validation messages, time and date formats -- **has been internationalized**, so _localization_ of a Rails application means "over-riding" these defaults.
<add>As part of this solution, **every static string in the Rails framework** — e.g. Active Record validation messages, time and date formats — **has been internationalized**, so _localization_ of a Rails application means "over-riding" these defaults.
<ide>
<ide> ### The Overall Architecture of the Library
<ide>
<ide> Thus, the Ruby I18n gem is split into two parts:
<ide>
<del>* The public API of the i18n framework -- a Ruby module with public methods that define how the library works
<add>* The public API of the i18n framework — a Ruby module with public methods that define how the library works
<ide> * A default backend (which is intentionally named _Simple_ backend) that implements these methods
<ide>
<ide> As a user you should always only access the public methods on the I18n module, but it is useful to know about the capabilities of the backend.
<ide> NOTE: Have a look at two plugins which simplify work with routes in this way: Sv
<ide>
<ide> ### Setting the Locale from the Client Supplied Information
<ide>
<del>In specific cases, it would make sense to set the locale from client-supplied information, i.e. not from the URL. This information may come for example from the users' preferred language (set in their browser), can be based on the users' geographical location inferred from their IP, or users can provide it simply by choosing the locale in your application interface and saving it to their profile. This approach is more suitable for web-based applications or services, not for websites -- see the box about _sessions_, _cookies_ and RESTful architecture above.
<add>In specific cases, it would make sense to set the locale from client-supplied information, i.e. not from the URL. This information may come for example from the users' preferred language (set in their browser), can be based on the users' geographical location inferred from their IP, or users can provide it simply by choosing the locale in your application interface and saving it to their profile. This approach is more suitable for web-based applications or services, not for websites — see the box about _sessions_, _cookies_ and RESTful architecture above.
<ide>
<ide>
<ide> #### Using `Accept-Language`
<ide> Of course, in a production environment you would need much more robust code, and
<ide>
<ide> #### Using GeoIP (or Similar) Database
<ide>
<del>Another way of choosing the locale from client information would be to use a database for mapping the client IP to the region, such as [GeoIP Lite Country](http://www.maxmind.com/app/geolitecountry). The mechanics of the code would be very similar to the code above -- you would need to query the database for the user's IP, and look up your preferred locale for the country/region/city returned.
<add>Another way of choosing the locale from client information would be to use a database for mapping the client IP to the region, such as [GeoIP Lite Country](http://www.maxmind.com/app/geolitecountry). The mechanics of the code would be very similar to the code above — you would need to query the database for the user's IP, and look up your preferred locale for the country/region/city returned.
<ide>
<ide> #### User Profile
<ide>
<del>You can also provide users of your application with means to set (and possibly over-ride) the locale in your application interface, as well. Again, mechanics for this approach would be very similar to the code above -- you'd probably let users choose a locale from a dropdown list and save it to their profile in the database. Then you'd set the locale to this value.
<add>You can also provide users of your application with means to set (and possibly over-ride) the locale in your application interface, as well. Again, mechanics for this approach would be very similar to the code above — you'd probably let users choose a locale from a dropdown list and save it to their profile in the database. Then you'd set the locale to this value.
<ide>
<ide> Internationalizing your Application
<ide> -----------------------------------
<ide> en:
<ide>
<ide> ### Adding Date/Time Formats
<ide>
<del>OK! Now let's add a timestamp to the view, so we can demo the **date/time localization** feature as well. To localize the time format you pass the Time object to `I18n.l` or (preferably) use Rails' `#l` helper. You can pick a format by passing the `:format` option -- by default the `:default` format is used.
<add>OK! Now let's add a timestamp to the view, so we can demo the **date/time localization** feature as well. To localize the time format you pass the Time object to `I18n.l` or (preferably) use Rails' `#l` helper. You can pick a format by passing the `:format` option — by default the `:default` format is used.
<ide>
<ide> ```erb
<ide> # app/views/home/index.html.erb
<ide><path>guides/source/security.md
<ide> In the <a href="#sessions">session chapter</a> you have learned that most Rails
<ide> * Bob's session at www.webapp.com is still alive, because he didn't log out a few minutes ago.
<ide> * By viewing the post, the browser finds an image tag. It tries to load the suspected image from www.webapp.com. As explained before, it will also send along the cookie with the valid session id.
<ide> * The web application at www.webapp.com verifies the user information in the corresponding session hash and destroys the project with the ID 1. It then returns a result page which is an unexpected result for the browser, so it will not display the image.
<del>* Bob doesn't notice the attack -- but a few days later he finds out that project number one is gone.
<add>* Bob doesn't notice the attack — but a few days later he finds out that project number one is gone.
<ide>
<ide> It is important to notice that the actual crafted image or link doesn't necessarily have to be situated in the web application's domain, it can be anywhere – in a forum, blog post or email.
<ide>
<del>CSRF appears very rarely in CVE (Common Vulnerabilities and Exposures) -- less than 0.1% in 2006 -- but it really is a 'sleeping giant' [Grossman]. This is in stark contrast to the results in my (and others) security contract work – _CSRF is an important security issue_.
<add>CSRF appears very rarely in CVE (Common Vulnerabilities and Exposures) — less than 0.1% in 2006 — but it really is a 'sleeping giant' [Grossman]. This is in stark contrast to the results in my (and others) security contract work – _CSRF is an important security issue_.
<ide>
<ide> ### CSRF Countermeasures
<ide>
<ide><path>guides/source/testing.md
<ide> Testing mailer classes requires some specific tools to do a thorough job.
<ide>
<ide> ### Keeping the Postman in Check
<ide>
<del>Your mailer classes -- like every other part of your Rails application -- should be tested to ensure that it is working as expected.
<add>Your mailer classes — like every other part of your Rails application — should be tested to ensure that it is working as expected.
<ide>
<ide> The goals of testing your mailer classes are to ensure that:
<ide>
| 12
|
PHP
|
PHP
|
add blank lines between test methods
|
f0789b5b4585076d55793e5563b948380030dfe4
|
<ide><path>tests/View/ViewBladeCompilerTest.php
<ide> public function testCompileSetAndGetThePath()
<ide> $this->assertEquals('foo', $compiler->getPath());
<ide> }
<ide>
<add>
<ide> public function testCompileWithPathSetBefore()
<ide> {
<ide> $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);
<ide> public function testCompileWithPathSetBefore()
<ide> $this->assertEquals('foo', $compiler->getPath());
<ide> }
<ide>
<add>
<ide> public function testCompileDoesntStoreFilesWhenCachePathIsNull()
<ide> {
<ide> $compiler = new BladeCompiler($files = $this->getFiles(), null);
| 1
|
PHP
|
PHP
|
use correct facade
|
c6f04411f53dc6dc2bd7dcd0259da7226ff6be00
|
<ide><path>resources/views/welcome.blade.php
<ide> @else
<ide> <a href="{{ route('login') }}">Login</a>
<ide>
<del> @if (Request::has('register'))
<add> @if (Route::has('register'))
<ide> <a href="{{ route('register') }}">Register</a>
<ide> @endif
<ide> @endauth
| 1
|
Javascript
|
Javascript
|
add test for v8 bug in toupper('ç')
|
e9b72916790b21daa6d1caac3a9540e8cdadad57
|
<ide><path>test/parallel/test-intl.js
<ide> function haveLocale(loc) {
<ide> return locs.indexOf(loc) !== -1;
<ide> }
<ide>
<add>// Always run these. They should always pass, even if the locale
<add>// param is ignored.
<add>assert.strictEqual('Ç'.toLocaleLowerCase('el'), 'ç');
<add>assert.strictEqual('Ç'.toLocaleLowerCase('tr'), 'ç');
<add>assert.strictEqual('Ç'.toLowerCase(), 'ç');
<add>
<add>assert.strictEqual('ç'.toLocaleUpperCase('el'), 'Ç');
<add>assert.strictEqual('ç'.toLocaleUpperCase('tr'), 'Ç');
<add>assert.strictEqual('ç'.toUpperCase(), 'Ç');
<add>
<ide> if (!common.hasIntl) {
<ide> const erMsg =
<ide> '"Intl" object is NOT present but v8_enable_i18n_support is ' +
| 1
|
Ruby
|
Ruby
|
fix rubocop warnings
|
c45e36ffde1805ec7706fa28895b120909f69de7
|
<ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def doctor
<ide> end
<ide>
<ide> out = checks.send(method)
<del> unless out.nil? || out.empty?
<del> if first_warning
<del> $stderr.puts <<-EOS.undent
<add> next if out.nil? || out.empty?
<add> if first_warning
<add> $stderr.puts <<-EOS.undent
<ide> #{Tty.white}Please note that these warnings are just used to help the Homebrew maintainers
<ide> with debugging if you file an issue. If everything you use Homebrew for is
<ide> working fine: please don't worry and just ignore them. Thanks!#{Tty.reset}
<del> EOS
<del> end
<del>
<del> $stderr.puts
<del> opoo out
<del> Homebrew.failed = true
<del> first_warning = false
<add> EOS
<ide> end
<add>
<add> $stderr.puts
<add> opoo out
<add> Homebrew.failed = true
<add> first_warning = false
<ide> end
<ide>
<ide> puts "Your system is ready to brew." unless Homebrew.failed?
| 1
|
PHP
|
PHP
|
use immutable classes by default
|
ac231e256cf867289cac4c971d142b0d8e3042a8
|
<ide><path>src/Database/Type/DateTimeType.php
<ide> public function __construct($name = null)
<ide> {
<ide> $this->_name = $name;
<ide>
<del> $this->useMutable();
<add> $this->useImmutable();
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Database/QueryTest.php
<ide> use Cake\Database\TypeMap;
<ide> use Cake\Datasource\ConnectionManager;
<ide> use Cake\TestSuite\TestCase;
<add>use DateTimeImmutable;
<ide>
<ide> /**
<ide> * Tests Query class
<ide> public function testSelectTypeConversion()
<ide> ->getSelectTypeMap()->setTypes(['id' => 'integer', 'the_date' => 'datetime']);
<ide> $result = $query->execute()->fetchAll('assoc');
<ide> $this->assertInternalType('integer', $result[0]['id']);
<del> $this->assertInstanceOf('DateTime', $result[0]['the_date']);
<add> $this->assertInstanceOf(DateTimeImmutable::class, $result[0]['the_date']);
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Database/Type/DateTimeTypeTest.php
<ide> public function setUp()
<ide> */
<ide> public function testGetDateTimeClassName()
<ide> {
<del> $this->assertSame(Time::class, $this->type->getDateTimeClassName());
<del>
<del> $this->type->useImmutable();
<ide> $this->assertSame(FrozenTime::class, $this->type->getDateTimeClassName());
<add>
<add> $this->type->useMutable();
<add> $this->assertSame(Time::class, $this->type->getDateTimeClassName());
<ide> }
<ide>
<ide> /**
<ide> public function testToPHPEmpty()
<ide> public function testToPHPString()
<ide> {
<ide> $result = $this->type->toPHP('2001-01-04 12:13:14', $this->driver);
<del> $this->assertInstanceOf('Cake\I18n\Time', $result);
<add> $this->assertInstanceOf(FrozenTime::class, $result);
<ide> $this->assertEquals('2001', $result->format('Y'));
<ide> $this->assertEquals('01', $result->format('m'));
<ide> $this->assertEquals('04', $result->format('d'));
<ide> public function testToPHPIncludingMilliseconds()
<ide> {
<ide> $in = '2014-03-24 20:44:36.315113';
<ide> $result = $this->type->toPHP($in, $this->driver);
<del> $this->assertInstanceOf('Cake\I18n\Time', $result);
<add> $this->assertInstanceOf(FrozenTime::class, $result);
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Database/Type/DateTypeTest.php
<ide> use Cake\Database\Type\DateType;
<ide> use Cake\I18n\Time;
<ide> use Cake\TestSuite\TestCase;
<add>use DateTimeImmutable;
<ide>
<ide> /**
<ide> * Test for the Date type.
<ide> public function testToPHP()
<ide> $this->assertNull($this->type->toPHP('0000-00-00', $this->driver));
<ide>
<ide> $result = $this->type->toPHP('2001-01-04', $this->driver);
<del> $this->assertInstanceOf('DateTime', $result);
<add> $this->assertInstanceOf(DateTimeImmutable::class, $result);
<ide> $this->assertEquals('2001', $result->format('Y'));
<ide> $this->assertEquals('01', $result->format('m'));
<ide> $this->assertEquals('04', $result->format('d'));
<ide><path>tests/TestCase/Database/Type/TimeTypeTest.php
<ide> use Cake\I18n\I18n;
<ide> use Cake\I18n\Time;
<ide> use Cake\TestSuite\TestCase;
<add>use DateTimeImmutable;
<ide>
<ide> /**
<ide> * Test for the Time type.
<ide> public function testToPHP()
<ide> $this->assertEquals('15', $result->format('s'));
<ide>
<ide> $result = $this->type->toPHP('16:30:15', $this->driver);
<del> $this->assertInstanceOf('DateTime', $result);
<add> $this->assertInstanceOf(DateTimeImmutable::class, $result);
<ide> $this->assertEquals('16', $result->format('H'));
<ide> $this->assertEquals('30', $result->format('i'));
<ide> $this->assertEquals('15', $result->format('s'));
<ide> public function testMarshal($value, $expected)
<ide> $result = $this->type->marshal($value);
<ide> if (is_object($expected)) {
<ide> $this->assertEquals($expected, $result);
<del> $this->assertInstanceOf('DateTime', $result);
<add> $this->assertInstanceOf(DateTimeImmutable::class, $result);
<ide> } else {
<ide> $this->assertSame($expected, $result);
<ide> }
| 5
|
Java
|
Java
|
delete unused imports in spring-web
|
76aa7b1cd96124762750bde93802bb477524a3b6
|
<ide><path>spring-web/src/main/java/org/springframework/http/codec/HttpMessageReader.java
<ide>
<ide> import java.util.List;
<ide>
<del>import org.reactivestreams.Publisher;
<ide> import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<ide>
<ide> import org.springframework.core.ResolvableType;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.ReactiveHttpInputMessage;
<del>import org.springframework.http.ReactiveHttpOutputMessage;
<ide>
<ide> /**
<ide> * Strategy interface that specifies a reader that can convert from the HTTP
<ide><path>spring-web/src/test/java/org/springframework/http/RequestEntityTests.java
<ide>
<ide> import java.net.URI;
<ide> import java.net.URISyntaxException;
<del>import java.nio.charset.Charset;
<ide> import java.nio.charset.StandardCharsets;
<ide> import java.util.Arrays;
<ide> import java.util.HashMap;
<ide><path>spring-web/src/test/java/org/springframework/http/converter/xml/SourceHttpMessageConverterTests.java
<ide> import java.io.IOException;
<ide> import java.io.InputStreamReader;
<ide> import java.io.StringReader;
<del>import java.nio.charset.Charset;
<ide> import java.nio.charset.StandardCharsets;
<ide> import javax.xml.parsers.DocumentBuilderFactory;
<ide> import javax.xml.stream.XMLStreamException;
<ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/FlushingIntegrationTests.java
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.http.client.reactive.ReactorClientHttpConnector;
<del>import org.springframework.http.server.reactive.bootstrap.ReactorHttpServer;
<ide> import org.springframework.web.client.reactive.ClientWebRequestBuilders;
<ide> import org.springframework.web.client.reactive.ResponseExtractors;
<ide> import org.springframework.web.client.reactive.WebClient;
<ide>
<del>import static org.junit.Assume.assumeFalse;
<del>
<ide> import java.time.Duration;
<ide>
<ide> /**
| 4
|
Go
|
Go
|
fix filepath.walk misusage in pkg/directory
|
cd53ec524410020db312089f2623b1a50f30121e
|
<ide><path>pkg/directory/directory_test.go
<ide> func TestMoveToSubdir(t *testing.T) {
<ide> t.Fatalf("Results after migration do not equal list of files: expected: %v, got: %v", filesList, results)
<ide> }
<ide> }
<add>
<add>// Test a non-existing directory
<add>func TestSizeNonExistingDirectory(t *testing.T) {
<add> if _, err := Size("/thisdirectoryshouldnotexist/TestSizeNonExistingDirectory"); err == nil {
<add> t.Fatalf("error is expected")
<add> }
<add>}
<ide><path>pkg/directory/directory_unix.go
<ide> import (
<ide> // Size walks a directory tree and returns its total size in bytes.
<ide> func Size(dir string) (size int64, err error) {
<ide> data := make(map[uint64]struct{})
<del> err = filepath.Walk(dir, func(d string, fileInfo os.FileInfo, e error) error {
<add> err = filepath.Walk(dir, func(d string, fileInfo os.FileInfo, err error) error {
<add> if err != nil {
<add> // if dir does not exist, Size() returns the error.
<add> // if dir/x disappeared while walking, Size() ignores dir/x.
<add> if os.IsNotExist(err) && d != dir {
<add> return nil
<add> }
<add> return err
<add> }
<add>
<ide> // Ignore directory sizes
<ide> if fileInfo == nil {
<ide> return nil
<ide><path>pkg/directory/directory_windows.go
<ide> import (
<ide>
<ide> // Size walks a directory tree and returns its total size in bytes.
<ide> func Size(dir string) (size int64, err error) {
<del> err = filepath.Walk(dir, func(d string, fileInfo os.FileInfo, e error) error {
<add> err = filepath.Walk(dir, func(d string, fileInfo os.FileInfo, err error) error {
<add> if err != nil {
<add> // if dir does not exist, Size() returns the error.
<add> // if dir/x disappeared while walking, Size() ignores dir/x.
<add> if os.IsNotExist(err) && d != dir {
<add> return nil
<add> }
<add> return err
<add> }
<add>
<ide> // Ignore directory sizes
<ide> if fileInfo == nil {
<ide> return nil
| 3
|
Go
|
Go
|
remove checks for deprecated flags
|
b38c71bfe06ddb663aa4919ff9c496c395311985
|
<ide><path>integration-cli/docker_cli_search_test.go
<ide> func (s *DockerSuite) TestSearchCmdOptions(c *check.C) {
<ide> assert.Assert(c, strings.Count(outSearchCmdStars, "\n") <= strings.Count(outSearchCmd, "\n"), "Number of images with 10+ stars should be less than that of all images:\noutSearchCmdStars: %s\noutSearch: %s\n", outSearchCmdStars, outSearchCmd)
<ide>
<ide> dockerCmd(c, "search", "--filter", "is-automated=true", "--filter", "stars=2", "--no-trunc=true", "busybox")
<del>
<del> // --automated deprecated since Docker 1.13
<del> outSearchCmdautomated1, _ := dockerCmd(c, "search", "--automated=true", "busybox") //The busybox is a busybox base image, not an AUTOMATED image.
<del> outSearchCmdautomatedSlice1 := strings.Split(outSearchCmdautomated1, "\n")
<del> for i := range outSearchCmdautomatedSlice1 {
<del> assert.Assert(c, !strings.HasPrefix(outSearchCmdautomatedSlice1[i], "busybox "), "The busybox is not an AUTOMATED image: %s", outSearchCmdautomated)
<del> }
<del>
<del> // -s --stars deprecated since Docker 1.13
<del> outSearchCmdStars1, _ := dockerCmd(c, "search", "--stars=2", "busybox")
<del> assert.Assert(c, strings.Count(outSearchCmdStars1, "[OK]") <= strings.Count(outSearchCmd, "[OK]"), "The quantity of images with stars should be less than that of all images: %s", outSearchCmdStars1)
<del>
<del> // -s --stars deprecated since Docker 1.13
<del> dockerCmd(c, "search", "--stars=2", "--automated=true", "--no-trunc=true", "busybox")
<ide> }
<ide>
<ide> // search for repos which start with "ubuntu-" on the central registry
| 1
|
Javascript
|
Javascript
|
don’t error when returning an empty fragment
|
d480782c4162431d06c077ebf8fdf6b8ba7896ef
|
<ide><path>packages/react-dom/src/__tests__/ReactDOMFiber-test.js
<ide> describe('ReactDOMFiber', () => {
<ide> expect(firstNode.tagName).toBe('DIV');
<ide> });
<ide>
<add> it('renders an empty fragment', () => {
<add> const Div = () => <div />;
<add> const EmptyFragment = () => <React.Fragment />;
<add> const NonEmptyFragment = () => (
<add> <React.Fragment>
<add> <Div />
<add> </React.Fragment>
<add> );
<add>
<add> ReactDOM.render(<EmptyFragment />, container);
<add> expect(container.firstChild).toBe(null);
<add>
<add> ReactDOM.render(<NonEmptyFragment />, container);
<add> expect(container.firstChild.tagName).toBe('DIV');
<add>
<add> ReactDOM.render(<EmptyFragment />, container);
<add> expect(container.firstChild).toBe(null);
<add>
<add> ReactDOM.render(<Div />, container);
<add> expect(container.firstChild.tagName).toBe('DIV');
<add>
<add> ReactDOM.render(<EmptyFragment />, container);
<add> expect(container.firstChild).toBe(null);
<add> });
<add>
<ide> let svgEls, htmlEls, mathEls;
<ide> const expectSVG = {ref: el => svgEls.push(el)};
<ide> const expectHTML = {ref: el => htmlEls.push(el)};
<ide><path>packages/react-reconciler/src/ReactChildFiber.js
<ide> function ChildReconciler(shouldTrackSideEffects) {
<ide> // Handle top level unkeyed fragments as if they were arrays.
<ide> // This leads to an ambiguity between <>{[...]}</> and <>...</>.
<ide> // We treat the ambiguous cases above the same.
<del> if (
<add> const isUnkeyedTopLevelFragment =
<ide> typeof newChild === 'object' &&
<ide> newChild !== null &&
<ide> newChild.type === REACT_FRAGMENT_TYPE &&
<del> newChild.key === null
<del> ) {
<add> newChild.key === null;
<add> if (isUnkeyedTopLevelFragment) {
<ide> newChild = newChild.props.children;
<ide> }
<ide>
<ide> function ChildReconciler(shouldTrackSideEffects) {
<ide> warnOnFunctionType();
<ide> }
<ide> }
<del> if (typeof newChild === 'undefined') {
<add> if (typeof newChild === 'undefined' && !isUnkeyedTopLevelFragment) {
<ide> // If the new child is undefined, and the return fiber is a composite
<ide> // component, throw an error. If Fiber return types are disabled,
<ide> // we already threw above.
| 2
|
Text
|
Text
|
update changelog [ci skip]
|
7905f2131547d3e3ab6eb97e4cb96411483f3c16
|
<ide><path>CHANGELOG.md
<ide> - [#17846](https://github.com/emberjs/ember.js/pull/17846) [BUGFIX] Fix issues with template-only components causing errors in subsequent updates.
<ide> - [#17870](https://github.com/emberjs/ember.js/pull/17870) / [#17871](https://github.com/emberjs/ember.js/pull/17871) [BUGFIX] Fix issue where `...attributes` may incorrectly overwrite attributes unexpectedly, depending on its position.
<ide> - [#17872](https://github.com/emberjs/ember.js/pull/17872) [BUGFIX] Fix issue where `{{link-to}}` is causing unexpected local variable shadowing assertions.
<add>- [#17874](https://github.com/emberjs/ember.js/pull/17874) [BUGFIX] Fix issue with `event.stopPropagation()` in component event handlers when jQuery is disabled.
<add>- [#17876](https://github.com/emberjs/ember.js/pull/17876) [BUGFIX] Fix issue with multiple `{{action}}` modifiers on the same element when jQuery is disabled.
<ide>
<ide> ### v3.10.0-beta.1 (April 02, 2019)
<ide>
| 1
|
Text
|
Text
|
add a bunch of redirects
|
d885894c6efa6c3eaca5905ddf95457044fdd570
|
<ide><path>docs/docs/addons-animation.md
<ide> layout: docs
<ide> category: Add-Ons
<ide> prev: addons.html
<ide> next: create-fragment.html
<add>redirect_from:
<add> - "docs/animation-ja-JP.html"
<add> - "docs/animation-ko-KR.html"
<add> - "docs/animation-zh-CN.html"
<ide> ---
<ide>
<ide> The [`ReactTransitionGroup`](#reacttransitiongroup) add-on component is a low-level API for animation, and [`ReactCSSTransitionGroup`](#reactcsstransitiongroup) is an add-on component for easily implementing basic CSS animations and transitions.
<ide><path>docs/docs/components-and-props.md
<ide> title: Components and Props
<ide> permalink: docs/components-and-props.html
<ide> redirect_from:
<ide> - "docs/reusable-components.html"
<add> - "docs/reusable-components-zh-CN.html"
<ide> - "docs/transferring-props.html"
<add> - "docs/transferring-props-it-IT.html"
<add> - "docs/transferring-props-ja-JP.html"
<add> - "docs/transferring-props-ko-KR.html"
<add> - "docs/transferring-props-zh-CN.html"
<ide> - "tips/props-in-getInitialState-as-anti-pattern.html"
<ide> - "tips/communicate-between-components.html"
<ide> prev: rendering-elements.html
<ide><path>docs/docs/forms.md
<ide> title: Forms
<ide> permalink: docs/forms.html
<ide> prev: state-and-lifecycle.html
<ide> next: lifting-state-up.html
<del>redirect_from: "tips/controlled-input-null-value.html"
<add>redirect_from:
<add> - "tips/controlled-input-null-value.html"
<add> - "docs/forms-zh-CN.html"
<ide> ---
<ide>
<ide> Form components such as `<input>`, `<textarea>`, and `<option>` differ from other native components because they can be mutated via user interactions. These components provide interfaces that make it easier to manage forms in response to user interactions.
<ide> class Form extends React.Component {
<ide> type="radio"
<ide> name="choice"
<ide> value="C"
<del> onChange={this.handleChange} />
<add> onChange={this.handleChange} />
<ide> Option C
<ide> </label>
<ide> <br />
<ide> class Form extends React.Component {
<ide> <input
<ide> type="checkbox"
<ide> value="A"
<del> onChange={this.handleChange} />
<add> onChange={this.handleChange} />
<ide> Option A
<ide> </label>
<ide> <br />
<ide> class Form extends React.Component {
<ide> type="checkbox"
<ide> value="B"
<ide> onChange={this.handleChange}
<del> defaultChecked={true} />
<add> defaultChecked={true} />
<ide> Option B
<ide> </label>
<ide> <br />
<ide> <label>
<ide> <input
<ide> type="checkbox"
<ide> value="C"
<del> onChange={this.handleChange} />
<add> onChange={this.handleChange} />
<ide> Option C
<ide> </label>
<ide> <br />
<ide><path>docs/docs/handling-events.md
<ide> title: Handling Events
<ide> permalink: docs/handling-events.html
<ide> prev: state-and-lifecycle.html
<ide> next: conditional-rendering.html
<add>redirect_from:
<add> - "docs/events-ko-KR.html"
<ide> ---
<ide>
<ide> Handling events with React elements is very similar to handling events on DOM elements. There are some syntactic differences:
<ide><path>docs/docs/hello-world.md
<ide> next: introducing-jsx.html
<ide> redirect_from:
<ide> - "docs/index.html"
<ide> - "docs/getting-started.html"
<add> - "docs/getting-started-ko-KR.html"
<add> - "docs/getting-started-zh-CN.html"
<ide> ---
<ide>
<ide> The easiest way to get started with React is to use [this Hello World example code on CodePen](http://codepen.io/gaearon/pen/ZpvBNJ?editors=0010). You don't need to install anything; you can just open it in another tab and follow along as we go through examples. If you'd rather use a local development environment, check out the [Installation](/react/docs/installation.html) page.
<ide><path>docs/docs/installation.md
<ide> id: installation
<ide> title: Installation
<ide> permalink: docs/installation.html
<ide> redirect_from:
<add> - "download.html"
<ide> - "downloads.html"
<ide> - "docs/tooling-integration.html"
<ide> - "docs/package-management.html"
<ide><path>docs/docs/jsx-in-depth.md
<ide> redirect_from:
<ide> - "tips/self-closing-tag.html"
<ide> - "tips/maximum-number-of-jsx-root-nodes.html"
<ide> - "tips/children-props-type.html"
<add> - "docs/jsx-in-depth-zh-CN.html"
<add> - "docs/jsx-in-depth-ko-KR.html"
<ide> ---
<ide>
<ide> Fundamentally, JSX just provides syntactic sugar for the `React.createElement(component, props, ...children)` function. The JSX code:
<ide><path>docs/docs/lifting-state-up.md
<ide> title: Lifting State Up
<ide> permalink: docs/lifting-state-up.html
<ide> prev: state-and-lifecycle.html
<ide> next: composition-vs-inheritance.html
<add>redirect_from:
<add> - "docs/flux-overview.html"
<add> - "docs/flux-todo-list.html"
<ide> ---
<ide>
<ide> Often, several components need to reflect the same changing data. We recommend lifting the shared state up to their closest common ancestor. Let's see how this works in action.
<ide><path>docs/docs/reference-dom-elements.md
<ide> redirect_from:
<ide> - "docs/tags-and-attributes.html"
<ide> - "docs/dom-differences.html"
<ide> - "docs/special-non-dom-attributes.html"
<add> - "docs/class-name-manipulation.html"
<ide> - "tips/inline-styles.html"
<ide> - "tips/style-props-value-px.html"
<ide> - "tips/dangerously-set-inner-html.html"
<ide><path>docs/docs/reference-react-component.md
<ide> permalink: docs/react-component.html
<ide> redirect_from:
<ide> - "docs/component-api.html"
<ide> - "docs/component-specs.html"
<add> - "docs/component-specs-ko-KR.html"
<add> - "docs/component-specs-zh-CN.html"
<ide> - "tips/componentWillReceiveProps-not-triggered-after-mounting.html"
<ide> - "tips/dom-event-listeners.html"
<ide> - "tips/initial-ajax.html"
<ide><path>docs/docs/reference-react.md
<ide> redirect_from:
<ide> - "docs/reference.html"
<ide> - "docs/clone-with-props.html"
<ide> - "docs/top-level-api.html"
<add> - "docs/top-level-api-ja-JP.html"
<add> - "docs/top-level-api-ko-KR.html"
<add> - "docs/top-level-api-zh-CN.html"
<ide> - "docs/glossary.html"
<ide> ---
<ide>
<ide><path>docs/docs/refs-and-the-dom.md
<ide> title: Refs and the DOM
<ide> redirect_from:
<ide> - "docs/working-with-the-browser.html"
<ide> - "docs/more-about-refs.html"
<add> - "docs/more-about-refs-ko-KR.html"
<add> - "docs/more-about-refs-zh-CN.html"
<ide> - "tips/expose-component-functions.html"
<ide> - "tips/children-undefined.html"
<ide> permalink: docs/refs-and-the-dom.html
<ide><path>docs/docs/thinking-in-react.md
<ide> id: thinking-in-react
<ide> title: Thinking in React
<ide> permalink: docs/thinking-in-react.html
<del>redirect_from: 'blog/2013/11/05/thinking-in-react.html'
<add>redirect_from:
<add> - 'blog/2013/11/05/thinking-in-react.html'
<add> - 'docs/thinking-in-react-zh-CN.html'
<ide> prev: composition-vs-inheritance.html
<ide> ---
<ide>
<ide><path>docs/tutorial/tutorial.md
<ide> permalink: /tutorial/tutorial.html
<ide> redirect_from:
<ide> - "docs/tutorial.html"
<ide> - "docs/why-react.html"
<add> - "docs/tutorial-ja-JP.html"
<add> - "docs/tutorial-ko-KR.html"
<add> - "docs/tutorial-zh-CN.html"
<ide> ---
<ide>
<ide> ## What We're Building
| 14
|
Ruby
|
Ruby
|
handle unparsed arguments
|
40432d86f94c52fb7ee5249fbce34c20e18b15ec
|
<ide><path>Library/Homebrew/cmd/uninstall.rb
<ide> def initialize(requireds, dependents)
<ide> protected
<ide>
<ide> def sample_command
<del> "brew uninstall --ignore-dependencies #{Homebrew.args.named.join(" ")}"
<add> "brew uninstall --ignore-dependencies #{Array(Homebrew.args.named).join(" ")}"
<ide> end
<ide>
<ide> def are_required_by_deps
| 1
|
Javascript
|
Javascript
|
add test for zlib.create*raw()
|
f6e33ef8bcfd0ccb4c7e95a1ba249f0c8d79ece5
|
<ide><path>test/parallel/test-zlib-create-raw.js
<add>'use strict';
<add>
<add>require('../common');
<add>const assert = require('assert');
<add>const zlib = require('zlib');
<add>
<add>{
<add> const inflateRaw = zlib.createInflateRaw();
<add> assert(inflateRaw instanceof zlib.InflateRaw);
<add>}
<add>
<add>{
<add> const deflateRaw = zlib.createDeflateRaw();
<add> assert(deflateRaw instanceof zlib.DeflateRaw);
<add>}
| 1
|
Python
|
Python
|
adapt onapp tests to the libcloud test framework
|
b079a012ef7c1908969a3c16e9cc6c7bac53562a
|
<ide><path>libcloud/compute/drivers/onapp.py
<ide> def destroy_node(self,
<ide> identifier=node.id)
<ide>
<ide> self.connection.request(action, params=server_params, method="DELETE")
<add> return True
<ide>
<ide> def list_nodes(self):
<ide> """
<ide><path>libcloud/test/compute/test_onapp.py
<ide> import unittest
<ide> import sys
<del>import json
<ide>
<del>from mock import call, MagicMock
<del>
<del>from libcloud.test.file_fixtures import ComputeFileFixtures
<add>from libcloud.compute.base import Node
<ide> from libcloud.compute.drivers.onapp import OnAppNodeDriver
<del>from libcloud.test import LibcloudTestCase
<add>from libcloud.test import MockHttpTestCase, LibcloudTestCase
<ide> from libcloud.test.secrets import ONAPP_PARAMS
<del>from libcloud.compute.base import Node
<add>from libcloud.test.file_fixtures import ComputeFileFixtures
<add>from libcloud.utils.py3 import httplib
<ide>
<ide>
<ide> class OnAppNodeTestCase(LibcloudTestCase):
<add> driver_klass = OnAppNodeDriver
<add>
<ide> def setUp(self):
<del> def _request(*args, **kwargs):
<del> fixtures = ComputeFileFixtures('onapp')
<del> response = MagicMock()
<del> method = kwargs.get('method', "GET")
<del>
<del> if method == 'GET' and args[0] == '/virtual_machines.json':
<del> response.object = json.loads(fixtures.load(
<del> 'list_nodes.json'))
<del> if method == 'POST' and args[0] == '/virtual_machines.json':
<del> response.object = json.loads(fixtures.load('create_node.json'))
<del> if method == 'DELETE' and args[0] == '/virtual_machines.json':
<del> response.status = 204
<del>
<del> return response
<del>
<del> self.connection_mock = MagicMock()
<del> self.connection_mock.return_value.request.side_effect = _request
<del> OnAppNodeDriver.connectionCls = self.connection_mock
<add> self.driver_klass.connectionCls.conn_classes = \
<add> (None, OnAppMockHttp)
<add>
<ide> self.driver = OnAppNodeDriver(*ONAPP_PARAMS)
<ide>
<ide> def test_create_node(self):
<ide> def test_create_node(self):
<ide> ex_required_ip_address_assignment=0
<ide> )
<ide>
<del> req_mock = self.connection_mock.return_value.request
<del> self.assertEqual('/virtual_machines.json', req_mock.call_args[0][0])
<del> self.assertEqual({'Content-type': 'application/json'},
<del> req_mock.call_args[1]['headers'])
<del> self.assertEqual(json.loads(
<del> '{"virtual_machine": {'
<del> '"swap_disk_size": 1, "required_ip_address_assignment": 0, '
<del> '"hostname": "onapp-new-fred", "cpus": 4, "label": '
<del> '"onapp-new-fred", "primary_disk_size": 100, "memory": 512, '
<del> '"required_virtual_machine_build": 0, "template_id": '
<del> '"template_id", "cpu_shares": 4, "rate_limit": null}}'),
<del> json.loads(req_mock.call_args[1]['data']))
<del> self.assertEqual('POST', req_mock.call_args[1]['method'])
<del>
<ide> extra = node.extra
<ide>
<ide> self.assertEqual('onapp-new-fred', node.name)
<ide> def test_destroy_node(self):
<ide> node = Node('identABC', 'testnode',
<ide> ['123.123.123.123'], [],
<ide> {'state': 'test', 'template_id': 88}, None)
<del> self.driver.destroy_node(node=node)
<del> self.assertEqual(call(
<del> '/virtual_machines/identABC.json',
<del> params={'destroy_all_backups': 0, 'convert_last_backup': 0},
<del> method='DELETE'),
<del> self.connection_mock.return_value.request.call_args)
<add> res = self.driver.destroy_node(node=node)
<add> self.assertTrue(res)
<ide>
<ide> def test_list_nodes(self):
<ide> nodes = self.driver.list_nodes()
<ide> def test_list_nodes(self):
<ide> self.assertEqual(1, len(private_ips))
<ide> self.assertEqual('192.168.15.72', private_ips[0])
<ide>
<del> self.assertEqual(call('/virtual_machines.json'),
<del> self.connection_mock.return_value.request.call_args)
<add>
<add>class OnAppMockHttp(MockHttpTestCase):
<add> fixtures = ComputeFileFixtures('onapp')
<add>
<add> def _virtual_machines_json(self, method, url, body, headers):
<add> if method == 'GET':
<add> body = self.fixtures.load('list_nodes.json')
<add> else:
<add> body = self.fixtures.load('create_node.json')
<add> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<add>
<add> def _virtual_machines_identABC_json(self, method, url, body, headers):
<add> return (
<add> httplib.NO_CONTENT,
<add> '',
<add> {},
<add> httplib.responses[httplib.NO_CONTENT]
<add> )
<ide>
<ide>
<ide> if __name__ == '__main__':
| 2
|
Text
|
Text
|
add example of self-reference in scoped packages
|
fe4d562dd95fb43961e43ec9b3799660b48e149e
|
<ide><path>doc/api/packages.md
<ide> and in a CommonJS one. For example, this code will also work:
<ide> const { something } = require('a-package/foo'); // Loads from ./foo.js.
<ide> ```
<ide>
<add>Finally, self-referencing also works with scoped packages. For example, this
<add>code will also work:
<add>
<add>```json
<add>// package.json
<add>{
<add> "name": "@my/package",
<add> "exports": "./index.js"
<add>}
<add>```
<add>
<add>```js
<add>// ./index.js
<add>module.exports = 42;
<add>```
<add>
<add>```js
<add>// ./other.js
<add>console.log(require('@my/package'));
<add>```
<add>
<add>```console
<add>$ node other.js
<add>42
<add>```
<add>
<ide> ## Dual CommonJS/ES module packages
<ide>
<ide> Prior to the introduction of support for ES modules in Node.js, it was a common
| 1
|
Javascript
|
Javascript
|
add keystream tests
|
3a25949b2c0f2e50e348c601185dc2eee043a423
|
<ide><path>packages/ember-views/tests/streams/key_stream_test.js
<add>import { set } from "ember-metal/property_set";
<add>import Stream from "ember-metal/streams/stream";
<add>import KeyStream from "ember-views/streams/key_stream";
<add>
<add>var source, object, count;
<add>
<add>function incrementCount() {
<add> count++;
<add>}
<add>
<add>QUnit.module('KeyStream', {
<add> setup: function() {
<add> count = 0;
<add> object = { name: "mmun" };
<add>
<add> source = new Stream(function() {
<add> return object;
<add> });
<add>
<add> source.setValue = function(value) {
<add> object = value;
<add> this.notify();
<add> };
<add> },
<add> teardown: function() {
<add> count = undefined;
<add> object = undefined;
<add> source = undefined;
<add> }
<add>});
<add>
<add>QUnit.test("can be instantiated manually", function() {
<add> var nameStream = new KeyStream(source, 'name');
<add> equal(nameStream.value(), "mmun", "Stream value is correct");
<add>});
<add>
<add>QUnit.test("can be instantiated via `Stream.prototype.get`", function() {
<add> var nameStream = source.get('name');
<add> equal(nameStream.value(), "mmun", "Stream value is correct");
<add>});
<add>
<add>QUnit.test("is notified when the observed object's property is mutated", function() {
<add> var nameStream = source.get('name');
<add> nameStream.subscribe(incrementCount);
<add>
<add> equal(count, 0, "Subscribers called correct number of times");
<add> equal(nameStream.value(), "mmun", "Stream value is correct");
<add>
<add> set(object, 'name', "wycats");
<add>
<add> equal(count, 1, "Subscribers called correct number of times");
<add> equal(nameStream.value(), "wycats", "Stream value is correct");
<add>});
<add>
<add>QUnit.test("is notified when the source stream's value changes to a new object", function() {
<add> var nameStream = source.get('name');
<add> nameStream.subscribe(incrementCount);
<add>
<add> equal(count, 0, "Subscribers called correct number of times");
<add> equal(nameStream.value(), "mmun", "Stream value is correct");
<add>
<add> object = { name: "wycats" };
<add> source.setValue(object);
<add>
<add> equal(count, 1, "Subscribers called correct number of times");
<add> equal(nameStream.value(), "wycats", "Stream value is correct");
<add>
<add> set(object, 'name', "kris");
<add>
<add> equal(count, 2, "Subscribers called correct number of times");
<add> equal(nameStream.value(), "kris", "Stream value is correct");
<add>});
<add>
<add>QUnit.test("is notified when the source stream's value changes to the same object", function() {
<add> var nameStream = source.get('name');
<add> nameStream.subscribe(incrementCount);
<add>
<add> equal(count, 0, "Subscribers called correct number of times");
<add> equal(nameStream.value(), "mmun", "Stream value is correct");
<add>
<add> source.setValue(object);
<add>
<add> equal(count, 1, "Subscribers called correct number of times");
<add> equal(nameStream.value(), "mmun", "Stream value is correct");
<add>
<add> set(object, 'name', "kris");
<add>
<add> equal(count, 2, "Subscribers called correct number of times");
<add> equal(nameStream.value(), "kris", "Stream value is correct");
<add>});
<add>
<add>QUnit.test("is notified when setSource is called with a new stream whose value is a new object", function() {
<add> var nameStream = source.get('name');
<add> nameStream.subscribe(incrementCount);
<add>
<add> equal(count, 0, "Subscribers called correct number of times");
<add> equal(nameStream.value(), "mmun", "Stream value is correct");
<add>
<add> object = { name: "wycats" };
<add> nameStream.setSource(new Stream(function() {
<add> return object;
<add> }));
<add>
<add> equal(count, 1, "Subscribers called correct number of times");
<add> equal(nameStream.value(), "wycats", "Stream value is correct");
<add>
<add> set(object, 'name', "kris");
<add>
<add> equal(count, 2, "Subscribers called correct number of times");
<add> equal(nameStream.value(), "kris", "Stream value is correct");
<add>});
<add>
<add>QUnit.test("is notified when setSource is called with a new stream whose value is the same object", function() {
<add> var nameStream = source.get('name');
<add> nameStream.subscribe(incrementCount);
<add>
<add> equal(count, 0, "Subscribers called correct number of times");
<add> equal(nameStream.value(), "mmun", "Stream value is correct");
<add>
<add> nameStream.setSource(new Stream(function() {
<add> return object;
<add> }));
<add>
<add> equal(count, 1, "Subscribers called correct number of times");
<add> equal(nameStream.value(), "mmun", "Stream value is correct");
<add>
<add> set(object, 'name', "kris");
<add>
<add> equal(count, 2, "Subscribers called correct number of times");
<add> equal(nameStream.value(), "kris", "Stream value is correct");
<add>});
| 1
|
Mixed
|
Ruby
|
force arel.sql for returning and on_duplicate
|
4bef82217cd6a63cc10fe7beb16298e935babb5f
|
<ide><path>activerecord/CHANGELOG.md
<del>* Add `update_sql` option to `#upsert_all` to make it possible to use raw SQL to update columns on conflict:
<add>* Allow passing SQL as `on_duplicate` value to `#upsert_all` to make it possible to use raw SQL to update columns on conflict:
<ide>
<ide> ```ruby
<ide> Book.upsert_all(
<ide> [{ id: 1, status: 1 }, { id: 2, status: 1 }],
<del> update_sql: "status = GREATEST(books.status, EXCLUDED.status)"
<add> on_duplicate: Arel.sql("status = GREATEST(books.status, EXCLUDED.status)")
<ide> )
<ide> ```
<ide>
<ide> *Vladimir Dementyev*
<ide>
<del>* Allow passing raw SQL as `returning` statement to `#upsert_all`:
<add>* Allow passing SQL as `returning` statement to `#upsert_all`:
<ide>
<ide> ```ruby
<ide> Article.insert_all(
<ide> [
<del> {title: "Article 1", slug: "article-1", published: false},
<del> {title: "Article 2", slug: "article-2", published: false}
<add> { title: "Article 1", slug: "article-1", published: false },
<add> { title: "Article 2", slug: "article-2", published: false }
<ide> ],
<del> # Some PostgreSQL magic here to detect which rows have been actually inserted
<del> returning: "id, (xmax = '0') as inserted, name as new_name"
<add> returning: Arel.sql("id, (xmax = '0') as inserted, name as new_name")
<ide> )
<ide> ```
<ide>
<ide><path>activerecord/lib/active_record/insert_all.rb
<ide> class InsertAll # :nodoc:
<ide> attr_reader :model, :connection, :inserts, :keys
<ide> attr_reader :on_duplicate, :returning, :unique_by, :update_sql
<ide>
<del> def initialize(model, inserts, on_duplicate:, returning: nil, unique_by: nil, update_sql: nil)
<add> def initialize(model, inserts, on_duplicate:, returning: nil, unique_by: nil)
<ide> raise ArgumentError, "Empty list of attributes passed" if inserts.blank?
<ide>
<ide> @model, @connection, @inserts, @keys = model, model.connection, inserts, inserts.first.keys.map(&:to_s)
<del> @on_duplicate, @returning, @unique_by, @update_sql = on_duplicate, returning, unique_by, update_sql
<add> @on_duplicate, @returning, @unique_by = on_duplicate, returning, unique_by
<add>
<add> disallow_raw_sql!(returning)
<add> disallow_raw_sql!(on_duplicate)
<add>
<add> if Arel.arel_node?(on_duplicate)
<add> @update_sql = on_duplicate
<add> @on_duplicate = :update
<add> end
<ide>
<ide> if model.scope_attributes?
<ide> @scope_attributes = model.scope_attributes
<ide> def verify_attributes(attributes)
<ide> end
<ide> end
<ide>
<add> def disallow_raw_sql!(value)
<add> return if !value.is_a?(String) || Arel.arel_node?(value)
<add>
<add> raise ArgumentError, "Dangerous query method (method whose arguments are used as raw " \
<add> "SQL) called: #{value}. " \
<add> "Known-safe values can be passed " \
<add> "by wrapping them in Arel.sql()."
<add> end
<add>
<ide> class Builder # :nodoc:
<ide> attr_reader :model
<ide>
<ide><path>activerecord/lib/active_record/persistence.rb
<ide> def insert_all!(attributes, returning: nil)
<ide> # go through Active Record's type casting and serialization.
<ide> #
<ide> # See <tt>ActiveRecord::Persistence#upsert_all</tt> for documentation.
<del> def upsert(attributes, returning: nil, unique_by: nil, update_sql: nil)
<del> upsert_all([ attributes ], returning: returning, unique_by: unique_by, update_sql: update_sql)
<add> def upsert(attributes, on_duplicate: :update, returning: nil, unique_by: nil)
<add> upsert_all([ attributes ], on_duplicate: on_duplicate, returning: returning, unique_by: unique_by)
<ide> end
<ide>
<ide> # Updates or inserts (upserts) multiple records into the database in a
<ide> def upsert(attributes, returning: nil, unique_by: nil, update_sql: nil)
<ide> # <tt>:unique_by</tt> is recommended to be paired with
<ide> # Active Record's schema_cache.
<ide> #
<del> # [:update_sql]
<add> # [:on_duplicate]
<ide> # Specify a custom SQL for updating rows on conflict.
<ide> #
<ide> # NOTE: in this case you must provide all the columns you want to update by yourself.
<ide> def upsert(attributes, returning: nil, unique_by: nil, update_sql: nil)
<ide> # ], unique_by: :isbn)
<ide> #
<ide> # Book.find_by(isbn: "1").title # => "Eloquent Ruby"
<del> def upsert_all(attributes, returning: nil, unique_by: nil, update_sql: nil)
<del> InsertAll.new(self, attributes, on_duplicate: :update, returning: returning, unique_by: unique_by, update_sql: update_sql).execute
<add> def upsert_all(attributes, on_duplicate: :update, returning: nil, unique_by: nil, update_sql: nil)
<add> InsertAll.new(self, attributes, on_duplicate: on_duplicate, returning: returning, unique_by: unique_by).execute
<ide> end
<ide>
<ide> # Given an attributes hash, +instantiate+ returns a new instance of
<ide><path>activerecord/test/cases/insert_all_test.rb
<ide> def test_insert_all_returns_requested_fields
<ide> def test_insert_all_returns_requested_sql_fields
<ide> skip unless supports_insert_returning?
<ide>
<del> result = Book.insert_all! [{ name: "Rework", author_id: 1 }], returning: "UPPER(name) as name"
<add> result = Book.insert_all! [{ name: "Rework", author_id: 1 }], returning: Arel.sql("UPPER(name) as name")
<ide> assert_equal %w[ REWORK ], result.pluck("name")
<ide> end
<ide>
<ide> def test_upsert_all_updates_using_provided_sql
<ide>
<ide> Book.upsert_all(
<ide> [{ id: 1, status: 1 }, { id: 2, status: 1 }],
<del> update_sql: "status = #{operator}(books.status, 1)"
<add> on_duplicate: Arel.sql("status = #{operator}(books.status, 1)")
<ide> )
<ide> assert_equal "published", Book.find(1).status
<ide> assert_equal "written", Book.find(2).status
| 4
|
Javascript
|
Javascript
|
add support for unbind()
|
6b7ddf414de82720bbf547b2fa661bf5fcec7bb6
|
<ide><path>src/jqLite.js
<ide> * - [clone()](http://api.jquery.com/clone/)
<ide> * - [css()](http://api.jquery.com/css/)
<ide> * - [data()](http://api.jquery.com/data/)
<add> * - [eq()](http://api.jquery.com/eq/)
<ide> * - [hasClass()](http://api.jquery.com/hasClass/)
<ide> * - [parent()](http://api.jquery.com/parent/)
<ide> * - [remove()](http://api.jquery.com/remove/)
<ide> * - [replaceWith()](http://api.jquery.com/replaceWith/)
<ide> * - [text()](http://api.jquery.com/text/)
<ide> * - [trigger()](http://api.jquery.com/trigger/)
<del> * - [eq()](http://api.jquery.com/eq/)
<add> * - [unbind()](http://api.jquery.com/unbind/)
<ide> *
<ide> * ## In addtion to the above, Angular privides an additional method to both jQuery and jQuery lite:
<ide> *
<ide> forEach({
<ide> });
<ide> },
<ide>
<add> unbind: function(element, type, fn) {
<add> var bind = JQLiteData(element, 'bind');
<add> if (!bind) return; //no listeners registered
<add>
<add> if (isUndefined(type)) {
<add> forEach(bind, function(eventHandler, type) {
<add> removeEventListenerFn(element, type, eventHandler);
<add> delete bind[type];
<add> });
<add> } else {
<add> if (isUndefined(fn)) {
<add> removeEventListenerFn(element, type, bind[type]);
<add> delete bind[type];
<add> } else {
<add> angularArray.remove(bind[type].fns, fn);
<add> }
<add> }
<add> },
<add>
<ide> replaceWith: function(element, replaceNode) {
<ide> var index, parent = element.parentNode;
<ide> JQLiteDealoc(element);
<ide><path>test/jqLiteSpec.js
<ide> describe('jqLite', function(){
<ide> });
<ide>
<ide>
<add> describe('unbind', function() {
<add> it('should do nothing when no listener was registered with bound', function() {
<add> var aElem = jqLite(a);
<add>
<add> aElem.unbind();
<add> aElem.unbind('click');
<add> aElem.unbind('click', function() {});
<add> });
<add>
<add>
<add> it('should deregister all listeners', function() {
<add> var aElem = jqLite(a),
<add> clickSpy = jasmine.createSpy('click'),
<add> mouseoverSpy = jasmine.createSpy('mouseover');
<add>
<add> aElem.bind('click', clickSpy);
<add> aElem.bind('mouseover', mouseoverSpy);
<add>
<add> browserTrigger(a, 'click');
<add> expect(clickSpy).toHaveBeenCalledOnce();
<add> browserTrigger(a, 'mouseover');
<add> expect(mouseoverSpy).toHaveBeenCalledOnce();
<add>
<add> clickSpy.reset();
<add> mouseoverSpy.reset();
<add>
<add> aElem.unbind();
<add>
<add> browserTrigger(a, 'click');
<add> expect(clickSpy).not.toHaveBeenCalled();
<add> browserTrigger(a, 'mouseover');
<add> expect(mouseoverSpy).not.toHaveBeenCalled();
<add> });
<add>
<add>
<add> it('should deregister listeners for specific type', function() {
<add> var aElem = jqLite(a),
<add> clickSpy = jasmine.createSpy('click'),
<add> mouseoverSpy = jasmine.createSpy('mouseover');
<add>
<add> aElem.bind('click', clickSpy);
<add> aElem.bind('mouseover', mouseoverSpy);
<add>
<add> browserTrigger(a, 'click');
<add> expect(clickSpy).toHaveBeenCalledOnce();
<add> browserTrigger(a, 'mouseover');
<add> expect(mouseoverSpy).toHaveBeenCalledOnce();
<add>
<add> clickSpy.reset();
<add> mouseoverSpy.reset();
<add>
<add> aElem.unbind('click');
<add>
<add> browserTrigger(a, 'click');
<add> expect(clickSpy).not.toHaveBeenCalled();
<add> browserTrigger(a, 'mouseover');
<add> expect(mouseoverSpy).toHaveBeenCalledOnce();
<add>
<add> mouseoverSpy.reset();
<add>
<add> aElem.unbind('mouseover');
<add> browserTrigger(a, 'mouseover');
<add> expect(mouseoverSpy).not.toHaveBeenCalled();
<add> });
<add>
<add>
<add> it('should deregister specific listener', function() {
<add> var aElem = jqLite(a),
<add> clickSpy1 = jasmine.createSpy('click1'),
<add> clickSpy2 = jasmine.createSpy('click2');
<add>
<add> aElem.bind('click', clickSpy1);
<add> aElem.bind('click', clickSpy2);
<add>
<add> browserTrigger(a, 'click');
<add> expect(clickSpy1).toHaveBeenCalledOnce();
<add> expect(clickSpy2).toHaveBeenCalledOnce();
<add>
<add> clickSpy1.reset();
<add> clickSpy2.reset();
<add>
<add> aElem.unbind('click', clickSpy1);
<add>
<add> browserTrigger(a, 'click');
<add> expect(clickSpy1).not.toHaveBeenCalled();
<add> expect(clickSpy2).toHaveBeenCalledOnce();
<add>
<add> clickSpy2.reset();
<add>
<add> aElem.unbind('click', clickSpy2);
<add> browserTrigger(a, 'click');
<add> expect(clickSpy2).not.toHaveBeenCalled();
<add> });
<add> });
<add>
<add>
<ide> describe('replaceWith', function(){
<ide> it('should replaceWith', function(){
<ide> var root = jqLite('<div>').html('before-<div></div>after');
| 2
|
Python
|
Python
|
fix crash when calling savetxt on a padded array
|
efdd3f50bd5a1e58b815ad8f82d896f4e72ae2b5
|
<ide><path>numpy/lib/npyio.py
<ide> def first_write(self, v):
<ide>
<ide> # Complex dtype -- each field indicates a separate column
<ide> else:
<del> ncol = len(X.dtype.descr)
<add> ncol = len(X.dtype.names)
<ide> else:
<ide> ncol = X.shape[1]
<ide>
<ide><path>numpy/lib/tests/test_io.py
<ide> def test_0D_3D(self):
<ide> assert_raises(ValueError, np.savetxt, c, np.array(1))
<ide> assert_raises(ValueError, np.savetxt, c, np.array([[[1], [2]]]))
<ide>
<del> def test_record(self):
<add> def test_structured(self):
<ide> a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
<ide> c = BytesIO()
<ide> np.savetxt(c, a, fmt='%d')
<ide> c.seek(0)
<ide> assert_equal(c.readlines(), [b'1 2\n', b'3 4\n'])
<ide>
<add> def test_structured_padded(self):
<add> # gh-13297
<add> a = np.array([(1, 2, 3),(4, 5, 6)], dtype=[
<add> ('foo', 'i4'), ('bar', 'i4'), ('baz', 'i4')
<add> ])
<add> c = BytesIO()
<add> c.seek(0)
<add> np.savetxt(c, a[['foo', 'baz']])
<add> assert_equal(c.readlines(), [b'1 3\n', b'4 6\n'])
<add>
<ide> @pytest.mark.skipif(Path is None, reason="No pathlib.Path")
<ide> def test_multifield_view(self):
<ide> a = np.ones(1, dtype=[('x', 'i4'), ('y', 'i4'), ('z', 'f4')])
| 2
|
Javascript
|
Javascript
|
fix typo `handle._reading` => `handle.reading`
|
755461219d6b60361d1b725833e5356e681d2ca3
|
<ide><path>lib/_tls_wrap.js
<ide> TLSSocket.prototype._wrapHandle = function(handle) {
<ide> tls.createSecureContext();
<ide> res = tls_wrap.wrap(handle, context.context, options.isServer);
<ide> res._parent = handle;
<del> res._reading = handle._reading;
<add> res.reading = handle.reading;
<ide>
<ide> // Proxy HandleWrap, PipeWrap and TCPWrap methods
<ide> proxiedMethods.forEach(function(name) {
| 1
|
PHP
|
PHP
|
add getname() to view
|
e828eb16e43b31750b57e009ce8f14bba8de22b7
|
<ide><path>src/View/View.php
<ide> public function __set($name, $value)
<ide> 'response' => 'setResponse',
<ide> 'subDir' => 'setSubDir',
<ide> 'plugin' => 'setPlugin',
<del> 'name' => 'setName',
<ide> 'elementCache' => 'setElementCache',
<ide> ];
<ide> if (isset($protected[$name])) {
<ide> public function __set($name, $value)
<ide> return $this->helpers = $value;
<ide> }
<ide>
<add> if ($name === 'name') {
<add> deprecationWarning(
<add> 'View::$name is protected now. ' .
<add> 'You can use viewBuilder()->setName() to change the name a view uses before building it.'
<add> );
<add> }
<add>
<ide> $this->{$name} = $value;
<ide> }
<ide>
<ide> public function getSubDir()
<ide> return $this->subDir;
<ide> }
<ide>
<add> /**
<add> * Returns the View's controller name.
<add> *
<add> * @return string|null
<add> * @since 3.7.7
<add> */
<add> public function getName()
<add> {
<add> return $this->name;
<add> }
<add>
<ide> /**
<ide> * Returns the plugin name.
<ide> *
<ide><path>tests/TestCase/View/ViewTest.php
<ide> public function testGetSetLayout()
<ide> $this->assertSame($layout, 'foo');
<ide> }
<ide>
<add> /**
<add> * Test getName() and getPlugin().
<add> *
<add> * @return void
<add> */
<add> public function testGetNamePlugin()
<add> {
<add> $this->assertSame('Posts', $this->View->getName());
<add> $this->assertNull($this->View->getPlugin());
<add>
<add> $this->assertSame($this->View, $this->View->setPlugin('TestPlugin'));
<add> $this->assertSame('TestPlugin', $this->View->getPlugin());
<add> }
<add>
<ide> /**
<ide> * Test testHasRendered property
<ide> *
| 2
|
Ruby
|
Ruby
|
move default middleware stack to middlewares.rb
|
0b22a96b7aa39cb7244d7cee23f3d03b6117b447
|
<ide><path>actionpack/lib/action_controller/dispatcher.rb
<ide> def to_prepare(identifier = nil, &block)
<ide>
<ide> cattr_accessor :middleware
<ide> self.middleware = MiddlewareStack.new do |middleware|
<del> middleware.use "ActionController::Lock", :if => lambda {
<del> !ActionController::Base.allow_concurrency
<del> }
<del> middleware.use "ActionController::Failsafe"
<del> middleware.use "ActiveRecord::QueryCache" if defined?(ActiveRecord)
<del>
<del> ["ActionController::Session::CookieStore",
<del> "ActionController::Session::MemCacheStore",
<del> "ActiveRecord::SessionStore"].each do |store|
<del> middleware.use(store, ActionController::Base.session_options,
<del> :if => lambda {
<del> if session_store = ActionController::Base.session_store
<del> session_store.name == store
<del> end
<del> }
<del> )
<del> end
<add> middlewares = File.join(File.dirname(__FILE__), "middlewares.rb")
<add> middleware.instance_eval(File.read(middlewares))
<ide> end
<ide>
<ide> include ActiveSupport::Callbacks
<ide><path>actionpack/lib/action_controller/middlewares.rb
<add>use "ActionController::Lock", :if => lambda {
<add> !ActionController::Base.allow_concurrency
<add>}
<add>
<add>use "ActionController::Failsafe"
<add>
<add>use "ActiveRecord::QueryCache", :if => lambda { defined?(ActiveRecord) }
<add>
<add>["ActionController::Session::CookieStore",
<add> "ActionController::Session::MemCacheStore",
<add> "ActiveRecord::SessionStore"].each do |store|
<add> use(store, ActionController::Base.session_options,
<add> :if => lambda {
<add> if session_store = ActionController::Base.session_store
<add> session_store.name == store
<add> end
<add> }
<add> )
<add>end
| 2
|
PHP
|
PHP
|
fix typo in doc block
|
c11c5c57191e870a07bf1587e313ec7c29d99a0b
|
<ide><path>lib/Cake/Model/Model.php
<ide> class Model extends Object {
<ide> * public $validate = array(
<ide> * 'login' => array(
<ide> * array(
<del> * 'role' => 'alphaNumeric',
<add> * 'rule' => 'alphaNumeric',
<ide> * 'message' => 'Only alphabets and numbers allowed',
<ide> * 'last' => true
<ide> * ),
<ide> * array(
<del> * 'role' => array('minLength', 8),
<add> * 'rule' => array('minLength', 8),
<ide> * 'message' => array('Minimum length of %d characters')
<ide> * )
<ide> * )
| 1
|
Text
|
Text
|
update changelog for 2.11.0
|
a6f3d6d31b21f116daa32c80a3235d83572a6506
|
<ide><path>CHANGELOG.md
<ide> Changelog
<ide> =========
<ide>
<add>### 2.11.0 [See full changelog](https://gist.github.com/ichernev/6594bc29719dde6b2f66)
<add>
<add>* [#2624](https://github.com/moment/moment/pull/2624) Proper handling of invalid moments
<add>* [#2634](https://github.com/moment/moment/pull/2634) Fix strict month parsing issue in cs,ru,sk
<add>* [#2735](https://github.com/moment/moment/pull/2735) Reset the locale back to 'en' after defining all locales in min/locales.js
<add>* [#2702](https://github.com/moment/moment/pull/2702) Week rework
<add>* [#2746](https://github.com/moment/moment/pull/2746) Changed September Abbreviation to "Sept" in locale-specific english
<add> files and default locale file
<add>* [#2646](https://github.com/moment/moment/pull/2646) Fix [#2645](https://github.com/moment/moment/pull/2645) - invalid dates pre-1970
<add>
<add>* [#2641](https://github.com/moment/moment/pull/2641) Implement basic format and comma as ms separator in ISO 8601
<add>* [#2665](https://github.com/moment/moment/pull/2665) Implement stricter weekday parsing
<add>* [#2700](https://github.com/moment/moment/pull/2700) Add [Hh]mm and [Hh]mmss formatting tokens, so you can parse 123 with
<add> hmm for example
<add>* [#2565](https://github.com/moment/moment/pull/2565) [#2835](https://github.com/moment/moment/pull/2835) Expose arguments used for moment creation with creationData
<add> (fix [#2443](https://github.com/moment/moment/pull/2443))
<add>* [#2648](https://github.com/moment/moment/pull/2648) fix issue [#2640](https://github.com/moment/moment/pull/2640): support instanceof operator
<add>* [#2709](https://github.com/moment/moment/pull/2709) Add isSameOrAfter and isSameOrBefore comparison methods
<add>* [#2721](https://github.com/moment/moment/pull/2721) Fix moment creation from object with strings values
<add>* [#2740](https://github.com/moment/moment/pull/2740) Enable 'd hh:mm:ss.sss' format for durations
<add>* [#2766](https://github.com/moment/moment/pull/2766) [#2833](https://github.com/moment/moment/pull/2833) Alternate Clock Source Support
<add>
<ide> ### 2.10.6
<ide>
<ide> [#2515](https://github.com/moment/moment/pull/2515) Fix regression introduced
| 1
|
Ruby
|
Ruby
|
fix regression on `assert_redirected_to`
|
7ec665303d125c945f7d59affb904f974143a087
|
<ide><path>actionpack/lib/action_dispatch/testing/assertions/response.rb
<ide> def normalize_argument_to_redirection(fragment)
<ide> if Regexp === fragment
<ide> fragment
<ide> else
<del> @controller._compute_redirect_to_location(fragment)
<add> handle = @controller || Class.new(ActionController::Metal) do
<add> include ActionController::Redirecting
<add> def initialize(request)
<add> @_request = request
<add> end
<add> end.new(@request)
<add> handle._compute_redirect_to_location(fragment)
<ide> end
<ide> end
<ide> end
<ide><path>actionpack/test/controller/integration_test.rb
<ide> def test_redirect
<ide> follow_redirect!
<ide> assert_response :success
<ide> assert_equal "/get", path
<add>
<add> get '/moved'
<add> assert_response :redirect
<add> assert_redirected_to '/method'
<ide> end
<ide> end
<ide>
<ide> def with_test_route_set
<ide> end
<ide>
<ide> set.draw do
<add> get 'moved' => redirect('/method')
<add>
<ide> match ':action', :to => controller, :via => [:get, :post], :as => :action
<ide> get 'get/:action', :to => controller, :as => :get_action
<ide> end
| 2
|
Javascript
|
Javascript
|
hide youtube suggestions
|
7ed1d520017a2c92a8b24cc1f021d364d85f0824
|
<ide><path>client/src/templates/Challenges/video/Show.js
<ide> export class Project extends Component {
<ide> }
<ide> onReady={this.videoIsReady}
<ide> opts={{
<del> rel: 0,
<add> playerVars: {
<add> rel: 0
<add> },
<ide> width: '960px',
<ide> height: '540px'
<ide> }}
| 1
|
PHP
|
PHP
|
add if method
|
71dfe0f0824412f106b80df8dedd7708e66dfb00
|
<ide><path>src/Illuminate/View/Compilers/BladeCompiler.php
<ide>
<ide> namespace Illuminate\View\Compilers;
<ide>
<add>use Closure;
<ide> use Illuminate\Support\Arr;
<ide> use Illuminate\Support\Str;
<ide>
<ide> public function getExtensions()
<ide> return $this->extensions;
<ide> }
<ide>
<add> /**
<add> * Register an "if" statement directive.
<add> *
<add> * @param string $name
<add> * @param \Closrue $callback
<add> * @return void
<add> */
<add> public function if($name, Closure $callback)
<add> {
<add> $this->conditions[$name] = $callback;
<add>
<add> $this->directive($name, function ($expression) use ($name) {
<add> return $expression
<add> ? "<?php if (\Illuminate\Support\Facades\Blade::check('{$name}', {$expression})): ?>"
<add> : "<?php if (\Illuminate\Support\Facades\Blade::check('{$name}')): ?>";
<add> });
<add>
<add> $this->directive('end'.$name, function () {
<add> return "<?php endif; ?>";
<add> });
<add> }
<add>
<add> /**
<add> * Check the result of a condition.
<add> *
<add> * @param string $name
<add> * @param array $parameters
<add> * @return bool
<add> */
<add> public function check($name, ...$parameters)
<add> {
<add> return call_user_func($this->conditions[$name], ...$parameters);
<add> }
<add>
<ide> /**
<ide> * Register a handler for custom directives.
<ide> *
<ide><path>tests/View/Blade/BladeCustomTest.php
<ide> public function testCustomExtensionOverwritesCore()
<ide> $expected = '<?php custom(); ?>';
<ide> $this->assertEquals($expected, $this->compiler->compileString($string));
<ide> }
<add>
<add> public function testCustomConditions()
<add> {
<add> $this->compiler->if('custom', function ($user) {
<add> return true;
<add> });
<add>
<add> $string = '@custom($user)
<add>@endcustom';
<add> $expected = '<?php if (\Illuminate\Support\Facades\Blade::check(\'custom\', $user)): ?>
<add><?php endif; ?>';
<add> $this->assertEquals($expected, $this->compiler->compileString($string));
<add> }
<ide> }
| 2
|
Text
|
Text
|
add link to angular 2 repo
|
06e96407a916255f3ff6b1505dcdbd77e1c1c210
|
<ide><path>README.md
<ide> piece of cake. Best of all? It makes development fun!
<ide> * Contribution guidelines: [CONTRIBUTING.md](https://github.com/angular/angular.js/blob/master/CONTRIBUTING.md)
<ide> * Dashboard: https://dashboard.angularjs.org
<ide>
<add>##### Looking for Angular 2 (beta)? Go here: https://github.com/angular/angular
<ide>
<ide> Building AngularJS
<ide> ---------
| 1
|
Ruby
|
Ruby
|
pick better names and add a little documentation
|
3a0d08163a76427611df0c109a5159daaf5b51bf
|
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> def initialize(connection, logger, connection_parameters, config)
<ide>
<ide> initialize_type_map
<ide> @local_tz = execute('SHOW TIME ZONE', 'SCHEMA').first["TimeZone"]
<del> self.use_returning = true
<add> self.enable_insert_returning!
<ide> end
<ide>
<ide> # Clears the prepared statements cache.
<ide> def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
<ide> pk = primary_key(table_ref) if table_ref
<ide> end
<ide>
<del> if pk && use_returning?
<add> if pk && use_insert_returning?
<ide> select_value("#{sql} RETURNING #{quote_column_name(pk)}")
<ide> elsif pk
<ide> super
<ide> def sql_for_insert(sql, pk, id_value, sequence_name, binds)
<ide> pk = primary_key(table_ref) if table_ref
<ide> end
<ide>
<del> if pk && use_returning?
<add> if pk && use_insert_returning?
<ide> sql = "#{sql} RETURNING #{quote_column_name(pk)}"
<ide> end
<ide>
<ide> def sql_for_insert(sql, pk, id_value, sequence_name, binds)
<ide>
<ide> def exec_insert(sql, name, binds, pk = nil, sequence_name = nil)
<ide> val = exec_query(sql, name, binds)
<del> if !use_returning? && pk
<add> if !use_insert_returning? && pk
<ide> unless sequence_name
<ide> table_ref = extract_table_ref_from_insert_sql(sql)
<ide> sequence_name = default_sequence_name(table_ref, pk)
<ide> def extract_schema_and_table(name)
<ide> end
<ide> end
<ide>
<del> def use_returning=(val)
<del> @use_returning = val
<add> # Enable insert statements to use INSERT ... RETURNING ... statements. On by default.
<add> def enable_insert_returning!
<add> @use_insert_returning = true
<ide> end
<ide>
<del> def use_returning?
<del> @use_returning
<add> # Disable INSERT ... RETURNING ... statements, using currval() instead.
<add> # Useful for trigger based insertions where INSERT RETURNING does the wrong thing.
<add> def disable_insert_returning!
<add> @use_insert_returning = false
<add> end
<add>
<add>
<add> def use_insert_returning?
<add> @use_insert_returning
<ide> end
<ide>
<ide> protected
<ide><path>activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb
<ide> def test_insert_sql_with_no_space_after_table_name
<ide> end
<ide>
<ide> def test_insert_sql_with_returning_disabled
<del> @connection.use_returning = false
<add> @connection.disable_insert_returning!
<ide> id = @connection.insert_sql("insert into postgresql_partitioned_table_parent (number) VALUES (1)")
<ide> expect = @connection.query('select max(id) from postgresql_partitioned_table_parent').first.first
<ide> assert_equal expect, id
<ide> ensure
<del> @connection.use_returning = true
<add> @connection.enable_insert_returning!
<ide> end
<ide>
<ide> def test_exec_insert_with_returning_disabled
<del> @connection.use_returning = false
<add> @connection.disable_insert_returning!
<ide> result = @connection.exec_insert("insert into postgresql_partitioned_table_parent (number) VALUES (1)", nil, [], 'id', 'postgresql_partitioned_table_parent_id_seq')
<ide> expect = @connection.query('select max(id) from postgresql_partitioned_table_parent').first.first
<ide> assert_equal expect, result.rows.first.first
<ide> ensure
<del> @connection.use_returning = true
<add> @connection.enable_insert_returning!
<ide> end
<ide>
<ide> def test_exec_insert_with_returning_disabled_and_no_sequence_name_given
<del> @connection.use_returning = false
<add> @connection.disable_insert_returning!
<ide> result = @connection.exec_insert("insert into postgresql_partitioned_table_parent (number) VALUES (1)", nil, [], 'id')
<ide> expect = @connection.query('select max(id) from postgresql_partitioned_table_parent').first.first
<ide> assert_equal expect, result.rows.first.first
<ide> ensure
<del> @connection.use_returning = true
<add> @connection.enable_insert_returning!
<ide> end
<ide>
<ide> def test_sql_for_insert_with_returning_disabled
<del> @connection.use_returning = false
<add> @connection.disable_insert_returning!
<ide> result = @connection.sql_for_insert('sql', nil, nil, nil, 'binds')
<ide> assert_equal ['sql', 'binds'], result
<ide> ensure
<del> @connection.use_returning = true
<add> @connection.enable_insert_returning!
<ide> end
<ide>
<ide> def test_serial_sequence
| 2
|
PHP
|
PHP
|
allow lenient log stacks
|
8999f5eebadee2433c8ad1ef8837a90de111fcc9
|
<ide><path>src/Illuminate/Log/LogManager.php
<ide> use Monolog\Handler\HandlerInterface;
<ide> use Monolog\Handler\RotatingFileHandler;
<ide> use Monolog\Handler\SlackWebhookHandler;
<add>use Monolog\Handler\WhatFailureGroupHandler;
<ide>
<ide> class LogManager implements LoggerInterface
<ide> {
<ide> protected function createStackDriver(array $config)
<ide> return $this->channel($channel)->getHandlers();
<ide> })->all();
<ide>
<add> if ($config['lenient'] ?? false) {
<add> $handlers = [new WhatFailureGroupHandler($handlers)];
<add> }
<add>
<ide> return new Monolog($this->parseChannel($config), $handlers);
<ide> }
<ide>
| 1
|
Text
|
Text
|
update readme to remove incorrect image link
|
e00931fbed334dfc043f264ee8312fa11bd16178
|
<ide><path>README.md
<ide> See [CONTRIBUTING.md](https://github.com/emberjs/ember.js/blob/master/CONTRIBUTI
<ide>
<ide> ---
<ide>
<del>Cross-browser testing provided by:
<del>
<del>
<del><a href="http://browserstack.com"><img height="70" src="https://p3.zdusercontent.com/attachment/1015988/PWfFdN71Aung2evRkIVQuKJpE?token=eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..aUrNFb8clSXsFwgw5BUTcg.IJr5piuCen7PmSSBHSrOnqM9K5YZfxX3lvbp-5LCqoKOi4CjjgdA419iqjofs0nLtm26FMURvZ8JRTuKB4iHer6lGu5f8dXHtIkYAHjP5fXDWkl044Yg2mSdrhF6uPy62GdlBYoYxwvgkNrac8nN_In8GY-qOC7bYmlZyJT7tsTZUTYbNMQiXS86YA5LgdCEWzWreMvc3C6cvZtVXIrcVgpkroIhvsTQPm4vQA-Uq6iCbTPA4oX5cpEtMtrlg4jYBnnAE4BTw5UwU_dY83ep5g.7wpc1IKv0rSRGsvqCG_q3g" alt="BrowserStack"></a>
<add>Cross-browser testing provided by <a href="http://browserstack.com">Browserstack</a>. Thank you!
| 1
|
Go
|
Go
|
add show error when attach to a paused container
|
de1d611990a80cf4a38ec501469c08c1aeee2d60
|
<ide><path>api/client/attach.go
<ide> func (cli *DockerCli) CmdAttach(args ...string) error {
<ide> return fmt.Errorf("You cannot attach to a stopped container, start it first")
<ide> }
<ide>
<add> if c.State.Paused {
<add> return fmt.Errorf("You cannot attach to a paused container, unpause it first")
<add> }
<add>
<ide> if err := cli.CheckTtyInput(!*noStdin, c.Config.Tty); err != nil {
<ide> return err
<ide> }
<ide><path>api/server/router/local/container.go
<ide> func (s *router) postContainersAttach(ctx context.Context, w http.ResponseWriter
<ide> return derr.ErrorCodeNoSuchContainer.WithArgs(containerName)
<ide> }
<ide>
<add> if s.daemon.IsPaused(containerName) {
<add> return derr.ErrorCodePausedContainer.WithArgs(containerName)
<add> }
<add>
<ide> inStream, outStream, err := httputils.HijackConnection(w)
<ide> if err != nil {
<ide> return err
<ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) Exists(id string) bool {
<ide> return c != nil
<ide> }
<ide>
<add>// IsPaused returns a bool indicating if the specified container is paused.
<add>func (daemon *Daemon) IsPaused(id string) bool {
<add> c, _ := daemon.Get(id)
<add> return c.State.isPaused()
<add>}
<add>
<ide> func (daemon *Daemon) containerRoot(id string) string {
<ide> return filepath.Join(daemon.repository, id)
<ide> }
<ide><path>errors/daemon.go
<ide> var (
<ide> HTTPStatusCode: http.StatusInternalServerError,
<ide> })
<ide>
<add> // ErrorCodePausedContainer is generated when we attempt to attach a
<add> // container but its paused.
<add> ErrorCodePausedContainer = errcode.Register(errGroup, errcode.ErrorDescriptor{
<add> Value: "CONTAINERPAUSED",
<add> Message: "Container %s is paused. Unpause the container before attach",
<add> Description: "The specified container is paused, unpause the container before attach",
<add> HTTPStatusCode: http.StatusConflict,
<add> })
<ide> // ErrorCodeAlreadyPaused is generated when we attempt to pause a
<ide> // container when its already paused.
<ide> ErrorCodeAlreadyPaused = errcode.Register(errGroup, errcode.ErrorDescriptor{
<ide><path>integration-cli/docker_cli_attach_test.go
<ide> import (
<ide> "sync"
<ide> "time"
<ide>
<add> "github.com/docker/docker/pkg/integration/checker"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> func (s *DockerSuite) TestAttachDisconnect(c *check.C) {
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(running, check.Equals, "true")
<ide> }
<add>
<add>func (s *DockerSuite) TestAttachPausedContainer(c *check.C) {
<add> defer unpauseAllContainers()
<add> dockerCmd(c, "run", "-d", "--name=test", "busybox", "top")
<add> dockerCmd(c, "pause", "test")
<add> out, _, err := dockerCmdWithError("attach", "test")
<add> c.Assert(err, checker.NotNil, check.Commentf(out))
<add> c.Assert(out, checker.Contains, "You cannot attach to a paused container, unpause it first")
<add>}
| 5
|
Python
|
Python
|
add rollaxis command and fix cross function
|
972ae975594790108be7bd3661d0d0be007e048c
|
<ide><path>numpy/core/numeric.py
<ide> 'asarray', 'asanyarray', 'ascontiguousarray', 'asfortranarray',
<ide> 'isfortran', 'empty_like', 'zeros_like',
<ide> 'correlate', 'convolve', 'inner', 'dot', 'outer', 'vdot',
<del> 'alterdot', 'restoredot', 'cross', 'tensordot',
<add> 'alterdot', 'restoredot', 'rollaxis', 'cross', 'tensordot',
<ide> 'array2string', 'get_printoptions', 'set_printoptions',
<ide> 'array_repr', 'array_str', 'set_string_function',
<ide> 'little_endian', 'require',
<ide> def tensordot(a, b, axes=(-1,0)):
<ide> res = dot(at, bt)
<ide> return res.reshape(olda + oldb)
<ide>
<add>def rollaxis(a, axis, start=0):
<add> """Return transposed array so that axis is rolled before start.
<ide>
<del>def _move_axis_to_0(a, axis):
<del> if axis == 0:
<del> return a
<add> if a.shape is (3,4,5,6)
<add> rollaxis(a, 3, 1).shape is (3,6,4,5)
<add> rollaxis(a, 2, 0).shape is (5,3,4,6)
<add> rollaxis(a, 1, 3).shape is (3,5,4,6)
<add> rollaxis(a, 1, 4).shape is (3,5,6,4)
<add> """
<ide> n = a.ndim
<ide> if axis < 0:
<ide> axis += n
<del> axes = range(1, axis+1) + [0,] + range(axis+1, n)
<add> if start < 0:
<add> start += n
<add> msg = 'rollaxis: %s (%d) must be >=0 and < %d'
<add> if not (0 <= axis < n):
<add> raise ValueError, msg % ('axis', axis, n)
<add> if not (0 <= start < n+1):
<add> raise ValueError, msg % ('start', start, n+1)
<add> if (axis < start): # it's been removed
<add> start -= 1
<add> if axis==start:
<add> return a
<add> axes = range(0,n)
<add> axes.remove(axis)
<add> axes.insert(start, axis)
<ide> return a.transpose(axes)
<ide>
<add># fix hack in scipy which imports this function
<add>def _move_axis_to_0(a, axis):
<add> return rollaxis(a, axis, 0)
<add>
<ide> def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):
<ide> """Return the cross product of two (arrays of) vectors.
<ide>
<ide> def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):
<ide> """
<ide> if axis is not None:
<ide> axisa,axisb,axisc=(axis,)*3
<del> a = _move_axis_to_0(asarray(a), axisa)
<del> b = _move_axis_to_0(asarray(b), axisb)
<add> a = asarray(a).swapaxes(axisa, 0)
<add> b = asarray(b).swapaxes(axisb, 0)
<ide> msg = "incompatible dimensions for cross product\n"\
<ide> "(dimension must be 2 or 3)"
<ide> if (a.shape[0] not in [2,3]) or (b.shape[0] not in [2,3]):
<ide> def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):
<ide> if cp.ndim == 0:
<ide> return cp
<ide> else:
<del> return cp.swapaxes(0,axisc)
<add> return cp.swapaxes(0, axisc)
<ide> else:
<ide> x = a[1]*b[2]
<ide> y = -a[0]*b[2]
| 1
|
Javascript
|
Javascript
|
extract version parsing from release script
|
cc1e3abb6eb0b48b31ef8aea5ef2880a8bc1e456
|
<ide><path>scripts/__tests__/version-utils-test.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @format
<add> */
<add>
<add>const {parseVersion} = require('../version-utils');
<add>
<add>describe('version-utils', () => {
<add> describe('parseVersion', () => {
<add> it('should throw error if invalid match', () => {
<add> function testInvalidVersion() {
<add> parseVersion('<invalid version>');
<add> }
<add> expect(testInvalidVersion).toThrowErrorMatchingInlineSnapshot(
<add> `"You must pass a correctly formatted version; couldn't parse <invalid version>"`,
<add> );
<add> });
<add>
<add> it('should parse pre-release version with .', () => {
<add> const {major, minor, patch, prerelease} = parseVersion('0.66.0-rc.4');
<add> expect(major).toBe('0');
<add> expect(minor).toBe('66');
<add> expect(patch).toBe('0');
<add> expect(prerelease).toBe('rc.4');
<add> });
<add>
<add> it('should parse stable version', () => {
<add> const {major, minor, patch, prerelease} = parseVersion('0.66.0');
<add> expect(major).toBe('0');
<add> expect(minor).toBe('66');
<add> expect(patch).toBe('0');
<add> expect(prerelease).toBeUndefined();
<add> });
<add> });
<add>});
<ide><path>scripts/bump-oss-version.js
<ide> const fs = require('fs');
<ide> const {cat, echo, exec, exit, sed} = require('shelljs');
<ide> const yargs = require('yargs');
<add>const {parseVersion} = require('./version-utils');
<ide>
<ide> let argv = yargs
<ide> .option('r', {
<ide> if (!nightlyBuild) {
<ide> }
<ide> }
<ide>
<del>// Generate version files to detect mismatches between JS and native.
<del>let match = version.match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);
<del>if (!match) {
<del> echo(
<del> `You must pass a correctly formatted version; couldn't parse ${version}`,
<del> );
<add>let major,
<add> minor,
<add> patch,
<add> prerelease = -1;
<add>try {
<add> ({major, minor, patch, prerelease} = parseVersion(version));
<add>} catch (e) {
<add> echo(e.message);
<ide> exit(1);
<ide> }
<del>let [, major, minor, patch, prerelease] = match;
<ide>
<ide> fs.writeFileSync(
<ide> 'ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/ReactNativeVersion.java',
<ide> if (!nightlyBuild) {
<ide> exec(`git push ${remote} v${version}`);
<ide>
<ide> // Tag latest if doing stable release
<del> if (version.indexOf('rc') === -1) {
<add> if (prerelease == null) {
<ide> exec('git tag -d latest');
<ide> exec(`git push ${remote} :latest`);
<ide> exec('git tag latest');
<ide><path>scripts/version-utils.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @format
<add> */
<add>
<add>function parseVersion(version) {
<add> const match = version.match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);
<add> if (!match) {
<add> throw new Error(
<add> `You must pass a correctly formatted version; couldn't parse ${version}`,
<add> );
<add> }
<add> const [, major, minor, patch, prerelease] = match;
<add> return {
<add> major,
<add> minor,
<add> patch,
<add> prerelease,
<add> };
<add>}
<add>
<add>module.exports = {
<add> parseVersion,
<add>};
| 3
|
Javascript
|
Javascript
|
append root to atom home value
|
8fa99a33beaee4c5776f301e227474c7fec60b41
|
<ide><path>src/compile-cache.js
<ide> var cacheDirectory = null
<ide> exports.setAtomHomeDirectory = function (atomHome) {
<ide> var cacheDir = path.join(atomHome, 'compile-cache')
<ide> if (process.env.USER === 'root' && process.env.SUDO_USER && process.env.SUDO_USER !== process.env.USER) {
<del> cacheDir = path.join(cacheDirectory, 'root')
<add> cacheDir = path.join(atomHome, 'root')
<ide> }
<ide> this.setCacheDirectory(cacheDir)
<ide> }
| 1
|
Python
|
Python
|
fix initial variable in evaluator.
|
3b83a1b1ac69d3bb3c2ac55e61878df1fd392768
|
<ide><path>examples/deep_dream.py
<ide> def eval_loss_and_grads(x):
<ide> class Evaluator(object):
<ide> def __init__(self):
<ide> self.loss_value = None
<del> self.grads_values = None
<add> self.grad_values = None
<ide>
<ide> def loss(self, x):
<ide> assert self.loss_value is None
| 1
|
Text
|
Text
|
fix documentation of the release process
|
1e97a71a829e698ddac0a5e15fbdec97d35ed2bc
|
<ide><path>scripts/release/README.md
<del># React Release Script
<add># React Release Scripts
<ide>
<del>At a high-level, the release script runs in 2 passes: **build** and **publish**.
<del>1. The **build** script does the heavy lifting (eg checking CI, running automated tests, building Rollup bundles) and then prints instructions for manual verification.
<del>1. The **publish** script then publishes the built artifacts to NPM and pushes to GitHub.
<add>At a high-level, the release process uses two scripts: **build** and **publish**.
<add>1. The **build** script does the heavy lifting (e.g., checking CI, running automated tests, building Rollup bundles) and then prints instructions for manual verification.
<add>1. The **publish** script then publishes the built artifacts to npm and pushes to GitHub.
<ide>
<del>Run either script without parameters to see its usage, eg:
<add>Run either script without parameters to see its usage, e.g.:
<ide> ```
<ide> ./scripts/release/build.js
<ide> ./scripts/release/publish.js
<ide> ```
<ide>
<del>Each script will guide the release engineer through any necessary steps (including environment setup and manual testing steps).
<ide>\ No newline at end of file
<add>Each script will guide the release engineer through any necessary steps (including environment setup and manual testing steps).
| 1
|
Python
|
Python
|
remove unused export
|
33e332e67ce7163982806dc5b45a97c6de697486
|
<ide><path>spacy/lang/en/__init__.py
<ide> class English(Language):
<ide> Defaults = EnglishDefaults
<ide>
<ide>
<del>__all__ = ['English', 'EnglishDefaults']
<add>__all__ = ['English']
| 1
|
Text
|
Text
|
add v3.26.0-beta.5 to changelog
|
e25282f6e854a1c9e4fb318b7aa162542b964804
|
<ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.26.0-beta.5 (March 16, 2021)
<add>
<add>- [#19405](https://github.com/emberjs/ember.js/pull/19405) [BUGFIX] Avoid instantiation errors when `app/router.js` injects the router service.
<add>
<ide> ### v3.26.0-beta.4 (March 08, 2021)
<ide>
<ide> - [#19436](https://github.com/emberjs/ember.js/pull/19436) [BUGFIX] Support observer keys with colons
| 1
|
PHP
|
PHP
|
fix more failing tests
|
1a6a5f2d268ecaacd662d04b41b4682eef99b002
|
<ide><path>lib/Cake/Test/TestCase/Console/ConsoleErrorHandlerTest.php
<ide> class ConsoleErrorHandlerTest extends TestCase {
<ide> */
<ide> public function setUp() {
<ide> parent::setUp();
<del> $this->Error = $this->getMock('Cake\Console\ConsoleErrorHandler', array('_stop'));
<del> ConsoleErrorHandler::$stderr = $this->getMock('Cake\Console\ConsoleOutput', array(), array(), '', false);
<add> $this->Error = $this->getMock('Cake\Console\ConsoleErrorHandler', ['_stop']);
<add> ConsoleErrorHandler::$stderr = $this->getMock('Cake\Console\ConsoleOutput', [], [], '', false);
<ide> }
<ide>
<ide> /**
<ide> public function testHandleFatalError() {
<ide> ConsoleErrorHandler::$stderr->expects($this->once())->method('write')
<ide> ->with($content);
<ide>
<del> $this->Error->expects($this->once())
<del> ->method('_stop')
<del> ->with(1);
<del>
<ide> $this->Error->handleError(E_USER_ERROR, 'This is a fatal error', '/some/file', 275);
<ide> }
<ide>
<ide><path>lib/Cake/Test/TestCase/Controller/Component/AuthComponentTest.php
<ide> public function testDefaultToLoginRedirect() {
<ide>
<ide> /**
<ide> * Throw ForbiddenException if AuthComponent::$unauthorizedRedirect set to false
<del> * @expectedException ForbiddenException
<add> * @expectedException Cake\Error\ForbiddenException
<ide> * @return void
<ide> */
<ide> public function testForbiddenException() {
<ide><path>lib/Cake/Test/TestCase/Controller/ScaffoldTest.php
<ide> public function testHabtmFieldAdditionWithScaffoldForm() {
<ide> $Scaffold = new Scaffold($this->Controller, $this->Controller->request);
<ide> $this->Controller->response->send();
<ide> $result = ob_get_clean();
<del> $this->assertRegExp('/name="data\[ScaffoldTag\]\[ScaffoldTag\]"/', $result);
<add> $this->assertContains('name="ScaffoldTag[ScaffoldTag]"', $result);
<ide>
<ide> $result = $Scaffold->controller->viewVars;
<ide> $this->assertEquals(array('id', 'user_id', 'title', 'body', 'published', 'created', 'updated', 'ScaffoldTag'), $result['scaffoldFields']);
<ide><path>lib/Cake/Test/TestCase/Utility/NumberTest.php
<ide> public function testFormat() {
<ide>
<ide> $value = -0.00001;
<ide> $result = $this->Number->format($value, array('places' => 1));
<del> $expected = '$0.0';
<add> $expected = '$-0.0';
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<ide> public function testFromReadableSize($params, $expected) {
<ide> /**
<ide> * testFromReadableSize
<ide> *
<del> * @expectedException CakeException
<add> * @expectedException Cake\Error\Exception
<ide> * @return void
<ide> */
<ide> public function testFromReadableSizeException() {
<ide><path>lib/Cake/Test/TestCase/View/Helper/FormHelperTest.php
<ide> <?php
<ide> /**
<del> * FormHelperTest file
<del> *
<del> * PHP 5
<del> *
<ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
<ide> * Copyright 2005-2012, Cake Software Foundation, Inc.
<ide> *
<ide> *
<ide> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc.
<ide> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
<del> * @package Cake.Test.Case.View.Helper
<ide> * @since CakePHP(tm) v 1.2.0.4206
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<ide> /**
<ide> * ContactTestController class
<ide> *
<del> * @package cake
<del> * @package Cake.Test.Case.View.Helper
<add> * @package Cake.Test.Case.View.Helper
<ide> */
<ide> class ContactTestController extends Controller {
<ide>
<ide> public function testRadioOptionWithZeroValue() {
<ide> 'legend' => array(),
<ide> 'Field',
<ide> '/legend',
<del> array('input' => array('type' => 'radio', 'name' => 'data[Model][field]', 'value' => '1', 'id' => 'ModelField1')),
<add> array('input' => array('type' => 'radio', 'name' => 'Model[field]', 'value' => '1', 'id' => 'ModelField1')),
<ide> array('label' => array('for' => 'ModelField1')),
<ide> 'Yes',
<ide> '/label',
<del> array('input' => array('type' => 'radio', 'name' => 'data[Model][field]', 'value' => '0', 'id' => 'ModelField0', 'checked' => 'checked')),
<add> array('input' => array('type' => 'radio', 'name' => 'Model[field]', 'value' => '0', 'id' => 'ModelField0', 'checked' => 'checked')),
<ide> array('label' => array('for' => 'ModelField0')),
<ide> 'No',
<ide> '/label',
<ide> public function testRadioOptionWithZeroValue() {
<ide> 'legend' => array(),
<ide> 'Field',
<ide> '/legend',
<del> 'input' => array('type' => 'hidden', 'name' => 'data[Model][field]', 'value' => '', 'id' => 'ModelField_'),
<del> array('input' => array('type' => 'radio', 'name' => 'data[Model][field]', 'value' => '1', 'id' => 'ModelField1')),
<add> 'input' => array('type' => 'hidden', 'name' => 'Model[field]', 'value' => '', 'id' => 'ModelField_'),
<add> array('input' => array('type' => 'radio', 'name' => 'Model[field]', 'value' => '1', 'id' => 'ModelField1')),
<ide> array('label' => array('for' => 'ModelField1')),
<ide> 'Yes',
<ide> '/label',
<del> array('input' => array('type' => 'radio', 'name' => 'data[Model][field]', 'value' => '0', 'id' => 'ModelField0')),
<add> array('input' => array('type' => 'radio', 'name' => 'Model[field]', 'value' => '0', 'id' => 'ModelField0')),
<ide> array('label' => array('for' => 'ModelField0')),
<ide> 'No',
<ide> '/label',
<ide><path>lib/Cake/Test/TestCase/View/Helper/HtmlHelperTest.php
<ide> public function testImageWithFullBase() {
<ide> $request = $this->Html->request;
<ide> $request->webroot = '/myproject/';
<ide> $request->base = '/myproject';
<del> Router::setRequestInfo($request);
<add> Router::pushRequest($request);
<ide>
<ide> $result = $this->Html->image('sub/test.gif', array('fullBase' => true));
<ide> $here = $this->Html->url('/', true);
<ide><path>lib/Cake/Test/TestCase/View/JsonViewTest.php
<ide> <?php
<ide> /**
<del> * JsonViewTest file
<del> *
<del> * PHP 5
<del> *
<ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
<ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> *
<ide> *
<ide> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
<del> * @package Cake.Test.Case.View
<ide> * @since CakePHP(tm) v 2.1.0
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<ide> /**
<ide> * JsonViewTest
<ide> *
<del> * @package Cake.Test.Case.View
<add> * @package Cake.Test.Case.View
<ide> */
<ide> class JsonViewTest extends TestCase {
<ide>
<ide> public function testRenderWithoutViewMultiple() {
<ide> * @return void
<ide> */
<ide> public function testRenderWithView() {
<del> App::build(array(
<del> 'View' => array(CAKE . 'Test/TestApp/View/')
<del> ));
<add> App::build([
<add> 'View' => [CAKE . 'Test/TestApp/View/']
<add> ]);
<ide> $Request = new Request();
<del> $Request->params['named'] = array('page' => 2);
<ide> $Response = new Response();
<ide> $Controller = new Controller($Request, $Response);
<ide> $Controller->name = $Controller->viewPath = 'Posts';
<ide>
<del> $data = array(
<del> 'User' => array(
<add> $data = [
<add> 'User' => [
<ide> 'username' => 'fake'
<del> ),
<del> 'Item' => array(
<del> array('name' => 'item1'),
<del> array('name' => 'item2')
<del> )
<del> );
<add> ],
<add> 'Item' => [
<add> ['name' => 'item1'],
<add> ['name' => 'item2']
<add> ]
<add> ];
<ide> $Controller->set('user', $data);
<ide> $View = new JsonView($Controller);
<del> $View->helpers = array('Paginator');
<add> $View->helpers = ['Paginator'];
<ide> $output = $View->render('index');
<ide>
<del> $expected = json_encode(array('user' => 'fake', 'list' => array('item1', 'item2'), 'paging' => array('page' => 2)));
<add> $expected = json_encode(['user' => 'fake', 'list' => ['item1', 'item2'], 'paging' => []]);
<ide> $this->assertSame($expected, $output);
<ide> $this->assertSame('application/json', $Response->type());
<ide> }
<ide><path>lib/Cake/View/Helper/PaginatorHelper.php
<ide> <?php
<ide> /**
<del> * Pagination Helper class file.
<del> *
<del> * Generates pagination links
<del> *
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> *
<ide> *
<ide> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> * @link http://cakephp.org CakePHP(tm) Project
<del> * @package Cake.View.Helper
<ide> * @since CakePHP(tm) v 1.2.0
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<ide> *
<ide> * PaginationHelper encloses all methods needed when working with pagination.
<ide> *
<del> * @package Cake.View.Helper
<del> * @property HtmlHelper $Html
<add> * @package Cake.View.Helper
<add> * @property HtmlHelper $Html
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html
<ide> */
<ide> class PaginatorHelper extends Helper {
| 8
|
Mixed
|
Python
|
add file option to generateschema
|
f81ca786427db40b648b5bcc0e67044163215457
|
<ide><path>docs/api-guide/schemas.md
<ide> into the commonly used YAML-based OpenAPI format.
<ide> If your schema is static, you can use the `generateschema` management command:
<ide>
<ide> ```bash
<del>./manage.py generateschema > openapi-schema.yml
<add>./manage.py generateschema --file openapi-schema.yml
<ide> ```
<ide>
<ide> Once you've generated a schema in this way you can annotate it with any
<ide><path>rest_framework/management/commands/generateschema.py
<ide> def add_arguments(self, parser):
<ide> parser.add_argument('--format', dest="format", choices=['openapi', 'openapi-json'], default='openapi', type=str)
<ide> parser.add_argument('--urlconf', dest="urlconf", default=None, type=str)
<ide> parser.add_argument('--generator_class', dest="generator_class", default=None, type=str)
<add> parser.add_argument('--file', dest="file", default=None, type=str)
<ide>
<ide> def handle(self, *args, **options):
<ide> if options['generator_class']:
<ide> def handle(self, *args, **options):
<ide> schema = generator.get_schema(request=None, public=True)
<ide> renderer = self.get_renderer(options['format'])
<ide> output = renderer.render(schema, renderer_context={})
<del> self.stdout.write(output.decode())
<add>
<add> if options['file']:
<add> with open(options['file'], 'wb') as f:
<add> f.write(output)
<add> else:
<add> self.stdout.write(output.decode())
<ide>
<ide> def get_renderer(self, format):
<ide> if self.get_mode() == COREAPI_MODE:
<ide><path>tests/schemas/test_managementcommand.py
<ide> import io
<add>import os
<add>import tempfile
<ide>
<ide> import pytest
<ide> from django.conf.urls import url
<ide> def test_accepts_custom_schema_generator(self):
<ide> out_json = yaml.safe_load(self.out.getvalue())
<ide> assert out_json == CustomSchemaGenerator.SCHEMA
<ide>
<add> def test_writes_schema_to_file_on_parameter(self):
<add> fd, path = tempfile.mkstemp()
<add> try:
<add> call_command('generateschema', '--file={}'.format(path), stdout=self.out)
<add> # nothing on stdout
<add> assert not self.out.getvalue()
<add>
<add> call_command('generateschema', stdout=self.out)
<add> expected_out = self.out.getvalue()
<add> # file output identical to stdout output
<add> with os.fdopen(fd) as fh:
<add> assert expected_out and fh.read() == expected_out
<add> finally:
<add> os.remove(path)
<add>
<ide> @pytest.mark.skipif(yaml is None, reason='PyYAML is required.')
<ide> @override_settings(REST_FRAMEWORK={'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.AutoSchema'})
<ide> def test_coreapi_renders_default_schema_with_custom_title_url_and_description(self):
| 3
|
Javascript
|
Javascript
|
react native fixups
|
2bbdbc704d93356343cf10af3983c12c8ee0b8e1
|
<ide><path>Examples/UIExplorer/ExampleTypes.js
<ide>
<ide> export type Example = {
<ide> title: string,
<add> /* $FlowFixMe(>=0.16.0) */
<ide> render: () => ?ReactElement<any, any, any>,
<ide> description?: string,
<ide> platform?: string;
<ide><path>Libraries/PushNotificationIOS/PushNotificationIOS.js
<ide> class PushNotificationIOS {
<ide> * Listening to the `notification` event and invoking
<ide> * `popInitialNotification` is sufficient
<ide> */
<del> constructor(nativeNotif) {
<add> constructor(nativeNotif: Object) {
<ide> this._data = {};
<ide>
<ide> // Extract data from Apple's `aps` dict as defined:
| 2
|
Python
|
Python
|
fix backfill crash on task retry or reschedule
|
1ec63123c4310f2343dcd7c349f90063c401c0d9
|
<ide><path>airflow/jobs/backfill_job.py
<ide> def _update_counters(self, ti_status, session=None):
<ide>
<ide> for ti in refreshed_tis:
<ide> # Here we remake the key by subtracting 1 to match in memory information
<del> key = ti.key.reduced
<add> reduced_key = ti.key.reduced
<ide> if ti.state == State.SUCCESS:
<del> ti_status.succeeded.add(key)
<add> ti_status.succeeded.add(reduced_key)
<ide> self.log.debug("Task instance %s succeeded. Don't rerun.", ti)
<del> ti_status.running.pop(key)
<add> ti_status.running.pop(reduced_key)
<ide> continue
<ide> if ti.state == State.SKIPPED:
<del> ti_status.skipped.add(key)
<add> ti_status.skipped.add(reduced_key)
<ide> self.log.debug("Task instance %s skipped. Don't rerun.", ti)
<del> ti_status.running.pop(key)
<add> ti_status.running.pop(reduced_key)
<ide> continue
<ide> if ti.state == State.FAILED:
<ide> self.log.error("Task instance %s failed", ti)
<del> ti_status.failed.add(key)
<del> ti_status.running.pop(key)
<add> ti_status.failed.add(reduced_key)
<add> ti_status.running.pop(reduced_key)
<ide> continue
<ide> # special case: if the task needs to run again put it back
<ide> if ti.state == State.UP_FOR_RETRY:
<ide> self.log.warning("Task instance %s is up for retry", ti)
<del> ti_status.running.pop(key)
<del> ti_status.to_run[key] = ti
<add> ti_status.running.pop(reduced_key)
<add> ti_status.to_run[ti.key] = ti
<ide> # special case: if the task needs to be rescheduled put it back
<ide> elif ti.state == State.UP_FOR_RESCHEDULE:
<ide> self.log.warning("Task instance %s is up for reschedule", ti)
<del> ti_status.running.pop(key)
<del> ti_status.to_run[key] = ti
<add> ti_status.running.pop(reduced_key)
<add> ti_status.to_run[ti.key] = ti
<ide> # special case: The state of the task can be set to NONE by the task itself
<ide> # when it reaches concurrency limits. It could also happen when the state
<ide> # is changed externally, e.g. by clearing tasks from the ui. We need to cover
<ide> def _update_counters(self, ti_status, session=None):
<ide> ti,
<ide> )
<ide> tis_to_be_scheduled.append(ti)
<del> ti_status.running.pop(key)
<del> ti_status.to_run[key] = ti
<add> ti_status.running.pop(reduced_key)
<add> ti_status.to_run[ti.key] = ti
<ide>
<ide> # Batch schedule of task instances
<ide> if tis_to_be_scheduled:
<ide><path>tests/jobs/test_backfill_job.py
<ide> from airflow.exceptions import (
<ide> AirflowException,
<ide> AirflowTaskTimeout,
<add> BackfillUnfinished,
<ide> DagConcurrencyLimitReached,
<ide> NoAvailablePoolSlot,
<ide> TaskConcurrencyLimitReached,
<ide> )
<ide> from airflow.jobs.backfill_job import BackfillJob
<ide> from airflow.models import DAG, DagBag, Pool, TaskInstance as TI
<ide> from airflow.models.dagrun import DagRun
<add>from airflow.models.taskinstance import TaskInstanceKey
<ide> from airflow.operators.dummy import DummyOperator
<ide> from airflow.utils import timezone
<ide> from airflow.utils.session import create_session
<ide> def test_backfill_rerun_failed_tasks_without_flag(self):
<ide> with pytest.raises(AirflowException):
<ide> job.run()
<ide>
<add> def test_backfill_retry_intermittent_failed_task(self):
<add> dag = DAG(
<add> dag_id='test_intermittent_failure_job',
<add> start_date=DEFAULT_DATE,
<add> schedule_interval="@daily",
<add> default_args={
<add> 'retries': 2,
<add> 'retry_delay': datetime.timedelta(seconds=0),
<add> },
<add> )
<add> task1 = DummyOperator(task_id="task1", dag=dag)
<add> dag.clear()
<add>
<add> executor = MockExecutor(parallelism=16)
<add> executor.mock_task_results[
<add> TaskInstanceKey(dag.dag_id, task1.task_id, DEFAULT_DATE, try_number=1)
<add> ] = State.UP_FOR_RETRY
<add> executor.mock_task_results[
<add> TaskInstanceKey(dag.dag_id, task1.task_id, DEFAULT_DATE, try_number=2)
<add> ] = State.UP_FOR_RETRY
<add> job = BackfillJob(
<add> dag=dag,
<add> executor=executor,
<add> start_date=DEFAULT_DATE,
<add> end_date=DEFAULT_DATE + datetime.timedelta(days=2),
<add> )
<add> job.run()
<add>
<add> def test_backfill_retry_always_failed_task(self):
<add> dag = DAG(
<add> dag_id='test_always_failure_job',
<add> start_date=DEFAULT_DATE,
<add> schedule_interval="@daily",
<add> default_args={
<add> 'retries': 1,
<add> 'retry_delay': datetime.timedelta(seconds=0),
<add> },
<add> )
<add> task1 = DummyOperator(task_id="task1", dag=dag)
<add> dag.clear()
<add>
<add> executor = MockExecutor(parallelism=16)
<add> executor.mock_task_results[
<add> TaskInstanceKey(dag.dag_id, task1.task_id, DEFAULT_DATE, try_number=1)
<add> ] = State.UP_FOR_RETRY
<add> executor.mock_task_fail(dag.dag_id, task1.task_id, DEFAULT_DATE, try_number=2)
<add> job = BackfillJob(
<add> dag=dag,
<add> executor=executor,
<add> start_date=DEFAULT_DATE,
<add> end_date=DEFAULT_DATE,
<add> )
<add> with self.assertRaises(BackfillUnfinished):
<add> job.run()
<add>
<ide> def test_backfill_ordered_concurrent_execute(self):
<ide> dag = DAG(
<ide> dag_id='test_backfill_ordered_concurrent_execute',
<ide><path>tests/test_utils/mock_executor.py
<ide> def sort_by(item):
<ide> for index in range(min((open_slots, len(sorted_queue)))):
<ide> (key, (_, _, _, ti)) = sorted_queue[index]
<ide> self.queued_tasks.pop(key)
<add> ti._try_number += 1
<ide> state = self.mock_task_results[key]
<ide> ti.set_state(state, session=session)
<ide> self.change_state(key, state)
| 3
|
Ruby
|
Ruby
|
fix rubocop warnings
|
ae43b79ca2b4e9ad595fbc70854423e214206102
|
<ide><path>Library/Homebrew/cmd/missing.rb
<ide> def missing
<ide>
<ide> Diagnostic.missing_deps(ff) do |name, missing|
<ide> print "#{name}: " if ff.size > 1
<del> puts "#{missing * " "}"
<add> puts (missing * " ").to_s
<ide> end
<ide> end
<ide> end
| 1
|
Javascript
|
Javascript
|
make reacttransitiongroup work with a null child
|
c75899f27753c5f67cdbd7b73606fe97bda8ded9
|
<ide><path>src/addons/transitions/ReactTransitionGroup.js
<ide> var ReactTransitionGroup = React.createClass({
<ide> var children = {};
<ide> var childMapping = ReactTransitionKeySet.getChildMapping(sourceChildren);
<ide>
<add> var prevKeys = this._transitionGroupCurrentKeys;
<ide> var currentKeys = ReactTransitionKeySet.mergeKeySets(
<del> this._transitionGroupCurrentKeys,
<add> prevKeys,
<ide> ReactTransitionKeySet.getKeySet(sourceChildren)
<ide> );
<ide>
<ide> var ReactTransitionGroup = React.createClass({
<ide> // may look up an old key in the new children, and it may switch to
<ide> // undefined. React's reconciler will keep the ReactTransitionableChild
<ide> // instance alive such that we can animate it.
<del> if (childMapping[key] || this.props.transitionLeave) {
<add> if (childMapping[key] || (this.props.transitionLeave && prevKeys[key])) {
<ide> children[key] = ReactTransitionableChild({
<ide> name: this.props.transitionName,
<ide> enter: this.props.transitionEnter,
<ide><path>src/addons/transitions/__tests__/ReactTransitionGroup-test.js
<ide> describe('ReactTransitionGroup', function() {
<ide> expect(a.getDOMNode().childNodes[1].id).toBe('two');
<ide> });
<ide>
<del> describe('with an undefined child', function () {
<del> it('should fail silently', function () {
<del> React.renderComponent(
<del> <ReactTransitionGroup transitionName="yolo">
<del> </ReactTransitionGroup>,
<del> container
<del> );
<del> });
<add> it('should work with no children', function () {
<add> React.renderComponent(
<add> <ReactTransitionGroup transitionName="yolo">
<add> </ReactTransitionGroup>,
<add> container
<add> );
<add> });
<add>
<add> it('should work with a null child', function () {
<add> React.renderComponent(
<add> <ReactTransitionGroup transitionName="yolo">
<add> {[null]}
<add> </ReactTransitionGroup>,
<add> container
<add> );
<ide> });
<ide> });
| 2
|
PHP
|
PHP
|
adjust all tests to use assertmpttvalues
|
c461b22559cef212136666018ab871e00d52a8eb
|
<ide><path>tests/TestCase/ORM/Behavior/TreeBehaviorTest.php
<ide> public function testAssertMpttValues()
<ide> '15:16 - 8:Link 8'
<ide> ];
<ide> $this->assertMpttValues($expected, $table);
<add>
<add> $table->removeBehavior('Tree');
<add> $table->addBehavior('Tree', ['scope' => ['menu' => 'categories']]);
<add> $expected = [
<add> ' 1:10 - 9:electronics',
<add> '_ 2: 9 - 10:televisions',
<add> '__ 3: 4 - 11:tube',
<add> '__ 5: 8 - 12:lcd',
<add> '___ 6: 7 - 13:plasma',
<add> '11:20 - 14:portable',
<add> '_12:15 - 15:mp3',
<add> '__13:14 - 16:flash',
<add> '_16:17 - 17:cd',
<add> '_18:19 - 18:radios'
<add> ];
<add> $this->assertMpttValues($expected, $table);
<ide> }
<ide>
<ide> /**
<ide> public function testMoveUp()
<ide> // top level, won't move
<ide> $node = $this->table->moveUp($table->get(1), 10);
<ide> $this->assertEquals(['lft' => 1, 'rght' => 10], $node->extract(['lft', 'rght']));
<add> $expected = [
<add> ' 1:10 - 1:Link 1',
<add> '_ 2: 3 - 2:Link 2',
<add> '_ 4: 9 - 3:Link 3',
<add> '__ 5: 8 - 4:Link 4',
<add> '___ 6: 7 - 5:Link 5',
<add> '11:14 - 6:Link 6',
<add> '_12:13 - 7:Link 7',
<add> '15:16 - 8:Link 8'
<add> ];
<add> $this->assertMpttValues($expected, $table);
<ide>
<ide> // edge cases
<ide> $this->assertFalse($this->table->moveUp($table->get(1), 0));
<ide> $node = $this->table->moveUp($table->get(1), -10);
<ide> $this->assertEquals(['lft' => 1, 'rght' => 10], $node->extract(['lft', 'rght']));
<add> $expected = [
<add> ' 1:10 - 1:Link 1',
<add> '_ 2: 3 - 2:Link 2',
<add> '_ 4: 9 - 3:Link 3',
<add> '__ 5: 8 - 4:Link 4',
<add> '___ 6: 7 - 5:Link 5',
<add> '11:14 - 6:Link 6',
<add> '_12:13 - 7:Link 7',
<add> '15:16 - 8:Link 8'
<add> ];
<add> $this->assertMpttValues($expected, $table);
<ide>
<ide> // move inner node
<ide> $node = $table->moveUp($table->get(3), 1);
<ide> $nodes = $table->find('children', ['for' => 1])->all();
<del> $this->assertEquals([3, 4, 5, 2], $nodes->extract('id')->toArray());
<ide> $this->assertEquals(['lft' => 2, 'rght' => 7], $node->extract(['lft', 'rght']));
<add> $expected = [
<add> ' 1:10 - 1:Link 1',
<add> '_ 2: 7 - 3:Link 3',
<add> '__ 3: 6 - 4:Link 4',
<add> '___ 4: 5 - 5:Link 5',
<add> '_ 8: 9 - 2:Link 2',
<add> '11:14 - 6:Link 6',
<add> '_12:13 - 7:Link 7',
<add> '15:16 - 8:Link 8'
<add> ];
<add> $this->assertMpttValues($expected, $table);
<ide> }
<ide>
<ide> /**
<ide> public function testMoveLeaf()
<ide> $table->addBehavior('Tree', ['scope' => ['menu' => 'main-menu']]);
<ide> $node = $table->moveUp($table->get(5), 1);
<ide> $this->assertEquals(['lft' => 6, 'rght' => 7], $node->extract(['lft', 'rght']));
<add> $expected = [
<add> ' 1:10 - 1:Link 1',
<add> '_ 2: 3 - 2:Link 2',
<add> '_ 4: 9 - 3:Link 3',
<add> '__ 5: 8 - 4:Link 4',
<add> '___ 6: 7 - 5:Link 5',
<add> '11:14 - 6:Link 6',
<add> '_12:13 - 7:Link 7',
<add> '15:16 - 8:Link 8'
<add> ];
<add> $this->assertMpttValues($expected, $table);
<ide> }
<ide>
<ide> /**
<ide> public function testMoveTop()
<ide> $table = TableRegistry::get('MenuLinkTrees');
<ide> $table->addBehavior('Tree', ['scope' => ['menu' => 'main-menu']]);
<ide> $node = $table->moveUp($table->get(8), true);
<del> $this->assertEquals(['lft' => 1, 'rght' => 2], $node->extract(['lft', 'rght']));
<del> $nodes = $table->find()
<del> ->select(['id'])
<del> ->where(function ($exp) {
<del> return $exp->isNull('parent_id');
<del> })
<del> ->where(['menu' => 'main-menu'])
<del> ->order(['lft' => 'ASC'])
<del> ->all();
<del> $this->assertEquals([8, 1, 6], $nodes->extract('id')->toArray());
<add> $expected = [
<add> ' 1: 2 - 8:Link 8',
<add> ' 3:12 - 1:Link 1',
<add> '_ 4: 5 - 2:Link 2',
<add> '_ 6:11 - 3:Link 3',
<add> '__ 7:10 - 4:Link 4',
<add> '___ 8: 9 - 5:Link 5',
<add> '13:16 - 6:Link 6',
<add> '_14:15 - 7:Link 7'
<add> ];
<add> $this->assertMpttValues($expected, $table);
<ide> }
<ide>
<ide> /**
<ide> public function testMoveNoTreeColumns()
<ide> $node->unsetProperty('rght');
<ide> $node = $table->moveUp($node, true);
<ide> $this->assertEquals(['lft' => 1, 'rght' => 2], $node->extract(['lft', 'rght']));
<del> $nodes = $table->find()
<del> ->select(['id'])
<del> ->where(function ($exp) {
<del> return $exp->isNull('parent_id');
<del> })
<del> ->where(['menu' => 'main-menu'])
<del> ->order(['lft' => 'ASC'])
<del> ->all();
<del> $this->assertEquals([8, 1, 6], $nodes->extract('id')->toArray());
<add> $expected = [
<add> ' 1: 2 - 8:Link 8',
<add> ' 3:12 - 1:Link 1',
<add> '_ 4: 5 - 2:Link 2',
<add> '_ 6:11 - 3:Link 3',
<add> '__ 7:10 - 4:Link 4',
<add> '___ 8: 9 - 5:Link 5',
<add> '13:16 - 6:Link 6',
<add> '_14:15 - 7:Link 7'
<add> ];
<add> $this->assertMpttValues($expected, $table);
<ide> }
<ide>
<ide> /**
<ide> public function testMoveDown()
<ide> $table = TableRegistry::get('MenuLinkTrees');
<ide> $table->addBehavior('Tree', ['scope' => ['menu' => 'main-menu']]);
<ide> // latest node, won't move
<del> $node = $this->table->moveDown($table->get(8), 10);
<del> $this->assertEquals(['lft' => 21, 'rght' => 22], $node->extract(['lft', 'rght']));
<add> $node = $table->moveDown($table->get(8), 10);
<add> $this->assertEquals(['lft' => 15, 'rght' => 16], $node->extract(['lft', 'rght']));
<add> $expected = [
<add> ' 1:10 - 1:Link 1',
<add> '_ 2: 3 - 2:Link 2',
<add> '_ 4: 9 - 3:Link 3',
<add> '__ 5: 8 - 4:Link 4',
<add> '___ 6: 7 - 5:Link 5',
<add> '11:14 - 6:Link 6',
<add> '_12:13 - 7:Link 7',
<add> '15:16 - 8:Link 8'
<add> ];
<add> $this->assertMpttValues($expected, $table);
<ide>
<ide> // edge cases
<ide> $this->assertFalse($this->table->moveDown($table->get(8), 0));
<add> $expected = [
<add> ' 1:10 - 1:Link 1',
<add> '_ 2: 3 - 2:Link 2',
<add> '_ 4: 9 - 3:Link 3',
<add> '__ 5: 8 - 4:Link 4',
<add> '___ 6: 7 - 5:Link 5',
<add> '11:14 - 6:Link 6',
<add> '_12:13 - 7:Link 7',
<add> '15:16 - 8:Link 8'
<add> ];
<add> $this->assertMpttValues($expected, $table);
<ide>
<ide> // move inner node
<ide> $node = $table->moveDown($table->get(2), 1);
<del> $nodes = $table->find('children', ['for' => 1])->all();
<del> $this->assertEquals([3, 4, 5, 2], $nodes->extract('id')->toArray());
<del> $this->assertEquals(['lft' => 11, 'rght' => 12], $node->extract(['lft', 'rght']));
<add> $this->assertEquals(['lft' => 8, 'rght' => 9], $node->extract(['lft', 'rght']));
<add> $expected = [
<add> ' 1:10 - 1:Link 1',
<add> '_ 2: 7 - 3:Link 3',
<add> '__ 3: 6 - 4:Link 4',
<add> '___ 4: 5 - 5:Link 5',
<add> '_ 8: 9 - 2:Link 2',
<add> '11:14 - 6:Link 6',
<add> '_12:13 - 7:Link 7',
<add> '15:16 - 8:Link 8'
<add> ];
<add> $this->assertMpttValues($expected, $table);
<ide> }
<ide>
<ide> /**
<ide> public function testMoveLeafDown()
<ide> $table->addBehavior('Tree', ['scope' => ['menu' => 'main-menu']]);
<ide> $node = $table->moveDown($table->get(5), 1);
<ide> $this->assertEquals(['lft' => 6, 'rght' => 7], $node->extract(['lft', 'rght']));
<add> $expected = [
<add> ' 1:10 - 1:Link 1',
<add> '_ 2: 3 - 2:Link 2',
<add> '_ 4: 9 - 3:Link 3',
<add> '__ 5: 8 - 4:Link 4',
<add> '___ 6: 7 - 5:Link 5',
<add> '11:14 - 6:Link 6',
<add> '_12:13 - 7:Link 7',
<add> '15:16 - 8:Link 8'
<add> ];
<add> $this->assertMpttValues($expected, $table);
<ide> }
<ide>
<ide> /**
<ide> public function testMoveToBottom()
<ide> $table->addBehavior('Tree', ['scope' => ['menu' => 'main-menu']]);
<ide> $node = $table->moveDown($table->get(1), true);
<ide> $this->assertEquals(['lft' => 7, 'rght' => 16], $node->extract(['lft', 'rght']));
<del> $nodes = $table->find()
<del> ->select(['id'])
<del> ->where(function ($exp) {
<del> return $exp->isNull('parent_id');
<del> })
<del> ->where(['menu' => 'main-menu'])
<del> ->order(['lft' => 'ASC'])
<del> ->all();
<del> $this->assertEquals([6, 8, 1], $nodes->extract('id')->toArray());
<add> $expected = [
<add> ' 1: 4 - 6:Link 6',
<add> '_ 2: 3 - 7:Link 7',
<add> ' 5: 6 - 8:Link 8',
<add> ' 7:16 - 1:Link 1',
<add> '_ 8: 9 - 2:Link 2',
<add> '_10:15 - 3:Link 3',
<add> '__11:14 - 4:Link 4',
<add> '___12:13 - 5:Link 5'
<add> ];
<add> $this->assertMpttValues($expected, $table);
<ide> }
<ide>
<ide> /**
<ide> public function testMoveDownNoTreeColumns()
<ide> $node->unsetProperty('rght');
<ide> $node = $table->moveDown($node, true);
<ide> $this->assertEquals(['lft' => 7, 'rght' => 16], $node->extract(['lft', 'rght']));
<del> $nodes = $table->find()
<del> ->select(['id'])
<del> ->where(function ($exp) {
<del> return $exp->isNull('parent_id');
<del> })
<del> ->where(['menu' => 'main-menu'])
<del> ->order(['lft' => 'ASC'])
<del> ->all();
<del> $this->assertEquals([6, 8, 1], $nodes->extract('id')->toArray());
<add> $expected = [
<add> ' 1: 4 - 6:Link 6',
<add> '_ 2: 3 - 7:Link 7',
<add> ' 5: 6 - 8:Link 8',
<add> ' 7:16 - 1:Link 1',
<add> '_ 8: 9 - 2:Link 2',
<add> '_10:15 - 3:Link 3',
<add> '__11:14 - 4:Link 4',
<add> '___12:13 - 5:Link 5'
<add> ];
<add> $this->assertMpttValues($expected, $table);
<ide> }
<ide>
<ide> public function testMoveDownMultiplePositions()
<ide> {
<ide> $node = $this->table->moveDown($this->table->get(3), 2);
<del> $result = $this->table
<del> ->find('children', ['for' => 2, 'direct' => true])
<del> ->order(['lft' => 'ASC'])
<del> ->extract('id')
<del> ->toArray();
<del>
<del> $this->assertEquals([4,5,3], $result);
<add> $this->assertEquals(['lft' => 7, 'rght' => 8], $node->extract(['lft', 'rght']));
<add> $expected = [
<add> ' 1:20 - 1:electronics',
<add> '_ 2: 9 - 2:televisions',
<add> '__ 3: 4 - 4:lcd',
<add> '__ 5: 6 - 5:plasma',
<add> '__ 7: 8 - 3:tube',
<add> '_10:19 - 6:portable',
<add> '__11:14 - 7:mp3',
<add> '___12:13 - 8:flash',
<add> '__15:16 - 9:cd',
<add> '__17:18 - 10:radios',
<add> '21:22 - 11:alien hardware'
<add> ];
<add> $this->assertMpttValues($expected, $this->table);
<ide> }
<ide>
<ide> /**
<ide> public function testMoveDownMultiplePositions()
<ide> public function testRecover()
<ide> {
<ide> $table = $this->table;
<del> $expected = $table->find()->order('lft')->hydrate(false)->toArray();
<ide> $table->updateAll(['lft' => null, 'rght' => null], []);
<ide> $table->recover();
<del> $result = $table->find()->order('lft')->hydrate(false)->toArray();
<del> $this->assertEquals($expected, $result);
<add>
<add> $expected = [
<add> ' 1:20 - 1:electronics',
<add> '_ 2: 9 - 2:televisions',
<add> '__ 3: 4 - 3:tube',
<add> '__ 5: 6 - 4:lcd',
<add> '__ 7: 8 - 5:plasma',
<add> '_10:19 - 6:portable',
<add> '__11:14 - 7:mp3',
<add> '___12:13 - 8:flash',
<add> '__15:16 - 9:cd',
<add> '__17:18 - 10:radios',
<add> '21:22 - 11:alien hardware'
<add> ];
<add> $this->assertMpttValues($expected, $this->table);
<ide> }
<ide>
<ide> /**
<ide> public function testRecoverScoped()
<ide> ->hydrate(false)
<ide> ->toArray();
<ide>
<del> $expected2 = $table->find()
<del> ->where(['menu' => 'categories'])
<del> ->order('lft')
<del> ->hydrate(false)
<del> ->toArray();
<ide>
<ide> $table->updateAll(['lft' => null, 'rght' => null], ['menu' => 'main-menu']);
<ide> $table->recover();
<del> $result = $table->find()
<del> ->where(['menu' => 'main-menu'])
<del> ->order('lft')
<del> ->hydrate(false)
<del> ->toArray();
<del> $this->assertEquals($expected, $result);
<ide>
<del> $result2 = $table->find()
<del> ->where(['menu' => 'categories'])
<del> ->order('lft')
<del> ->hydrate(false)
<del> ->toArray();
<del> $this->assertEquals($expected2, $result2);
<add> $expected = [
<add> ' 1:10 - 1:Link 1',
<add> '_ 2: 3 - 2:Link 2',
<add> '_ 4: 9 - 3:Link 3',
<add> '__ 5: 8 - 4:Link 4',
<add> '___ 6: 7 - 5:Link 5',
<add> '11:14 - 6:Link 6',
<add> '_12:13 - 7:Link 7',
<add> '15:16 - 8:Link 8'
<add> ];
<add> $this->assertMpttValues($expected, $table);
<add>
<add> $table->removeBehavior('Tree');
<add> $table->addBehavior('Tree', ['scope' => ['menu' => 'categories']]);
<add> $expected = [
<add> ' 1:10 - 9:electronics',
<add> '_ 2: 9 - 10:televisions',
<add> '__ 3: 4 - 11:tube',
<add> '__ 5: 8 - 12:lcd',
<add> '___ 6: 7 - 13:plasma',
<add> '11:20 - 14:portable',
<add> '_12:15 - 15:mp3',
<add> '__13:14 - 16:flash',
<add> '_16:17 - 17:cd',
<add> '_18:19 - 18:radios'
<add> ];
<add> $this->assertMpttValues($expected, $table);
<ide> }
<ide>
<ide> /**
<ide> public function testAddOrphan()
<ide> ['name' => 'New Orphan', 'parent_id' => null, 'level' => null],
<ide> ['markNew' => true]
<ide> );
<del> $expected = $table->find()->order('lft')->hydrate(false)->toArray();
<ide> $this->assertSame($entity, $table->save($entity));
<ide> $this->assertEquals(23, $entity->lft);
<ide> $this->assertEquals(24, $entity->rght);
<ide>
<del> $expected[] = $entity->toArray();
<del> $results = $table->find()->order('lft')->hydrate(false)->toArray();
<del> $this->assertEquals($expected, $results);
<add> $expected = [
<add> ' 1:20 - 1:electronics',
<add> '_ 2: 9 - 2:televisions',
<add> '__ 3: 4 - 3:tube',
<add> '__ 5: 6 - 4:lcd',
<add> '__ 7: 8 - 5:plasma',
<add> '_10:19 - 6:portable',
<add> '__11:14 - 7:mp3',
<add> '___12:13 - 8:flash',
<add> '__15:16 - 9:cd',
<add> '__17:18 - 10:radios',
<add> '21:22 - 11:alien hardware',
<add> '23:24 - 12:New Orphan',
<add> ];
<add> $this->assertMpttValues($expected, $this->table);
<ide> }
<ide>
<ide> /**
<ide> public function testAddMiddle()
<ide> $this->assertEquals(20, $entity->lft);
<ide> $this->assertEquals(21, $entity->rght);
<ide>
<del> $result = $table->find()->order('lft')->hydrate(false)->toArray();
<del> $table->recover();
<del> $expected = $table->find()->order('lft')->hydrate(false)->toArray();
<del> $this->assertEquals($expected, $result);
<add> $expected = [
<add> ' 1:22 - 1:electronics',
<add> '_ 2: 9 - 2:televisions',
<add> '__ 3: 4 - 3:tube',
<add> '__ 5: 6 - 4:lcd',
<add> '__ 7: 8 - 5:plasma',
<add> '_10:19 - 6:portable',
<add> '__11:14 - 7:mp3',
<add> '___12:13 - 8:flash',
<add> '__15:16 - 9:cd',
<add> '__17:18 - 10:radios',
<add> '_20:21 - 12:laptops',
<add> '23:24 - 11:alien hardware',
<add> ];
<add> $this->assertMpttValues($expected, $this->table);
<ide> }
<ide>
<ide> /**
<ide> public function testAddLeaf()
<ide> $this->assertEquals(9, $entity->lft);
<ide> $this->assertEquals(10, $entity->rght);
<ide>
<del> $results = $table->find()->order('lft')->hydrate(false)->toArray();
<del> $table->recover();
<del> $expected = $table->find()->order('lft')->hydrate(false)->toArray();
<del> $this->assertEquals($expected, $results);
<add> $expected = [
<add> ' 1:22 - 1:electronics',
<add> '_ 2:11 - 2:televisions',
<add> '__ 3: 4 - 3:tube',
<add> '__ 5: 6 - 4:lcd',
<add> '__ 7: 8 - 5:plasma',
<add> '__ 9:10 - 12:laptops',
<add> '_12:21 - 6:portable',
<add> '__13:16 - 7:mp3',
<add> '___14:15 - 8:flash',
<add> '__17:18 - 9:cd',
<add> '__19:20 - 10:radios',
<add> '23:24 - 11:alien hardware'
<add> ];
<add> $this->assertMpttValues($expected, $this->table);
<ide> }
<ide>
<ide> /**
<ide> public function testReParentSubTreeRight()
<ide>
<ide> $expected = [
<ide> ' 1:20 - 1:electronics',
<del> '_ 2: 7 - 2:televisions',
<del> '__ 3: 4 - 3:tube',
<del> '__ 5: 6 - 4:lcd',
<del> '_ 8:19 - 6:portable',
<del> '__ 9:12 - 7:mp3',
<del> '___10:11 - 8:flash',
<del> '__13:14 - 9:cd',
<del> '__15:16 - 10:radios',
<del> '__17:18 - 5:plasma',
<del> '___16:17 - 4:lcd',
<add> '_ 2:19 - 6:portable',
<add> '__ 3: 6 - 7:mp3',
<add> '___ 4: 5 - 8:flash',
<add> '__ 7: 8 - 9:cd',
<add> '__ 9:10 - 10:radios',
<add> '__11:18 - 2:televisions',
<add> '___12:13 - 3:tube',
<add> '___14:15 - 4:lcd',
<add> '___16:17 - 5:plasma',
<ide> '21:22 - 11:alien hardware'
<ide> ];
<ide> $this->assertMpttValues($expected, $table);
<ide> public function testReParentSubTreeLeft()
<ide> $this->assertEquals(9, $entity->lft);
<ide> $this->assertEquals(18, $entity->rght);
<ide>
<del> $result = $table->find()->order('lft')->hydrate(false)->toArray();
<del> $table->recover();
<del> $expected = $table->find()->order('lft')->hydrate(false)->toArray();
<del> $this->assertEquals($expected, $result);
<add> $expected = [
<add> ' 1:20 - 1:electronics',
<add> '_ 2:19 - 2:televisions',
<add> '__ 3: 4 - 3:tube',
<add> '__ 5: 6 - 4:lcd',
<add> '__ 7: 8 - 5:plasma',
<add> '__ 9:18 - 6:portable',
<add> '___10:13 - 7:mp3',
<add> '____11:12 - 8:flash',
<add> '___14:15 - 9:cd',
<add> '___16:17 - 10:radios',
<add> '21:22 - 11:alien hardware'
<add> ];
<add> $this->assertMpttValues($expected, $this->table);
<ide> }
<ide>
<ide> /**
<ide> public function testReParentLeafLeft()
<ide> $this->assertEquals(9, $entity->lft);
<ide> $this->assertEquals(10, $entity->rght);
<ide>
<del> $result = $table->find()->order('lft')->hydrate(false)->toArray();
<del> $table->recover();
<del> $expected = $table->find()->order('lft')->hydrate(false)->toArray();
<del> $this->assertEquals($expected, $result);
<add> $expected = [
<add> ' 1:20 - 1:electronics',
<add> '_ 2:11 - 2:televisions',
<add> '__ 3: 4 - 3:tube',
<add> '__ 5: 6 - 4:lcd',
<add> '__ 7: 8 - 5:plasma',
<add> '__ 9:10 - 10:radios',
<add> '_12:19 - 6:portable',
<add> '__13:16 - 7:mp3',
<add> '___14:15 - 8:flash',
<add> '__17:18 - 9:cd',
<add> '21:22 - 11:alien hardware'
<add> ];
<add> $this->assertMpttValues($expected, $this->table);
<ide> }
<ide>
<ide> /**
<ide> public function testReParentNoTreeColumns()
<ide> $this->assertEquals(9, $entity->lft);
<ide> $this->assertEquals(18, $entity->rght);
<ide>
<del> $result = $table->find()->order('lft')->hydrate(false)->toArray();
<del> $table->recover();
<del> $expected = $table->find()->order('lft')->hydrate(false)->toArray();
<del> $this->assertEquals($expected, $result);
<add> $expected = [
<add> ' 1:20 - 1:electronics',
<add> '_ 2:19 - 2:televisions',
<add> '__ 3: 4 - 3:tube',
<add> '__ 5: 6 - 4:lcd',
<add> '__ 7: 8 - 5:plasma',
<add> '__ 9:18 - 6:portable',
<add> '___10:13 - 7:mp3',
<add> '____11:12 - 8:flash',
<add> '___14:15 - 9:cd',
<add> '___16:17 - 10:radios',
<add> '21:22 - 11:alien hardware'
<add> ];
<add> $this->assertMpttValues($expected, $this->table);
<ide> }
<ide>
<ide> /**
<ide> public function testRootingSubTree()
<ide> $this->assertEquals(15, $entity->lft);
<ide> $this->assertEquals(22, $entity->rght);
<ide>
<del> $result = $table->find()->order('lft')->hydrate(false);
<del> $expected = [1, 6, 7, 8, 9, 10, 11, 2, 3, 4, 5];
<add> $expected = [
<add> ' 1:12 - 1:electronics',
<add> '_ 2:11 - 6:portable',
<add> '__ 3: 6 - 7:mp3',
<add> '___ 4: 5 - 8:flash',
<add> '__ 7: 8 - 9:cd',
<add> '__ 9:10 - 10:radios',
<add> '13:14 - 11:alien hardware',
<add> '15:22 - 2:televisions',
<add> '_16:17 - 3:tube',
<add> '_18:19 - 4:lcd',
<add> '_20:21 - 5:plasma'
<add> ];
<ide> $this->assertMpttValues($expected, $table);
<ide> }
<ide>
<ide> public function testRootingNoTreeColumns()
<ide> $this->assertEquals(15, $entity->lft);
<ide> $this->assertEquals(22, $entity->rght);
<ide>
<del> $result = $table->find()->order('lft')->hydrate(false);
<del> $expected = [1, 6, 7, 8, 9, 10, 11, 2, 3, 4, 5];
<add> $expected = [
<add> ' 1:12 - 1:electronics',
<add> '_ 2:11 - 6:portable',
<add> '__ 3: 6 - 7:mp3',
<add> '___ 4: 5 - 8:flash',
<add> '__ 7: 8 - 9:cd',
<add> '__ 9:10 - 10:radios',
<add> '13:14 - 11:alien hardware',
<add> '15:22 - 2:televisions',
<add> '_16:17 - 3:tube',
<add> '_18:19 - 4:lcd',
<add> '_20:21 - 5:plasma'
<add> ];
<ide> $this->assertMpttValues($expected, $table);
<ide> }
<ide>
<ide> public function testDeleteLeaf()
<ide> $table = $this->table;
<ide> $entity = $table->get(4);
<ide> $this->assertTrue($table->delete($entity));
<del> $result = $table->find()->order('lft')->hydrate(false)->toArray();
<del> $table->recover();
<del> $expected = $table->find()->order('lft')->hydrate(false)->toArray();
<del> $this->assertEquals($expected, $result);
<add>
<add> $expected = [
<add> ' 1:18 - 1:electronics',
<add> '_ 2: 7 - 2:televisions',
<add> '__ 3: 4 - 3:tube',
<add> '__ 5: 6 - 5:plasma',
<add> '_ 8:17 - 6:portable',
<add> '__ 9:12 - 7:mp3',
<add> '___10:11 - 8:flash',
<add> '__13:14 - 9:cd',
<add> '__15:16 - 10:radios',
<add> '19:20 - 11:alien hardware'
<add> ];
<add> $this->assertMpttValues($expected, $this->table);
<ide> }
<ide>
<ide> /**
<ide> public function testDeleteSubTree()
<ide> $table = $this->table;
<ide> $entity = $table->get(6);
<ide> $this->assertTrue($table->delete($entity));
<del> $result = $table->find()->order('lft')->hydrate(false)->toArray();
<del> $table->recover();
<del> $expected = $table->find()->order('lft')->hydrate(false)->toArray();
<del> $this->assertEquals($expected, $result);
<add>
<add> $expected = [
<add> ' 1:10 - 1:electronics',
<add> '_ 2: 9 - 2:televisions',
<add> '__ 3: 4 - 3:tube',
<add> '__ 5: 6 - 4:lcd',
<add> '__ 7: 8 - 5:plasma',
<add> '11:12 - 11:alien hardware'
<add> ];
<add> $this->assertMpttValues($expected, $this->table);
<ide> }
<ide>
<ide> /**
<ide> public function testDeleteRoot()
<ide> $table = $this->table;
<ide> $entity = $table->get(1);
<ide> $this->assertTrue($table->delete($entity));
<del> $result = $table->find()->order('lft')->hydrate(false)->toArray();
<del> $table->recover();
<del> $expected = $table->find()->order('lft')->hydrate(false)->toArray();
<del> $this->assertEquals($expected, $result);
<add>
<add> $expected = [
<add> ' 1: 2 - 11:alien hardware'
<add> ];
<add> $this->assertMpttValues($expected, $this->table);
<ide> }
<ide>
<ide> /**
<ide> public function testDeleteRootNoTreeColumns()
<ide> $entity->unsetProperty('lft');
<ide> $entity->unsetProperty('rght');
<ide> $this->assertTrue($table->delete($entity));
<del> $result = $table->find()->order('lft')->hydrate(false)->toArray();
<del> $table->recover();
<del> $expected = $table->find()->order('lft')->hydrate(false)->toArray();
<del> $this->assertEquals($expected, $result);
<add>
<add> $expected = [
<add> ' 1: 2 - 11:alien hardware'
<add> ];
<add> $this->assertMpttValues($expected, $this->table);
<ide> }
<ide>
<ide> /**
<ide> public function assertMpttValues($expected, $table, $query = null)
<ide> $displayField = $table->displayField();
<ide>
<ide> $options = [
<del> 'valuePath' => function($item, $key, $iterator) use ($primaryKey, $displayField) {
<add> 'valuePath' => function ($item, $key, $iterator) use ($primaryKey, $displayField) {
<ide> return sprintf(
<ide> '%s:%s - %s:%s',
<ide> str_pad($item->lft, 2, ' ', STR_PAD_LEFT),
| 1
|
Javascript
|
Javascript
|
add dispose method to all controls
|
8bfe403c00b09093bcf7082888696e371671a789
|
<ide><path>examples/js/controls/DeviceOrientationControls.js
<ide> THREE.DeviceOrientationControls = function ( object ) {
<ide>
<ide> };
<ide>
<add> this.dispose = function () {
<add>
<add> this.disconnect();
<add>
<add> };
<add>
<ide> this.connect();
<ide>
<ide> };
<ide><path>examples/js/controls/DragControls.js
<ide> THREE.DragControls = function( _camera, _objects, _domElement ) {
<ide>
<ide> };
<ide>
<add> this.dispose = function() {
<add>
<add> me.deactivate();
<add>
<add> };
<add>
<ide> this.activate();
<ide>
<ide> function onDocumentMouseMove( event ) {
<ide><path>examples/js/controls/EditorControls.js
<ide> THREE.EditorControls = function ( object, domElement ) {
<ide>
<ide> }
<ide>
<del> domElement.addEventListener( 'contextmenu', function ( event ) {
<add> function contextmenu( event ) {
<ide>
<ide> event.preventDefault();
<ide>
<del> }, false );
<add> }
<add>
<add> this.dispose = function() {
<add>
<add> domElement.removeEventListener( 'contextmenu', contextmenu, false );
<add> domElement.removeEventListener( 'mousedown', onMouseDown, false );
<add> domElement.removeEventListener( 'mousewheel', onMouseWheel, false );
<add> domElement.removeEventListener( 'DOMMouseScroll', onMouseWheel, false ); // firefox
<add>
<add> domElement.removeEventListener( 'mousemove', onMouseMove, false );
<add> domElement.removeEventListener( 'mouseup', onMouseUp, false );
<add> domElement.removeEventListener( 'mouseout', onMouseUp, false );
<add> domElement.removeEventListener( 'dblclick', onMouseUp, false );
<add>
<add> domElement.removeEventListener( 'touchstart', touchStart, false );
<add> domElement.removeEventListener( 'touchmove', touchMove, false );
<add>
<add> }
<add>
<add> domElement.addEventListener( 'contextmenu', contextmenu, false );
<ide> domElement.addEventListener( 'mousedown', onMouseDown, false );
<ide> domElement.addEventListener( 'mousewheel', onMouseWheel, false );
<ide> domElement.addEventListener( 'DOMMouseScroll', onMouseWheel, false ); // firefox
<ide><path>examples/js/controls/FirstPersonControls.js
<ide> THREE.FirstPersonControls = function ( object, domElement ) {
<ide>
<ide> };
<ide>
<del>
<del> this.domElement.addEventListener( 'contextmenu', function ( event ) {
<add> function contextmenu( event ) {
<ide>
<ide> event.preventDefault();
<ide>
<del> }, false );
<add> }
<add>
<add> this.dispose = function() {
<add>
<add> this.domElement.removeEventListener( 'contextmenu', contextmenu, false );
<add> this.domElement.removeEventListener( 'mousedown', _onMouseDown, false );
<add> this.domElement.removeEventListener( 'mousemove', _onMouseMove, false );
<add> this.domElement.removeEventListener( 'mouseup', _onMouseUp, false );
<add>
<add> window.removeEventListener( 'keydown', _onKeyDown, false );
<add> window.removeEventListener( 'keyup', _onKeyUp, false );
<add>
<add> }
<add>
<add> var _onMouseMove = bind( this, this.onMouseMove );
<add> var _onMouseDown = bind( this, this.onMouseDown );
<add> var _onMouseUp = bind( this, this.onMouseUp );
<add> var _onKeyDown = bind( this, this.onKeyDown );
<add> var _onKeyUp = bind( this, this.onKeyUp );
<ide>
<del> this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
<del> this.domElement.addEventListener( 'mousedown', bind( this, this.onMouseDown ), false );
<del> this.domElement.addEventListener( 'mouseup', bind( this, this.onMouseUp ), false );
<add> this.domElement.addEventListener( 'contextmenu', contextmenu, false );
<add> this.domElement.addEventListener( 'mousemove', _onMouseMove, false );
<add> this.domElement.addEventListener( 'mousedown', _onMouseDown, false );
<add> this.domElement.addEventListener( 'mouseup', _onMouseUp, false );
<ide>
<del> window.addEventListener( 'keydown', bind( this, this.onKeyDown ), false );
<del> window.addEventListener( 'keyup', bind( this, this.onKeyUp ), false );
<add> window.addEventListener( 'keydown', _onKeyDown, false );
<add> window.addEventListener( 'keyup', _onKeyUp, false );
<ide>
<ide> function bind( scope, fn ) {
<ide>
<ide><path>examples/js/controls/FlyControls.js
<ide> THREE.FlyControls = function ( object, domElement ) {
<ide>
<ide> }
<ide>
<del> this.domElement.addEventListener( 'contextmenu', function ( event ) {
<add> function contextmenu( event ) {
<ide>
<ide> event.preventDefault();
<ide>
<del> }, false );
<add> }
<add>
<add> this.dispose = function() {
<add>
<add> this.domElement.removeEventListener( 'contextmenu', contextmenu, false );
<add> this.domElement.removeEventListener( 'mousedown', _mousedown, false );
<add> this.domElement.removeEventListener( 'mousemove', _mousemove, false );
<add> this.domElement.removeEventListener( 'mouseup', _mouseup, false );
<add>
<add> window.removeEventListener( 'keydown', _keydown, false );
<add> window.removeEventListener( 'keyup', _keyup, false );
<add>
<add> }
<add>
<add> var _mousemove = bind( this, this.mousemove );
<add> var _mousedown = bind( this, this.mousedown );
<add> var _mouseup = bind( this, this.mouseup );
<add> var _keydown = bind( this, this.keydown );
<add> var _keyup = bind( this, this.keyup );
<add>
<add> this.domElement.addEventListener( 'contextmenu', contextmenu, false );
<ide>
<del> this.domElement.addEventListener( 'mousemove', bind( this, this.mousemove ), false );
<del> this.domElement.addEventListener( 'mousedown', bind( this, this.mousedown ), false );
<del> this.domElement.addEventListener( 'mouseup', bind( this, this.mouseup ), false );
<add> this.domElement.addEventListener( 'mousemove', _mousemove, false );
<add> this.domElement.addEventListener( 'mousedown', _mousedown, false );
<add> this.domElement.addEventListener( 'mouseup', _mouseup, false );
<ide>
<del> window.addEventListener( 'keydown', bind( this, this.keydown ), false );
<del> window.addEventListener( 'keyup', bind( this, this.keyup ), false );
<add> window.addEventListener( 'keydown', _keydown, false );
<add> window.addEventListener( 'keyup', _keyup, false );
<ide>
<ide> this.updateMovementVector();
<ide> this.updateRotationVector();
<ide><path>examples/js/controls/MouseControls.js
<ide> THREE.MouseControls = function ( object ) {
<ide>
<ide> };
<ide>
<add> this.dispose = function() {
<add>
<add> document.removeEventListener( 'mousemove', onMouseMove, false );
<add>
<add> }
<add>
<ide> document.addEventListener( 'mousemove', onMouseMove, false );
<ide>
<ide> };
<ide><path>examples/js/controls/OrbitControls.js
<ide>
<ide> }
<ide>
<del> this.domElement.addEventListener( 'contextmenu', function ( event ) {
<add> function contextmenu( event ) {
<ide>
<ide> event.preventDefault();
<ide>
<del> }, false );
<add> }
<add>
<add> this.dispose = function() {
<add>
<add> this.domElement.removeEventListener( 'contextmenu', contextmenu, false );
<add> this.domElement.removeEventListener( 'mousedown', onMouseDown, false );
<add> this.domElement.removeEventListener( 'mousewheel', onMouseWheel, false );
<add> this.domElement.removeEventListener( 'DOMMouseScroll', onMouseWheel, false ); // firefox
<add>
<add> this.domElement.removeEventListener( 'touchstart', touchstart, false );
<add> this.domElement.removeEventListener( 'touchend', touchend, false );
<add> this.domElement.removeEventListener( 'touchmove', touchmove, false );
<add>
<add> document.removeEventListener( 'mousemove', onMouseMove, false );
<add> document.removeEventListener( 'mouseup', onMouseUp, false );
<add>
<add> window.removeEventListener( 'keydown', onKeyDown, false );
<add>
<add> }
<add>
<add> this.domElement.addEventListener( 'contextmenu', contextmenu, false );
<ide>
<ide> this.domElement.addEventListener( 'mousedown', onMouseDown, false );
<ide> this.domElement.addEventListener( 'mousewheel', onMouseWheel, false );
<ide><path>examples/js/controls/OrthographicTrackballControls.js
<ide> THREE.OrthographicTrackballControls = function ( object, domElement ) {
<ide>
<ide> }
<ide>
<del> this.domElement.addEventListener( 'contextmenu', function ( event ) {
<add> function contextmenu( event ) {
<ide>
<ide> event.preventDefault();
<ide>
<del> }, false );
<add> }
<ide>
<del> this.domElement.addEventListener( 'mousedown', mousedown, false );
<add> this.dispose = function() {
<add>
<add> this.domElement.removeEventListener( 'contextmenu', contextmenu, false );
<add> this.domElement.removeEventListener( 'mousedown', mousedown, false );
<add> this.domElement.removeEventListener( 'mousewheel', mousewheel, false );
<add> this.domElement.removeEventListener( 'DOMMouseScroll', mousewheel, false ); // firefox
<add>
<add> this.domElement.removeEventListener( 'touchstart', touchstart, false );
<add> this.domElement.removeEventListener( 'touchend', touchend, false );
<add> this.domElement.removeEventListener( 'touchmove', touchmove, false );
<add>
<add> document.removeEventListener( 'mousemove', mousemove, false );
<add> document.removeEventListener( 'mouseup', mouseup, false );
<ide>
<add> window.removeEventListener( 'keydown', keydown, false );
<add> window.removeEventListener( 'keyup', keyup, false );
<add>
<add> }
<add>
<add>
<add> this.domElement.addEventListener( 'contextmenu', contextmenu, false );
<add> this.domElement.addEventListener( 'mousedown', mousedown, false );
<ide> this.domElement.addEventListener( 'mousewheel', mousewheel, false );
<ide> this.domElement.addEventListener( 'DOMMouseScroll', mousewheel, false ); // firefox
<ide>
<ide><path>examples/js/controls/PointerLockControls.js
<ide> THREE.PointerLockControls = function ( camera ) {
<ide>
<ide> };
<ide>
<add> this.dispose = function() {
<add>
<add> document.removeEventListener( 'mousemove', onMouseMove, false );
<add>
<add> }
<add>
<ide> document.addEventListener( 'mousemove', onMouseMove, false );
<ide>
<ide> this.enabled = false;
<ide><path>examples/js/controls/TrackballControls.js
<ide> THREE.TrackballControls = function ( object, domElement ) {
<ide>
<ide> }
<ide>
<del> this.domElement.addEventListener( 'contextmenu', function ( event ) {
<add> function contextmenu( event ) {
<ide>
<ide> event.preventDefault();
<ide>
<del> }, false );
<add> }
<ide>
<del> this.domElement.addEventListener( 'mousedown', mousedown, false );
<add> this.dispose = function() {
<add>
<add> this.domElement.removeEventListener( 'contextmenu', contextmenu, false );
<add> this.domElement.removeEventListener( 'mousedown', mousedown, false );
<add> this.domElement.removeEventListener( 'mousewheel', mousewheel, false );
<add> this.domElement.removeEventListener( 'DOMMouseScroll', mousewheel, false ); // firefox
<add>
<add> this.domElement.removeEventListener( 'touchstart', touchstart, false );
<add> this.domElement.removeEventListener( 'touchend', touchend, false );
<add> this.domElement.removeEventListener( 'touchmove', touchmove, false );
<add>
<add> document.removeEventListener( 'mousemove', mousemove, false );
<add> document.removeEventListener( 'mouseup', mouseup, false );
<ide>
<add> window.removeEventListener( 'keydown', keydown, false );
<add> window.removeEventListener( 'keyup', keyup, false );
<add>
<add> }
<add>
<add> this.domElement.addEventListener( 'contextmenu', contextmenu, false );
<add> this.domElement.addEventListener( 'mousedown', mousedown, false );
<ide> this.domElement.addEventListener( 'mousewheel', mousewheel, false );
<ide> this.domElement.addEventListener( 'DOMMouseScroll', mousewheel, false ); // firefox
<ide>
<ide><path>examples/js/controls/VRControls.js
<ide> THREE.VRControls = function ( object, onError ) {
<ide>
<ide> };
<ide>
<add> this.dispose = function () {
<add>
<add> vrInputs = [];
<add>
<add> };
<add>
<ide> };
| 11
|
Ruby
|
Ruby
|
run `rails new` using specified prerelease version
|
218412f6a3b17a13fb59c4633736087ecbcd44ae
|
<ide><path>railties/lib/rails/generators/app_base.rb
<ide> def self.add_shared_options_for(name)
<ide> desc: "Show this help message and quit"
<ide> end
<ide>
<del> def initialize(*)
<add> def initialize(positional_argv, option_argv, *)
<add> @argv = [*positional_argv, *option_argv]
<ide> @gem_filter = lambda { |gem| true }
<ide> super
<ide> end
<ide> def rails_prerelease?
<ide>
<ide> def rails_gemfile_entry
<ide> if options.dev?
<del> [
<del> GemfileEntry.path("rails", Rails::Generators::RAILS_DEV_PATH, "Use local checkout of Rails")
<del> ]
<add> GemfileEntry.path("rails", Rails::Generators::RAILS_DEV_PATH, "Use local checkout of Rails")
<ide> elsif options.edge?
<ide> edge_branch = Rails.gem_version.prerelease? ? "main" : [*Rails.gem_version.segments.first(2), "stable"].join("-")
<del> [
<del> GemfileEntry.github("rails", "rails/rails", edge_branch, "Use specific branch of Rails")
<del> ]
<add> GemfileEntry.github("rails", "rails/rails", edge_branch, "Use specific branch of Rails")
<ide> elsif options.main?
<del> [
<del> GemfileEntry.github("rails", "rails/rails", "main", "Use main development branch of Rails")
<del> ]
<add> GemfileEntry.github("rails", "rails/rails", "main", "Use main development branch of Rails")
<ide> else
<del> [GemfileEntry.version("rails",
<del> rails_version_specifier,
<del> %(Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main"))]
<add> GemfileEntry.version("rails", rails_version_specifier,
<add> %(Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main"))
<ide> end
<ide> end
<ide>
<ide> def depend_on_bootsnap?
<ide> !options[:skip_bootsnap] && !options[:dev] && !defined?(JRUBY_VERSION)
<ide> end
<ide>
<add> def target_rails_prerelease(self_command = "new")
<add> return unless rails_prerelease? && bundle_install?
<add>
<add> if !File.exist?(File.expand_path("Gemfile", destination_root))
<add> create_file("Gemfile", <<~GEMFILE)
<add> source "https://rubygems.org"
<add> git_source(:github) { |repo| "https://github.com/\#{repo}.git" }
<add> #{rails_gemfile_entry}
<add> GEMFILE
<add>
<add> run_bundle
<add>
<add> @argv[0] = destination_root
<add> require "shellwords"
<add> bundle_command("exec rails #{self_command} #{Shellwords.join(@argv)}")
<add> exit
<add> else
<add> remove_file("Gemfile")
<add> remove_file("Gemfile.lock")
<add> end
<add> end
<add>
<ide> def run_bundle
<ide> bundle_command("install", "BUNDLE_IGNORE_MESSAGES" => "1") if bundle_install?
<ide> end
<ide><path>railties/lib/rails/generators/rails/app/app_generator.rb
<ide> def initialize(*args)
<ide>
<ide> public_task :set_default_accessors!
<ide> public_task :create_root
<add> public_task :target_rails_prerelease
<ide>
<ide> def create_root_files
<ide> build(:readme)
<ide><path>railties/lib/rails/generators/rails/plugin/plugin_generator.rb
<ide> def initialize(*args)
<ide> public_task :set_default_accessors!
<ide> public_task :create_root
<ide>
<add> def target_rails_prerelease
<add> super("plugin new")
<add> end
<add>
<ide> def create_root_files
<ide> build(:readme)
<ide> build(:rakefile)
<ide><path>railties/lib/rails/generators/testing/behaviour.rb
<ide> def destination(path)
<ide> # printed by the generator.
<ide> def run_generator(args = default_arguments, config = {})
<ide> capture(:stdout) do
<del> args += ["--skip-bundle"] unless args.include? "--dev"
<del> args |= ["--skip-bootsnap"] unless args.include? "--no-skip-bootsnap"
<add> args += ["--skip-bundle"] unless args.include?("--no-skip-bundle") || args.include?("--dev")
<add> args |= ["--skip-bootsnap"] unless args.include?("--no-skip-bootsnap")
<ide>
<ide> generator_class.start(args, config.reverse_merge(destination_root: destination_root))
<ide> end
<ide><path>railties/test/generators/app_generator_test.rb
<ide> def test_generation_use_original_bundle_environment
<ide> end
<ide> end
<ide>
<del> def test_dev_option
<del> generator([destination_root], dev: true)
<del> run_generator_instance
<del>
<del> assert_equal 1, @bundle_commands.count("install")
<del> rails_path = File.expand_path("../../..", Rails.root)
<del> assert_file "Gemfile", /^gem\s+["']rails["'],\s+path:\s+["']#{Regexp.escape(rails_path)}["']$/
<del> end
<del>
<del> def test_edge_option
<del> Rails.stub(:gem_version, Gem::Version.new("2.1.0")) do
<del> generator([destination_root], edge: true)
<del> run_generator_instance
<del> end
<del>
<del> assert_equal 1, @bundle_commands.count("install")
<del> assert_file "Gemfile", %r{^gem\s+["']rails["'],\s+github:\s+["']#{Regexp.escape("rails/rails")}["'],\s+branch:\s+["']2-1-stable["']$}
<del> end
<del>
<del> def test_edge_option_during_alpha
<del> Rails.stub(:gem_version, Gem::Version.new("2.1.0.alpha")) do
<del> generator([destination_root], edge: true)
<del> run_generator_instance
<del> end
<del>
<del> assert_equal 1, @bundle_commands.count("install")
<del> assert_file "Gemfile", %r{^gem\s+["']rails["'],\s+github:\s+["']#{Regexp.escape("rails/rails")}["'],\s+branch:\s+["']main["']$}
<del> end
<del>
<del> def test_master_option
<del> run_generator [destination_root, "--master"]
<del> assert_file "Gemfile", %r{^gem\s+["']rails["'],\s+github:\s+["']#{Regexp.escape("rails/rails")}["'],\s+branch:\s+["']main["']$}
<del> end
<del>
<del> def test_main_option
<del> generator([destination_root], main: true)
<del> run_generator_instance
<del>
<del> assert_equal 1, @bundle_commands.count("install")
<del> assert_file "Gemfile", %r{^gem\s+["']rails["'],\s+github:\s+["']#{Regexp.escape("rails/rails")}["'],\s+branch:\s+["']main["']$}
<del> end
<del>
<ide> def test_bundler_binstub
<ide> generator([destination_root])
<ide> run_generator_instance
<ide> def test_webpack_option
<ide> end
<ide>
<ide> def test_hotwire
<del> run_generator [destination_root, "--dev"]
<add> run_generator [destination_root, "--no-skip-bundle"]
<ide> assert_gem "turbo-rails"
<ide> assert_gem "stimulus-rails"
<ide> assert_file "app/views/layouts/application.html.erb" do |content|
<ide> def test_skip_hotwire
<ide> end
<ide>
<ide> def test_css_option_with_asset_pipeline_tailwind
<del> run_generator [destination_root, "--dev", "--css", "tailwind"]
<add> run_generator [destination_root, "--css", "tailwind", "--no-skip-bundle"]
<ide> assert_gem "tailwindcss-rails"
<ide> assert_file "app/views/layouts/application.html.erb" do |content|
<ide> assert_match(/tailwind/, content)
<ide> end
<ide> end
<ide>
<ide> def test_css_option_with_cssbundling_gem
<del> run_generator [destination_root, "--dev", "--css", "postcss"]
<add> run_generator [destination_root, "--css", "postcss", "--no-skip-bundle"]
<ide> assert_gem "cssbundling-rails"
<ide> assert_file "app/assets/stylesheets/application.postcss.css"
<ide> end
<ide> def test_skip_bootsnap
<ide> end
<ide>
<ide> def test_bootsnap_with_dev_option
<del> run_generator [destination_root, "--dev", "--skip-bundle"]
<add> run_generator_using_prerelease [destination_root, "--dev"]
<ide>
<ide> assert_no_gem "bootsnap"
<ide> assert_file "config/boot.rb" do |content|
<ide><path>railties/test/generators/plugin_generator_test.rb
<ide> def test_generation_runs_bundle_install
<ide> assert_empty @bundle_commands
<ide> end
<ide>
<del> def test_dev_option
<del> generator([destination_root], dev: true)
<del> run_generator_instance
<del>
<del> assert_empty @bundle_commands
<del> rails_path = File.expand_path("../../..", Rails.root)
<del> assert_file "Gemfile", /^gem\s+["']rails["'],\s+path:\s+["']#{Regexp.escape(rails_path)}["']$/
<del> end
<del>
<del> def test_edge_option
<del> Rails.stub(:gem_version, Gem::Version.new("2.1.0")) do
<del> generator([destination_root], edge: true)
<del> run_generator_instance
<del> end
<del>
<del> assert_empty @bundle_commands
<del> assert_file "Gemfile", %r{^gem\s+["']rails["'],\s+github:\s+["']#{Regexp.escape("rails/rails")}["'],\s+branch:\s+["']2-1-stable["']$}
<del> end
<del>
<del> def test_edge_option_during_alpha
<del> Rails.stub(:gem_version, Gem::Version.new("2.1.0.alpha")) do
<del> generator([destination_root], edge: true)
<del> run_generator_instance
<del> end
<del>
<del> assert_empty @bundle_commands
<del> assert_file "Gemfile", %r{^gem\s+["']rails["'],\s+github:\s+["']#{Regexp.escape("rails/rails")}["'],\s+branch:\s+["']main["']$}
<del> end
<del>
<ide> def test_generation_does_not_run_bundle_install_with_full_and_mountable
<del> generator([destination_root], mountable: true, full: true, dev: true)
<add> generator([destination_root], mountable: true, full: true)
<ide> run_generator_instance
<ide>
<ide> assert_empty @bundle_commands
<ide><path>railties/test/generators/shared_generator_tests.rb
<ide> # frozen_string_literal: true
<ide>
<add>require "shellwords"
<add>
<ide> #
<ide> # Tests, setup, and teardown common to the application and plugin generator suites.
<ide> #
<ide> def test_generator_when_sprockets_is_not_used
<ide> end
<ide> end
<ide>
<add> def test_dev_option
<add> run_generator_using_prerelease [destination_root, "--dev"]
<add> rails_path = File.expand_path("../../..", Rails.root)
<add> assert_file "Gemfile", %r{^gem ["']rails["'], path: ["']#{Regexp.escape rails_path}["']$}
<add> end
<add>
<add> def test_edge_option
<add> Rails.stub(:gem_version, Gem::Version.new("2.1.0")) do
<add> run_generator_using_prerelease [destination_root, "--edge"]
<add> end
<add> assert_file "Gemfile", %r{^gem ["']rails["'], github: ["']rails/rails["'], branch: ["']2-1-stable["']$}
<add> end
<add>
<add> def test_edge_option_during_alpha
<add> Rails.stub(:gem_version, Gem::Version.new("2.1.0.alpha")) do
<add> run_generator_using_prerelease [destination_root, "--edge"]
<add> end
<add> assert_file "Gemfile", %r{^gem ["']rails["'], github: ["']rails/rails["'], branch: ["']main["']$}
<add> end
<add>
<add> def test_main_option
<add> run_generator_using_prerelease [destination_root, "--main"]
<add> assert_file "Gemfile", %r{^gem ["']rails["'], github: ["']rails/rails["'], branch: ["']main["']$}
<add> end
<add>
<add> def test_master_option
<add> run_generator_using_prerelease [destination_root, "--master"]
<add> assert_file "Gemfile", %r{^gem ["']rails["'], github: ["']rails/rails["'], branch: ["']main["']$}
<add> end
<add>
<add> def test_target_rails_prerelease_with_relative_app_path
<add> run_generator_using_prerelease ["myproject", "--main"]
<add> assert_file "myproject/Gemfile", %r{^gem ["']rails["'], github: ["']rails/rails["'], branch: ["']main["']$}
<add> end
<add>
<ide> private
<ide> def run_generator_instance
<ide> @bundle_commands = []
<del> bundle_command_stub = -> (command, *) { @bundle_commands << command }
<add> @bundle_command_stub ||= -> (command, *) { @bundle_commands << command }
<ide>
<del> generator.stub(:bundle_command, bundle_command_stub) do
<add> generator.stub(:bundle_command, @bundle_command_stub) do
<ide> super
<ide> end
<ide> end
<add>
<add> def run_generator_using_prerelease(args)
<add> option_args, positional_args = args.partition { |arg| arg.start_with?("--") }
<add> project_path = File.expand_path(positional_args.first, destination_root)
<add> expected_args = [project_path, *positional_args.drop(1), *option_args]
<add>
<add> generator(positional_args, option_args)
<add>
<add> rails_gem_pattern = /^gem ["']rails["'], .+/
<add> bundle_command_rails_gems = []
<add> @bundle_command_stub = -> (command, *) do
<add> @bundle_commands << command
<add> assert_file File.expand_path("Gemfile", project_path) do |gemfile|
<add> bundle_command_rails_gems << gemfile[rails_gem_pattern]
<add> end
<add> end
<add>
<add> # run target_rails_prerelease on exit to mimic re-running generator
<add> generator.stub :exit, generator.method(:target_rails_prerelease) do
<add> run_generator_instance
<add> end
<add>
<add> assert_file File.expand_path("Gemfile", project_path) do |gemfile|
<add> assert_equal "install", @bundle_commands[0]
<add> assert_equal gemfile[rails_gem_pattern], bundle_command_rails_gems[0]
<add>
<add> assert_match %r"^exec rails (?:plugin )?new #{Regexp.escape Shellwords.join(expected_args)}", @bundle_commands[1]
<add> assert_equal gemfile[rails_gem_pattern], bundle_command_rails_gems[1]
<add> end
<add> end
<ide> end
| 7
|
Go
|
Go
|
force delete sandbox during sandboxcleanup
|
a7c52918fd25735a7303556e7a606159fc53228a
|
<ide><path>libnetwork/controller.go
<ide> func (c *controller) NewNetwork(networkType, name string, options ...NetworkOpti
<ide>
<ide> // Make sure we have a driver available for this network type
<ide> // before we allocate anything.
<del> if _, err := network.driver(); err != nil {
<add> if _, err := network.driver(true); err != nil {
<ide> return nil, err
<ide> }
<ide>
<ide> func (c *controller) NewNetwork(networkType, name string, options ...NetworkOpti
<ide> }
<ide>
<ide> func (c *controller) addNetwork(n *network) error {
<del> d, err := n.driver()
<add> d, err := n.driver(true)
<ide> if err != nil {
<ide> return err
<ide> }
<ide><path>libnetwork/default_gateway.go
<ide> func (sb *sandbox) clearDefaultGW() error {
<ide> return nil
<ide> }
<ide>
<del> if err := ep.sbLeave(sb); err != nil {
<add> if err := ep.sbLeave(sb, false); err != nil {
<ide> return fmt.Errorf("container %s: endpoint leaving GW Network failed: %v", sb.containerID, err)
<ide> }
<ide> if err := ep.Delete(false); err != nil {
<ide><path>libnetwork/endpoint.go
<ide> func (ep *endpoint) sbJoin(sbox Sandbox, options ...EndpointOption) error {
<ide>
<ide> ep.processOptions(options...)
<ide>
<del> driver, err := network.driver()
<add> driver, err := network.driver(true)
<ide> if err != nil {
<ide> return fmt.Errorf("failed to join endpoint: %v", err)
<ide> }
<ide> func (ep *endpoint) Leave(sbox Sandbox, options ...EndpointOption) error {
<ide> sb.joinLeaveStart()
<ide> defer sb.joinLeaveEnd()
<ide>
<del> return ep.sbLeave(sbox, options...)
<add> return ep.sbLeave(sbox, false, options...)
<ide> }
<ide>
<del>func (ep *endpoint) sbLeave(sbox Sandbox, options ...EndpointOption) error {
<add>func (ep *endpoint) sbLeave(sbox Sandbox, force bool, options ...EndpointOption) error {
<ide> sb, ok := sbox.(*sandbox)
<ide> if !ok {
<ide> return types.BadRequestErrorf("not a valid Sandbox interface")
<ide> func (ep *endpoint) sbLeave(sbox Sandbox, options ...EndpointOption) error {
<ide>
<ide> ep.processOptions(options...)
<ide>
<del> d, err := n.driver()
<add> d, err := n.driver(!force)
<ide> if err != nil {
<ide> return fmt.Errorf("failed to leave endpoint: %v", err)
<ide> }
<ide> func (ep *endpoint) sbLeave(sbox Sandbox, options ...EndpointOption) error {
<ide> ep.network = n
<ide> ep.Unlock()
<ide>
<del> if err := d.Leave(n.id, ep.id); err != nil {
<del> if _, ok := err.(types.MaskableError); !ok {
<del> log.Warnf("driver error disconnecting container %s : %v", ep.name, err)
<add> if d != nil {
<add> if err := d.Leave(n.id, ep.id); err != nil {
<add> if _, ok := err.(types.MaskableError); !ok {
<add> log.Warnf("driver error disconnecting container %s : %v", ep.name, err)
<add> }
<ide> }
<ide> }
<ide>
<ide> func (ep *endpoint) Delete(force bool) error {
<ide> }
<ide>
<ide> if sb != nil {
<del> if e := ep.sbLeave(sb); e != nil {
<add> if e := ep.sbLeave(sb, force); e != nil {
<ide> log.Warnf("failed to leave sandbox for endpoint %s : %v", name, e)
<ide> }
<ide> }
<ide> func (ep *endpoint) Delete(force bool) error {
<ide> // unwatch for service records
<ide> n.getController().unWatchSvcRecord(ep)
<ide>
<del> if err = ep.deleteEndpoint(); err != nil && !force {
<add> if err = ep.deleteEndpoint(force); err != nil && !force {
<ide> return err
<ide> }
<ide>
<ide> func (ep *endpoint) Delete(force bool) error {
<ide> return nil
<ide> }
<ide>
<del>func (ep *endpoint) deleteEndpoint() error {
<add>func (ep *endpoint) deleteEndpoint(force bool) error {
<ide> ep.Lock()
<ide> n := ep.network
<ide> name := ep.name
<ide> epid := ep.id
<ide> ep.Unlock()
<ide>
<del> driver, err := n.driver()
<add> driver, err := n.driver(!force)
<ide> if err != nil {
<ide> return fmt.Errorf("failed to delete endpoint: %v", err)
<ide> }
<ide>
<add> if driver == nil {
<add> return nil
<add> }
<add>
<ide> if err := driver.DeleteEndpoint(n.id, epid); err != nil {
<ide> if _, ok := err.(types.ForbiddenError); ok {
<ide> return err
<ide><path>libnetwork/endpoint_info.go
<ide> func (ep *endpoint) DriverInfo() (map[string]interface{}, error) {
<ide> return nil, fmt.Errorf("could not find network in store for driver info: %v", err)
<ide> }
<ide>
<del> driver, err := n.driver()
<add> driver, err := n.driver(true)
<ide> if err != nil {
<ide> return nil, fmt.Errorf("failed to get driver info: %v", err)
<ide> }
<ide><path>libnetwork/network.go
<ide> func (n *network) driverScope() string {
<ide> return dd.capability.DataScope
<ide> }
<ide>
<del>func (n *network) driver() (driverapi.Driver, error) {
<add>func (n *network) driver(load bool) (driverapi.Driver, error) {
<ide> c := n.getController()
<ide>
<ide> c.Lock()
<ide> // Check if a driver for the specified network type is available
<ide> dd, ok := c.drivers[n.networkType]
<ide> c.Unlock()
<ide>
<del> if !ok {
<add> if !ok && load {
<ide> var err error
<ide> dd, err = c.loadDriver(n.networkType)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<add> } else if !ok {
<add> // dont fail if driver loading is not required
<add> return nil, nil
<ide> }
<ide>
<ide> return dd.driver, nil
<ide> func (n *network) Delete() error {
<ide> }
<ide>
<ide> func (n *network) deleteNetwork() error {
<del> d, err := n.driver()
<add> d, err := n.driver(true)
<ide> if err != nil {
<ide> return fmt.Errorf("failed deleting network: %v", err)
<ide> }
<ide> func (n *network) deleteNetwork() error {
<ide> }
<ide>
<ide> func (n *network) addEndpoint(ep *endpoint) error {
<del> d, err := n.driver()
<add> d, err := n.driver(true)
<ide> if err != nil {
<ide> return fmt.Errorf("failed to add endpoint: %v", err)
<ide> }
<ide> func (n *network) CreateEndpoint(name string, options ...EndpointOption) (Endpoi
<ide> }
<ide> defer func() {
<ide> if err != nil {
<del> if e := ep.deleteEndpoint(); e != nil {
<add> if e := ep.deleteEndpoint(false); e != nil {
<ide> log.Warnf("cleaning up endpoint failed %s : %v", name, e)
<ide> }
<ide> }
<ide><path>libnetwork/sandbox.go
<ide> func (sb *sandbox) Statistics() (map[string]*types.InterfaceStatistics, error) {
<ide> }
<ide>
<ide> func (sb *sandbox) Delete() error {
<add> return sb.delete(false)
<add>}
<add>
<add>func (sb *sandbox) delete(force bool) error {
<ide> sb.Lock()
<ide> if sb.inDelete {
<ide> sb.Unlock()
<ide> func (sb *sandbox) Delete() error {
<ide> continue
<ide> }
<ide>
<del> if err := ep.Leave(sb); err != nil {
<del> log.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
<add> if !force {
<add> if err := ep.Leave(sb); err != nil {
<add> log.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
<add> }
<ide> }
<ide>
<del> if err := ep.Delete(false); err != nil {
<add> if err := ep.Delete(force); err != nil {
<ide> log.Warnf("Failed deleting endpoint %s: %v\n", ep.ID(), err)
<ide> }
<ide> }
<ide><path>libnetwork/sandbox_store.go
<ide> func (c *controller) sandboxCleanup() {
<ide> heap.Push(&sb.endpoints, ep)
<ide> }
<ide>
<del> if err := sb.Delete(); err != nil {
<add> if err := sb.delete(true); err != nil {
<ide> logrus.Errorf("failed to delete sandbox %s while trying to cleanup: %v", sb.id, err)
<ide> }
<ide> }
| 7
|
Ruby
|
Ruby
|
duplicate missingenvironmentvariables exception
|
57d7d4c9dd13fe5c4c17ac29ff7b3b093b03eadf
|
<ide><path>Library/Homebrew/brew.rb
<ide> raise "Homebrew must be run under Ruby 2.3! You're running #{RUBY_VERSION}."
<ide> end
<ide>
<add># Also define here so we can rescue regardless of location.
<add>class MissingEnvironmentVariables < RuntimeError; end
<add>
<ide> begin
<ide> require_relative "global"
<ide> rescue MissingEnvironmentVariables => e
| 1
|
Text
|
Text
|
update chart type documentation
|
33df3a6d73b97a342221ab239aad71bc75f189cc
|
<ide><path>docs/charts/bar.md
<ide> module.exports = {
<ide> };
<ide> ```
<ide>
<del>## Example Usage
<add>## Dataset Properties
<ide>
<del>```javascript
<del>var myBarChart = new Chart(ctx, {
<del> type: 'bar',
<del> data: data,
<del> options: options
<del>});
<del>```
<add>Namespaces:
<ide>
<del>## Dataset Properties
<add>* `data.datasets[index]` - options for this dataset only
<add>* `options.datasets.bar` - options for all bar datasets
<add>* `options.elements.bar` - options for all [bar elements](../configuration/elements.md#bar-configuration)
<add>* `options` - options for the whole chart
<ide>
<ide> The bar chart allows a number of properties to be specified for each dataset.
<ide> These are used to set display properties for a specific dataset. For example,
<ide> the color of the bars is generally set this way.
<add>Only the `data` option needs to be specified in the dataset namespace.
<ide>
<ide> | Name | Type | [Scriptable](../general/options.md#scriptable-options) | [Indexable](../general/options.md#indexable-options) | Default
<ide> | ---- | ---- | :----: | :----: | ----
<ide> | [`backgroundColor`](#styling) | [`Color`](../general/colors.md) | Yes | Yes | `'rgba(0, 0, 0, 0.1)'`
<ide> | [`base`](#general) | `number` | Yes | Yes |
<add>| [`barPercentage`](#barpercentage) | `number` | - | - | `0.9` |
<add>| [`barThickness`](#barthickness) | `number`\|`string` | - | - | |
<ide> | [`borderColor`](#styling) | [`Color`](../general/colors.md) | Yes | Yes | `'rgba(0, 0, 0, 0.1)'`
<ide> | [`borderSkipped`](#borderskipped) | `string` | Yes | Yes | `'start'`
<ide> | [`borderWidth`](#borderwidth) | `number`\|`object` | Yes | Yes | `0`
<ide> | [`borderRadius`](#borderradius) | `number`\|`object` | Yes | Yes | `0`
<del>| [`clip`](#general) | `number`\|`object` | - | - | `undefined`
<del>| [`data`](#data-structure) | `object`\|`object[]`\|`number[]`\|`string[]` | - | - | **required**
<del>| [`hoverBackgroundColor`](#interactions) | [`Color`](../general/colors.md) | Yes | Yes | `undefined`
<del>| [`hoverBorderColor`](#interactions) | [`Color`](../general/colors.md) | Yes | Yes | `undefined`
<add>| [`categoryPercentage`](#categorypercentage) | `number` | - | - | `0.8` |
<add>| [`clip`](#general) | `number`\|`object` | - | - |
<add>| [`data`](#data-structure) | `object`\|`object[]`\| `number[]`\|`string[]` | - | - | **required**
<add>| [`grouped`](#general) | `boolean` | - | - | `true` |
<add>| [`hoverBackgroundColor`](#interactions) | [`Color`](../general/colors.md) | Yes | Yes |
<add>| [`hoverBorderColor`](#interactions) | [`Color`](../general/colors.md) | Yes | Yes |
<ide> | [`hoverBorderWidth`](#interactions) | `number` | Yes | Yes | `1`
<ide> | [`hoverBorderRadius`](#interactions) | `number` | Yes | Yes | `0`
<ide> | [`indexAxis`](#general) | `string` | - | - | `'x'`
<add>| [`maxBarThickness`](#maxbarthickness) | `number` | - | - | |
<add>| [`minBarLength`](#styling) | `number` | - | - | |
<ide> | [`label`](#general) | `string` | - | - | `''`
<ide> | [`order`](#general) | `number` | - | - | `0`
<ide> | [`pointStyle`](../configuration/elements.md#point-styles) | `string`\|`Image` | Yes | - | `'circle'`
<add>| [`skipNull`](#general) | `boolean` | - | - | |
<add>| [`stack`](#general) | `string` | - | - | `'bar'` |
<ide> | [`xAxisID`](#general) | `string` | - | - | first x axis
<ide> | [`yAxisID`](#general) | `string` | - | - | first y axis
<ide>
<add>All these values, if `undefined`, fallback to the scopes described in [option resolution](../general/options)
<add>
<add>### Example dataset configuration
<add>
<add>```javascript
<add>data: {
<add> datasets: [{
<add> barPercentage: 0.5,
<add> barThickness: 6,
<add> maxBarThickness: 8,
<add> minBarLength: 2,
<add> data: [10, 20, 30, 40, 50, 60, 70]
<add> }]
<add>};
<add>```
<add>
<ide> ### General
<ide>
<ide> | Name | Description
<ide> | ---- | ----
<ide> | `base` | Base value for the bar in data units along the value axis. If not set, defaults to the value axis base value.
<ide> | `clip` | How to clip relative to chartArea. Positive value allows overflow, negative value clips that many pixels inside chartArea. `0` = clip at chartArea. Clipping can also be configured per side: `clip: {left: 5, top: false, right: -2, bottom: 0}`
<add>| `grouped` | Should the bars be grouped on index axis. When `true`, all the datasets at same index value will be placed next to each other centering on that index value. When `false`, each bar is placed on its actual index-axis value.
<ide> | `indexAxis` | The base axis of the dataset. `'x'` for vertical bars and `'y'` for horizontal bars.
<ide> | `label` | The label for the dataset which appears in the legend and tooltips.
<ide> | `order` | The drawing order of dataset. Also affects order for stacking, tooltip, and legend.
<add>| `skipNull` | If `true`, null or undefined values will not be used for spacing calculations when determining bar size.
<add>| `stack` | The ID of the group to which this dataset belongs to (when stacked, each group will be a separate stack). [more](#stacked-bar-charts)
<ide> | `xAxisID` | The ID of the x-axis to plot this dataset on.
<ide> | `yAxisID` | The ID of the y-axis to plot this dataset on.
<ide>
<ide> The style of each bar can be controlled with the following properties:
<ide> | [`borderSkipped`](#borderskipped) | The edge to skip when drawing bar.
<ide> | [`borderWidth`](#borderwidth) | The bar border width (in pixels).
<ide> | [`borderRadius`](#borderradius) | The bar border radius (in pixels).
<add>| `minBarLength` | Set this to ensure that bars have a minimum length in pixels.
<ide> | `pointStyle` | Style of the point for legend. [more...](../configuration/elements.md#point-styles)
<ide>
<ide> All these values, if `undefined`, fallback to the associated [`elements.bar.*`](../configuration/elements.md#bar-configuration) options.
<ide> The interaction with each bar can be controlled with the following properties:
<ide>
<ide> All these values, if `undefined`, fallback to the associated [`elements.bar.*`](../configuration/elements.md#bar-configuration) options.
<ide>
<del>## Dataset Configuration
<add>### barPercentage
<ide>
<del>The bar chart accepts the following configuration from the associated dataset options:
<add>Percent (0-1) of the available width each bar should be within the category width. 1.0 will take the whole category width and put the bars right next to each other. [more...](#barpercentage-vs-categorypercentage)
<ide>
<del>| Name | Type | Default | Description
<del>| ---- | ---- | ------- | -----------
<del>| `barPercentage` | `number` | `0.9` | Percent (0-1) of the available width each bar should be within the category width. 1.0 will take the whole category width and put the bars right next to each other. [more...](#barpercentage-vs-categorypercentage)
<del>| `categoryPercentage` | `number` | `0.8` | Percent (0-1) of the available width each category should be within the sample width. [more...](#barpercentage-vs-categorypercentage)
<del>| `barThickness` | `number`\|`string` | | Manually set width of each bar in pixels. If set to `'flex'`, it computes "optimal" sample widths that globally arrange bars side by side. If not set (default), bars are equally sized based on the smallest interval. [more...](#barthickness)
<del>| `base` | `number` | | Base value for the bar in data units along the value axis. If not set, defaults to the value axis base value.
<del>| `grouped` | `boolean` | `true` | Should the bars be grouped on index axis. When `true`, all the datasets at same index value will be placed next to each other centering on that index value. When `false`, each bar is placed on its actual index-axis value.
<del>| `maxBarThickness` | `number` | | Set this to ensure that bars are not sized thicker than this.
<del>| `minBarLength` | `number` | | Set this to ensure that bars have a minimum length in pixels.
<add>### categoryPercentage
<ide>
<del>### Example dataset configuration
<del>
<del>```javascript
<del>data: {
<del> datasets: [{
<del> barPercentage: 0.5,
<del> barThickness: 6,
<del> maxBarThickness: 8,
<del> minBarLength: 2,
<del> data: [10, 20, 30, 40, 50, 60, 70]
<del> }]
<del>};
<del>```
<add>Percent (0-1) of the available width each category should be within the sample width. [more...](#barpercentage-vs-categorypercentage)
<ide>
<ide> ### barThickness
<ide>
<ide> If set to `'flex'`, the base sample widths are calculated automatically based on
<ide>
<ide> If not set (default), the base sample widths are calculated using the smallest interval that prevents bar overlapping, and bars are sized using `barPercentage` and `categoryPercentage`. This mode always generates bars equally sized.
<ide>
<del>## Config Options
<add>### maxBarThickness
<ide>
<del>These are the customisation options specific to Bar charts. These options are looked up on access, and form together with the global chart configuration, `Chart.defaults`, the options of the chart.
<del>
<del>| Name | Type | Default | Description
<del>| ---- | ---- | ------- | -----------
<del>| `skipNull` | `boolean` | `undefined` | If `true`, null or undefined values will not be drawn
<add>Set this to ensure that bars are not sized thicker than this.
<ide>
<ide> ## Scale Configuration
<ide>
<ide> var stackedBar = new Chart(ctx, {
<ide> });
<ide> ```
<ide>
<del>The following dataset properties are specific to stacked bar charts.
<del>
<del>| Name | Type | Description
<del>| ---- | ---- | -----------
<del>| `stack` | `string` | The ID of the group to which this dataset belongs to (when stacked, each group will be a separate stack). Defaults to `bar`.
<del>
<ide> ## Horizontal Bar Chart
<ide>
<ide> A horizontal bar chart is a variation on a vertical bar chart. It is sometimes used to show trend data, and the comparison of multiple data sets side by side.
<ide><path>docs/charts/bubble.md
<ide> const data = {
<ide> const config = {
<ide> type: 'bubble',
<ide> data: data,
<add> options: {}
<ide> };
<ide> // </block:config>
<ide>
<ide> module.exports = {
<ide> };
<ide> ```
<ide>
<del>## Example Usage
<add>## Dataset Properties
<ide>
<del>```javascript
<del>// For a bubble chart
<del>var myBubbleChart = new Chart(ctx, {
<del> type: 'bubble',
<del> data: data,
<del> options: options
<del>});
<del>```
<add>Namespaces:
<ide>
<del>## Dataset Properties
<add>* `data.datasets[index]` - options for this dataset only
<add>* `options.datasets.bubble` - options for all bubble datasets
<add>* `options.elements.point` - options for all [point elements](../configuration/elements.md#point-configuration)
<add>* `options` - options for the whole chart
<ide>
<ide> The bubble chart allows a number of properties to be specified for each dataset. These are used to set display properties for a specific dataset. For example, the colour of the bubbles is generally set this way.
<ide>
<ide> The bubble chart allows a number of properties to be specified for each dataset.
<ide> | [`rotation`](#styling) | `number` | Yes | Yes | `0`
<ide> | [`radius`](#styling) | `number` | Yes | Yes | `3`
<ide>
<add>All these values, if `undefined`, fallback to the scopes described in [option resolution](../general/options)
<add>
<ide> ### General
<ide>
<ide> | Name | Description
<ide><path>docs/charts/doughnut.md
<ide> module.exports = {
<ide>
<ide> ## Dataset Properties
<ide>
<add>Namespaces:
<add>
<add>* `data.datasets[index]` - options for this dataset only
<add>* `options.datasets.doughnut` - options for all doughnut datasets
<add>* `options.datasets.pie` - options for all pie datasets
<add>* `options.elements.arc` - options for all [arc elements](../configuration/elements.md#arc-configuration)
<add>* `options` - options for the whole chart
<add>
<ide> The doughnut/pie chart allows a number of properties to be specified for each dataset. These are used to set display properties for a specific dataset. For example, the colours of the dataset's arcs are generally set this way.
<ide>
<ide> | Name | Type | [Scriptable](../general/options.md#scriptable-options) | [Indexable](../general/options.md#indexable-options) | Default
<ide> The doughnut/pie chart allows a number of properties to be specified for each da
<ide> | [`rotation`](#general) | `number` | - | - | `undefined`
<ide> | [`weight`](#styling) | `number` | - | - | `1`
<ide>
<add>All these values, if `undefined`, fallback to the scopes described in [option resolution](../general/options)
<add>
<ide> ### General
<ide>
<ide> | Name | Description
<ide><path>docs/charts/line.md
<ide> module.exports = {
<ide> };
<ide> ```
<ide>
<del>## Example Usage
<add>## Dataset Properties
<ide>
<del>```javascript
<del>var myLineChart = new Chart(ctx, {
<del> type: 'line',
<del> data: data,
<del> options: options
<del>});
<del>```
<add>Namespaces:
<ide>
<del>## Dataset Properties
<add>* `data.datasets[index]` - options for this dataset only
<add>* `options.datasets.line` - options for all line datasets
<add>* `options.elements.line` - options for all [line elements](../configuration/elements.md#line-configuration)
<add>* `options.elements.point` - options for all [point elements](../configuration/elements.md#point-configuration)
<add>* `options` - options for the whole chart
<ide>
<ide> The line chart allows a number of properties to be specified for each dataset. These are used to set display properties for a specific dataset. For example, the colour of a line is generally set this way.
<ide>
<ide> The line chart allows a number of properties to be specified for each dataset. T
<ide> | [`borderJoinStyle`](#line-styling) | `string` | Yes | - | `'miter'`
<ide> | [`borderWidth`](#line-styling) | `number` | Yes | - | `3`
<ide> | [`clip`](#general) | `number`\|`object` | - | - | `undefined`
<del>| [`data`](#data-structure) | `object`\|`object[]`\|`number[]`\|`string[]` | - | - | **required**
<add>| [`data`](#data-structure) | `object`\|`object[]`\| `number[]`\|`string[]` | - | - | **required**
<ide> | [`cubicInterpolationMode`](#cubicinterpolationmode) | `string` | Yes | - | `'default'`
<ide> | [`fill`](#line-styling) | `boolean`\|`string` | Yes | - | `false`
<ide> | [`hoverBackgroundColor`](#line-styling) | [`Color`](../general/colors.md) | Yes | - | `undefined`
<ide> The line chart allows a number of properties to be specified for each dataset. T
<ide> | [`pointStyle`](#point-styling) | `string`\|`Image` | Yes | Yes | `'circle'`
<ide> | [`showLine`](#line-styling) | `boolean` | - | - | `true`
<ide> | [`spanGaps`](#line-styling) | `boolean`\|`number` | - | - | `undefined`
<add>| [`stack`](#general) | `string` | - | - | `'line'` |
<ide> | [`stepped`](#stepped) | `boolean`\|`string` | - | - | `false`
<ide> | [`xAxisID`](#general) | `string` | - | - | first x axis
<ide> | [`yAxisID`](#general) | `string` | - | - | first y axis
<ide>
<add>All these values, if `undefined`, fallback to the scopes described in [option resolution](../general/options)
<add>
<ide> ### General
<ide>
<ide> | Name | Description
<ide> The line chart allows a number of properties to be specified for each dataset. T
<ide> | `indexAxis` | The base axis of the dataset. `'x'` for horizontal lines and `'y'` for vertical lines.
<ide> | `label` | The label for the dataset which appears in the legend and tooltips.
<ide> | `order` | The drawing order of dataset. Also affects order for stacking, tooltip, and legend.
<add>| `stack` | The ID of the group to which this dataset belongs to (when stacked, each group will be a separate stack). [more](#stacked-area-charts)
<ide> | `xAxisID` | The ID of the x-axis to plot this dataset on.
<ide> | `yAxisID` | The ID of the y-axis to plot this dataset on.
<ide>
<ide> The following values are supported for `stepped`.
<ide>
<ide> If the `stepped` value is set to anything other than false, `tension` will be ignored.
<ide>
<del>## Configuration Options
<del>
<del>The line chart defines the following configuration options. These options are looked up on access, and form together with the global chart configuration, `Chart.defaults`, the options of the chart.
<del>
<del>| Name | Type | Default | Description
<del>| ---- | ---- | ------- | -----------
<del>| `showLine` | `boolean` | `true` | If false, the lines between points are not drawn.
<del>| `spanGaps` | `boolean`\|`number` | `false` | If true, lines will be drawn between points with no or null data. If false, points with `null` data will create a break in the line. Can also be a number specifying the maximum gap length to span. The unit of the value depends on the scale used.
<del>
<ide> ## Default Options
<ide>
<ide> It is common to want to apply a configuration setting to all created line charts. The global line chart settings are stored in `Chart.overrides.line`. Changing the global options only affects charts created after the change. Existing charts are not changed.
<ide> module.exports = {
<ide> };
<ide> ```
<ide>
<del>## Example
<del>
<del>```javascript
<del>var myLineChart = new Chart(ctx, {
<del> type: 'line',
<del> data: data,
<del> options: {
<del> indexAxis: 'y'
<del> }
<del>});
<del>```
<del>
<ide> ### Config Options
<ide>
<ide> The configuration options for the vertical line chart are the same as for the [line chart](#configuration-options). However, any options specified on the x-axis in a line chart, are applied to the y-axis in a vertical line chart.
<ide><path>docs/charts/polar.md
<ide> const data = {
<ide> const config = {
<ide> type: 'polarArea',
<ide> data: data,
<add> options: {}
<ide> };
<ide> // </block:config>
<ide>
<ide> module.exports = {
<ide> };
<ide> ```
<ide>
<del>## Example Usage
<add>## Dataset Properties
<ide>
<del>```javascript
<del>new Chart(ctx, {
<del> data: data,
<del> type: 'polarArea',
<del> options: options
<del>});
<del>```
<add>Namespaces:
<ide>
<del>## Dataset Properties
<add>* `data.datasets[index]` - options for this dataset only
<add>* `options.datasets.polarArea` - options for all polarArea datasets
<add>* `options.elements.arc` - options for all [arc elements](../configuration/elements.md#arc-configuration)
<add>* `options` - options for the whole chart
<ide>
<ide> The following options can be included in a polar area chart dataset to configure options for that specific dataset.
<ide>
<ide> The following options can be included in a polar area chart dataset to configure
<ide> | [`hoverBorderColor`](#interactions) | [`Color`](../general/colors.md) | Yes | Yes | `undefined`
<ide> | [`hoverBorderWidth`](#interactions) | `number` | Yes | Yes | `undefined`
<ide>
<add>All these values, if `undefined`, fallback to the scopes described in [option resolution](../general/options)
<add>
<ide> ### General
<ide>
<ide> | Name | Description
<ide><path>docs/charts/radar.md
<ide> module.exports = {
<ide> };
<ide> ```
<ide>
<del><ExampleChart/>
<add>## Dataset Properties
<ide>
<del>## Example Usage
<add>Namespaces:
<ide>
<del>```javascript
<del>var myRadarChart = new Chart(ctx, {
<del> type: 'radar',
<del> data: data,
<del> options: options
<del>});
<del>```
<del>
<del>## Dataset Properties
<add>* `data.datasets[index]` - options for this dataset only
<add>* `options.datasets.line` - options for all line datasets
<add>* `options.elements.line` - options for all [line elements](../configuration/elements.md#line-configuration)
<add>* `options.elements.point` - options for all [point elements](../configuration/elements.md#point-configuration)
<add>* `options` - options for the whole chart
<ide>
<ide> The radar chart allows a number of properties to be specified for each dataset. These are used to set display properties for a specific dataset. For example, the colour of a line is generally set this way.
<ide>
<ide> The radar chart allows a number of properties to be specified for each dataset.
<ide> | [`pointStyle`](#point-styling) | `string`\|`Image` | Yes | Yes | `'circle'`
<ide> | [`spanGaps`](#line-styling) | `boolean` | - | - | `undefined`
<ide>
<add>All these values, if `undefined`, fallback to the scopes described in [option resolution](../general/options)
<add>
<ide> ### General
<ide>
<ide> | Name | Description
<ide> The interaction with each point can be controlled with the following properties:
<ide> | `pointHoverBorderWidth` | Border width of point when hovered.
<ide> | `pointHoverRadius` | The radius of the point when hovered.
<ide>
<del>## Configuration Options
<del>
<del>The radar chart defines the following configuration options. These options are looked up on access, and form together with the global chart configuration, `Chart.defaults`, the options of the chart.
<del>
<del>| Name | Type | Default | Description
<del>| ---- | ---- | ------- | -----------
<del>| `spanGaps` | `boolean` | `false` | If false, `null` data causes a break in the line.
<del>
<ide> ## Scale Options
<ide>
<ide> The radar chart supports only a single scale. The options for this scale are defined in the `scale` property.
<ide><path>docs/charts/scatter.md
<ide> module.exports = {
<ide>
<ide> ## Dataset Properties
<ide>
<add>Namespaces:
<add>
<add>* `data.datasets[index]` - options for this dataset only
<add>* `options.datasets.scatter` - options for all scatter datasets
<add>* `options.elements.line` - options for all [line elements](../configuration/elements.md#line-configuration)
<add>* `options.elements.point` - options for all [point elements](../configuration/elements.md#point-configuration)
<add>* `options` - options for the whole chart
<add>
<ide> The scatter chart supports all of the same properties as the [line chart](./charts/line.md#dataset-properties).
<ide> By default, the scatter chart will override the showLine property of the line chart to `false`.
<ide>
| 7
|
PHP
|
PHP
|
fix cs errors
|
9cfd8c707025fca1c267513315b008bd6f30f587
|
<ide><path>tests/TestCase/Controller/ControllerTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Controller;
<ide>
<del>use Cake\Controller\Component;
<ide> use Cake\Controller\Controller;
<ide> use Cake\Core\Configure;
<ide> use Cake\Event\EventInterface;
<ide><path>tests/TestCase/Error/ExceptionRendererTest.php
<ide> use Cake\Http\Exception\InternalErrorException;
<ide> use Cake\Http\Exception\MethodNotAllowedException;
<ide> use Cake\Http\Exception\NotFoundException;
<del>use Cake\Http\Response;
<ide> use Cake\Http\ServerRequest;
<ide> use Cake\Mailer\Exception\MissingActionException as MissingMailerActionException;
<ide> use Cake\ORM\Exception\MissingBehaviorException;
<ide><path>tests/TestCase/Utility/MergeVariablesTraitTest.php
<ide> namespace Cake\Test\TestCase\Utility;
<ide>
<ide> use Cake\TestSuite\TestCase;
<del>use Cake\Utility\MergeVariablesTrait;
<del>use TestApp\Utility\Base;
<ide> use TestApp\Utility\Child;
<ide> use TestApp\Utility\Grandchild;
<ide>
| 3
|
Javascript
|
Javascript
|
allow the disabling of navigation gestures
|
0cf95056303b8690077ae8aa842f4d810bf3cbc9
|
<ide><path>Examples/UIExplorer/js/NavigationExperimental/NavigationCardStack-NoGesture-example.js
<add>/**
<add> * Copyright (c) 2013-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * The examples provided by Facebook are for non-commercial testing and
<add> * evaluation purposes only.
<add> *
<add> * Facebook reserves all rights not expressly granted.
<add> *
<add> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add> * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
<add> * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
<add> * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
<add> * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
<add> * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>*/
<add>'use strict';
<add>
<add>const NavigationExampleRow = require('./NavigationExampleRow');
<add>const React = require('react');
<add>const ReactNative = require('react-native');
<add>
<add>/**
<add> * Basic example that shows how to use <NavigationCardStack /> to build
<add> * an app with controlled navigation system but without gestures.
<add> */
<add>const {
<add> NavigationExperimental,
<add> ScrollView,
<add> StyleSheet,
<add>} = ReactNative;
<add>
<add>const {
<add> CardStack: NavigationCardStack,
<add> StateUtils: NavigationStateUtils,
<add>} = NavigationExperimental;
<add>
<add>// Step 1:
<add>// Define a component for your application.
<add>class YourApplication extends React.Component {
<add>
<add> // This sets up the initial navigation state.
<add> constructor(props, context) {
<add> super(props, context);
<add>
<add> this.state = {
<add> // This defines the initial navigation state.
<add> navigationState: {
<add> index: 0, // starts with first route focused.
<add> routes: [{key: 'Welcome'}], // starts with only one route.
<add> },
<add> };
<add>
<add> this._exit = this._exit.bind(this);
<add> this._onNavigationChange = this._onNavigationChange.bind(this);
<add> }
<add>
<add> // User your own navigator (see Step 2).
<add> render(): ReactElement {
<add> return (
<add> <YourNavigator
<add> navigationState={this.state.navigationState}
<add> onNavigationChange={this._onNavigationChange}
<add> onExit={this._exit}
<add> />
<add> );
<add> }
<add>
<add> // This handles the navigation state changes. You're free and responsible
<add> // to define the API that changes that navigation state. In this exmaple,
<add> // we'd simply use a `function(type: string)` to update the navigation state.
<add> _onNavigationChange(type: string): void {
<add> let {navigationState} = this.state;
<add> switch (type) {
<add> case 'push':
<add> // push a new route.
<add> const route = {key: 'route-' + Date.now()};
<add> navigationState = NavigationStateUtils.push(navigationState, route);
<add> break;
<add>
<add> case 'pop':
<add> navigationState = NavigationStateUtils.pop(navigationState);
<add> break;
<add> }
<add>
<add> // NavigationStateUtils gives you back the same `navigationState` if nothing
<add> // has changed. You could use that to avoid redundant re-rendering.
<add> if (this.state.navigationState !== navigationState) {
<add> this.setState({navigationState});
<add> }
<add> }
<add>
<add> // Exits the example. `this.props.onExampleExit` is provided
<add> // by the UI Explorer.
<add> _exit(): void {
<add> this.props.onExampleExit && this.props.onExampleExit();
<add> }
<add>
<add> // This public method is optional. If exists, the UI explorer will call it
<add> // the "back button" is pressed. Normally this is the cases for Android only.
<add> handleBackAction(): boolean {
<add> return this._onNavigationChange('pop');
<add> }
<add>}
<add>
<add>// Step 2:
<add>// Define your own controlled navigator.
<add>//
<add>// +------------+
<add>// +-+ |
<add>// +-+ | |
<add>// | | | |
<add>// | | | Active |
<add>// | | | Scene |
<add>// | | | |
<add>// +-+ | |
<add>// +-+ |
<add>// +------------+
<add>//
<add>class YourNavigator extends React.Component {
<add>
<add> // This sets up the methods (e.g. Pop, Push) for navigation.
<add> constructor(props: any, context: any) {
<add> super(props, context);
<add>
<add> this._onPushRoute = this.props.onNavigationChange.bind(null, 'push');
<add> this._onPopRoute = this.props.onNavigationChange.bind(null, 'pop');
<add>
<add> this._renderScene = this._renderScene.bind(this);
<add> }
<add>
<add> // Now use the `NavigationCardStack` to render the scenes.
<add> render(): ReactElement {
<add> return (
<add> <NavigationCardStack
<add> onNavigateBack={this._onPopRoute}
<add> navigationState={this.props.navigationState}
<add> renderScene={this._renderScene}
<add> style={styles.navigator}
<add> enableGestures={false}
<add> />
<add> );
<add> }
<add>
<add> // Render a scene for route.
<add> // The detailed spec of `sceneProps` is defined at `NavigationTypeDefinition`
<add> // as type `NavigationSceneRendererProps`.
<add> _renderScene(sceneProps: Object): ReactElement {
<add> return (
<add> <YourScene
<add> route={sceneProps.scene.route}
<add> onPushRoute={this._onPushRoute}
<add> onPopRoute={this._onPopRoute}
<add> onExit={this.props.onExit}
<add> />
<add> );
<add> }
<add>}
<add>
<add>// Step 3:
<add>// Define your own scene.
<add>class YourScene extends React.Component {
<add> render() {
<add> return (
<add> <ScrollView>
<add> <NavigationExampleRow
<add> text={'route = ' + this.props.route.key}
<add> />
<add> <NavigationExampleRow
<add> text="Push Route"
<add> onPress={this.props.onPushRoute}
<add> />
<add> <NavigationExampleRow
<add> text="Pop Route"
<add> onPress={this.props.onPopRoute}
<add> />
<add> <NavigationExampleRow
<add> text="Exit Card Stack Example"
<add> onPress={this.props.onExit}
<add> />
<add> </ScrollView>
<add> );
<add> }
<add>}
<add>
<add>const styles = StyleSheet.create({
<add> navigator: {
<add> flex: 1,
<add> },
<add>});
<add>
<add>module.exports = YourApplication;
<ide><path>Examples/UIExplorer/js/NavigationExperimental/NavigationExperimentalExample.js
<ide> const View = require('View');
<ide> const EXAMPLES = {
<ide> 'CardStack + Header + Tabs Example': require('./NavigationCardStack-NavigationHeader-Tabs-example'),
<ide> 'CardStack Example': require('./NavigationCardStack-example'),
<add> 'CardStack Without Gestures Example': require('./NavigationCardStack-NoGesture-example'),
<ide> 'Transitioner + Animated View Example': require('./NavigationTransitioner-AnimatedView-example'),
<ide> 'Transitioner + Animated View Pager Example': require('./NavigationTransitioner-AnimatedView-pager-example'),
<ide> };
<ide><path>Libraries/CustomComponents/NavigationExperimental/NavigationCardStack.js
<ide> type Props = {
<ide> cardStyle?: any,
<ide> style: any,
<ide> gestureResponseDistance?: ?number,
<add> enableGestures: ?boolean
<ide> };
<ide>
<ide> type DefaultProps = {
<ide> direction: NavigationGestureDirection,
<add> enableGestures: boolean
<ide> };
<ide>
<ide> /**
<ide> class NavigationCardStack extends React.Component<DefaultProps, Props, void> {
<ide> */
<ide> gestureResponseDistance: PropTypes.number,
<ide>
<add> /**
<add> * Enable gestures. Default value is true
<add> */
<add> enableGestures: PropTypes.bool,
<add>
<ide> /**
<ide> * The controlled navigation state. Typically, the navigation state
<ide> * look like this:
<ide> class NavigationCardStack extends React.Component<DefaultProps, Props, void> {
<ide>
<ide> static defaultProps: DefaultProps = {
<ide> direction: Directions.HORIZONTAL,
<add> enableGestures: true,
<ide> };
<ide>
<ide> constructor(props: Props, context: any) {
<ide> class NavigationCardStack extends React.Component<DefaultProps, Props, void> {
<ide> NavigationCardStackStyleInterpolator.forVertical(props) :
<ide> NavigationCardStackStyleInterpolator.forHorizontal(props);
<ide>
<del> const panHandlersProps = {
<del> ...props,
<del> onNavigateBack: this.props.onNavigateBack,
<del> gestureResponseDistance: this.props.gestureResponseDistance,
<del> };
<del> const panHandlers = isVertical ?
<del> NavigationCardStackPanResponder.forVertical(panHandlersProps) :
<del> NavigationCardStackPanResponder.forHorizontal(panHandlersProps);
<add> let panHandlers = null;
<add>
<add> if (this.props.enableGestures) {
<add> const panHandlersProps = {
<add> ...props,
<add> onNavigateBack: this.props.onNavigateBack,
<add> gestureResponseDistance: this.props.gestureResponseDistance,
<add> };
<add> panHandlers = isVertical ?
<add> NavigationCardStackPanResponder.forVertical(panHandlersProps) :
<add> NavigationCardStackPanResponder.forHorizontal(panHandlersProps);
<add> }
<ide>
<ide> return (
<ide> <NavigationCard
| 3
|
Javascript
|
Javascript
|
replace basename helper by node's one
|
26d33424bb916db37c01df94b25d3acdbf0d52da
|
<ide><path>lib/SourceMapDevToolPlugin.js
<ide> const createHash = require("./util/createHash");
<ide> const validateOptions = require("schema-utils");
<ide> const schema = require("../schemas/plugins/SourceMapDevToolPlugin.json");
<ide>
<del>const basename = name => {
<del> if (!name.includes("/")) return name;
<del> return name.substr(name.lastIndexOf("/") + 1);
<del>};
<del>
<ide> const assetsCache = new WeakMap();
<ide>
<ide> const getTaskForFile = (file, chunk, options, compilation) => {
<ide> class SourceMapDevToolPlugin {
<ide> ? path.relative(options.fileContext, filename)
<ide> : filename,
<ide> query,
<del> basename: basename(filename),
<add> basename: path.basename(filename),
<ide> contentHash: createHash("md4")
<ide> .update(sourceMapString)
<ide> .digest("hex")
| 1
|
Javascript
|
Javascript
|
add getdescendants to object3d
|
8a960ad7fda5c87af940bb31b9c571c3cab92be0
|
<ide><path>src/core/Object3D.js
<ide> THREE.Object3D.prototype = {
<ide> return undefined;
<ide>
<ide> },
<add>
<add> getDescendants: function (returnValue) {
<add> var children = this.children,l = children.length,child;
<add>
<add> if (returnValue === undefined){
<add> returnValue = [];
<add> }
<add>
<add> for (var i = 0; i < l ; i++){
<add> child = children[i];
<add> returnValue.push(child);
<add> child.getDescendants(returnValue);
<add> };
<add>
<add> return returnValue;
<add>
<add> },
<ide>
<ide> updateMatrix: function () {
<ide>
| 1
|
Ruby
|
Ruby
|
remove appcast checkpoints
|
c68526ac09261f29bf261b530a5d449544380ecb
|
<ide><path>Library/Homebrew/cask/lib/hbc/audit.rb
<ide> def run!
<ide> check_version_and_checksum
<ide> check_version
<ide> check_sha256
<del> check_appcast
<add> check_appcast_checkpoint
<ide> check_url
<ide> check_generic_artifacts
<ide> check_token_conflicts
<ide> def check_sha256_invalid(sha256: cask.sha256, stanza: "sha256")
<ide> add_error "cannot use the sha256 for an empty string in #{stanza}: #{empty_sha256}"
<ide> end
<ide>
<del> def check_appcast
<add> def check_appcast_checkpoint
<ide> return unless cask.appcast
<del> odebug "Auditing appcast"
<del> check_appcast_has_checkpoint
<ide> return unless cask.appcast.checkpoint
<del> check_sha256_actually_256(sha256: cask.appcast.checkpoint, stanza: "appcast :checkpoint")
<del> check_sha256_invalid(sha256: cask.appcast.checkpoint, stanza: "appcast :checkpoint")
<del> return unless download
<del> check_appcast_http_code
<del> check_appcast_checkpoint_accuracy
<del> end
<del>
<del> def check_appcast_has_checkpoint
<del> odebug "Verifying appcast has :checkpoint key"
<del> add_error "a checkpoint sha256 is required for appcast" unless cask.appcast.checkpoint
<del> end
<del>
<del> def check_appcast_http_code
<del> odebug "Verifying appcast returns 200 HTTP response code"
<del>
<del> curl_executable, *args = curl_args(
<del> "--compressed", "--location", "--fail",
<del> "--write-out", "%{http_code}",
<del> "--output", "/dev/null",
<del> cask.appcast,
<del> user_agent: :fake
<del> )
<del> result = @command.run(curl_executable, args: args, print_stderr: false)
<del> if result.success?
<del> http_code = result.stdout.chomp
<del> add_warning "unexpected HTTP response code retrieving appcast: #{http_code}" unless http_code == "200"
<del> else
<del> add_warning "error retrieving appcast: #{result.stderr}"
<del> end
<del> end
<del>
<del> def check_appcast_checkpoint_accuracy
<del> odebug "Verifying appcast checkpoint is accurate"
<del> result = cask.appcast.calculate_checkpoint
<ide>
<del> actual_checkpoint = result[:checkpoint]
<del>
<del> if actual_checkpoint.nil?
<del> add_warning "error retrieving appcast: #{result[:command_result].stderr}"
<del> else
<del> expected = cask.appcast.checkpoint
<del> add_warning <<~EOS unless expected == actual_checkpoint
<del> appcast checkpoint mismatch
<del> Expected: #{expected}
<del> Actual: #{actual_checkpoint}
<del> EOS
<del> end
<add> add_error "Appcast checkpoints have been removed from Homebrew-Cask"
<ide> end
<ide>
<ide> def check_latest_with_appcast
<ide><path>Library/Homebrew/test/cask/audit_spec.rb
<ide> def include_msg?(messages, msg)
<ide> end
<ide> end
<ide>
<del> describe "appcast checks" do
<del> context "when appcast has no sha256" do
<del> let(:cask_token) { "appcast-missing-checkpoint" }
<add> describe "appcast checkpoint check" do
<add> let(:error_msg) { "Appcast checkpoints have been removed from Homebrew-Cask" }
<ide>
<del> it { is_expected.to fail_with(/checkpoint sha256 is required for appcast/) }
<del> end
<del>
<del> context "when appcast checkpoint is not a string of 64 hexadecimal characters" do
<del> let(:cask_token) { "appcast-invalid-checkpoint" }
<del>
<del> it { is_expected.to fail_with(/string must be of 64 hexadecimal characters/) }
<del> end
<del>
<del> context "when appcast checkpoint is sha256 for empty string" do
<del> let(:cask_token) { "appcast-checkpoint-sha256-for-empty-string" }
<del>
<del> it { is_expected.to fail_with(/cannot use the sha256 for an empty string/) }
<del> end
<del>
<del> context "when appcast checkpoint is valid sha256" do
<del> let(:cask_token) { "appcast-valid-checkpoint" }
<del>
<del> it { is_expected.not_to fail_with(/appcast :checkpoint/) }
<del> end
<del>
<del> context "when verifying appcast HTTP code" do
<del> let(:cask_token) { "appcast-valid-checkpoint" }
<del> let(:download) { instance_double(Hbc::Download) }
<del> let(:wrong_code_msg) { /unexpected HTTP response code/ }
<del> let(:curl_error_msg) { /error retrieving appcast/ }
<del> let(:fake_curl_result) { instance_double(Hbc::SystemCommand::Result) }
<del>
<del> before do
<del> allow(audit).to receive(:check_appcast_checkpoint_accuracy)
<del> allow(fake_system_command).to receive(:run).and_return(fake_curl_result)
<del> allow(fake_curl_result).to receive(:success?).and_return(success)
<del> end
<del>
<del> context "when curl succeeds" do
<del> let(:success) { true }
<del>
<del> before do
<del> allow(fake_curl_result).to receive(:stdout).and_return(stdout)
<del> end
<del>
<del> context "when HTTP code is 200" do
<del> let(:stdout) { "200" }
<del>
<del> it { is_expected.not_to warn_with(wrong_code_msg) }
<del> end
<del>
<del> context "when HTTP code is not 200" do
<del> let(:stdout) { "404" }
<del>
<del> it { is_expected.to warn_with(wrong_code_msg) }
<del> end
<del> end
<del>
<del> context "when curl fails" do
<del> let(:success) { false }
<del>
<del> before do
<del> allow(fake_curl_result).to receive(:stderr).and_return("Some curl error")
<del> end
<add> context "when the Cask does not have a checkpoint" do
<add> let(:cask_token) { "with-appcast" }
<ide>
<del> it { is_expected.to warn_with(curl_error_msg) }
<del> end
<add> it { is_expected.not_to fail_with(error_msg) }
<ide> end
<ide>
<del> context "when verifying appcast checkpoint" do
<del> let(:cask_token) { "appcast-valid-checkpoint" }
<del> let(:download) { instance_double(Hbc::Download) }
<del> let(:mismatch_msg) { /appcast checkpoint mismatch/ }
<del> let(:curl_error_msg) { /error retrieving appcast/ }
<del> let(:fake_curl_result) { instance_double(Hbc::SystemCommand::Result) }
<del> let(:expected_checkpoint) { "d5b2dfbef7ea28c25f7a77cd7fa14d013d82b626db1d82e00e25822464ba19e2" }
<del>
<del> before do
<del> allow(audit).to receive(:check_appcast_http_code)
<del> allow(Hbc::SystemCommand).to receive(:run).and_return(fake_curl_result)
<del> allow(fake_curl_result).to receive(:success?).and_return(success)
<del> end
<del>
<del> context "when appcast download succeeds" do
<del> let(:success) { true }
<del> let(:appcast_text) { instance_double(::String) }
<del>
<del> before do
<del> allow(fake_curl_result).to receive(:stdout).and_return(appcast_text)
<del> allow(appcast_text).to receive(:gsub).and_return(appcast_text)
<del> allow(appcast_text).to receive(:end_with?).with("\n").and_return(true)
<del> allow(Digest::SHA2).to receive(:hexdigest).and_return(actual_checkpoint)
<del> end
<del>
<del> context "when appcast checkpoint is out of date" do
<del> let(:actual_checkpoint) { "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" }
<del>
<del> it { is_expected.to warn_with(mismatch_msg) }
<del> it { is_expected.not_to warn_with(curl_error_msg) }
<del> end
<del>
<del> context "when appcast checkpoint is up to date" do
<del> let(:actual_checkpoint) { expected_checkpoint }
<del>
<del> it { is_expected.not_to warn_with(mismatch_msg) }
<del> it { is_expected.not_to warn_with(curl_error_msg) }
<del> end
<del> end
<del>
<del> context "when appcast download fails" do
<del> let(:success) { false }
<del>
<del> before do
<del> allow(fake_curl_result).to receive(:stderr).and_return("Some curl error")
<del> end
<add> context "when the Cask has a checkpoint" do
<add> let(:cask_token) { "appcast-with-checkpoint" }
<ide>
<del> it { is_expected.to warn_with(curl_error_msg) }
<del> end
<add> it { is_expected.to fail_with(error_msg) }
<ide> end
<ide> end
<ide>
<add><path>Library/Homebrew/test/support/fixtures/cask/Casks/appcast-with-checkpoint.rb
<del><path>Library/Homebrew/test/support/fixtures/cask/Casks/appcast-valid-checkpoint.rb
<del>cask 'appcast-valid-checkpoint' do
<add>cask 'appcast-with-checkpoint' do
<ide> appcast 'http://localhost/appcast.xml',
<ide> checkpoint: 'd5b2dfbef7ea28c25f7a77cd7fa14d013d82b626db1d82e00e25822464ba19e2'
<ide> end
| 3
|
PHP
|
PHP
|
apply special wrapping logic to notifiable models
|
e128a9a579eba3a06e9e73040a568b447c091fee
|
<ide><path>src/Illuminate/Notifications/SendQueuedNotifications.php
<ide>
<ide> use Illuminate\Bus\Queueable;
<ide> use Illuminate\Contracts\Queue\ShouldQueue;
<add>use Illuminate\Database\Eloquent\Collection as EloquentCollection;
<add>use Illuminate\Database\Eloquent\Model;
<ide> use Illuminate\Queue\InteractsWithQueue;
<ide> use Illuminate\Queue\SerializesModels;
<ide> use Illuminate\Support\Collection;
<ide> class SendQueuedNotifications implements ShouldQueue
<ide> /**
<ide> * Create a new job instance.
<ide> *
<del> * @param \Illuminate\Support\Collection $notifiables
<add> * @param mixed $notifiables
<ide> * @param \Illuminate\Notifications\Notification $notification
<ide> * @param array|null $channels
<ide> * @return void
<ide> public function __construct($notifiables, $notification, array $channels = null)
<ide> {
<ide> $this->channels = $channels;
<ide> $this->notification = $notification;
<del> $this->notifiables = Collection::wrap($notifiables);
<add> $this->notifiables = $this->wrapNotifiables($notifiables);
<ide> $this->tries = property_exists($notification, 'tries') ? $notification->tries : null;
<ide> $this->timeout = property_exists($notification, 'timeout') ? $notification->timeout : null;
<ide> }
<ide> public function __clone()
<ide> $this->notifiables = clone $this->notifiables;
<ide> $this->notification = clone $this->notification;
<ide> }
<add>
<add> /**
<add> * Wrap the notifiable(s) in a collection.
<add> *
<add> * @param mixed $notifiables
<add> * @return \Illuminate\Support\Collection
<add> */
<add> protected function wrapNotifiables($notifiables)
<add> {
<add> if ($notifiables instanceof Collection) {
<add> // If the notifiable(s) are already wrapped, pass them as is.
<add> // This prevents any custom queueable collections from being re-wrapped
<add> return $notifiables;
<add> }
<add>
<add> if ($notifiables instanceof Model) {
<add> // In the case of a model we want to wrap it in an eloquent collection
<add> // This way the job can take advantage of model serialization
<add> return EloquentCollection::wrap($notifiables);
<add> }
<add>
<add> return Collection::wrap($notifiables);
<add> }
<ide> }
<ide><path>tests/Notifications/NotificationSendQueuedNotificationTest.php
<ide>
<ide> namespace Illuminate\Tests\Notifications;
<ide>
<add>use Illuminate\Contracts\Database\ModelIdentifier;
<add>use Illuminate\Notifications\AnonymousNotifiable;
<ide> use Illuminate\Notifications\ChannelManager;
<ide> use Illuminate\Notifications\SendQueuedNotifications;
<ide> use Illuminate\Support\Collection;
<add>use Illuminate\Tests\Integration\Notifications\NotifiableUser;
<ide> use Mockery as m;
<ide> use PHPUnit\Framework\TestCase;
<ide>
<ide> public function testNotificationsCanBeSent()
<ide> });
<ide> $job->handle($manager);
<ide> }
<add>
<add> public function testSerializationOfNotifiableModel()
<add> {
<add> $identifier = new ModelIdentifier(NotifiableUser::class, [null], [], null);
<add> $serializedIdentifier = serialize($identifier);
<add>
<add> $job = new SendQueuedNotifications(new NotifiableUser(), 'notification');
<add> $serialized = serialize($job);
<add>
<add> $this->assertStringContainsString($serializedIdentifier, $serialized);
<add> }
<add>
<add> public function testSerializationOfNormalNotifiable()
<add> {
<add> $notifiable = new AnonymousNotifiable();
<add> $serializedNotifiable = serialize($notifiable);
<add>
<add> $job = new SendQueuedNotifications($notifiable, 'notification');
<add> $serialized = serialize($job);
<add>
<add> $this->assertStringContainsString($serializedNotifiable, $serialized);
<add> }
<ide> }
| 2
|
PHP
|
PHP
|
remove the "unauthenticated" method
|
6ed8b3a3e9a454a0959ea8ecd70a166cc3dbf357
|
<ide><path>src/Illuminate/Foundation/Exceptions/Handler.php
<ide> protected function convertValidationExceptionToResponse(ValidationException $e,
<ide> return redirect()->back()->withInput($request->input())->withErrors($errors);
<ide> }
<ide>
<del> /**
<del> * Convert an authentication exception into an unauthenticated response.
<del> *
<del> * @param \Illuminate\Http\Request $request
<del> * @param \Illuminate\Auth\AuthenticationException $e
<del> * @return \Symfony\Component\HttpFoundation\Response
<del> */
<del> protected function unauthenticated($request, AuthenticationException $e)
<del> {
<del> if ($request->ajax() || $request->wantsJson()) {
<del> return response('Unauthorized.', 401);
<del> } else {
<del> return redirect()->guest('login');
<del> }
<del> }
<del>
<ide> /**
<ide> * Create a Symfony response for the given exception.
<ide> *
| 1
|
Ruby
|
Ruby
|
add databaseconfig struct and associated methods
|
1756094b22bf81f15ffdfdb5208075b58c45296f
|
<ide><path>activerecord/lib/active_record/core.rb
<ide> def self.configurations
<ide> @@configurations
<ide> end
<ide>
<add> DatabaseConfig = Struct.new(:env_name, :spec_name, :config) # :nodoc
<add>
<add> # Given an env, spec and config creates DatabaseConfig structs with
<add> # each attribute set.
<add> def self.walk_configs(env_name, spec_name, config) # :nodoc:
<add> if config["database"] || env_name == "default"
<add> DatabaseConfig.new(env_name, spec_name, config)
<add> else
<add> config.each_pair.map do |spec_name, sub_config|
<add> walk_configs(env_name, spec_name, sub_config)
<add> end
<add> end
<add> end
<add>
<add> # Walks all the configs passed in and returns an array
<add> # of DatabaseConfig structs for each configuration.
<add> def self.db_configs(configs = configurations) # :nodoc:
<add> configs.each_pair.flat_map do |env_name, config|
<add> walk_configs(env_name, "primary", config)
<add> end
<add> end
<add>
<add> # Collects the configs for the environment passed in.
<add> #
<add> # If a block is given returns the specification name and configuration
<add> # otherwise returns an array of DatabaseConfig structs for the environment.
<add> def self.configs_for(environment, configs = configurations, &blk) # :nodoc:
<add> env_with_configs = db_configs(configs).select do |db_config|
<add> db_config.env_name == environment
<add> end
<add>
<add> if block_given?
<add> env_with_configs.each do |env_with_config|
<add> yield env_with_config.spec_name, env_with_config.config
<add> end
<add> else
<add> env_with_configs
<add> end
<add> end
<ide> ##
<ide> # :singleton-method:
<ide> # Determines whether to use Time.utc (using :utc) or Time.local (using :local) when pulling
| 1
|
Javascript
|
Javascript
|
inspect unserializable objects
|
afd29c9502449121aacba37b253dc39e159aae03
|
<ide><path>lib/v8.js
<ide> const {
<ide> } = internalBinding('serdes');
<ide> const assert = require('internal/assert');
<ide> const { copy } = internalBinding('buffer');
<add>const { inspect } = require('internal/util/inspect');
<ide> const { FastBuffer } = require('internal/buffer');
<ide> const { getValidatedPath } = require('internal/fs/utils');
<ide> const { toNamespacedPath } = require('path');
<ide> class DefaultSerializer extends Serializer {
<ide> i = arrayBufferViewTypeToIndex.get(tag);
<ide>
<ide> if (i === undefined) {
<del> throw new this._getDataCloneError(`Unknown host object type: ${tag}`);
<add> throw new this._getDataCloneError(
<add> `Unserializable host object: ${inspect(abView)}`);
<ide> }
<ide> }
<ide> this.writeUint32(i);
<ide><path>test/parallel/test-v8-serdes.js
<ide> const deserializerTypeError =
<ide> }
<ide>
<ide> {
<del> assert.throws(() => v8.serialize(hostObject),
<del> /^Error: Unknown host object type: \[object .*\]$/);
<add> assert.throws(() => v8.serialize(hostObject), {
<add> constructor: Error,
<add> message: 'Unserializable host object: JSStream {}'
<add> });
<ide> }
<ide>
<ide> {
| 2
|
Text
|
Text
|
combine rendered note section
|
f444937bd888cd8d5020f17bc3a592c9f5fec5b5
|
<ide><path>docs/docs/accessibility.md
<ide> the cancel button (preventing the keyboard user from accidentally activating the
<ide> initially triggered the modal.
<ide>
<ide> >Note:
<del>
<add>>
<ide> >While this is a very important accessibility feature, it is also a technique that should be used judiciously. Use it to repair the keyboard focus flow when it is disturbed, not to try and anticipate how
<ide> >users want to use applications.
<ide>
| 1
|
Javascript
|
Javascript
|
move custom style
|
b870cbad0f38235d1bc19efd8f331f85aec34e76
|
<ide><path>src/util.js
<ide> var Util = (function UtilClosure() {
<ide> return Util;
<ide> })();
<ide>
<del>// optimised CSS custom property getter/setter
<del>var CustomStyle = (function CustomStyleClosure() {
<del>
<del> // As noted on: http://www.zachstronaut.com/posts/2009/02/17/
<del> // animate-css-transforms-firefox-webkit.html
<del> // in some versions of IE9 it is critical that ms appear in this list
<del> // before Moz
<del> var prefixes = ['ms', 'Moz', 'Webkit', 'O'];
<del> var _cache = { };
<del>
<del> function CustomStyle() {
<del> }
<del>
<del> CustomStyle.getProp = function get(propName, element) {
<del> // check cache only when no element is given
<del> if (arguments.length == 1 && typeof _cache[propName] == 'string') {
<del> return _cache[propName];
<del> }
<del>
<del> element = element || document.documentElement;
<del> var style = element.style, prefixed, uPropName;
<del>
<del> // test standard property first
<del> if (typeof style[propName] == 'string') {
<del> return (_cache[propName] = propName);
<del> }
<del>
<del> // capitalize
<del> uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
<del>
<del> // test vendor specific properties
<del> for (var i = 0, l = prefixes.length; i < l; i++) {
<del> prefixed = prefixes[i] + uPropName;
<del> if (typeof style[prefixed] == 'string') {
<del> return (_cache[propName] = prefixed);
<del> }
<del> }
<del>
<del> //if all fails then set to undefined
<del> return (_cache[propName] = 'undefined');
<del> }
<del>
<del> CustomStyle.setProp = function set(propName, element, str) {
<del> var prop = this.getProp(propName);
<del> if (prop != 'undefined')
<del> element.style[prop] = str;
<del> }
<del>
<del> return CustomStyle;
<del>})();
<del>
<ide> var PDFStringTranslateTable = [
<ide> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
<ide> 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,
<ide><path>web/viewer.js
<ide> var DocumentOutlineView = function documentOutlineView(outline) {
<ide> }
<ide> };
<ide>
<add>// optimised CSS custom property getter/setter
<add>var CustomStyle = (function CustomStyleClosure() {
<add>
<add> // As noted on: http://www.zachstronaut.com/posts/2009/02/17/
<add> // animate-css-transforms-firefox-webkit.html
<add> // in some versions of IE9 it is critical that ms appear in this list
<add> // before Moz
<add> var prefixes = ['ms', 'Moz', 'Webkit', 'O'];
<add> var _cache = { };
<add>
<add> function CustomStyle() {
<add> }
<add>
<add> CustomStyle.getProp = function get(propName, element) {
<add> // check cache only when no element is given
<add> if (arguments.length == 1 && typeof _cache[propName] == 'string') {
<add> return _cache[propName];
<add> }
<add>
<add> element = element || document.documentElement;
<add> var style = element.style, prefixed, uPropName;
<add>
<add> // test standard property first
<add> if (typeof style[propName] == 'string') {
<add> return (_cache[propName] = propName);
<add> }
<add>
<add> // capitalize
<add> uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
<add>
<add> // test vendor specific properties
<add> for (var i = 0, l = prefixes.length; i < l; i++) {
<add> prefixed = prefixes[i] + uPropName;
<add> if (typeof style[prefixed] == 'string') {
<add> return (_cache[propName] = prefixed);
<add> }
<add> }
<add>
<add> //if all fails then set to undefined
<add> return (_cache[propName] = 'undefined');
<add> }
<add>
<add> CustomStyle.setProp = function set(propName, element, str) {
<add> var prop = this.getProp(propName);
<add> if (prop != 'undefined')
<add> element.style[prop] = str;
<add> }
<add>
<add> return CustomStyle;
<add>})();
<add>
<ide> var TextLayerBuilder = function textLayerBuilder(textLayerDiv) {
<ide> this.textLayerDiv = textLayerDiv;
<ide>
| 2
|
Javascript
|
Javascript
|
add type definition for scope#$watchcollection
|
8f329ffb829410e1fd8f86a766929134e736e3e5
|
<ide><path>closure/angular.js
<ide> angular.Module.requires;
<ide> * $parent: angular.Scope,
<ide> * $root: angular.Scope,
<ide> * $watch: function(
<del> * (string|Function), (string|Function)=, boolean=):function()
<add> * (string|Function), (string|Function)=, boolean=):function(),
<add> * $watchCollection: function(
<add> * (string|Function), (string|Function)=):function()
<ide> * }}
<ide> */
<ide> angular.Scope;
<ide> angular.Scope.$root;
<ide> */
<ide> angular.Scope.$watch = function(exp, opt_listener, opt_objectEquality) {};
<ide>
<add>/**
<add> * @param {string|Function} exp
<add> * @param {(string|Function)=} opt_listener
<add> * @return {function()}
<add> */
<add>angular.Scope.$watchCollection = function(exp, opt_listener) {};
<add>
<ide> /**
<ide> * @typedef {{
<ide> * currentScope: angular.Scope,
| 1
|
Python
|
Python
|
remove unused imports and lint
|
eef72ed6e4fb0523c2e936e546c6c5b2ea7cfc91
|
<ide><path>official/transformer/utils/schedule.py
<ide> from __future__ import print_function
<ide>
<ide> import math
<del>import time
<ide>
<ide> import tensorflow as tf
<ide>
<del>from official.transformer.utils import dataset
<del>
<ide>
<ide> _TRAIN, _EVAL = tf.estimator.ModeKeys.TRAIN, tf.estimator.ModeKeys.EVAL
<ide>
<ide> def epochs_to_steps(self, num_epochs, mode):
<ide>
<ide> Args:
<ide> num_epochs: An integer of the number of epochs to convert to steps.
<del> batch_size: The mini-batch size used.
<ide> mode: The estimator ModeKey of the computation
<ide>
<ide> Returns:
<ide><path>official/utils/accelerator/tpu.py
<ide> # ==============================================================================
<ide> """Functions specific to running TensorFlow on TPUs."""
<ide>
<del>import time
<del>
<ide> import tensorflow as tf
<del>from tensorflow.python.framework import dtypes
<del>from tensorflow.python.framework import ops
<del>from tensorflow.python.ops import array_ops
<del>from tensorflow.python.ops import embedding_ops
<del>from tensorflow.python.ops import math_ops
<ide>
<ide>
<ide> # "local" is a magic word in the TPU cluster resolver; it informs the resolver
<ide> def host_call_fn(global_step, *args):
<ide> return host_call_fn, [global_step_tensor] + other_tensors
<ide>
<ide>
<del>def embedding_matmul(embedding_table, values, mask, name='embedding_matmul'):
<add>def embedding_matmul(embedding_table, values, mask, name="embedding_matmul"):
<ide> """Performs embedding lookup via a matmul.
<ide>
<ide> The matrix to be multiplied by the embedding table Tensor is constructed
<ide> def embedding_matmul(embedding_table, values, mask, name='embedding_matmul'):
<ide> Rank 3 tensor of embedding vectors.
<ide> """
<ide>
<del> with ops.name_scope(name):
<del> n_embeddings, embedding_dim = embedding_table.get_shape().as_list()
<add> with tf.name_scope(name):
<add> n_embeddings = embedding_table.get_shape().as_list()[0]
<ide> batch_size, padded_size = values.shape.as_list()
<ide>
<del> emb_idcs = array_ops.tile(
<del> array_ops.reshape(values, (batch_size, padded_size, 1)), (1, 1,
<del> n_embeddings))
<del> emb_weights = array_ops.tile(
<del> array_ops.reshape(mask, (batch_size, padded_size, 1)),
<del> (1, 1, n_embeddings))
<del> col_idcs = array_ops.tile(
<del> array_ops.reshape(math_ops.range(n_embeddings), (1, 1, n_embeddings)),
<add> emb_idcs = tf.tile(
<add> tf.reshape(values, (batch_size, padded_size, 1)), (1, 1, n_embeddings))
<add> emb_weights = tf.tile(
<add> tf.reshape(mask, (batch_size, padded_size, 1)), (1, 1, n_embeddings))
<add> col_idcs = tf.tile(
<add> tf.reshape(tf.range(n_embeddings), (1, 1, n_embeddings)),
<ide> (batch_size, padded_size, 1))
<del> one_hot = array_ops.where(
<del> math_ops.equal(emb_idcs, col_idcs), emb_weights,
<del> array_ops.zeros((batch_size, padded_size, n_embeddings)))
<add> one_hot = tf.where(
<add> tf.equal(emb_idcs, col_idcs), emb_weights,
<add> tf.zeros((batch_size, padded_size, n_embeddings)))
<ide>
<del> return math_ops.tensordot(one_hot, embedding_table, 1)
<add> return tf.tensordot(one_hot, embedding_table, 1)
| 2
|
Python
|
Python
|
remove default value
|
99842387cbe9a5ba8d38e292d7c3c3ff0df0db51
|
<ide><path>spacy/language.py
<ide> def from_config(
<ide> return nlp
<ide>
<ide> def replace_listeners(
<del> self,
<del> tok2vec_name: str,
<del> pipe_name: str,
<del> listeners: Iterable[str] = SimpleFrozenList(),
<add> self, tok2vec_name: str, pipe_name: str, listeners: Iterable[str],
<ide> ) -> None:
<ide> """Find listener layers (connecting to a token-to-vector embedding
<ide> component) of a given pipeline component model and replace
| 1
|
Ruby
|
Ruby
|
add support for generating click shell completions
|
5c7d53476eed5ad93287292e3b7c588d21dbb31d
|
<ide><path>Library/Homebrew/formula.rb
<ide> def extract_macho_slice_from(file, arch = Hardware::CPU.arch)
<ide> # @param base_name [String] the base name of the generated completion script. Defaults to the formula name.
<ide> # @param shells [Array<Symbol>] the shells to generate completion scripts for. Defaults to `[:bash, :zsh, :fish]`.
<ide> # @param shell_parameter_format [String, Symbol] specify how `shells` should each be passed
<del> # to the `executable`. Takes either a String representing a prefix, or one of [:flag, :arg, :none].
<add> # to the `executable`. Takes either a String representing a prefix, or one of [:flag, :arg, :none, :click].
<ide> # Defaults to plainly passing the shell.
<ide> #
<ide> # @example Using default values for optional arguments
<ide> def extract_macho_slice_from(file, arch = Hardware::CPU.arch)
<ide> #
<ide> # (bash_completion/"foo").write Utils.safe_popen_read({ "SHELL" => "bash" }, bin/"foo", "completions")
<ide> #
<add> # @example Using predefined shell_parameter_format :click
<add> # generate_completions_from_executable(bin/"foo", shell_parameter_format: :click, shells: [:zsh])
<add> # translates to
<add> #
<add> # (zsh_completion/"_foo").write Utils.safe_popen_read({ "SHELL" => "zsh", "_FOO_COMPLETE" => "zsh_source" },
<add> # bin/"foo")
<add> #
<ide> # @example Using custom shell_parameter_format
<ide> # generate_completions_from_executable(bin/"foo", "completions", shell_parameter_format: "--selected-shell=",
<ide> # shells: [:bash])
<ide> def generate_completions_from_executable(*commands,
<ide> }
<ide>
<ide> shells.each do |shell|
<add> popen_read_env = { "SHELL" => shell.to_s }
<ide> script_path = completion_script_path_map[shell]
<ide> shell_parameter = if shell_parameter_format.nil?
<ide> shell.to_s
<ide> def generate_completions_from_executable(*commands,
<ide> "--shell=#{shell}"
<ide> elsif shell_parameter_format == :none
<ide> nil
<add> elsif shell_parameter_format == :click
<add> prog_name = File.basename(commands.first.to_s).upcase.tr("-", "_")
<add> popen_read_env["_#{prog_name}_COMPLETE"] = "#{shell}_source"
<add> nil
<ide> else
<ide> "#{shell_parameter_format}#{shell}"
<ide> end
<ide> def generate_completions_from_executable(*commands,
<ide> popen_read_args.flatten!
<ide>
<ide> script_path.dirname.mkpath
<del> script_path.write Utils.safe_popen_read({ "SHELL" => shell.to_s }, *popen_read_args)
<add> script_path.write Utils.safe_popen_read(popen_read_env, *popen_read_args)
<ide> end
<ide> end
<ide>
| 1
|
PHP
|
PHP
|
remove unused app variables from the tests
|
ff424f62a1d855c5a4b7c9a5ffa0f9a17b25c551
|
<ide><path>tests/Foundation/ProviderRepositoryTest.php
<ide> public function testLoadManifestReturnsParsedJSON()
<ide> $repo = new Illuminate\Foundation\ProviderRepository($files = m::mock('Illuminate\Filesystem\Filesystem'), __DIR__);
<ide> $files->shouldReceive('exists')->once()->with(__DIR__.'/services.json')->andReturn(true);
<ide> $files->shouldReceive('get')->once()->with(__DIR__.'/services.json')->andReturn(json_encode($array = array('users' => array('dayle' => true))));
<del> $app = new Illuminate\Foundation\Application;
<ide> $array['when'] = array();
<ide>
<ide> $this->assertEquals($array, $repo->loadManifest());
<ide> public function testWriteManifestStoresToProperLocation()
<ide> {
<ide> $repo = new Illuminate\Foundation\ProviderRepository($files = m::mock('Illuminate\Filesystem\Filesystem'), __DIR__);
<ide> $files->shouldReceive('put')->once()->with(__DIR__.'/services.json', json_encode(array('foo')));
<del> $app = new Illuminate\Foundation\Application;
<ide>
<ide> $result = $repo->writeManifest(array('foo'));
<ide>
| 1
|
Javascript
|
Javascript
|
ignore errors related to fetching
|
4cbb64521a9a3fbbef9cf741314060ef71f07357
|
<ide><path>packager/src/lib/GlobalTransformCache.js
<ide> class TransformProfileSet {
<ide> }
<ide> }
<ide>
<add>class FetchFailedError extends Error {
<add> constructor(message) {
<add> super();
<add> this.message = message;
<add> }
<add>}
<add>
<ide> /**
<ide> * For some reason the result stored by the server for a key might mismatch what
<ide> * we expect a result to be. So we need to verify carefully the data.
<ide> class GlobalTransformCache {
<ide> _profileSet: TransformProfileSet;
<ide> _store: ?KeyResultStore;
<ide>
<add> static FetchFailedError;
<add>
<ide> /**
<ide> * For using the global cache one needs to have some kind of central key-value
<ide> * store that gets prefilled using keyOf() and the transformed results. The
<ide> class GlobalTransformCache {
<ide> static async _fetchResultFromURI(uri: string): Promise<CachedResult> {
<ide> const response = await fetch(uri, {method: 'GET', timeout: 8000});
<ide> if (response.status !== 200) {
<del> throw new Error(`Unexpected HTTP status: ${response.status} ${response.statusText} `);
<add> const msg = `Unexpected HTTP status: ${response.status} ${response.statusText} `;
<add> throw new FetchFailedError(msg);
<ide> }
<ide> const unvalidatedResult = await response.json();
<ide> const result = validateCachedResult(unvalidatedResult);
<ide> if (result == null) {
<del> throw new Error('Server returned invalid result.');
<add> throw new FetchFailedError('Server returned invalid result.');
<ide> }
<ide> return result;
<ide> }
<ide> class GlobalTransformCache {
<ide>
<ide> }
<ide>
<add>GlobalTransformCache.FetchFailedError = FetchFailedError;
<add>
<ide> module.exports = GlobalTransformCache;
| 1
|
Javascript
|
Javascript
|
remove reactproptypelocationnames module
|
bef723e47f09f1136d6a94e4db81fb1ca59cb359
|
<ide><path>src/isomorphic/classic/__tests__/ReactContextValidator-test.js
<ide> describe('ReactContextValidator', () => {
<ide> ReactTestUtils.renderIntoDocument(<Component testContext={{bar: 123}} />);
<ide> expectDev(console.error.calls.count()).toBe(1);
<ide> expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
<del> 'Warning: Failed childContext type: ' +
<add> 'Warning: Failed child context type: ' +
<ide> 'The child context `foo` is marked as required in `Component`, but its ' +
<ide> 'value is `undefined`.\n' +
<ide> ' in Component (at **)'
<ide> describe('ReactContextValidator', () => {
<ide>
<ide> expectDev(console.error.calls.count()).toBe(2);
<ide> expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(1)[0])).toBe(
<del> 'Warning: Failed childContext type: ' +
<add> 'Warning: Failed child context type: ' +
<ide> 'Invalid child context `foo` of type `number` ' +
<ide> 'supplied to `Component`, expected `string`.\n' +
<ide> ' in Component (at **)'
<ide><path>src/isomorphic/classic/class/ReactClass.js
<ide>
<ide> var ReactBaseClasses = require('ReactBaseClasses');
<ide> var ReactElement = require('ReactElement');
<del>var ReactPropTypeLocationNames = require('ReactPropTypeLocationNames');
<ide> var ReactNoopUpdateQueue = require('ReactNoopUpdateQueue');
<ide>
<ide> var emptyObject = require('emptyObject');
<ide> var warning = require('warning');
<ide>
<ide> var ReactComponent = ReactBaseClasses.Component;
<ide>
<del>import type { ReactPropTypeLocations } from 'ReactPropTypeLocations';
<del>
<ide> var MIXINS_KEY = 'mixins';
<ide>
<ide> // Helper function to allow the creation of anonymous functions which do not
<ide> var RESERVED_SPEC_KEYS = {
<ide> validateTypeDef(
<ide> Constructor,
<ide> childContextTypes,
<del> 'childContext'
<add> 'child context'
<ide> );
<ide> }
<ide> Constructor.childContextTypes = Object.assign(
<ide> var RESERVED_SPEC_KEYS = {
<ide> function validateTypeDef(
<ide> Constructor,
<ide> typeDef,
<del> location: ReactPropTypeLocations,
<add> location: string,
<ide> ) {
<ide> for (var propName in typeDef) {
<ide> if (typeDef.hasOwnProperty(propName)) {
<ide> function validateTypeDef(
<ide> '%s: %s type `%s` is invalid; it must be a function, usually from ' +
<ide> 'React.PropTypes.',
<ide> Constructor.displayName || 'ReactClass',
<del> ReactPropTypeLocationNames[location],
<add> location,
<ide> propName
<ide> );
<ide> }
<ide><path>src/isomorphic/classic/types/ReactPropTypes.js
<ide> 'use strict';
<ide>
<ide> var ReactElement = require('ReactElement');
<del>var ReactPropTypeLocationNames = require('ReactPropTypeLocationNames');
<ide> var ReactPropTypesSecret = require('ReactPropTypesSecret');
<ide>
<ide> var emptyFunction = require('emptyFunction');
<ide> function createChainableTypeChecker(validate) {
<ide> }
<ide> }
<ide> if (props[propName] == null) {
<del> var locationName = ReactPropTypeLocationNames[location];
<ide> if (isRequired) {
<ide> if (props[propName] === null) {
<ide> return new PropTypeError(
<del> `The ${locationName} \`${propFullName}\` is marked as required ` +
<add> `The ${location} \`${propFullName}\` is marked as required ` +
<ide> `in \`${componentName}\`, but its value is \`null\`.`
<ide> );
<ide> }
<ide> return new PropTypeError(
<del> `The ${locationName} \`${propFullName}\` is marked as required in ` +
<add> `The ${location} \`${propFullName}\` is marked as required in ` +
<ide> `\`${componentName}\`, but its value is \`undefined\`.`
<ide> );
<ide> }
<ide> function createPrimitiveTypeChecker(expectedType) {
<ide> var propValue = props[propName];
<ide> var propType = getPropType(propValue);
<ide> if (propType !== expectedType) {
<del> var locationName = ReactPropTypeLocationNames[location];
<ide> // `propValue` being instance of, say, date/regexp, pass the 'object'
<ide> // check, but we can offer a more precise error message here rather than
<ide> // 'of type `object`'.
<ide> var preciseType = getPreciseType(propValue);
<ide>
<ide> return new PropTypeError(
<del> `Invalid ${locationName} \`${propFullName}\` of type ` +
<add> `Invalid ${location} \`${propFullName}\` of type ` +
<ide> `\`${preciseType}\` supplied to \`${componentName}\`, expected ` +
<ide> `\`${expectedType}\`.`
<ide> );
<ide> function createArrayOfTypeChecker(typeChecker) {
<ide> }
<ide> var propValue = props[propName];
<ide> if (!Array.isArray(propValue)) {
<del> var locationName = ReactPropTypeLocationNames[location];
<ide> var propType = getPropType(propValue);
<ide> return new PropTypeError(
<del> `Invalid ${locationName} \`${propFullName}\` of type ` +
<add> `Invalid ${location} \`${propFullName}\` of type ` +
<ide> `\`${propType}\` supplied to \`${componentName}\`, expected an array.`
<ide> );
<ide> }
<ide> function createElementTypeChecker() {
<ide> function validate(props, propName, componentName, location, propFullName) {
<ide> var propValue = props[propName];
<ide> if (!ReactElement.isValidElement(propValue)) {
<del> var locationName = ReactPropTypeLocationNames[location];
<ide> var propType = getPropType(propValue);
<ide> return new PropTypeError(
<del> `Invalid ${locationName} \`${propFullName}\` of type ` +
<add> `Invalid ${location} \`${propFullName}\` of type ` +
<ide> `\`${propType}\` supplied to \`${componentName}\`, expected a single ReactElement.`
<ide> );
<ide> }
<ide> function createElementTypeChecker() {
<ide> function createInstanceTypeChecker(expectedClass) {
<ide> function validate(props, propName, componentName, location, propFullName) {
<ide> if (!(props[propName] instanceof expectedClass)) {
<del> var locationName = ReactPropTypeLocationNames[location];
<ide> var expectedClassName = expectedClass.name || ANONYMOUS;
<ide> var actualClassName = getClassName(props[propName]);
<ide> return new PropTypeError(
<del> `Invalid ${locationName} \`${propFullName}\` of type ` +
<add> `Invalid ${location} \`${propFullName}\` of type ` +
<ide> `\`${actualClassName}\` supplied to \`${componentName}\`, expected ` +
<ide> `instance of \`${expectedClassName}\`.`
<ide> );
<ide> function createEnumTypeChecker(expectedValues) {
<ide> }
<ide> }
<ide>
<del> var locationName = ReactPropTypeLocationNames[location];
<ide> var valuesString = JSON.stringify(expectedValues);
<ide> return new PropTypeError(
<del> `Invalid ${locationName} \`${propFullName}\` of value \`${propValue}\` ` +
<add> `Invalid ${location} \`${propFullName}\` of value \`${propValue}\` ` +
<ide> `supplied to \`${componentName}\`, expected one of ${valuesString}.`
<ide> );
<ide> }
<ide> function createObjectOfTypeChecker(typeChecker) {
<ide> var propValue = props[propName];
<ide> var propType = getPropType(propValue);
<ide> if (propType !== 'object') {
<del> var locationName = ReactPropTypeLocationNames[location];
<ide> return new PropTypeError(
<del> `Invalid ${locationName} \`${propFullName}\` of type ` +
<add> `Invalid ${location} \`${propFullName}\` of type ` +
<ide> `\`${propType}\` supplied to \`${componentName}\`, expected an object.`
<ide> );
<ide> }
<ide> function createUnionTypeChecker(arrayOfTypeCheckers) {
<ide> }
<ide> }
<ide>
<del> var locationName = ReactPropTypeLocationNames[location];
<ide> return new PropTypeError(
<del> `Invalid ${locationName} \`${propFullName}\` supplied to ` +
<add> `Invalid ${location} \`${propFullName}\` supplied to ` +
<ide> `\`${componentName}\`.`
<ide> );
<ide> }
<ide> function createUnionTypeChecker(arrayOfTypeCheckers) {
<ide> function createNodeChecker() {
<ide> function validate(props, propName, componentName, location, propFullName) {
<ide> if (!isNode(props[propName])) {
<del> var locationName = ReactPropTypeLocationNames[location];
<ide> return new PropTypeError(
<del> `Invalid ${locationName} \`${propFullName}\` supplied to ` +
<add> `Invalid ${location} \`${propFullName}\` supplied to ` +
<ide> `\`${componentName}\`, expected a ReactNode.`
<ide> );
<ide> }
<ide> function createShapeTypeChecker(shapeTypes) {
<ide> var propValue = props[propName];
<ide> var propType = getPropType(propValue);
<ide> if (propType !== 'object') {
<del> var locationName = ReactPropTypeLocationNames[location];
<ide> return new PropTypeError(
<del> `Invalid ${locationName} \`${propFullName}\` of type \`${propType}\` ` +
<add> `Invalid ${location} \`${propFullName}\` of type \`${propType}\` ` +
<ide> `supplied to \`${componentName}\`, expected \`object\`.`
<ide> );
<ide> }
<ide><path>src/isomorphic/classic/types/__tests__/ReactPropTypesProduction-test.js
<ide> describe('ReactPropTypesProduction', function() {
<ide> var PropTypes;
<ide> var React;
<del> var ReactPropTypeLocations;
<ide> var ReactTestUtils;
<ide> var oldProcess;
<ide>
<ide> describe('ReactPropTypesProduction', function() {
<ide> jest.resetModules();
<ide> PropTypes = require('ReactPropTypes');
<ide> React = require('React');
<del> ReactPropTypeLocations = require('ReactPropTypeLocations');
<ide> ReactTestUtils = require('ReactTestUtils');
<ide> });
<ide>
<ide> describe('ReactPropTypesProduction', function() {
<ide> props,
<ide> 'testProp',
<ide> 'testComponent',
<del> ReactPropTypeLocations.prop
<add> 'prop'
<ide> );
<ide> }).toThrowError(
<ide> 'React.PropTypes type checking code is stripped in production.'
<ide><path>src/renderers/shared/fiber/ReactFiberContext.js
<ide> function processChildContext(fiber : Fiber, parentContext : Object, isReconcilin
<ide> // assume anything about the given fiber. We won't pass it down if we aren't sure.
<ide> // TODO: remove this hack when we delete unstable_renderSubtree in Fiber.
<ide> const workInProgress = isReconciling ? fiber : null;
<del> checkReactTypeSpec(childContextTypes, childContext, 'childContext', name, null, workInProgress);
<add> checkReactTypeSpec(childContextTypes, childContext, 'child context', name, null, workInProgress);
<ide> }
<ide> return {...parentContext, ...childContext};
<ide> }
<ide><path>src/renderers/shared/stack/reconciler/ReactCompositeComponent.js
<ide> var shallowEqual = require('shallowEqual');
<ide> var shouldUpdateReactComponent = require('shouldUpdateReactComponent');
<ide> var warning = require('warning');
<ide>
<del>import type { ReactPropTypeLocations } from 'ReactPropTypeLocations';
<del>
<ide> function StatelessComponent(Component) {
<ide> }
<ide> StatelessComponent.prototype.render = function() {
<ide> var ReactCompositeComponent = {
<ide> this._checkContextTypes(
<ide> Component.childContextTypes,
<ide> childContext,
<del> 'childContext'
<add> 'child context'
<ide> );
<ide> }
<ide> for (var name in childContext) {
<ide> var ReactCompositeComponent = {
<ide> _checkContextTypes: function(
<ide> typeSpecs,
<ide> values,
<del> location: ReactPropTypeLocations,
<add> location: string,
<ide> ) {
<ide> if (__DEV__) {
<ide> checkReactTypeSpec(
<ide><path>src/shared/types/ReactPropTypeLocationNames.js
<del>/**
<del> * Copyright 2013-present, Facebook, Inc.
<del> * All rights reserved.
<del> *
<del> * This source code is licensed under the BSD-style license found in the
<del> * LICENSE file in the root directory of this source tree. An additional grant
<del> * of patent rights can be found in the PATENTS file in the same directory.
<del> *
<del> * @flow
<del> * @providesModule ReactPropTypeLocationNames
<del> */
<del>
<del>'use strict';
<del>
<del>import type { ReactPropTypeLocations } from 'ReactPropTypeLocations';
<del>
<del>type NamesType = {[key: ReactPropTypeLocations]: string};
<del>
<del>var ReactPropTypeLocationNames: NamesType = {};
<del>
<del>if (__DEV__) {
<del> ReactPropTypeLocationNames = {
<del> prop: 'prop',
<del> context: 'context',
<del> childContext: 'child context',
<del> };
<del>}
<del>
<del>module.exports = ReactPropTypeLocationNames;
<ide><path>src/shared/types/ReactPropTypeLocations.js
<del>/**
<del> * Copyright 2013-present, Facebook, Inc.
<del> * All rights reserved.
<del> *
<del> * This source code is licensed under the BSD-style license found in the
<del> * LICENSE file in the root directory of this source tree. An additional grant
<del> * of patent rights can be found in the PATENTS file in the same directory.
<del> *
<del> * @flow
<del> * @providesModule ReactPropTypeLocations
<del> */
<del>
<del>'use strict';
<del>
<del>export type ReactPropTypeLocations =
<del> 'prop' |
<del> 'context' |
<del> 'childContext';
<ide><path>src/shared/types/checkReactTypeSpec.js
<ide>
<ide> 'use strict';
<ide>
<del>var ReactPropTypeLocationNames = require('ReactPropTypeLocationNames');
<ide> var ReactPropTypesSecret = require('ReactPropTypesSecret');
<ide>
<ide> var invariant = require('invariant');
<ide> var warning = require('warning');
<ide>
<del>import type { ReactPropTypeLocations } from 'ReactPropTypeLocations';
<del>
<ide> var ReactComponentTreeHook;
<ide>
<ide> if (
<ide> var loggedTypeFailures = {};
<ide> function checkReactTypeSpec(
<ide> typeSpecs,
<ide> values,
<del> location: ReactPropTypeLocations,
<add> location: string,
<ide> componentName,
<ide> element,
<ide> // It is only safe to pass fiber if it is the work-in-progress version, and
<ide> function checkReactTypeSpec(
<ide> '%s: %s type `%s` is invalid; it must be a function, usually from ' +
<ide> 'React.PropTypes.',
<ide> componentName || 'React class',
<del> ReactPropTypeLocationNames[location],
<add> location,
<ide> typeSpecName
<ide> );
<ide> error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
<ide> function checkReactTypeSpec(
<ide> 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
<ide> 'shape all require an argument).',
<ide> componentName || 'React class',
<del> ReactPropTypeLocationNames[location],
<add> location,
<ide> typeSpecName,
<ide> typeof error
<ide> );
| 9
|
Python
|
Python
|
update version of this trunk
|
9821ee7d64ff4bc5ded66fb89dfe02311f29602f
|
<ide><path>numpy/version.py
<del>version='1.0.2'
<add>version='1.0.3'
<ide> release=False
<ide>
<ide> if not release:
| 1
|
Ruby
|
Ruby
|
add special token comparison examples
|
144a454e3487a75c68759eb5035a8c8ac41082f0
|
<ide><path>Library/Homebrew/test/version_spec.rb
<ide> specify "#to_s" do
<ide> expect(described_class.new("foo").to_s).to eq("foo")
<ide> end
<add>
<add> it "can be compared against nil" do
<add> expect(described_class.create("2")).to be > nil
<add> expect(described_class.create("p194")).to be > nil
<add> end
<add>
<add> it "can be compared against Version::NULL_TOKEN" do
<add> expect(described_class.create("2")).to be > Version::NULL_TOKEN
<add> expect(described_class.create("p194")).to be > Version::NULL_TOKEN
<add> end
<add>
<add> it "can be compared against strings" do
<add> expect(described_class.create("2")).to be == "2"
<add> expect(described_class.create("p194")).to be == "p194"
<add> expect(described_class.create("1")).to be == 1
<add> end
<add>
<add> specify "comparison returns nil for non-token" do
<add> v = described_class.create("1")
<add> expect(v <=> Object.new).to be nil
<add> expect { v > Object.new }.to raise_error(ArgumentError)
<add> end
<ide> end
<ide>
<ide> describe Version::NULL do
| 1
|
Javascript
|
Javascript
|
fix stdout=null when stdio=['pipe']
|
b48684c6f1958930741e2cf34a6a6d5cafa7f478
|
<ide><path>lib/child_process.js
<ide> ChildProcess.prototype.spawn = function(options) {
<ide> }
<ide>
<ide> // At least 3 stdio will be created
<del> if (stdio.length < 3) {
<del> stdio = stdio.concat(new Array(3 - stdio.length));
<del> }
<add> // Don't concat() a new Array() because it would be sparse, and
<add> // stdio.reduce() would skip the sparse elements of stdio.
<add> // See http://stackoverflow.com/a/5501711/3561
<add> while (stdio.length < 3) stdio.push(undefined);
<ide>
<ide> // Translate stdio into C++-readable form
<ide> // (i.e. PipeWraps or fds)
<ide><path>test/simple/test-child-process-stdio.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>var common = require('../common');
<add>var assert = require('assert');
<add>var spawn = require('child_process').spawn;
<add>
<add>var options = {stdio: ['pipe']};
<add>var child = common.spawnPwd(options);
<add>
<add>assert.notEqual(child.stdout, null);
<add>assert.notEqual(child.stderr, null);
<add>
<add>options = {stdio: 'ignore'};
<add>child = common.spawnPwd(options);
<add>
<add>assert.equal(child.stdout, null);
<add>assert.equal(child.stderr, null);
| 2
|
Ruby
|
Ruby
|
handle recommended/optional options better
|
34930586c342dcf10e36ab3eb0c5388dff708e5f
|
<ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit_deps
<ide> end
<ide>
<ide> dep.options.reject do |opt|
<del> # TODO -- fix for :recommended, should still allow --with-xyz
<del> dep_f.build.has_option?(opt.name)
<add> next true if dep_f.build.has_option?(opt.name)
<add> dep_f.requirements.detect do |r|
<add> if r.tags.include? :recommended
<add> opt.name == "with-#{r.name}"
<add> elsif r.tags.include? :optional
<add> opt.name == "without-#{r.name}"
<add> end
<add> end
<ide> end.each do |opt|
<ide> problem "Dependency #{dep} does not define option #{opt.name.inspect}"
<ide> end
| 1
|
Javascript
|
Javascript
|
add an edit button on the docs pages
|
8fbee6c42b6517ab1b31ca20deb04675776204d3
|
<ide><path>website/docusaurus.config.js
<ide> module.exports = {
<ide> docs: {
<ide> path: '../docs',
<ide> routeBasePath: '/',
<del> sidebarPath: require.resolve('./sidebars.js')
<add> sidebarPath: require.resolve('./sidebars.js'),
<add> editUrl: 'https://github.com/reduxjs/redux/edit/master/website'
<ide> },
<ide> theme: {
<ide> customCss: require.resolve('./src/css/custom.css')
| 1
|
Javascript
|
Javascript
|
fix serializing of buffers
|
7786a6a0ed8add7109d2dbf64a272c7630a25b91
|
<ide><path>lib/serialization/ObjectMiddleware.js
<ide> class ObjectMiddleware extends SerializerMiddleware {
<ide> result.push(ESCAPE, ref - currentPos);
<ide> return;
<ide> }
<del> if (typeof item === "object" && item !== null) {
<add> if (Buffer.isBuffer(item)) {
<add> addReferenceable(item);
<add> result.push(item);
<add> } else if (typeof item === "object" && item !== null) {
<ide> if (cycleStack.has(item)) {
<ide> throw new Error(
<ide> `Circular references can't be serialized (${Array.from(cycleStack)
<ide> class ObjectMiddleware extends SerializerMiddleware {
<ide> addReferenceable(item);
<ide> }
<ide> result.push(item);
<del> } else if (Buffer.isBuffer(item)) {
<del> addReferenceable(item);
<del> result.push(item);
<ide> } else if (item === ESCAPE) {
<ide> result.push(ESCAPE, ESCAPE_ESCAPE_VALUE);
<ide> } else if (typeof item === "function") {
| 1
|
Ruby
|
Ruby
|
add a test-case for gh
|
0a43bf3146f0796fe23da50fa5c40e28b1398139
|
<ide><path>railties/test/app_rails_loader_test.rb
<ide> def expects_exec(exe)
<ide> exe = "#{script_dir}/rails"
<ide>
<ide> test "is not in a Rails application if #{exe} is not found in the current or parent directories" do
<del> File.stubs(:exist?).with('bin/rails').returns(false)
<del> File.stubs(:exist?).with('script/rails').returns(false)
<add> File.stubs(:file?).with('bin/rails').returns(false)
<add> File.stubs(:file?).with('script/rails').returns(false)
<add>
<add> assert !Rails::AppRailsLoader.exec_app_rails
<add> end
<add>
<add> test "is not in a Rails application if #{exe} exists but is a folder" do
<add> FileUtils.mkdir_p(exe)
<ide>
<ide> assert !Rails::AppRailsLoader.exec_app_rails
<ide> end
| 1
|
Text
|
Text
|
add changelog entries for [ci skip]
|
5a212939c279e8c5a7dd49fd6766d8cb2fb220f8
|
<ide><path>actionmailer/CHANGELOG.md
<add>* `ActionDispatch::IntegrationTest` includes `ActionMailer::TestHelper` module by default.
<add>
<add> *Ricardo Díaz*
<add>
<ide> * Add `perform_deliveries` to a payload of `deliver.action_mailer` notification.
<ide>
<ide> *Yoshiyuki Kinjo*
<ide><path>activejob/CHANGELOG.md
<add>* `ActionDispatch::IntegrationTest` includes `ActiveJob::TestHelper` module by default.
<add>
<add> *Ricardo Díaz*
<add>
<ide> * Added `enqueue_retry.active_job`, `retry_stopped.active_job`, and `discard.active_job` hooks.
<ide>
<ide> *steves*
| 2
|
Javascript
|
Javascript
|
add test case for source-map bug
|
2935d149a4277dfe470dc3ce29ee49a6f01ad318
|
<ide><path>test/configCases/source-map/sources-array-production/index.js
<add>it("should include test.js in SourceMap", function() {
<add> var fs = require("fs");
<add> var source = fs.readFileSync(__filename + ".map", "utf-8");
<add> var map = JSON.parse(source);
<add> map.sources.should.containEql("webpack:///./test.js");
<add>});
<add>
<add>require.include("./test.js");
<ide><path>test/configCases/source-map/sources-array-production/test.js
<add>var foo = {};
<add>
<add>module.exports = foo;
<ide>\ No newline at end of file
<ide><path>test/configCases/source-map/sources-array-production/webpack.config.js
<add>var webpack = require("../../../../");
<add>module.exports = {
<add> node: {
<add> __dirname: false,
<add> __filename: false
<add> },
<add> devtool: "source-map",
<add> plugins: [
<add> new webpack.optimize.UglifyJsPlugin()
<add> ]
<add>};
<ide>\ No newline at end of file
| 3
|
Python
|
Python
|
add validation every epoch
|
abe9e96afdc49131472fcf64cf626fa8815590ff
|
<ide><path>official/recommendation/ncf_keras_main.py
<ide> def preprocess_train_input(features, labels):
<ide> train_input_fn = producer.make_input_fn(is_training=True)
<ide> train_input_dataset = train_input_fn(params).map(
<ide> preprocess_train_input)
<add> train_input_dataset = train_input_dataset.repeat(FLAGS.train_epochs)
<add>
<ide>
<ide> def preprocess_eval_input(features):
<ide> """Pre-process the eval data.
<ide> def run_ncf(_):
<ide> cloning=params["clone_model_in_keras_dist_strat"])
<ide>
<ide> history = keras_model.fit(train_input_dataset,
<add> steps_per_epoch=num_train_steps,
<ide> epochs=FLAGS.train_epochs,
<ide> callbacks=[
<ide> IncrementEpochCallback(producer),
<ide> time_callback],
<add> validation_data=eval_input_dataset,
<add> validation_steps=num_eval_steps,
<ide> verbose=2)
<ide>
<ide> logging.info("Training done. Start evaluating")
| 1
|
Text
|
Text
|
fix description of n-api exception handlers
|
8dea6dc2fbd527fdf7deda9be2858ec24c24ac48
|
<ide><path>doc/api/n-api.md
<ide> napi_status napi_get_and_clear_last_exception(napi_env env,
<ide>
<ide> Returns `napi_ok` if the API succeeded.
<ide>
<del>This API returns true if an exception is pending.
<del>
<ide> This API can be called even if there is a pending JavaScript exception.
<ide>
<ide> #### napi_is_exception_pending
<ide> napi_status napi_is_exception_pending(napi_env env, bool* result);
<ide>
<ide> Returns `napi_ok` if the API succeeded.
<ide>
<del>This API returns true if an exception is pending.
<del>
<ide> This API can be called even if there is a pending JavaScript exception.
<ide>
<ide> #### napi_fatal_exception
| 1
|
PHP
|
PHP
|
fix unit tests
|
e2c84468bdfd07efdefb8013e5b8ff314c2f2daf
|
<ide><path>tests/Pagination/PaginationBootstrapPresenterTest.php
<ide> public function testGetPageRange()
<ide> $presenter->setCurrentPage(1);
<ide> $content = $presenter->getPageRange(1, 2);
<ide>
<del> $this->assertEquals('<li class="active"><a href="#">1</a></li><li><a href="http://foo.com?page=2">2</a></li>', $content);
<add> $this->assertEquals('<li class="active"><span>1</span></li><li><a href="http://foo.com?page=2">2</a></li>', $content);
<ide> }
<ide>
<ide>
<ide> public function testSliderIsCreatedWhenCloseToStart()
<ide> public function testPreviousLinkCanBeRendered()
<ide> {
<ide> $output = $this->getPresenter()->getPrevious();
<del>
<del> $this->assertEquals('<li class="disabled"><a href="#">«</a></li>', $output);
<add>
<add> $this->assertEquals('<li class="disabled"><span>«</span></li>', $output);
<ide>
<ide> $presenter = $this->getPresenter();
<ide> $presenter->setCurrentPage(2);
<ide> public function testNextLinkCanBeRendered()
<ide> $presenter->setCurrentPage(2);
<ide> $output = $presenter->getNext();
<ide>
<del> $this->assertEquals('<li class="disabled"><a href="#">»</a></li>', $output);
<add> $this->assertEquals('<li class="disabled"><span>»</span></li>', $output);
<ide>
<ide> $presenter = $this->getPresenter();
<ide> $presenter->setCurrentPage(1);
<ide> public function testGetStart()
<ide> $presenter = $this->getPresenter();
<ide> $output = $presenter->getStart();
<ide>
<del> $this->assertEquals('<li class="active"><a href="#">1</a></li><li><a href="http://foo.com?page=2">2</a></li><li class="disabled"><a href="#">...</a></li>', $output);
<add> $this->assertEquals('<li class="active"><span>1</a></li><li><a href="http://foo.com?page=2">2</a></li><li class="disabled"><span>...</span></li>', $output);
<ide> }
<ide>
<ide>
<ide> public function testGetFinish()
<ide> $presenter = $this->getPresenter();
<ide> $output = $presenter->getFinish();
<ide>
<del> $this->assertEquals('<li class="disabled"><a href="#">...</a></li><li class="active"><a href="#">1</a></li><li><a href="http://foo.com?page=2">2</a></li>', $output);
<add> $this->assertEquals('<li class="disabled"><span>...</span></li><li class="active"><span>1</a></li><li><a href="http://foo.com?page=2">2</a></li>', $output);
<ide> }
<ide>
<ide>
<ide> protected function getPaginator()
<ide> return $paginator;
<ide> }
<ide>
<del>}
<ide>\ No newline at end of file
<add>}
| 1
|
Javascript
|
Javascript
|
add a better filename to the dynamic import chunk.
|
247dd98cf377f4c663b137632244a974cdc7c500
|
<ide><path>server/build/babel/plugins/handle-import.js
<ide> export default () => ({
<ide> visitor: {
<ide> CallExpression (path) {
<ide> if (path.node.callee.type === TYPE_IMPORT) {
<add> const moduleName = path.node.arguments[0].value
<add> const name = `${moduleName.replace(/[^\w]/g, '-')}-${UUID.v4()}`
<ide> const newImport = buildImport({
<del> name: UUID.v4()
<add> name
<ide> })({
<ide> SOURCE: path.node.arguments
<ide> })
| 1
|
PHP
|
PHP
|
fix requestaction() not working with middleware
|
d7d0e22ac639472912c99cf1ccbef445e2b1d0c4
|
<ide><path>src/Routing/RequestActionTrait.php
<ide> use Cake\Network\Request;
<ide> use Cake\Network\Response;
<ide> use Cake\Network\Session;
<add>use Cake\Routing\Filter\ControllerFactoryFilter;
<add>use Cake\Routing\Filter\RoutingFilter;
<ide>
<ide> /**
<ide> * Provides the requestAction() method for doing sub-requests
<ide> public function requestAction($url, array $extra = [])
<ide> $request = new Request($params);
<ide> $request->addParams($extra);
<ide> $dispatcher = DispatcherFactory::create();
<add>
<add> // If an application is using PSR7 middleware,
<add> // we need to 'fix' their missing dispatcher filters.
<add> $needed = [
<add> 'routing' => RoutingFilter::class,
<add> 'controller' => ControllerFactoryFilter::class
<add> ];
<add> foreach ($dispatcher->filters() as $filter) {
<add> if ($filter instanceof RoutingFilter) {
<add> unset($needed['routing']);
<add> }
<add> if ($filter instanceof ControllerFactoryFilter) {
<add> unset($needed['controller']);
<add> }
<add> }
<add> foreach ($needed as $class) {
<add> $dispatcher->addFilter(new $class);
<add> }
<ide> $result = $dispatcher->dispatch($request, new Response());
<ide> Router::popRequest();
<ide>
<ide><path>tests/TestCase/Routing/RequestActionTraitTest.php
<ide> */
<ide> class RequestActionTraitTest extends TestCase
<ide> {
<del>
<ide> /**
<ide> * fixtures
<ide> *
<ide> public function testRequestActionSession()
<ide> );
<ide> $this->assertEquals('bar', $result);
<ide> }
<add>
<add> /**
<add> * requestAction relies on both the RoutingFilter and ControllerFactory
<add> * filters being connected. Ensure it can correct the missing state.
<add> *
<add> * @return void
<add> */
<add> public function testRequestActionAddsRequiredFilters()
<add> {
<add> DispatcherFactory::clear();
<add>
<add> $result = $this->object->requestAction('/request_action/test_request_action');
<add> $expected = 'This is a test';
<add> $this->assertEquals($expected, $result);
<add> }
<ide> }
| 2
|
Javascript
|
Javascript
|
fix typo in server response example
|
09f8962df2131cad446b207a6ab0551c8acd31d0
|
<ide><path>src/ngResource/resource.js
<ide> function shallowClearAndCopy(src, dst) {
<ide> newCard.name = "Mike Smith";
<ide> newCard.$save();
<ide> // POST: /user/123/card {number:'0123', name:'Mike Smith'}
<del> // server returns: {id:789, number:'01234', name: 'Mike Smith'};
<add> // server returns: {id:789, number:'0123', name: 'Mike Smith'};
<ide> expect(newCard.id).toEqual(789);
<ide> * </pre>
<ide> *
<ide> function shallowClearAndCopy(src, dst) {
<ide> });
<ide> </pre>
<ide>
<del> * @example
<ide> * # Creating a custom 'PUT' request
<ide> * In this example we create a custom method on our resource to make a PUT request
<ide> * <pre>
| 1
|
Java
|
Java
|
improve clienthttprequestfactory javadoc
|
09327181c4d07031e4ed8aa7a822c34075de935a
|
<ide><path>spring-web-reactive/src/main/java/org/springframework/http/client/reactive/ClientHttpRequestFactory.java
<ide>
<ide> import java.net.URI;
<ide>
<add>import org.reactivestreams.Publisher;
<add>
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<ide>
<ide> public interface ClientHttpRequestFactory {
<ide>
<ide> /**
<ide> * Create a new {@link ClientHttpRequest} for the specified HTTP method, URI and headers
<add> * <p>The returned request can be {@link ClientHttpRequest#setBody(Publisher) written to},
<add> * and then executed by calling {@link ClientHttpRequest#execute()}
<ide> *
<ide> * @param httpMethod the HTTP method to execute
<ide> * @param uri the URI to create a request for
| 1
|
Ruby
|
Ruby
|
add missing `macos.release` deprecation
|
6714acc09809b3548960ee1d29d180e036348391
|
<ide><path>Library/Homebrew/compat.rb
<ide> require "compat/extend/string"
<ide> require "compat/gpg"
<ide> require "compat/dependable"
<add>require "compat/os/mac"
<ide><path>Library/Homebrew/compat/os/mac.rb
<add>module OS
<add> module Mac
<add> class << self
<add> def release
<add> odeprecated "MacOS.release", "MacOS.version"
<add> version
<add> end
<add> end
<add> end
<add>end
| 2
|
Javascript
|
Javascript
|
add backwards compatibility to three.audio's .load
|
bf5d23f461f0ecc5ab18a78469877998085ffa7b
|
<ide><path>src/audio/Audio.js
<ide> THREE.Audio.prototype.getOutput = function() {
<ide>
<ide> };
<ide>
<del>THREE.Audio.prototype.load = function() {
<add>THREE.Audio.prototype.load = function( url ) {
<ide>
<ide> console.warn( 'THREE.Audio: .load has been deprecated. Please use THREE.AudioLoader.' );
<ide>
<add> var audioLoader = new THREE.AudioLoader(this.context);
<add>
<add> audioLoader.load( url, function( buffer ) {
<add> this.setBuffer( buffer );
<add> });
<add>
<ide> };
<ide>
<ide> THREE.Audio.prototype.setNodeSource = function( audioNode ) {
| 1
|
Ruby
|
Ruby
|
add missing tests for memory store of cache
|
6b0792266b025e57f666b01cc206e78f31c01df4
|
<ide><path>activesupport/test/caching_test.rb
<ide> def with_env(kv)
<ide> end
<ide>
<ide> class CacheStoreSettingTest < ActiveSupport::TestCase
<add> def test_memory_store_gets_created_if_no_arguments_passed_to_lookup_store_method
<add> store = ActiveSupport::Cache.lookup_store
<add> assert_kind_of(ActiveSupport::Cache::MemoryStore, store)
<add> end
<add>
<add> def test_memory_store
<add> store = ActiveSupport::Cache.lookup_store :memory_store
<add> assert_kind_of(ActiveSupport::Cache::MemoryStore, store)
<add> end
<add>
<ide> def test_file_fragment_cache_store
<ide> store = ActiveSupport::Cache.lookup_store :file_store, "/path/to/cache/directory"
<ide> assert_kind_of(ActiveSupport::Cache::FileStore, store)
| 1
|
Text
|
Text
|
add missing punctuation marks and url name
|
f3ed69374dc8b181bbde497a824b165e31f13457
|
<ide><path>docs/topics/api-clients.md
<ide> First, install the API documentation views. These will include the schema resour
<ide>
<ide> urlpatterns = [
<ide> ...
<del> url(r'^docs/', include_docs_urls(title='My API service'))
<add> url(r'^docs/', include_docs_urls(title='My API service'), name='api-docs'),
<ide> ]
<ide>
<ide> Once the API documentation URLs are installed, you'll be able to include both the required JavaScript resources. Note that the ordering of these two lines is important, as the schema loading requires CoreAPI to already be installed.
<ide> Once the API documentation URLs are installed, you'll be able to include both th
<ide>
<ide> The `coreapi` library, and the `schema` object will now both be available on the `window` instance.
<ide>
<del> const coreapi = window.coreapi
<del> const schema = window.schema
<add> const coreapi = window.coreapi;
<add> const schema = window.schema;
<ide>
<ide> ## Instantiating a client
<ide>
<ide> In order to interact with the API you'll need a client instance.
<ide>
<del> var client = new coreapi.Client()
<add> var client = new coreapi.Client();
<ide>
<ide> Typically you'll also want to provide some authentication credentials when
<ide> instantiating the client.
<ide> the user to login, and then instantiate a client using session authentication:
<ide>
<ide> let auth = new coreapi.auth.SessionAuthentication({
<ide> csrfCookieName: 'csrftoken',
<del> csrfHeaderName: 'X-CSRFToken'
<del> })
<del> let client = new coreapi.Client({auth: auth})
<add> csrfHeaderName: 'X-CSRFToken',
<add> });
<add> let client = new coreapi.Client({auth: auth});
<ide>
<ide> The authentication scheme will handle including a CSRF header in any outgoing
<ide> requests for unsafe HTTP methods.
<ide> The `TokenAuthentication` class can be used to support REST framework's built-in
<ide> `TokenAuthentication`, as well as OAuth and JWT schemes.
<ide>
<ide> let auth = new coreapi.auth.TokenAuthentication({
<del> scheme: 'JWT'
<del> token: '<token>'
<del> })
<del> let client = new coreapi.Client({auth: auth})
<add> scheme: 'JWT',
<add> token: '<token>',
<add> });
<add> let client = new coreapi.Client({auth: auth});
<ide>
<ide> When using TokenAuthentication you'll probably need to implement a login flow
<ide> using the CoreAPI client.
<ide> request to an "obtain token" endpoint
<ide> For example, using the "Django REST framework JWT" package
<ide>
<ide> // Setup some globally accessible state
<del> window.client = new coreapi.Client()
<del> window.loggedIn = false
<add> window.client = new coreapi.Client();
<add> window.loggedIn = false;
<ide>
<ide> function loginUser(username, password) {
<del> let action = ["api-token-auth", "obtain-token"]
<del> let params = {username: "example", email: "example@example.com"}
<add> let action = ["api-token-auth", "obtain-token"];
<add> let params = {username: "example", email: "example@example.com"};
<ide> client.action(schema, action, params).then(function(result) {
<ide> // On success, instantiate an authenticated client.
<ide> let auth = window.coreapi.auth.TokenAuthentication({
<ide> scheme: 'JWT',
<del> token: result['token']
<add> token: result['token'],
<ide> })
<del> window.client = coreapi.Client({auth: auth})
<del> window.loggedIn = true
<add> window.client = coreapi.Client({auth: auth});
<add> window.loggedIn = true;
<ide> }).catch(function (error) {
<ide> // Handle error case where eg. user provides incorrect credentials.
<ide> })
<ide> The `BasicAuthentication` class can be used to support HTTP Basic Authentication
<ide>
<ide> let auth = new coreapi.auth.BasicAuthentication({
<ide> username: '<username>',
<del> password: '<password>'
<add> password: '<password>',
<ide> })
<del> let client = new coreapi.Client({auth: auth})
<add> let client = new coreapi.Client({auth: auth});
<ide>
<ide> ## Using the client
<ide>
<ide> Making requests:
<ide>
<del> let action = ["users", "list"]
<add> let action = ["users", "list"];
<ide> client.action(schema, action).then(function(result) {
<ide> // Return value is in 'result'
<ide> })
<ide>
<ide> Including parameters:
<ide>
<del> let action = ["users", "create"]
<del> let params = {username: "example", email: "example@example.com"}
<add> let action = ["users", "create"];
<add> let params = {username: "example", email: "example@example.com"};
<ide> client.action(schema, action, params).then(function(result) {
<ide> // Return value is in 'result'
<ide> })
<ide> The coreapi package is available on NPM.
<ide>
<ide> You'll either want to include the API schema in your codebase directly, by copying it from the `schema.js` resource, or else load the schema asynchronously. For example:
<ide>
<del> let client = new coreapi.Client()
<del> let schema = null
<add> let client = new coreapi.Client();
<add> let schema = null;
<ide> client.get("https://api.example.org/").then(function(data) {
<ide> // Load a CoreJSON API schema.
<del> schema = data
<del> console.log('schema loaded')
<add> schema = data;
<add> console.log('schema loaded');
<ide> })
<ide>
<ide> [heroku-api]: https://devcenter.heroku.com/categories/platform-api
| 1
|
Ruby
|
Ruby
|
extract common decompression code to a method
|
7541f1316422d89b96af763a4c9cce68aff1f4cd
|
<ide><path>Library/Homebrew/download_strategy.rb
<ide> def fetch
<ide> tarball_path
<ide> end
<ide>
<add> # gunzip and bunzip2 write the output file in the same directory as the input
<add> # file regardless of the current working directory, so we need to write it to
<add> # the correct location ourselves.
<add> def buffered_write(tool)
<add> target = File.basename(basename_without_params, tarball_path.extname)
<add>
<add> IO.popen("#{tool} -f '#{tarball_path}' -c") do |pipe|
<add> File.open(target, "wb") do |f|
<add> buf = ""
<add> f.write(buf) while pipe.read(1024, buf)
<add> end
<add> end
<add> end
<add>
<ide> def stage
<ide> case tarball_path.compression_type
<ide> when :zip
<ide> with_system_path { quiet_safe_system 'unzip', {:quiet_flag => '-qq'}, tarball_path }
<ide> chdir
<ide> when :gzip_only
<del> # gunzip writes the compressed data in the location of the original,
<del> # regardless of the current working directory; the only way to
<del> # write elsewhere is to use the stdout
<del> with_system_path do
<del> target = File.basename(basename_without_params, ".gz")
<del>
<del> IO.popen("gunzip -f '#{tarball_path}' -c") do |pipe|
<del> File.open(target, "wb") do |f|
<del> buf = ""
<del> f.write(buf) while pipe.read(1024, buf)
<del> end
<del> end
<del> end
<add> with_system_path { buffered_write("gunzip") }
<ide> when :bzip2_only
<del> with_system_path do
<del> target = File.basename(basename_without_params, ".bz2")
<del>
<del> IO.popen("bunzip2 -f '#{tarball_path}' -c") do |pipe|
<del> File.open(target, "wb") do |f|
<del> buf = ""
<del> f.write(buf) while pipe.read(1024, buf)
<del> end
<del> end
<del> end
<add> with_system_path { buffered_write("bunzip2") }
<ide> when :gzip, :bzip2, :compress, :tar
<ide> # Assume these are also tarred
<ide> # TODO check if it's really a tar archive
| 1
|
Javascript
|
Javascript
|
fix the versions script again
|
9bfbb16e235767aeb8f50855b38626159fa35278
|
<ide><path>lib/versions/version-info.js
<ide> var getTaggedVersion = function() {
<ide>
<ide> if ( version && semver.satisfies(version, currentPackage.branchVersion)) {
<ide> version.codeName = getCodeName(tag);
<del> version.full = version.version + '+' + version.build;
<add> version.full = version.version;
<ide> return version;
<ide> }
<ide> }
| 1
|
Java
|
Java
|
improve charset management in xpathresultmatchers
|
f9881511637c52836c8a1743fa586113de5cdfd5
|
<ide><path>spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java
<ide> public boolean isWriterAccessAllowed() {
<ide> return this.writerAccessAllowed;
<ide> }
<ide>
<add> /**
<add> * Return whether the character encoding has been set.
<add> * <p>If {@code false}, {@link #getCharacterEncoding()} will return a default encoding value.
<add> */
<add> public boolean isCharset() {
<add> return charset;
<add> }
<add>
<ide> @Override
<ide> public void setCharacterEncoding(String characterEncoding) {
<ide> this.characterEncoding = characterEncoding;
<ide><path>spring-test/src/main/java/org/springframework/test/util/XpathExpectationsHelper.java
<ide>
<ide> package org.springframework.test.util;
<ide>
<del>import java.io.StringReader;
<add>import static org.hamcrest.MatcherAssert.*;
<add>import static org.springframework.test.util.AssertionErrors.*;
<add>
<add>import java.io.ByteArrayInputStream;
<ide> import java.util.Collections;
<ide> import java.util.Map;
<add>
<ide> import javax.xml.namespace.QName;
<ide> import javax.xml.parsers.DocumentBuilder;
<ide> import javax.xml.parsers.DocumentBuilderFactory;
<ide> import org.xml.sax.InputSource;
<ide>
<ide> import org.springframework.util.CollectionUtils;
<add>import org.springframework.util.StringUtils;
<ide> import org.springframework.util.xml.SimpleNamespaceContext;
<ide>
<del>import static org.hamcrest.MatcherAssert.*;
<del>import static org.springframework.test.util.AssertionErrors.*;
<del>
<ide> /**
<ide> * A helper class for applying assertions via XPath expressions.
<ide> *
<ide> protected XPathExpression getXpathExpression() {
<ide> * Parse the content, evaluate the XPath expression as a {@link Node}, and
<ide> * assert it with the given {@code Matcher<Node>}.
<ide> */
<del> public void assertNode(String content, final Matcher<? super Node> matcher) throws Exception {
<del> Document document = parseXmlString(content);
<add> public void assertNode(byte[] content, String encoding, final Matcher<? super Node> matcher) throws Exception {
<add> Document document = parseXmlByteArray(content, encoding);
<ide> Node node = evaluateXpath(document, XPathConstants.NODE, Node.class);
<ide> assertThat("XPath " + this.expression, node, matcher);
<ide> }
<ide>
<ide> /**
<ide> * Parse the given XML content to a {@link Document}.
<ide> * @param xml the content to parse
<add> * @param encoding optional content encoding, if provided as metadata (e.g. in HTTP headers)
<ide> * @return the parsed document
<del> * @throws Exception in case of errors
<add> * @throws Exception
<ide> */
<del> protected Document parseXmlString(String xml) throws Exception {
<add> protected Document parseXmlByteArray(byte[] xml, String encoding) throws Exception {
<ide> DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
<ide> factory.setNamespaceAware(this.hasNamespaces);
<ide> DocumentBuilder documentBuilder = factory.newDocumentBuilder();
<del> InputSource inputSource = new InputSource(new StringReader(xml));
<add> InputSource inputSource = new InputSource(new ByteArrayInputStream(xml));
<add> if(StringUtils.hasText(encoding)) {
<add> inputSource.setEncoding(encoding);
<add> }
<ide> return documentBuilder.parse(inputSource);
<ide> }
<ide>
<ide> protected <T> T evaluateXpath(Document document, QName evaluationType, Class<T>
<ide> * Apply the XPath expression and assert the resulting content exists.
<ide> * @throws Exception if content parsing or expression evaluation fails
<ide> */
<del> public void exists(String content) throws Exception {
<del> Document document = parseXmlString(content);
<add> public void exists(byte[] content, String encoding) throws Exception {
<add> Document document = parseXmlByteArray(content, encoding);
<ide> Node node = evaluateXpath(document, XPathConstants.NODE, Node.class);
<ide> assertTrue("XPath " + this.expression + " does not exist", node != null);
<ide> }
<ide> public void exists(String content) throws Exception {
<ide> * Apply the XPath expression and assert the resulting content does not exist.
<ide> * @throws Exception if content parsing or expression evaluation fails
<ide> */
<del> public void doesNotExist(String content) throws Exception {
<del> Document document = parseXmlString(content);
<add> public void doesNotExist(byte[] content, String encoding) throws Exception {
<add> Document document = parseXmlByteArray(content, encoding);
<ide> Node node = evaluateXpath(document, XPathConstants.NODE, Node.class);
<ide> assertTrue("XPath " + this.expression + " exists", node == null);
<ide> }
<ide> public void doesNotExist(String content) throws Exception {
<ide> * given Hamcrest matcher.
<ide> * @throws Exception if content parsing or expression evaluation fails
<ide> */
<del> public void assertNodeCount(String content, Matcher<Integer> matcher) throws Exception {
<del> Document document = parseXmlString(content);
<add> public void assertNodeCount(byte[] content, String encoding, Matcher<Integer> matcher) throws Exception {
<add> Document document = parseXmlByteArray(content, encoding);
<ide> NodeList nodeList = evaluateXpath(document, XPathConstants.NODESET, NodeList.class);
<ide> assertThat("nodeCount for XPath " + this.expression, nodeList.getLength(), matcher);
<ide> }
<ide> public void assertNodeCount(String content, Matcher<Integer> matcher) throws Exc
<ide> * Apply the XPath expression and assert the resulting content as an integer.
<ide> * @throws Exception if content parsing or expression evaluation fails
<ide> */
<del> public void assertNodeCount(String content, int expectedCount) throws Exception {
<del> Document document = parseXmlString(content);
<add> public void assertNodeCount(byte[] content, String encoding, int expectedCount) throws Exception {
<add> Document document = parseXmlByteArray(content, encoding);
<ide> NodeList nodeList = evaluateXpath(document, XPathConstants.NODESET, NodeList.class);
<ide> assertEquals("nodeCount for XPath " + this.expression, expectedCount, nodeList.getLength());
<ide> }
<ide> public void assertNodeCount(String content, int expectedCount) throws Exception
<ide> * given Hamcrest matcher.
<ide> * @throws Exception if content parsing or expression evaluation fails
<ide> */
<del> public void assertString(String content, Matcher<? super String> matcher) throws Exception {
<del> Document document = parseXmlString(content);
<add> public void assertString(byte[] content, String encoding, Matcher<? super String> matcher) throws Exception {
<add> Document document = parseXmlByteArray(content, encoding);
<ide> String result = evaluateXpath(document, XPathConstants.STRING, String.class);
<ide> assertThat("XPath " + this.expression, result, matcher);
<ide> }
<ide> public void assertString(String content, Matcher<? super String> matcher) throws
<ide> * Apply the XPath expression and assert the resulting content as a String.
<ide> * @throws Exception if content parsing or expression evaluation fails
<ide> */
<del> public void assertString(String content, String expectedValue) throws Exception {
<del> Document document = parseXmlString(content);
<add> public void assertString(byte[] content, String encoding, String expectedValue) throws Exception {
<add> Document document = parseXmlByteArray(content, encoding);
<ide> String actual = evaluateXpath(document, XPathConstants.STRING, String.class);
<ide> assertEquals("XPath " + this.expression, expectedValue, actual);
<ide> }
<ide> public void assertString(String content, String expectedValue) throws Exception
<ide> * given Hamcrest matcher.
<ide> * @throws Exception if content parsing or expression evaluation fails
<ide> */
<del> public void assertNumber(String content, Matcher<? super Double> matcher) throws Exception {
<del> Document document = parseXmlString(content);
<add> public void assertNumber(byte[] content, String encoding, Matcher<? super Double> matcher) throws Exception {
<add> Document document = parseXmlByteArray(content, encoding);
<ide> Double result = evaluateXpath(document, XPathConstants.NUMBER, Double.class);
<ide> assertThat("XPath " + this.expression, result, matcher);
<ide> }
<ide> public void assertNumber(String content, Matcher<? super Double> matcher) throws
<ide> * Apply the XPath expression and assert the resulting content as a Double.
<ide> * @throws Exception if content parsing or expression evaluation fails
<ide> */
<del> public void assertNumber(String content, Double expectedValue) throws Exception {
<del> Document document = parseXmlString(content);
<add> public void assertNumber(byte[] content, String encoding, Double expectedValue) throws Exception {
<add> Document document = parseXmlByteArray(content, encoding);
<ide> Double actual = evaluateXpath(document, XPathConstants.NUMBER, Double.class);
<ide> assertEquals("XPath " + this.expression, expectedValue, actual);
<ide> }
<ide> public void assertNumber(String content, Double expectedValue) throws Exception
<ide> * Apply the XPath expression and assert the resulting content as a Boolean.
<ide> * @throws Exception if content parsing or expression evaluation fails
<ide> */
<del> public void assertBoolean(String content, boolean expectedValue) throws Exception {
<del> Document document = parseXmlString(content);
<add> public void assertBoolean(byte[] content, String encoding, boolean expectedValue) throws Exception {
<add> Document document = parseXmlByteArray(content, encoding);
<ide> String actual = evaluateXpath(document, XPathConstants.STRING, String.class);
<ide> assertEquals("XPath " + this.expression, expectedValue, Boolean.parseBoolean(actual));
<ide> }
<ide><path>spring-test/src/main/java/org/springframework/test/web/client/match/XpathRequestMatchers.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2015 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> */
<ide> public class XpathRequestMatchers {
<ide>
<add> private static final String DEFAULT_ENCODING = "UTF-8";
<add>
<ide> private final XpathExpectationsHelper xpathHelper;
<ide>
<ide>
<ide> public <T> RequestMatcher node(final Matcher<? super Node> matcher) {
<ide> return new AbstractXpathRequestMatcher() {
<ide> @Override
<ide> protected void matchInternal(MockClientHttpRequest request) throws Exception {
<del> xpathHelper.assertNode(request.getBodyAsString(), matcher);
<add> xpathHelper.assertNode(request.getBodyAsBytes(), DEFAULT_ENCODING, matcher);
<ide> }
<ide> };
<ide> }
<ide> public <T> RequestMatcher exists() {
<ide> return new AbstractXpathRequestMatcher() {
<ide> @Override
<ide> protected void matchInternal(MockClientHttpRequest request) throws Exception {
<del> xpathHelper.exists(request.getBodyAsString());
<add> xpathHelper.exists(request.getBodyAsBytes(), DEFAULT_ENCODING);
<ide> }
<ide> };
<ide> }
<ide> public <T> RequestMatcher doesNotExist() {
<ide> return new AbstractXpathRequestMatcher() {
<ide> @Override
<ide> protected void matchInternal(MockClientHttpRequest request) throws Exception {
<del> xpathHelper.doesNotExist(request.getBodyAsString());
<add> xpathHelper.doesNotExist(request.getBodyAsBytes(), DEFAULT_ENCODING);
<ide> }
<ide> };
<ide> }
<ide> public <T> RequestMatcher nodeCount(final Matcher<Integer> matcher) {
<ide> return new AbstractXpathRequestMatcher() {
<ide> @Override
<ide> protected void matchInternal(MockClientHttpRequest request) throws Exception {
<del> xpathHelper.assertNodeCount(request.getBodyAsString(), matcher);
<add> xpathHelper.assertNodeCount(request.getBodyAsBytes(), DEFAULT_ENCODING, matcher);
<ide> }
<ide> };
<ide> }
<ide> public <T> RequestMatcher nodeCount(final int expectedCount) {
<ide> return new AbstractXpathRequestMatcher() {
<ide> @Override
<ide> protected void matchInternal(MockClientHttpRequest request) throws Exception {
<del> xpathHelper.assertNodeCount(request.getBodyAsString(), expectedCount);
<add> xpathHelper.assertNodeCount(request.getBodyAsBytes(), DEFAULT_ENCODING, expectedCount);
<ide> }
<ide> };
<ide> }
<ide> public <T> RequestMatcher string(final Matcher<? super String> matcher) {
<ide> return new AbstractXpathRequestMatcher() {
<ide> @Override
<ide> protected void matchInternal(MockClientHttpRequest request) throws Exception {
<del> xpathHelper.assertString(request.getBodyAsString(), matcher);
<add> xpathHelper.assertString(request.getBodyAsBytes(), DEFAULT_ENCODING, matcher);
<ide> }
<ide> };
<ide> }
<ide> public RequestMatcher string(final String value) {
<ide> return new AbstractXpathRequestMatcher() {
<ide> @Override
<ide> protected void matchInternal(MockClientHttpRequest request) throws Exception {
<del> xpathHelper.assertString(request.getBodyAsString(), value);
<add> xpathHelper.assertString(request.getBodyAsBytes(), DEFAULT_ENCODING, value);
<ide> }
<ide> };
<ide> }
<ide> public <T> RequestMatcher number(final Matcher<? super Double> matcher) {
<ide> return new AbstractXpathRequestMatcher() {
<ide> @Override
<ide> protected void matchInternal(MockClientHttpRequest request) throws Exception {
<del> xpathHelper.assertNumber(request.getBodyAsString(), matcher);
<add> xpathHelper.assertNumber(request.getBodyAsBytes(), DEFAULT_ENCODING, matcher);
<ide> }
<ide> };
<ide> }
<ide> public RequestMatcher number(final Double value) {
<ide> return new AbstractXpathRequestMatcher() {
<ide> @Override
<ide> protected void matchInternal(MockClientHttpRequest request) throws Exception {
<del> xpathHelper.assertNumber(request.getBodyAsString(), value);
<add> xpathHelper.assertNumber(request.getBodyAsBytes(), DEFAULT_ENCODING, value);
<ide> }
<ide> };
<ide> }
<ide> public <T> RequestMatcher booleanValue(final Boolean value) {
<ide> return new AbstractXpathRequestMatcher() {
<ide> @Override
<ide> protected void matchInternal(MockClientHttpRequest request) throws Exception {
<del> xpathHelper.assertBoolean(request.getBodyAsString(), value);
<add> xpathHelper.assertBoolean(request.getBodyAsBytes(), DEFAULT_ENCODING, value);
<ide> }
<ide> };
<ide> }
<ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/result/XpathResultMatchers.java
<ide> import org.hamcrest.Matcher;
<ide> import org.w3c.dom.Node;
<ide>
<add>import org.springframework.mock.web.MockHttpServletResponse;
<ide> import org.springframework.test.util.XpathExpectationsHelper;
<ide> import org.springframework.test.web.servlet.MvcResult;
<ide> import org.springframework.test.web.servlet.ResultMatcher;
<ide> public ResultMatcher node(final Matcher<? super Node> matcher) {
<ide> return new ResultMatcher() {
<ide> @Override
<ide> public void match(MvcResult result) throws Exception {
<del> String content = result.getResponse().getContentAsString();
<del> xpathHelper.assertNode(content, matcher);
<add> MockHttpServletResponse response = result.getResponse();
<add> xpathHelper.assertNode(response.getContentAsByteArray(), getDefinedEncoding(response), matcher);
<ide> }
<ide> };
<ide> }
<ide>
<add> /**
<add> * Get the response encoding if explicitely defined in the response, null otherwise
<add> */
<add> private String getDefinedEncoding(MockHttpServletResponse response) {
<add> return response.isCharset() ? response.getCharacterEncoding() : null;
<add> }
<add>
<ide> /**
<ide> * Evaluate the XPath and assert that content exists.
<ide> */
<ide> public ResultMatcher exists() {
<ide> return new ResultMatcher() {
<ide> @Override
<ide> public void match(MvcResult result) throws Exception {
<del> String content = result.getResponse().getContentAsString();
<del> xpathHelper.exists(content);
<add> MockHttpServletResponse response = result.getResponse();
<add> xpathHelper.exists(response.getContentAsByteArray(), getDefinedEncoding(response));
<ide> }
<ide> };
<ide> }
<ide> public ResultMatcher doesNotExist() {
<ide> return new ResultMatcher() {
<ide> @Override
<ide> public void match(MvcResult result) throws Exception {
<del> String content = result.getResponse().getContentAsString();
<del> xpathHelper.doesNotExist(content);
<add> MockHttpServletResponse response = result.getResponse();
<add> xpathHelper.doesNotExist(response.getContentAsByteArray(), getDefinedEncoding(response));
<ide> }
<ide> };
<ide> }
<ide> public ResultMatcher nodeCount(final Matcher<Integer> matcher) {
<ide> return new ResultMatcher() {
<ide> @Override
<ide> public void match(MvcResult result) throws Exception {
<del> String content = result.getResponse().getContentAsString();
<del> xpathHelper.assertNodeCount(content, matcher);
<add> MockHttpServletResponse response = result.getResponse();
<add> xpathHelper.assertNodeCount(response.getContentAsByteArray(), getDefinedEncoding(response), matcher);
<ide> }
<ide> };
<ide> }
<ide> public ResultMatcher nodeCount(final int expectedCount) {
<ide> return new ResultMatcher() {
<ide> @Override
<ide> public void match(MvcResult result) throws Exception {
<del> String content = result.getResponse().getContentAsString();
<del> xpathHelper.assertNodeCount(content, expectedCount);
<add> MockHttpServletResponse response = result.getResponse();
<add> xpathHelper.assertNodeCount(response.getContentAsByteArray(), getDefinedEncoding(response), expectedCount);
<ide> }
<ide> };
<ide> }
<ide> public ResultMatcher string(final Matcher<? super String> matcher) {
<ide> return new ResultMatcher() {
<ide> @Override
<ide> public void match(MvcResult result) throws Exception {
<del> String content = result.getResponse().getContentAsString();
<del> xpathHelper.assertString(content, matcher);
<add> MockHttpServletResponse response = result.getResponse();
<add> xpathHelper.assertString(response.getContentAsByteArray(), getDefinedEncoding(response), matcher);
<ide> }
<ide> };
<ide> }
<ide> public ResultMatcher string(final String expectedValue) {
<ide> return new ResultMatcher() {
<ide> @Override
<ide> public void match(MvcResult result) throws Exception {
<del> String content = result.getResponse().getContentAsString();
<del> xpathHelper.assertString(content, expectedValue);
<add> MockHttpServletResponse response = result.getResponse();
<add> xpathHelper.assertString(response.getContentAsByteArray(), getDefinedEncoding(response), expectedValue);
<ide> }
<ide> };
<ide> }
<ide> public ResultMatcher number(final Matcher<? super Double> matcher) {
<ide> return new ResultMatcher() {
<ide> @Override
<ide> public void match(MvcResult result) throws Exception {
<del> String content = result.getResponse().getContentAsString();
<del> xpathHelper.assertNumber(content, matcher);
<add> MockHttpServletResponse response = result.getResponse();
<add> xpathHelper.assertNumber(response.getContentAsByteArray(), getDefinedEncoding(response), matcher);
<ide> }
<ide> };
<ide> }
<ide> public ResultMatcher number(final Double expectedValue) {
<ide> return new ResultMatcher() {
<ide> @Override
<ide> public void match(MvcResult result) throws Exception {
<del> String content = result.getResponse().getContentAsString();
<del> xpathHelper.assertNumber(content, expectedValue);
<add> MockHttpServletResponse response = result.getResponse();
<add> xpathHelper.assertNumber(response.getContentAsByteArray(), getDefinedEncoding(response), expectedValue);
<ide> }
<ide> };
<ide> }
<ide> public ResultMatcher booleanValue(final Boolean value) {
<ide> return new ResultMatcher() {
<ide> @Override
<ide> public void match(MvcResult result) throws Exception {
<del> String content = result.getResponse().getContentAsString();
<del> xpathHelper.assertBoolean(content, value);
<add> MockHttpServletResponse response = result.getResponse();
<add> xpathHelper.assertBoolean(response.getContentAsByteArray(), getDefinedEncoding(response), value);
<ide> }
<ide> };
<ide> }
<ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/result/XpathResultMatchersTests.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2015 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> */
<ide> package org.springframework.test.web.servlet.result;
<ide>
<add>import java.nio.charset.Charset;
<add>
<ide> import org.hamcrest.Matchers;
<ide> import org.junit.Test;
<ide>
<ide> import org.springframework.mock.web.MockHttpServletResponse;
<ide> import org.springframework.test.web.servlet.StubMvcResult;
<add>import org.springframework.util.StreamUtils;
<add>import org.springframework.util.StringUtils;
<ide>
<ide> /**
<ide> * Tests for {@link XpathResultMatchers}.
<ide> public void testBooleanNoMatch() throws Exception {
<ide> new XpathResultMatchers("/foo/bar[2]", null).booleanValue(false).match(getStubMvcResult());
<ide> }
<ide>
<add> @Test
<add> public void testStringEncodingDetection() throws Exception {
<add> String content = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
<add> "<person><name>Jürgen</name></person>";
<add> byte[] bytes = content.getBytes(Charset.forName("UTF-8"));
<add> MockHttpServletResponse response = new MockHttpServletResponse();
<add> response.addHeader("Content-Type", "application/xml");
<add> StreamUtils.copy(bytes, response.getOutputStream());
<add> StubMvcResult result = new StubMvcResult(null, null, null, null, null, null, response);
<add>
<add> new XpathResultMatchers("/person/name", null).string("Jürgen").match(result);
<add> }
<add>
<ide>
<ide> private static final String RESPONSE_CONTENT = "<foo><bar>111</bar><bar>true</bar></foo>";
<ide>
<ide> private StubMvcResult getStubMvcResult() throws Exception {
<ide> MockHttpServletResponse response = new MockHttpServletResponse();
<del> response.addHeader("Content-Type", "application/json");
<add> response.addHeader("Content-Type", "application/xml");
<ide> response.getWriter().print(new String(RESPONSE_CONTENT.getBytes("ISO-8859-1")));
<ide> return new StubMvcResult(null, null, null, null, null, null, response);
<ide> }
| 5
|
Text
|
Text
|
update some more features of arraylist
|
03c2ca04f27eb5df66a95b5a2e8759f71a49e026
|
<ide><path>guide/english/java/arraylist/index.md
<ide> Since ArrayList implements *List*, an ArrayList can be created using the followi
<ide>
<ide> An ArrayList is dynamic, meaning it will grow in size if required and similarly shrink in size if elements are deleted from it. This is what makes it better to use than normal arrays.
<ide>
<add>**Add elements to the list**
<add> ```java
<add> variable.add(String e);
<add> variable.add(int index, String element);
<add> ```
<add>
<ide> **Clear/Delete all elements from the list**
<ide> ```java
<ide> variable.clear();
<ide> Since ArrayList implements *List*, an ArrayList can be created using the followi
<ide>
<ide> **Modify/update element at specified index**
<ide> ```java
<del> variable_name.set(index_number,element);
<add> variable_name.set(index_number, element);
<add> ```
<add>
<add>**Get the size of the list**
<add> ```java
<add> variable_name.size();
<add> ```
<add>
<add>**Get a sublist of the list**
<add> ```java
<add> variable_name.subList(int fromIndex, int toIndex);
<ide> ```
<ide>
<ide> **Reverse elements in list**
| 1
|
Ruby
|
Ruby
|
use utils.popen_read instead of backticks
|
144453368ed42c13e24143dd4e234795eb67f3cb
|
<ide><path>Library/Homebrew/cmd/test-bot.rb
<ide> def formula formula_name
<ide> end
<ide>
<ide> test "brew", "uses", canonical_formula_name
<del> dependencies = `brew deps #{canonical_formula_name}`.split("\n")
<del> dependencies -= `brew list`.split("\n")
<add> dependencies = Utils.popen_read("brew", "deps", canonical_formula_name).split("\n")
<add> dependencies -= Utils.popen_read("brew", "list").split("\n")
<ide> unchanged_dependencies = dependencies - @formulae
<ide> changed_dependences = dependencies - unchanged_dependencies
<ide>
<del> dependents = `brew uses --skip-build --skip-optional #{canonical_formula_name}`.split("\n")
<add> dependents = Utils.popen_read("brew", "uses", "--skip-build", "--skip-optional", canonical_formula_name).split("\n")
<ide> dependents -= @formulae
<ide> dependents = dependents.map {|d| Formulary.factory(d)}
<ide>
<ide> def formulae
<ide> non_dependencies = []
<ide>
<ide> @formulae.each do |formula|
<del> formula_dependencies = `brew deps #{formula}`.split("\n")
<add> formula_dependencies = Utils.popen_read("brew", "deps", formula).split("\n")
<ide> unchanged_dependencies = formula_dependencies - @formulae
<ide> changed_dependences = formula_dependencies - unchanged_dependencies
<ide> changed_dependences.each do |changed_formula|
<ide><path>Library/Homebrew/extend/pathname.rb
<ide> def install_metafiles from=Pathname.pwd
<ide> end
<ide>
<ide> def abv
<del> out=''
<del> n=`find #{to_s} -type f ! -name .DS_Store | wc -l`.to_i
<add> out = ""
<add> n = Utils.popen_read("find", expand_path.to_s, "-type", "f", "!", "-name", ".DS_Store").split("\n").size
<ide> out << "#{n} files, " if n > 1
<del> out << `/usr/bin/du -hs #{to_s} | cut -d"\t" -f1`.strip
<add> out << Utils.popen_read("/usr/bin/du", "-hs", expand_path.to_s).split("\t")[0]
<add> out
<ide> end
<ide>
<ide> # We redefine these private methods in order to add the /o modifier to
| 2
|
Javascript
|
Javascript
|
handle content from loaders
|
eaaccf9d6c17db39830ab65d73213b03a4861a18
|
<ide><path>lib/asset/AssetGenerator.js
<ide> const encodeDataUri = (encoding, source) => {
<ide> return encodedContent;
<ide> };
<ide>
<add>const decodeDataUriContent = (encoding, content) => {
<add> const isBase64 = encoding === "base64";
<add> return isBase64
<add> ? Buffer.from(content, "base64")
<add> : Buffer.from(decodeURIComponent(content), "ascii");
<add>};
<add>
<ide> const JS_TYPES = new Set(["javascript"]);
<ide> const JS_AND_ASSET_TYPES = new Set(["javascript", "asset"]);
<ide>
<ide> class AssetGenerator extends Generator {
<ide>
<ide> let encodedContent;
<ide>
<del> const decodeDataURI = uri => {
<del> const match = URIRegEx.exec(uri);
<del> if (!match) return null;
<del>
<del> const isBase64 = match[3];
<del> const body = match[4];
<del> return isBase64
<del> ? Buffer.from(body, "base64")
<del> : Buffer.from(decodeURIComponent(body), "ascii");
<del> };
<del>
<del> const decodeDataUriContent = (encoding, content) => {
<del> const isBase64 = encoding === "base64";
<del> return isBase64
<del> ? Buffer.from(content, "base64")
<del> : Buffer.from(decodeURIComponent(content), "ascii");
<del> };
<del>
<ide> if (
<ide> module.resourceResolveData &&
<ide> module.resourceResolveData.encoding === encoding &&
<ide> decodeDataUriContent(
<ide> module.resourceResolveData.encoding,
<del> module.resourceResolveData.encodedContent,
<add> module.resourceResolveData.encodedContent
<ide> ).equals(originalSource.buffer())
<ide> ) {
<ide> encodedContent = module.resourceResolveData.encodedContent;
| 1
|
PHP
|
PHP
|
remove dead code
|
d905965e0086f3220776e81614dfaf2049e516b6
|
<ide><path>src/Database/Expression/Comparison.php
<ide> public function __construct($field, $value, $type, $conjunction) {
<ide> if (is_string($type)) {
<ide> $this->_type = $type;
<ide> }
<del>
<del> if (is_string($field) && isset($types[$this->_field])) {
<del> $this->_type = current($types);
<del> }
<ide> }
<ide>
<ide> /**
| 1
|
Python
|
Python
|
use k.cast for compatibility
|
c6f68f8311c8918276d0a4dbb655c68726ad8da1
|
<ide><path>keras/layers/recurrent.py
<ide> def get_output(self, train=False):
<ide> mask = self.get_output_mask(train)
<ide> if mask:
<ide> # apply mask
<del> X *= K.expand_dims(mask).astype(X.dtype)
<add> X *= K.cast(K.expand_dims(mask), X.dtype)
<ide> masking = True
<ide> else:
<ide> masking = False
| 1
|
Text
|
Text
|
remove parentheses [ci skip]
|
27e5c76a77cbca90836ad4fc3a861d9c47cf8588
|
<ide><path>guides/source/autoloading_and_reloading_constants.md
<ide> How files are autoloaded depends on `eager_load` and `cache_classes` config sett
<ide> What is described above are the defaults with a newly generated Rails app. There are multiple ways this can be configured differently (see [Configuring Rails Applications](configuring.html#rails-general-configuration).
<ide> ). But using `autoload_paths` on its own in the past (before Rails 5) developers might configure `autoload_paths` to add in extra locations (e.g. `lib` which used to be an autoload path list years ago, but no longer is). However this is now discouraged for most purposes, as it is likely to lead to production-only errors. It is possible to add new locations to both `config.eager_load_paths` and `config.autoload_paths` but use at your own risk.
<ide>
<del>See also ([Autoloading in the Test Environment](#autoloading-in-the-test-environment).
<add>See also [Autoloading in the Test Environment](#autoloading-in-the-test-environment).
<ide>
<ide> `config.autoload_paths` is not changeable from environment-specific configuration files.
<ide>
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.