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
|
---|---|---|---|---|---|
Python | Python | update ut 5th | be235550ef05043fef1b18706ef7b2015861375b | <ide><path>keras/utils/conv_utils_test.py
<ide> def test_normalize_tuple(self):
<ide> ValueError, r'The `strides` argument .* a tuple of 3 integers.* \(2, 1\)$'):
<ide> conv_utils.normalize_tuple((2, 1), n=3, name='strides', allow_zero=True)
<ide>
<del> with self.assertRaises(
<add> with self.assertRaisesRegex(
<ide> ValueError, r'The `kernel_size` argument .* tuple of 3 integers.* None$'):
<ide> conv_utils.normalize_tuple(None, n=3, name='kernel_size')
<ide>
<del> with self.assertRaises(
<add> with self.assertRaisesRegex(
<ide> ValueError, r'including \[-4, -4, -4\] that does not .* `>= 0`'):
<ide> conv_utils.normalize_tuple(-4, n=3, name='strides', allow_zero=True)
<ide>
<del> with self.assertRaises(
<add> with self.assertRaisesRegex(
<ide> ValueError, r'including \[0\] that does not .* `> 0`'):
<ide> conv_utils.normalize_tuple((0, 1, 2), n=3, name='pool_size')
<ide> | 1 |
Python | Python | ignore the result of periodictask's by default | 4722cfa99cbc467eba77db1cae7bc93eb8cda178 | <ide><path>celery/task/base.py
<ide> class PeriodicTask(Task):
<ide>
<ide> """
<ide> run_every = timedelta(days=1)
<add> ignore_result = True
<ide> type = "periodic"
<ide>
<ide> def __init__(self): | 1 |
Text | Text | update form examples [ci skip] | f2cedf91516f64f170e0567af12fc46f9620febe | <ide><path>guides/source/action_text_overview.md
<ide> Then refer to this field in the form for the model:
<ide>
<ide> ```erb
<ide> <%# app/views/messages/_form.html.erb %>
<del><%= form_with(model: message) do |form| %>
<add><%= form_with model: message do |form| %>
<ide> <div class="field">
<ide> <%= form.label :content %>
<ide> <%= form.rich_text_area :content %>
<ide><path>guides/source/action_view_overview.md
<ide> Form helpers are designed to make working with models much easier compared to us
<ide>
<ide> There are two types of form helpers: those that specifically work with model attributes and those that don't. This helper deals with those that work with model attributes; to see an example of form helpers that don't work with model attributes, check the `ActionView::Helpers::FormTagHelper` documentation.
<ide>
<del>The core method of this helper, `form_for`, gives you the ability to create a form for a model instance; for example, let's say that you have a model Person and want to create a new instance of it:
<add>The core method of this helper, `form_with`, gives you the ability to create a form for a model instance; for example, let's say that you have a model Person and want to create a new instance of it:
<ide>
<ide> ```html+erb
<del># Note: a @person variable will have been created in the controller (e.g. @person = Person.new)
<del><%= form_for @person, url: { action: "create" } do |f| %>
<del> <%= f.text_field :first_name %>
<del> <%= f.text_field :last_name %>
<add><!-- Note: a @person variable will have been created in the controller (e.g. @person = Person.new) -->
<add><%= form_with model: @person do |form| %>
<add> <%= form.text_field :first_name %>
<add> <%= form.text_field :last_name %>
<ide> <%= submit_tag 'Create' %>
<ide> <% end %>
<ide> ```
<ide> check_box("article", "validated")
<ide>
<ide> #### fields_for
<ide>
<del>Creates a scope around a specific model object like `form_for`, but doesn't create the form tags themselves. This makes `fields_for` suitable for specifying additional model objects in the same form:
<add>Creates a scope around a specific model object. This makes `fields_for` suitable for specifying additional model objects in the same form:
<ide>
<ide> ```html+erb
<del><%= form_for @person, url: { action: "update" } do |person_form| %>
<add><%= form_with model: @person do |person_form| %>
<ide> First name: <%= person_form.text_field :first_name %>
<ide> Last name : <%= person_form.text_field :last_name %>
<ide>
<ide> file_field(:user, :avatar)
<ide> # => <input type="file" id="user_avatar" name="user[avatar]" />
<ide> ```
<ide>
<del>#### form_for
<add>#### form_with
<ide>
<del>Creates a form and a scope around a specific model object that is used as a base for questioning about values for the fields.
<add>Creates a form builder to work with. If a `model` argument is specified, form fields will be scoped to that model, and form field values will be prepopulated with corresponding model attributes.
<ide>
<ide> ```html+erb
<del><%= form_for @article do |f| %>
<del> <%= f.label :title, 'Title' %>:
<del> <%= f.text_field :title %><br>
<del> <%= f.label :body, 'Body' %>:
<del> <%= f.text_area :body %><br>
<add><%= form_with model: @article do |form| %>
<add> <%= form.label :title, 'Title' %>:
<add> <%= form.text_field :title %><br>
<add> <%= form.label :body, 'Body' %>:
<add> <%= form.text_area :body %><br>
<ide> <% end %>
<ide> ```
<ide>
<ide> date_field("user", "dob")
<ide>
<ide> ### FormTagHelper
<ide>
<del>Provides a number of methods for creating form tags that don't rely on an Active Record object assigned to the template like FormHelper does. Instead, you provide the names and values manually.
<add>Provides a number of methods for creating form tags that are not scoped to model objects. Instead, you provide the names and values manually.
<ide>
<ide> #### check_box_tag
<ide>
<ide> Creates a field set for grouping HTML form elements.
<ide> Creates a file upload field.
<ide>
<ide> ```html+erb
<del><%= form_tag({ action: "post" }, multipart: true) do %>
<del> <label for="file">File to Upload</label> <%= file_field_tag "file" %>
<add><%= form_with url: new_account_avatar_path(@account), multipart: true do %>
<add> <label for="file">Avatar:</label> <%= file_field_tag 'avatar' %>
<ide> <%= submit_tag %>
<ide> <% end %>
<ide> ```
<ide> file_field_tag 'attachment'
<ide> # => <input id="attachment" name="attachment" type="file" />
<ide> ```
<ide>
<del>#### form_tag
<del>
<del>Starts a form tag that points the action to a URL configured with `url_for_options` just like `ActionController::Base#url_for`.
<del>
<del>```html+erb
<del><%= form_tag '/articles' do %>
<del> <div><%= submit_tag 'Save' %></div>
<del><% end %>
<del># => <form action="/articles" method="post"><div><input type="submit" name="submit" value="Save" /></div></form>
<del>```
<del>
<ide> #### hidden_field_tag
<ide>
<ide> Creates a hidden form input field used to transmit data that would be lost due to HTTP's statelessness or data that should be hidden from the user.
<ide><path>guides/source/active_model_basics.md
<ide> email_contact.valid? # => true
<ide> email_contact.persisted? # => false
<ide> ```
<ide>
<del>Any class that includes `ActiveModel::Model` can be used with `form_for`,
<add>Any class that includes `ActiveModel::Model` can be used with `form_with`,
<ide> `render` and any other Action View helper methods, just like Active Record
<ide> objects.
<ide>
<ide><path>guides/source/engines.md
<ide> directory at `app/views/blorgh/comments` and in it a new file called
<ide>
<ide> ```html+erb
<ide> <h3>New comment</h3>
<del><%= form_with(model: [@article, @article.comments.build], local: true) do |form| %>
<add><%= form_with model: [@article, @article.comments.build], local: true do |form| %>
<ide> <p>
<ide> <%= form.label :text %><br>
<ide> <%= form.text_area :text %>
<ide><path>guides/source/form_helpers.md
<ide> One of the most basic forms you see on the web is a search form. This form conta
<ide> To create this form you will use `form_with`, `label_tag`, `text_field_tag`, and `submit_tag`, respectively. Like this:
<ide>
<ide> ```erb
<del><%= form_with(url: "/search", method: "get") do %>
<del> <%= label_tag(:q, "Search for:") %>
<del> <%= text_field_tag(:q) %>
<del> <%= submit_tag("Search") %>
<add><%= form_with url: "/search", method: :get do |form| %>
<add> <%= form.label :q, "Search for:" %>
<add> <%= form.text_field :q %>
<add> <%= form.submit "Search" %>
<ide> <% end %>
<ide> ```
<ide>
<ide> end
<ide> The corresponding view `app/views/articles/new.html.erb` using `form_with` looks like this:
<ide>
<ide> ```erb
<del><%= form_with model: @article, class: "nifty_form" do |f| %>
<del> <%= f.text_field :title %>
<del> <%= f.text_area :body, size: "60x12" %>
<del> <%= f.submit "Create" %>
<add><%= form_with model: @article, class: "nifty_form" do |form| %>
<add> <%= form.text_field :title %>
<add> <%= form.text_area :body, size: "60x12" %>
<add> <%= form.submit "Create" %>
<ide> <% end %>
<ide> ```
<ide>
<ide> A common task is uploading some sort of file, whether it's a picture of a person
<ide> The following two forms both upload a file.
<ide>
<ide> ```erb
<del><%= form_with(url: {action: :upload}, multipart: true) do %>
<del> <%= file_field_tag 'picture' %>
<add><%= form_with model: @person do |form| %>
<add> <%= form.file_field :picture %>
<ide> <% end %>
<ide>
<del><%= form_with model: @person do |f| %>
<del> <%= f.file_field :picture %>
<add><%= form_with url: "/uploads", multipart: true do |form| %>
<add> <%= form.file_field 'picture' %>
<ide> <% end %>
<ide> ```
<ide>
<ide> Customizing Form Builders
<ide> The object yielded by `form_with` and `fields_for` is an instance of [`ActionView::Helpers::FormBuilder`](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html). Form builders encapsulate the notion of displaying form elements for a single object. While you can write helpers for your forms in the usual way, you can also create subclass `ActionView::Helpers::FormBuilder` and add the helpers there. For example:
<ide>
<ide> ```erb
<del><%= form_with model: @person do |f| %>
<del> <%= text_field_with_label f, :first_name %>
<add><%= form_with model: @person do |form| %>
<add> <%= text_field_with_label form, :first_name %>
<ide> <% end %>
<ide> ```
<ide>
<ide> can be replaced with
<ide>
<ide> ```erb
<del><%= form_with model: @person, builder: LabellingFormBuilder do |f| %>
<del> <%= f.text_field :first_name %>
<add><%= form_with model: @person, builder: LabellingFormBuilder do |form| %>
<add> <%= form.text_field :first_name %>
<ide> <% end %>
<ide> ```
<ide>
<ide> This creates an `addresses_attributes=` method on `Person` that allows you to cr
<ide> The following form allows a user to create a `Person` and its associated addresses.
<ide>
<ide> ```html+erb
<del><%= form_with model: @person do |f| %>
<add><%= form_with model: @person do |form| %>
<ide> Addresses:
<ide> <ul>
<del> <%= f.fields_for :addresses do |addresses_form| %>
<add> <%= form.fields_for :addresses do |addresses_form| %>
<ide> <li>
<ide> <%= addresses_form.label :kind %>
<ide> <%= addresses_form.text_field :kind %>
<ide> evaluates to `true` (e.g. 1, '1', true, or 'true') then the object will be destr
<ide> This form allows users to remove addresses:
<ide>
<ide> ```erb
<del><%= form_with model: @person do |f| %>
<add><%= form_with model: @person do |form| %>
<ide> Addresses:
<ide> <ul>
<del> <%= f.fields_for :addresses do |addresses_form| %>
<add> <%= form.fields_for :addresses do |addresses_form| %>
<ide> <li>
<ide> <%= addresses_form.check_box :_destroy %>
<ide> <%= addresses_form.label :kind %>
<ide><path>guides/source/getting_started.md
<ide> it look as follows:
<ide> ```html+erb
<ide> <h1>Edit article</h1>
<ide>
<del><%= form_with(model: @article, local: true) do |form| %>
<add><%= form_with model: @article, local: true do |form| %>
<ide>
<ide> <% if @article.errors.any? %>
<ide> <div id="error_explanation">
<ide> So first, we'll wire up the Article show template
<ide> </p>
<ide>
<ide> <h2>Add a comment:</h2>
<del><%= form_with(model: [ @article, @article.comments.build ], local: true) do |form| %>
<add><%= form_with model: [ @article, @article.comments.build ], local: true do |form| %>
<ide> <p>
<ide> <%= form.label :commenter %><br>
<ide> <%= form.text_field :commenter %>
<ide> add that to the `app/views/articles/show.html.erb`.
<ide> <% end %>
<ide>
<ide> <h2>Add a comment:</h2>
<del><%= form_with(model: [ @article, @article.comments.build ], local: true) do |form| %>
<add><%= form_with model: [ @article, @article.comments.build ], local: true do |form| %>
<ide> <p>
<ide> <%= form.label :commenter %><br>
<ide> <%= form.text_field :commenter %>
<ide> following:
<ide> <%= render @article.comments %>
<ide>
<ide> <h2>Add a comment:</h2>
<del><%= form_with(model: [ @article, @article.comments.build ], local: true) do |form| %>
<add><%= form_with model: [ @article, @article.comments.build ], local: true do |form| %>
<ide> <p>
<ide> <%= form.label :commenter %><br>
<ide> <%= form.text_field :commenter %>
<ide> Let us also move that new comment section out to its own partial. Again, you
<ide> create a file `app/views/comments/_form.html.erb` containing:
<ide>
<ide> ```html+erb
<del><%= form_with(model: [ @article, @article.comments.build ], local: true) do |form| %>
<add><%= form_with model: [ @article, @article.comments.build ], local: true do |form| %>
<ide> <p>
<ide> <%= form.label :commenter %><br>
<ide> <%= form.text_field :commenter %>
<ide><path>guides/source/layouts_and_rendering.md
<ide> If a template with the specified format does not exist an `ActionView::MissingTe
<ide> ##### The `:variants` Option
<ide>
<ide> This tells Rails to look for template variations of the same format.
<del>You can specify a list of variants by passing the `:variants` option with a symbol or an array.
<add>You can specify a list of variants by passing the `:variants` option with a symbol or an array.
<ide>
<ide> An example of use would be this.
<ide>
<ide> end
<ide> private
<ide>
<ide> def determine_variant
<del> variant = nil
<add> variant = nil
<ide> # some code to determine the variant(s) to use
<ide> variant = :mobile if session[:use_mobile]
<del>
<del> variant
<add>
<add> variant
<ide> end
<ide> ```
<ide>
<ide> definitions for several similar resources:
<ide> * `users/index.html.erb`
<ide>
<ide> ```html+erb
<del> <%= render "shared/search_filters", search: @q do |f| %>
<add> <%= render "shared/search_filters", search: @q do |form| %>
<ide> <p>
<del> Name contains: <%= f.text_field :name_contains %>
<add> Name contains: <%= form.text_field :name_contains %>
<ide> </p>
<ide> <% end %>
<ide> ```
<ide>
<ide> * `roles/index.html.erb`
<ide>
<ide> ```html+erb
<del> <%= render "shared/search_filters", search: @q do |f| %>
<add> <%= render "shared/search_filters", search: @q do |form| %>
<ide> <p>
<del> Title contains: <%= f.text_field :title_contains %>
<add> Title contains: <%= form.text_field :title_contains %>
<ide> </p>
<ide> <% end %>
<ide> ```
<ide>
<ide> * `shared/_search_filters.html.erb`
<ide>
<ide> ```html+erb
<del> <%= form_for(search) do |f| %>
<add> <%= form_with model: search do |form| %>
<ide> <h1>Search form:</h1>
<ide> <fieldset>
<del> <%= yield f %>
<add> <%= yield form %>
<ide> </fieldset>
<ide> <p>
<del> <%= f.submit "Search" %>
<add> <%= form.submit "Search" %>
<ide> </p>
<ide> <% end %>
<ide> ```
<ide> You can also pass local variables into partials, making them even more powerful
<ide> * `_form.html.erb`
<ide>
<ide> ```html+erb
<del> <%= form_for(zone) do |f| %>
<add> <%= form_with model: zone do |form| %>
<ide> <p>
<ide> <b>Zone name</b><br>
<del> <%= f.text_field :name %>
<add> <%= form.text_field :name %>
<ide> </p>
<ide> <p>
<del> <%= f.submit %>
<add> <%= form.submit %>
<ide> </p>
<ide> <% end %>
<ide> ```
<ide><path>guides/source/routing.md
<ide> resolve("Basket") { [:basket] }
<ide> ```
<ide>
<ide> ``` erb
<del><%= form_for @basket do |form| %>
<add><%= form_with model: @basket do |form| %>
<ide> <!-- basket form -->
<ide> <% end %>
<ide> ```
<ide><path>guides/source/working_with_javascript_in_rails.md
<ide> your form will be using Ajax. You can opt out of this behavior by
<ide> passing the `:local` option `form_with`.
<ide>
<ide> ```erb
<del><%= form_with(model: @article) do |f| %>
<add><%= form_with model: @article do |form| %>
<ide> ...
<ide> <% end %>
<ide> ```
<ide> This also works for links with `data-method` attribute.
<ide> For example:
<ide>
<ide> ```erb
<del><%= form_with(model: @article.new) do |f| %>
<del> <%= f.submit data: { "disable-with": "Saving..." } %>
<add><%= form_with model: @article.new do |form| %>
<add> <%= form.submit data: { disable_with: "Saving..." } %>
<ide> <%= end %>
<ide> ```
<ide>
<ide> The index view (`app/views/users/index.html.erb`) contains:
<ide>
<ide> <br>
<ide>
<del><%= form_with(model: @user) do |f| %>
<del> <%= f.label :name %><br>
<del> <%= f.text_field :name %>
<del> <%= f.submit %>
<add><%= form_with model: @user do |form| %>
<add> <%= form.label :name %><br>
<add> <%= form.text_field :name %>
<add> <%= form.submit %>
<ide> <% end %>
<ide> ```
<ide> | 9 |
Text | Text | add date to 3.12 release | 68b23075a2d72935f1e6c428c664d49412a8af68 | <ide><path>docs/community/release-notes.md
<ide> You can determine your currently installed version using `pip show`:
<ide>
<ide> ### 3.12.0
<ide>
<add>Date: 28th September 2020
<add>
<ide> * Add `--file` option to `generateschema` command. [#7130]
<ide> * Support `tags` for OpenAPI schema generation. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#grouping-operations-with-tags). [#7184]
<ide> * Support customising the operation ID for schema generation. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#operationid). [#7190] | 1 |
PHP | PHP | fix bugs. add tests | d48e5312550e7df050f63c5040c3043cde96f369 | <ide><path>src/Illuminate/Database/Connection.php
<ide> public function select($query, $bindings = [], $useReadPdo = true)
<ide> }
<ide>
<ide> /**
<del> * Run a select statement against the database and returns a cursor.
<add> * Run a select statement against the database and returns a generator.
<ide> *
<ide> * @param string $query
<ide> * @param array $bindings
<ide> * @param bool $useReadPdo
<del> * @return mixed
<add> * @return \Generator
<ide> */
<ide> public function cursor($query, $bindings = [], $useReadPdo = true)
<ide> {
<ide> public function cursor($query, $bindings = [], $useReadPdo = true)
<ide> return [];
<ide> }
<ide>
<del> // For select statements, we'll simply execute the query and return an array
<del> // of the database result set. Each element in the array will be a single
<del> // row from the database table, and will either be an array or objects.
<ide> $statement = $this->getPdoForSelect($useReadPdo)->prepare($query);
<ide>
<del> $statement->setFetchMode($me->getFetchMode());
<add> if ($me->getFetchMode() === PDO::FETCH_CLASS) {
<add> $statement->setFetchMode($me->getFetchMode(), 'StdClass');
<add> } else {
<add> $statement->setFetchMode($me->getFetchMode());
<add> }
<ide>
<ide> $statement->execute($me->prepareBindings($bindings));
<ide>
<del> return $statement;
<add> while ($record = $statement->fetch()) {
<add> yield $record;
<add> }
<ide> });
<ide> }
<ide>
<ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> public function firstOrFail($columns = ['*'])
<ide> }
<ide>
<ide> /**
<del> * Traverses through a result set using a cursor.
<add> * Get a generator for the given query.
<ide> *
<del> * @return void
<add> * @return \Generator
<ide> */
<ide> public function cursor()
<ide> {
<ide> $builder = $this->applyScopes();
<ide>
<del> $statement = $builder->query->cursor();
<del>
<del> while ($row = $statement->fetch()) {
<del> // On each result set, we will pass them to the callback and then let the
<del> // developer take care of everything within the callback, which allows us to
<del> // keep the memory low for spinning through large result sets for working.
<del>
<del> if ($row === false) {
<del> return;
<del> }
<del>
<del> //Hydrate and yield an Eloquent Model
<del> $model = $this->model->newFromBuilder($row);
<del>
<del> yield $model;
<add> foreach ($builder->query->cursor() as $record) {
<add> yield $this->model->newFromBuilder($record);
<ide> }
<ide> }
<ide>
<ide><path>src/Illuminate/Database/Query/Builder.php
<ide> protected function restoreFieldsForCount()
<ide> }
<ide>
<ide> /**
<del> * Execute the query as a "select" statement.
<add> * Get a generator for the given query.
<ide> *
<del> * @return mixed
<add> * @return \Generator
<ide> */
<ide> public function cursor()
<ide> {
<del> $results = $this->connection->cursor($this->toSql(), $this->getBindings(), ! $this->useWritePdo);
<add> if (is_null($this->columns)) {
<add> $this->columns = ['*'];
<add> }
<ide>
<del> return $results;
<add> return $this->connection->cursor(
<add> $this->toSql(), $this->getBindings(), ! $this->useWritePdo
<add> );
<ide> }
<ide>
<ide> /**
<ide><path>tests/Database/DatabaseEloquentIntegrationTest.php
<ide> public function testBasicModelRetrieval()
<ide> $collection = EloquentTestUser::find([1, 2, 3]);
<ide> $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $collection);
<ide> $this->assertEquals(2, $collection->count());
<add>
<add> $models = EloquentTestUser::where('id', 1)->cursor();
<add> foreach ($models as $model) {
<add> $this->assertEquals(1, $model->id);
<add> }
<add>
<add> $records = DB::table('users')->where('id', 1)->cursor();
<add> foreach ($records as $record) {
<add> $this->assertEquals(1, $record->id);
<add> }
<add>
<add> $records = DB::cursor('select * from users where id = ?', [1]);
<add> foreach ($records as $record) {
<add> $this->assertEquals(1, $record->id);
<add> }
<ide> }
<ide>
<ide> public function testBasicModelCollectionRetrieval() | 4 |
Text | Text | fix spacy convert argument | 02369f91d307a6ba43f1d9ad97efbb5e348cc599 | <ide><path>website/docs/usage/adding-languages.md
<ide> One thing to keep in mind is that spaCy expects to train its models from **whole
<ide> documents**, not just single sentences. If your corpus only contains single
<ide> sentences, spaCy's models will never learn to expect multi-sentence documents,
<ide> leading to low performance on real text. To mitigate this problem, you can use
<del>the `-N` argument to the `spacy convert` command, to merge some of the sentences
<add>the `-n` argument to the `spacy convert` command, to merge some of the sentences
<ide> into longer pseudo-documents.
<ide>
<ide> ### Training the tagger and parser {#train-tagger-parser} | 1 |
Javascript | Javascript | attach "default events" to all viewconfigs | d01676630362bcb4da11780ae61f43dc56d86677 | <ide><path>Libraries/ReactNative/getNativeComponentAttributes.js
<ide> function getNativeComponentAttributes(uiViewClassName: string): any {
<ide> directEventTypes,
<ide> });
<ide>
<del> if (!hasAttachedDefaultEventTypes) {
<del> attachDefaultEventTypes(viewConfig);
<del> hasAttachedDefaultEventTypes = true;
<del> }
<add> attachDefaultEventTypes(viewConfig);
<ide>
<ide> return viewConfig;
<ide> }
<ide>
<del>// TODO: Figure out how this makes sense. We're using a global boolean to only
<del>// initialize this on the first eagerly initialized native component.
<del>let hasAttachedDefaultEventTypes = false;
<ide> function attachDefaultEventTypes(viewConfig: any) {
<ide> // This is supported on UIManager platforms (ex: Android),
<ide> // as lazy view managers are not implemented for all platforms. | 1 |
Javascript | Javascript | add missing semicolons in sea3dloader | 6160d83b220550730a5310a3b96fab43aa60434e | <ide><path>examples/js/loaders/sea3d/SEA3DLoader.js
<ide> THREE.SEA3D.ScriptDomain = function( domain, root ) {
<ide>
<ide> return domain.id;
<ide>
<del> }
<add> };
<ide>
<ide> this.isRoot = function() {
<ide>
<ide> return root;
<ide>
<del> }
<add> };
<ide>
<ide> this.addEvent = function( type, listener ) {
<ide>
<ide> events.addEventListener( type, listener );
<ide>
<del> }
<add> };
<ide>
<ide> this.hasEvent = function( type, listener ) {
<ide>
<ide> return events.hasEventListener( type, listener );
<ide>
<del> }
<add> };
<ide>
<ide> this.removeEvent = function( type, listener ) {
<ide>
<ide> events.removeEventListener( type, listener );
<ide>
<del> }
<add> };
<ide>
<ide> this.dispatchEvent = function( event ) {
<ide>
<ide> event.script = this;
<ide>
<ide> events.dispatchEvent( event );
<ide>
<del> }
<add> };
<ide>
<ide> this.dispose = function() {
<ide>
<ide> THREE.SEA3D.ScriptDomain = function( domain, root ) {
<ide>
<ide> this.dispatchEvent( { type : "dispose" } );
<ide>
<del> }
<add> };
<ide>
<ide> };
<ide>
<ide> THREE.SEA3D.ScriptManager = function() {
<ide>
<ide> this.scripts.push( src );
<ide>
<del> }
<add> };
<ide>
<ide> this.remove = function( src ) {
<ide>
<ide> src.removeEvent( "dispose", onDisposeScript );
<ide>
<ide> this.scripts.splice( this.scripts.indexOf( src ), 1 );
<ide>
<del> }
<add> };
<ide>
<ide> this.contains = function( src ) {
<ide>
<ide> return this.scripts.indexOf( src ) > - 1;
<ide>
<del> }
<add> };
<ide>
<ide> this.dispatchEvent = function( event ) {
<ide>
<ide> THREE.SEA3D.ScriptManager = function() {
<ide>
<ide> }
<ide>
<del> }
<add> };
<ide>
<ide> };
<ide>
<ide> THREE.SEA3D.QUABUF = new THREE.Quaternion();
<ide>
<ide> THREE.SEA3D.prototype.setShadowMap = function( light ) {
<ide>
<del> light.shadow.mapSize.width = 2048
<add> light.shadow.mapSize.width = 2048;
<ide> light.shadow.mapSize.height = 1024;
<ide>
<ide> light.castShadow = true;
<ide> THREE.SEA3D.prototype.readCubeMap = function( sea ) {
<ide>
<ide> }
<ide>
<del> }
<add> };
<ide>
<ide> cubeImage.src = this.bufferToTexture( faces[ i ].buffer );
<ide>
<ide> THREE.SEA3D.prototype.readJavaScriptMethod = function( sea ) {
<ide> 'hasEvent = $SRC.hasEvent.bind( $SRC ),\n' +
<ide> 'dispatchEvent = $SRC.dispatchEvent.bind( $SRC ),\n' +
<ide> 'removeEvent = $SRC.removeEvent.bind( $SRC ),\n' +
<del> 'dispose = $SRC.dispose.bind( $SRC );\n'
<add> 'dispose = $SRC.dispose.bind( $SRC );\n';
<ide>
<ide> for ( var name in sea.methods ) {
<ide>
<ide> src += '$METHOD["' + name + '"] = ' + declare + sea.methods[ name ].src + '}\n';
<ide>
<ide> }
<ide>
<del> src += 'return $METHOD; })'
<add> src += 'return $METHOD; })';
<ide>
<ide> this.domain.methods = eval( src )();
<ide>
<ide> THREE.SEA3D.prototype.readGLSL = function( sea ) {
<ide> THREE.SEA3D.prototype.materialTechnique =
<ide> ( function() {
<ide>
<del> var techniques = {}
<add> var techniques = {};
<ide>
<ide> // FINAL
<ide> techniques.onComplete = function( mat, sea ) { | 1 |
PHP | PHP | add method to register a 'retrieved' model event | e00feed421ab788a593e3a19a41fc0b342c03c07 | <ide><path>src/Illuminate/Database/Eloquent/Concerns/HasEvents.php
<ide> public static function deleted($callback)
<ide> static::registerModelEvent('deleted', $callback);
<ide> }
<ide>
<add> /**
<add> * Register a retrieved model event with the dispatcher.
<add> *
<add> * @param \Closure|string $callback
<add> * @return void
<add> */
<add> public static function retrieved($callback)
<add> {
<add> static::registerModelEvent('retrieved', $callback);
<add> }
<add>
<ide> /**
<ide> * Remove all of the event listeners for the model.
<ide> * | 1 |
Javascript | Javascript | add cachebreaker to remote assets | 3ade096f02191b3f978fec71c3dff3cffa676f66 | <ide><path>Libraries/Image/AssetSourceResolver.js
<ide> export type ResolvedAssetSource = {|
<ide> import type {PackagerAsset} from '@react-native/assets/registry';
<ide>
<ide> const PixelRatio = require('../Utilities/PixelRatio');
<del>const pickScale = require('./AssetSourcePickScale');
<add>const {pickScale} = require('./AssetUtils');
<ide> const Platform = require('../Utilities/Platform');
<ide>
<ide> const invariant = require('invariant');
<add><path>Libraries/Image/AssetUtils.js
<del><path>Libraries/Image/AssetSourcePickScale.js
<ide>
<ide> 'use strict';
<ide>
<del>const PixelRatio = require('../Utilities/PixelRatio');
<del>function AssetSourcePickScale(
<del> scales: Array<number>,
<del> deviceScale?: number,
<del>): number {
<add>import PixelRatio from '../Utilities/PixelRatio';
<add>
<add>let cacheBreaker;
<add>let warnIfCacheBreakerUnset = true;
<add>
<add>export function pickScale(scales: Array<number>, deviceScale?: number): number {
<ide> if (deviceScale == null) {
<ide> deviceScale = PixelRatio.get();
<ide> }
<ide> function AssetSourcePickScale(
<ide> // in which case we default to 1
<ide> return scales[scales.length - 1] || 1;
<ide> }
<del>module.exports = AssetSourcePickScale;
<add>
<add>export function setUrlCacheBreaker(appendage: string) {
<add> cacheBreaker = appendage;
<add>}
<add>
<add>export function getUrlCacheBreaker(): string {
<add> if (__DEV__ && warnIfCacheBreakerUnset && cacheBreaker == null) {
<add> warnIfCacheBreakerUnset = false;
<add> console.warn('AssetUtils.getUrlCacheBreaker: Cache breaker value is unset');
<add> return '';
<add> }
<add> return cacheBreaker;
<add>}
<ide><path>Libraries/Image/resolveAssetSource.js
<ide>
<ide> const AssetRegistry = require('@react-native/assets/registry');
<ide> const AssetSourceResolver = require('./AssetSourceResolver');
<del>const AssetSourcePickScale = require('./AssetSourcePickScale');
<add>const {pickScale} = require('./AssetUtils');
<ide>
<ide> import type {ResolvedAssetSource} from './AssetSourceResolver';
<ide>
<ide> function resolveAssetSource(source: any): ?ResolvedAssetSource {
<ide> }
<ide>
<ide> module.exports = resolveAssetSource;
<del>module.exports.pickScale = AssetSourcePickScale;
<add>module.exports.pickScale = pickScale;
<ide> module.exports.setCustomSourceTransformer = setCustomSourceTransformer; | 3 |
Text | Text | fix typo - stacks being managed, not tasks? | 88da491cd9e2c2ea15df15654ac4d98f425d54ed | <ide><path>experimental/docker-stacks-and-bundles.md
<ide> axqh55ipl40h vossibility-stack_vossibility-collector 1 icecrime/vossibility-co
<ide>
<ide> ## Managing stacks
<ide>
<del>Tasks are managed using the `docker stack` command:
<add>Stacks are managed using the `docker stack` command:
<ide>
<ide> ```bash
<ide> # docker stack --help | 1 |
Javascript | Javascript | name anonymous functions in _http_outgoing | 2ccf601efefe116a4bc208387cba39408cdd9547 | <ide><path>lib/_http_outgoing.js
<ide> function utcDate() {
<ide> }
<ide> return dateCache;
<ide> }
<del>utcDate._onTimeout = function() {
<add>utcDate._onTimeout = function _onTimeout() {
<ide> dateCache = undefined;
<ide> };
<ide>
<ide> util.inherits(OutgoingMessage, Stream);
<ide> exports.OutgoingMessage = OutgoingMessage;
<ide>
<ide>
<del>OutgoingMessage.prototype.setTimeout = function(msecs, callback) {
<add>OutgoingMessage.prototype.setTimeout = function setTimeout(msecs, callback) {
<ide>
<ide> if (callback) {
<ide> this.on('timeout', callback);
<ide> OutgoingMessage.prototype.setTimeout = function(msecs, callback) {
<ide> // It's possible that the socket will be destroyed, and removed from
<ide> // any messages, before ever calling this. In that case, just skip
<ide> // it, since something else is destroying this connection anyway.
<del>OutgoingMessage.prototype.destroy = function(error) {
<add>OutgoingMessage.prototype.destroy = function destroy(error) {
<ide> if (this.socket)
<ide> this.socket.destroy(error);
<ide> else
<ide> OutgoingMessage.prototype.destroy = function(error) {
<ide>
<ide>
<ide> // This abstract either writing directly to the socket or buffering it.
<del>OutgoingMessage.prototype._send = function(data, encoding, callback) {
<add>OutgoingMessage.prototype._send = function _send(data, encoding, callback) {
<ide> // This is a shameful hack to get the headers and first body chunk onto
<ide> // the same packet. Future versions of Node are going to take care of
<ide> // this at a lower level and in a more general way.
<ide> OutgoingMessage.prototype._send = function(data, encoding, callback) {
<ide> };
<ide>
<ide>
<del>OutgoingMessage.prototype._writeRaw = function(data, encoding, callback) {
<add>OutgoingMessage.prototype._writeRaw = _writeRaw;
<add>function _writeRaw(data, encoding, callback) {
<ide> if (typeof encoding === 'function') {
<ide> callback = encoding;
<ide> encoding = null;
<ide> OutgoingMessage.prototype._writeRaw = function(data, encoding, callback) {
<ide> // buffer, as long as we're not destroyed.
<ide> return this._buffer(data, encoding, callback);
<ide> }
<del>};
<add>}
<ide>
<ide>
<del>OutgoingMessage.prototype._buffer = function(data, encoding, callback) {
<add>OutgoingMessage.prototype._buffer = function _buffer(data, encoding, callback) {
<ide> this.output.push(data);
<ide> this.outputEncodings.push(encoding);
<ide> this.outputCallbacks.push(callback);
<ide> OutgoingMessage.prototype._buffer = function(data, encoding, callback) {
<ide> };
<ide>
<ide>
<del>OutgoingMessage.prototype._storeHeader = function(firstLine, headers) {
<add>OutgoingMessage.prototype._storeHeader = _storeHeader;
<add>function _storeHeader(firstLine, headers) {
<ide> // firstLine in the case of request is: 'GET /index.html HTTP/1.1\r\n'
<ide> // in the case of response it is: 'HTTP/1.1 200 OK\r\n'
<ide> var state = {
<ide> OutgoingMessage.prototype._storeHeader = function(firstLine, headers) {
<ide> // wait until the first body chunk, or close(), is sent to flush,
<ide> // UNLESS we're sending Expect: 100-continue.
<ide> if (state.sentExpect) this._send('');
<del>};
<add>}
<ide>
<ide> function storeHeader(self, state, field, value) {
<ide> if (!common._checkIsHttpToken(field)) {
<ide> function storeHeader(self, state, field, value) {
<ide> }
<ide>
<ide>
<del>OutgoingMessage.prototype.setHeader = function(name, value) {
<add>OutgoingMessage.prototype.setHeader = function setHeader(name, value) {
<ide> if (!common._checkIsHttpToken(name))
<ide> throw new TypeError(
<ide> 'Header name must be a valid HTTP Token ["' + name + '"]');
<ide> OutgoingMessage.prototype.setHeader = function(name, value) {
<ide> };
<ide>
<ide>
<del>OutgoingMessage.prototype.getHeader = function(name) {
<add>OutgoingMessage.prototype.getHeader = function getHeader(name) {
<ide> if (arguments.length < 1) {
<ide> throw new Error('"name" argument is required for getHeader(name)');
<ide> }
<ide> OutgoingMessage.prototype.getHeader = function(name) {
<ide> };
<ide>
<ide>
<del>OutgoingMessage.prototype.removeHeader = function(name) {
<add>OutgoingMessage.prototype.removeHeader = function removeHeader(name) {
<ide> if (arguments.length < 1) {
<ide> throw new Error('"name" argument is required for removeHeader(name)');
<ide> }
<ide> OutgoingMessage.prototype.removeHeader = function(name) {
<ide> };
<ide>
<ide>
<del>OutgoingMessage.prototype._renderHeaders = function() {
<add>OutgoingMessage.prototype._renderHeaders = function _renderHeaders() {
<ide> if (this._header) {
<ide> throw new Error('Can\'t render headers after they are sent to the client');
<ide> }
<ide> OutgoingMessage.prototype._renderHeaders = function() {
<ide> return headers;
<ide> };
<ide>
<del>OutgoingMessage.prototype._implicitHeader = function() {
<add>OutgoingMessage.prototype._implicitHeader = function _implicitHeader() {
<ide> throw new Error('_implicitHeader() method is not implemented');
<ide> };
<ide>
<ide> Object.defineProperty(OutgoingMessage.prototype, 'headersSent', {
<ide> });
<ide>
<ide>
<del>OutgoingMessage.prototype.write = function(chunk, encoding, callback) {
<add>OutgoingMessage.prototype.write = function write(chunk, encoding, callback) {
<ide> if (this.finished) {
<ide> var err = new Error('write after end');
<ide> process.nextTick(writeAfterEndNT, this, err, callback);
<ide> function escapeHeaderValue(value) {
<ide> }
<ide>
<ide>
<del>OutgoingMessage.prototype.addTrailers = function(headers) {
<add>OutgoingMessage.prototype.addTrailers = function addTrailers(headers) {
<ide> this._trailer = '';
<ide> var keys = Object.keys(headers);
<ide> var isArray = Array.isArray(headers);
<ide> OutgoingMessage.prototype.addTrailers = function(headers) {
<ide> const crlf_buf = Buffer.from('\r\n');
<ide>
<ide>
<del>OutgoingMessage.prototype.end = function(data, encoding, callback) {
<add>OutgoingMessage.prototype.end = function end(data, encoding, callback) {
<ide> if (typeof data === 'function') {
<ide> callback = data;
<ide> data = null;
<ide> OutgoingMessage.prototype.end = function(data, encoding, callback) {
<ide> };
<ide>
<ide>
<del>OutgoingMessage.prototype._finish = function() {
<add>OutgoingMessage.prototype._finish = function _finish() {
<ide> assert(this.connection);
<ide> this.emit('prefinish');
<ide> };
<ide> OutgoingMessage.prototype._finish = function() {
<ide> //
<ide> // This function, outgoingFlush(), is called by both the Server and Client
<ide> // to attempt to flush any pending messages out to the socket.
<del>OutgoingMessage.prototype._flush = function() {
<add>OutgoingMessage.prototype._flush = function _flush() {
<ide> var socket = this.socket;
<ide> var ret;
<ide>
<ide> OutgoingMessage.prototype._flushOutput = function _flushOutput(socket) {
<ide> };
<ide>
<ide>
<del>OutgoingMessage.prototype.flushHeaders = function() {
<add>OutgoingMessage.prototype.flushHeaders = function flushHeaders() {
<ide> if (!this._header) {
<ide> this._implicitHeader();
<ide> } | 1 |
Java | Java | add dedicated concat for array of publishers | 3f324c6889b5369b79bdd3dfb8b4854b650a90be | <ide><path>src/main/java/io/reactivex/Flowable.java
<ide> public static <T> Flowable<T> concat(
<ide> return concatArray(p1, p2, p3, p4, p5, p6, p7, p8, p9);
<ide> }
<ide>
<del> @SuppressWarnings({ "unchecked", "rawtypes" })
<ide> @BackpressureSupport(BackpressureKind.FULL)
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<add> @Deprecated // prefetch is unnecessary when the sources is synchronously available
<ide> public static <T> Flowable<T> concatArray(int prefetch, Publisher<? extends T>... sources) {
<del> Objects.requireNonNull(sources, "sources is null");
<del> return fromArray(sources).concatMap((Function)Functions.identity(), prefetch);
<add> return concatArray(sources);
<ide> }
<ide>
<ide> /**
<ide> public static <T> Flowable<T> concatArray(int prefetch, Publisher<? extends T>..
<ide> * Note: named this way because of overload conflict with concat(NbpObservable<NbpObservable>)
<ide> * @param sources the array of sources
<ide> * @param <T> the common base value type
<del> * @return the new NbpObservable instance
<add> * @return the new Observable instance
<ide> * @throws NullPointerException if sources is null
<ide> */
<del> @SuppressWarnings({ "unchecked", "rawtypes" })
<ide> @BackpressureSupport(BackpressureKind.FULL)
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> public static <T> Flowable<T> concatArray(Publisher<? extends T>... sources) {
<ide> public static <T> Flowable<T> concatArray(Publisher<? extends T>... sources) {
<ide> if (sources.length == 1) {
<ide> return fromPublisher(sources[0]);
<ide> }
<del> return fromArray(sources).concatMap((Function)Functions.identity());
<add> return new FlowableConcatArray<T>(sources, false);
<add> }
<add>
<add> /**
<add> * Concatenates a variable number of Observable sources and delays errors from any of them
<add> * till all terminate.
<add> * @param sources the array of sources
<add> * @param <T> the common base value type
<add> * @return the new Flowable instance
<add> * @throws NullPointerException if sources is null
<add> */
<add> @BackpressureSupport(BackpressureKind.FULL)
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> public static <T> Flowable<T> concatArrayDelayError(Publisher<? extends T>... sources) {
<add> if (sources.length == 0) {
<add> return empty();
<add> } else
<add> if (sources.length == 1) {
<add> return fromPublisher(sources[0]);
<add> }
<add> return new FlowableConcatArray<T>(sources, true);
<ide> }
<ide>
<ide> public static <T> Flowable<T> concatArrayEager(Publisher<? extends T>... sources) {
<ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatArray.java
<add>/**
<add> * Copyright 2016 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>package io.reactivex.internal.operators.flowable;
<add>
<add>import java.util.*;
<add>import java.util.concurrent.atomic.AtomicInteger;
<add>
<add>import org.reactivestreams.*;
<add>
<add>import io.reactivex.Flowable;
<add>import io.reactivex.exceptions.CompositeException;
<add>import io.reactivex.internal.subscriptions.SubscriptionArbiter;
<add>
<add>public final class FlowableConcatArray<T> extends Flowable<T> {
<add>
<add> final Publisher<? extends T>[] sources;
<add>
<add> final boolean delayError;
<add>
<add> public FlowableConcatArray(Publisher<? extends T>[] sources, boolean delayError) {
<add> this.sources = sources;
<add> this.delayError = delayError;
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(Subscriber<? super T> s) {
<add> ConcatArraySubscriber<T> parent = new ConcatArraySubscriber<T>(sources, delayError, s);
<add> s.onSubscribe(parent);
<add>
<add> parent.onComplete();
<add> }
<add>
<add> static final class ConcatArraySubscriber<T> extends SubscriptionArbiter implements Subscriber<T> {
<add> /** */
<add> private static final long serialVersionUID = -8158322871608889516L;
<add>
<add> final Subscriber<? super T> actual;
<add>
<add> final Publisher<? extends T>[] sources;
<add>
<add> final boolean delayError;
<add>
<add> final AtomicInteger wip;
<add>
<add> int index;
<add>
<add> List<Throwable> errors;
<add>
<add> long produced;
<add>
<add> public ConcatArraySubscriber(Publisher<? extends T>[] sources, boolean delayError, Subscriber<? super T> actual) {
<add> this.actual = actual;
<add> this.sources = sources;
<add> this.delayError = delayError;
<add> this.wip = new AtomicInteger();
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Subscription s) {
<add> setSubscription(s);
<add> }
<add>
<add> @Override
<add> public void onNext(T t) {
<add> produced++;
<add> actual.onNext(t);
<add> }
<add>
<add> @Override
<add> public void onError(Throwable t) {
<add> if (delayError) {
<add> List<Throwable> list = errors;
<add> if (list == null) {
<add> list = new ArrayList<Throwable>(sources.length - index + 1);
<add> errors = list;
<add> }
<add> list.add(t);
<add> onComplete();
<add> } else {
<add> actual.onError(t);
<add> }
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> if (wip.getAndIncrement() == 0) {
<add> Publisher<? extends T>[] srcs = sources;
<add> int n = srcs.length;
<add> int i = index;
<add> for (;;) {
<add>
<add> if (i == n) {
<add> List<Throwable> list = errors;
<add> if (list != null) {
<add> if (list.size() == 1) {
<add> actual.onError(list.get(0));
<add> } else {
<add> actual.onError(new CompositeException(list));
<add> }
<add> } else {
<add> actual.onComplete();
<add> }
<add> return;
<add> }
<add>
<add> Publisher<? extends T> p = srcs[i];
<add>
<add> if (p == null) {
<add> Throwable ex = new NullPointerException("A Publisher entry is null");
<add> if (delayError) {
<add> List<Throwable> list = errors;
<add> if (list == null) {
<add> list = new ArrayList<Throwable>(n - i + 1);
<add> errors = list;
<add> }
<add> list.add(ex);
<add> i++;
<add> continue;
<add> } else {
<add> actual.onError(ex);
<add> return;
<add> }
<add> } else {
<add> long r = produced;
<add> if (r != 0L) {
<add> produced = 0L;
<add> produced(r);
<add> }
<add> p.subscribe(this);
<add> }
<add>
<add> index = ++i;
<add>
<add> if (wip.decrementAndGet() == 0) {
<add> break;
<add> }
<add> }
<add> }
<add> }
<add> }
<add>
<add>}
<ide><path>src/main/java/io/reactivex/subscribers/TestSubscriber.java
<ide> public final TestSubscriber<T> assertResult(T... values) {
<ide> * @param values the expected values, asserted in order
<ide> * @return this
<ide> */
<del> public final TestSubscriber<T> assertFailure(Class<Throwable> error, T... values) {
<add> public final TestSubscriber<T> assertFailure(Class<? extends Throwable> error, T... values) {
<ide> return assertValues(values)
<ide> .assertError(error)
<ide> .assertNotComplete();
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java
<ide>
<ide> import io.reactivex.*;
<ide> import io.reactivex.disposables.*;
<add>import io.reactivex.exceptions.*;
<ide> import io.reactivex.functions.Function;
<del>import io.reactivex.internal.subscriptions.*;
<add>import io.reactivex.internal.subscriptions.BooleanSubscription;
<ide> import io.reactivex.processors.*;
<ide> import io.reactivex.schedulers.*;
<del>import io.reactivex.subscribers.DefaultObserver;
<del>import io.reactivex.subscribers.TestSubscriber;
<add>import io.reactivex.subscribers.*;
<ide>
<ide> public class FlowableConcatTest {
<ide>
<ide> public Flowable<Integer> apply(Integer t) {
<ide> assertEquals((Integer)999, ts.values().get(999));
<ide> }
<ide> }
<del>
<add>
<add> @SuppressWarnings("unchecked")
<add> @Test
<add> public void arrayDelayError() {
<add> Publisher<Integer>[] sources = new Publisher[] {
<add> Flowable.just(1),
<add> null,
<add> Flowable.range(2, 3),
<add> Flowable.error(new TestException()),
<add> Flowable.empty()
<add> };
<add>
<add> TestSubscriber<Integer> ts = Flowable.concatArrayDelayError(sources).test();
<add>
<add> ts.assertFailure(CompositeException.class, 1, 2, 3, 4);
<add>
<add> CompositeException composite = (CompositeException)ts.errors().get(0);
<add> List<Throwable> list = composite.getExceptions();
<add> assertTrue(list.get(0).toString(), list.get(0) instanceof NullPointerException);
<add> assertTrue(list.get(1).toString(), list.get(1) instanceof TestException);
<add> }
<ide> }
<ide>\ No newline at end of file | 4 |
Javascript | Javascript | fix composition mode in ie for korean input | 2789ccbcf9666b64211c08b188b168175109f563 | <ide><path>src/ng/directive/input.js
<ide> function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
<ide> composing = true;
<ide> });
<ide>
<add> // Support: IE9+
<add> element.on('compositionupdate', function(ev) {
<add> // End composition when ev.data is empty string on 'compositionupdate' event.
<add> // When the input de-focusses (e.g. by clicking away), IE triggers 'compositionupdate'
<add> // instead of 'compositionend'.
<add> if (isUndefined(ev.data) || ev.data === '') {
<add> composing = false;
<add> }
<add> });
<add>
<ide> element.on('compositionend', function() {
<ide> composing = false;
<ide> listener(); | 1 |
Javascript | Javascript | add known issue about firefox selection behavior | dcc57f1718b1b52a22ad833de4d093bcb418064b | <ide><path>src/ng/directive/select.js
<ide> var SelectController =
<ide> * @param {string=} ngAttrSize sets the size of the select element dynamically. Uses the
<ide> * {@link guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes ngAttr} directive.
<ide> *
<add> *
<add> * @knownIssue
<add> *
<add> * In Firefox, the select model is only updated when the select element is blurred. For example,
<add> * when switching between options with the keyboard, the select model is only set to the
<add> * currently selected option when the select is blurred, e.g via tab key or clicking the mouse
<add> * outside the select.
<add> *
<add> * This is due to an ambiguity in the select element specification. See the
<add> * [issue on the Firefox bug tracker](https://bugzilla.mozilla.org/show_bug.cgi?id=126379)
<add> * for more information, and this
<add> * [Github comment for a workaround](https://github.com/angular/angular.js/issues/9134#issuecomment-130800488)
<add> *
<ide> * @example
<ide> * ### Simple `select` elements with static options
<ide> * | 1 |
Text | Text | add notes on authenticating locally | fa6de3c83f473d577daf7519549fe786dace34e0 | <ide><path>docs/how-to-setup-freecodecamp-locally.md
<ide> Meaning, if you visit <http://localhost:3000/explorer> you should see the APIs t
<ide>
<ide> Congratulations 🎉! You now have a copy of freeCodeCamp's entire learning platform running on your local machine.
<ide>
<add>## How to Sign in when working locally
<add>
<add>Your local setup automatically populates a local user in the database. Clicking the sign in button will automatically authenticate you into the local application.
<add>
<add>However, accessing the user portfolio page is a little tricky. In development, Gatsby takes over serving the client side pages and hence you will get a 404 page for the user portfolio when working locally.
<add>
<add>Simply clicking the `Preview Custom 404 Page` button will forward you to the correct page.
<add>
<add>
<add>
<ide> ## Quick commands reference when working locally
<ide>
<ide> [Here is a quick reference](/docs/README.md) to a list of commands that you may need locally from time to time: | 1 |
Ruby | Ruby | add class name to method_added error | fb83fc7bc4bb7260ea300cf1b2f4874ee7268755 | <ide><path>Library/Homebrew/formula.rb
<ide> def patch
<ide> def self.method_added method
<ide> case method
<ide> when :brew
<del> raise "You cannot override Formula#brew"
<add> raise "You cannot override Formula#brew in class #{name}"
<ide> when :test
<ide> @test_defined = true
<ide> end | 1 |
Javascript | Javascript | remove extra newline in errors | 49d1c366d85f4b7e321b1d71eabaae59c20b83c5 | <ide><path>lib/child_process.js
<ide> function checkExecSyncError(ret) {
<ide> if (!err) {
<ide> var msg = 'Command failed: ';
<ide> msg += ret.cmd || ret.args.join(' ');
<del> if (ret.stderr)
<add> if (ret.stderr && ret.stderr.length > 0)
<ide> msg += '\n' + ret.stderr.toString();
<ide> err = new Error(msg);
<ide> }
<ide><path>test/sequential/test-child-process-execsync.js
<ide> assert.strictEqual(ret, msg + '\n',
<ide> const msg = `Command failed: ${process.execPath} ${args.join(' ')}`;
<ide>
<ide> assert(err instanceof Error);
<del> assert.strictEqual(err.message.trim(), msg);
<add> assert.strictEqual(err.message, msg);
<ide> assert.strictEqual(err.status, 1);
<ide> return true;
<ide> }); | 2 |
Ruby | Ruby | remove unreachable branch in env.fortran | 38c1d25036d3851de120df46179dd78d31ccb369 | <ide><path>Library/Homebrew/extend/ENV.rb
<ide> def fortran
<ide>
<ide> HomebrewEnvExtension::FC_FLAG_VARS.each {|key| self[key] = cflags}
<ide> set_cpu_flags(HomebrewEnvExtension::FC_FLAG_VARS)
<del> else
<del> onoe <<-EOS
<del>This formula requires a fortran compiler, but we could not find one by
<del>looking at the FC environment variable or searching your PATH for `gfortran`.
<del>Please take one of the following actions:
<del>
<del> - Decide to use the build of gfortran 4.2.x provided by Homebrew using
<del> `brew install gfortran`
<del>
<del> - Choose another Fortran compiler by setting the FC environment variable:
<del> export FC=/path/to/some/fortran/compiler
<del> Using an alternative compiler may produce more efficient code, but we will
<del> not be able to provide support for build errors.
<del> EOS
<del> exit 1
<ide> end
<ide> end
<del>
<ide> end | 1 |
PHP | PHP | update a test to cover more cases | bb435dfdae377be94bebd7d3a721a084e4349a2a | <ide><path>tests/TestCase/Console/ConsoleOptionParserTest.php
<ide> public function testMultipleOptions()
<ide> public function testAddOptionWithMultiple()
<ide> {
<ide> $parser = new ConsoleOptionParser('test', false);
<del> $parser->addOption('source', ['multiple' => true]);
<add> $parser->addOption('source', ['short' => 's', 'multiple' => true]);
<ide>
<del> $result = $parser->parse(['--source', 'mysql', '--source', 'postgres']);
<add> $result = $parser->parse(['--source', 'mysql', '-s', 'postgres']);
<ide> $expected = [
<ide> 'source' => [
<ide> 'mysql', | 1 |
Python | Python | add cache_dir to save features textdataset | 21d719238c68154798bff21581b82410f303e9ba | <ide><path>examples/language-modeling/run_language_modeling.py
<ide> class DataTrainingArguments:
<ide> )
<ide>
<ide>
<del>def get_dataset(args: DataTrainingArguments, tokenizer: PreTrainedTokenizer, evaluate=False):
<add>def get_dataset(
<add> args: DataTrainingArguments,
<add> tokenizer: PreTrainedTokenizer,
<add> evaluate: bool = False,
<add> cache_dir: Optional[str] = None,
<add>):
<ide> file_path = args.eval_data_file if evaluate else args.train_data_file
<ide> if args.line_by_line:
<ide> return LineByLineTextDataset(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size)
<ide> else:
<ide> return TextDataset(
<del> tokenizer=tokenizer, file_path=file_path, block_size=args.block_size, overwrite_cache=args.overwrite_cache
<add> tokenizer=tokenizer,
<add> file_path=file_path,
<add> block_size=args.block_size,
<add> overwrite_cache=args.overwrite_cache,
<add> cache_dir=cache_dir,
<ide> )
<ide>
<ide>
<ide> def main():
<ide>
<ide> # Get datasets
<ide>
<del> train_dataset = get_dataset(data_args, tokenizer=tokenizer) if training_args.do_train else None
<del> eval_dataset = get_dataset(data_args, tokenizer=tokenizer, evaluate=True) if training_args.do_eval else None
<add> train_dataset = (
<add> get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None
<add> )
<add> eval_dataset = (
<add> get_dataset(data_args, tokenizer=tokenizer, evaluate=True, cache_dir=model_args.cache_dir)
<add> if training_args.do_eval
<add> else None
<add> )
<ide> if config.model_type == "xlnet":
<ide> data_collator = DataCollatorForPermutationLanguageModeling(
<ide> tokenizer=tokenizer,
<ide><path>src/transformers/data/datasets/language_modeling.py
<ide> import os
<ide> import pickle
<ide> import time
<add>from typing import Optional
<ide>
<ide> import torch
<ide> from torch.utils.data.dataset import Dataset
<ide> def __init__(
<ide> file_path: str,
<ide> block_size: int,
<ide> overwrite_cache=False,
<add> cache_dir: Optional[str] = None,
<ide> ):
<ide> assert os.path.isfile(file_path), f"Input file path {file_path} not found"
<ide>
<ide> block_size = block_size - tokenizer.num_special_tokens_to_add(pair=False)
<ide>
<ide> directory, filename = os.path.split(file_path)
<ide> cached_features_file = os.path.join(
<del> directory,
<add> cache_dir if cache_dir is not None else directory,
<ide> "cached_lm_{}_{}_{}".format(
<ide> tokenizer.__class__.__name__,
<ide> str(block_size), | 2 |
Javascript | Javascript | react onlychild utility | 1112f1a00305626377f0f9402f139622c57be014 | <ide><path>src/utils/__tests__/onlyChild-test.js
<add>/**
<add> * @emails react-core
<add> * @jsx React.DOM
<add> */
<add>
<add>"use strict";
<add>
<add>describe('onlyChild', function() {
<add>
<add> var React;
<add> var onlyChild;
<add> var WrapComponent;
<add>
<add> beforeEach(function() {
<add> React = require('React');
<add> onlyChild = require('onlyChild');
<add> WrapComponent = React.createClass({
<add> render: function() {
<add> return (
<add> <div>
<add> {onlyChild(this.props.children, this.props.mapFn, this)}
<add> </div>
<add> );
<add> }
<add> });
<add> });
<add>
<add> it('should fail when passed two children', function() {
<add> expect(function() {
<add> var instance =
<add> <WrapComponent>
<add> <div />
<add> <span />
<add> </WrapComponent>;
<add> onlyChild(instance.props.children);
<add> }).toThrow();
<add> });
<add>
<add> it('should fail when passed nully values', function() {
<add> expect(function() {
<add> var instance =
<add> <WrapComponent>
<add> {null}
<add> </WrapComponent>;
<add> onlyChild(instance.props.children);
<add> }).toThrow();
<add>
<add> expect(function() {
<add> var instance =
<add> <WrapComponent>
<add> {undefined}
<add> </WrapComponent>;
<add> onlyChild(instance.props.children);
<add> }).toThrow();
<add> });
<add>
<add> it('should fail when key/value objects', function() {
<add> expect(function() {
<add> var instance =
<add> <WrapComponent>
<add> {{oneThing: <span />}}
<add> </WrapComponent>;
<add> onlyChild(instance.props.children);
<add> }).toThrow();
<add> });
<add>
<add>
<add> it('should not fail when passed interpolated single child', function() {
<add> expect(function() {
<add> var instance =
<add> <WrapComponent>
<add> {<span />}
<add> </WrapComponent>;
<add> onlyChild(instance.props.children);
<add> }).not.toThrow();
<add> });
<add>
<add>
<add> it('should return the only child', function() {
<add> expect(function() {
<add> var instance =
<add> <WrapComponent>
<add> <span />
<add> </WrapComponent>;
<add> onlyChild(instance.props.children);
<add> }).not.toThrow();
<add> });
<add>
<add>});
<ide><path>src/utils/onlyChild.js
<add>/**
<add> * @providesModule onlyChild
<add> */
<add>"use strict";
<add>
<add>var ReactComponent = require('ReactComponent');
<add>
<add>var invariant = require('invariant');
<add>
<add>/**
<add> * Returns the first child in a collection of children and verifies that there
<add> * is only one child in the collection. The current implementation of this
<add> * function assumes that children have been flattened, but the purpose of this
<add> * helper function is to abstract away the particular structure of children.
<add> *
<add> * @param {?object} children Child collection structure.
<add> * @return {ReactComponent} The first and only `ReactComponent` contained in the
<add> * structure.
<add> */
<add>function onlyChild(children) {
<add> invariant(Array.isArray(children), 'onlyChild must be passed a valid Array.');
<add> invariant(
<add> children.length === 1,
<add> 'onlyChild must be passed an Array with exactly one child.'
<add> );
<add> invariant(
<add> ReactComponent.isValidComponent(children[0]),
<add> 'onlyChild must be passed an Array with exactly one child.'
<add> );
<add> return children[0];
<add>}
<add>
<add>module.exports = onlyChild; | 2 |
PHP | PHP | fix missing quotation mark | a121e0b628993604b5b869c3b80b0c49ef8dfac2 | <ide><path>cake/console/templates/skel/config/bootstrap.php
<ide> /**
<ide> * As of 1.3, additional rules for the inflector are added below
<ide> *
<del> * Inflector::rules('singular', array('rules' => array(), irregular' => array(), 'uninflected' => array()));
<add> * Inflector::rules('singular', array('rules' => array(), 'irregular' => array(), 'uninflected' => array()));
<ide> * Inflector::rules('plural', array('rules' => array(), 'irregular' => array(), 'uninflected' => array()));
<ide> *
<ide> */ | 1 |
Mixed | Python | initialize trues to 0.0 in training example | ae5601beae505d46861aae230522d956d9979b17 | <ide><path>.github/contributors/gavrieltal.md
<add># spaCy contributor agreement
<add>
<add>This spaCy Contributor Agreement (**"SCA"**) is based on the
<add>[Oracle Contributor Agreement](http://www.oracle.com/technetwork/oca-405177.pdf).
<add>The SCA applies to any contribution that you make to any product or project
<add>managed by us (the **"project"**), and sets out the intellectual property rights
<add>you grant to us in the contributed materials. The term **"us"** shall mean
<add>[ExplosionAI UG (haftungsbeschränkt)](https://explosion.ai/legal). The term
<add>**"you"** shall mean the person or entity identified below.
<add>
<add>If you agree to be bound by these terms, fill in the information requested
<add>below and include the filled-in version with your first pull request, under the
<add>folder [`.github/contributors/`](/.github/contributors/). The name of the file
<add>should be your GitHub username, with the extension `.md`. For example, the user
<add>example_user would create the file `.github/contributors/example_user.md`.
<add>
<add>Read this agreement carefully before signing. These terms and conditions
<add>constitute a binding legal agreement.
<add>
<add>## Contributor Agreement
<add>
<add>1. The term "contribution" or "contributed materials" means any source code,
<add>object code, patch, tool, sample, graphic, specification, manual,
<add>documentation, or any other material posted or submitted by you to the project.
<add>
<add>2. With respect to any worldwide copyrights, or copyright applications and
<add>registrations, in your contribution:
<add>
<add> * you hereby assign to us joint ownership, and to the extent that such
<add> assignment is or becomes invalid, ineffective or unenforceable, you hereby
<add> grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge,
<add> royalty-free, unrestricted license to exercise all rights under those
<add> copyrights. This includes, at our option, the right to sublicense these same
<add> rights to third parties through multiple levels of sublicensees or other
<add> licensing arrangements;
<add>
<add> * you agree that each of us can do all things in relation to your
<add> contribution as if each of us were the sole owners, and if one of us makes
<add> a derivative work of your contribution, the one who makes the derivative
<add> work (or has it made will be the sole owner of that derivative work;
<add>
<add> * you agree that you will not assert any moral rights in your contribution
<add> against us, our licensees or transferees;
<add>
<add> * you agree that we may register a copyright in your contribution and
<add> exercise all ownership rights associated with it; and
<add>
<add> * you agree that neither of us has any duty to consult with, obtain the
<add> consent of, pay or render an accounting to the other for any use or
<add> distribution of your contribution.
<add>
<add>3. With respect to any patents you own, or that you can license without payment
<add>to any third party, you hereby grant to us a perpetual, irrevocable,
<add>non-exclusive, worldwide, no-charge, royalty-free license to:
<add>
<add> * make, have made, use, sell, offer to sell, import, and otherwise transfer
<add> your contribution in whole or in part, alone or in combination with or
<add> included in any product, work or materials arising out of the project to
<add> which your contribution was submitted, and
<add>
<add> * at our option, to sublicense these same rights to third parties through
<add> multiple levels of sublicensees or other licensing arrangements.
<add>
<add>4. Except as set out above, you keep all right, title, and interest in your
<add>contribution. The rights that you grant to us under these terms are effective
<add>on the date you first submitted a contribution to us, even if your submission
<add>took place before the date you sign these terms.
<add>
<add>5. You covenant, represent, warrant and agree that:
<add>
<add> * Each contribution that you submit is and shall be an original work of
<add> authorship and you can legally grant the rights set out in this SCA;
<add>
<add> * to the best of your knowledge, each contribution will not violate any
<add> third party's copyrights, trademarks, patents, or other intellectual
<add> property rights; and
<add>
<add> * each contribution shall be in compliance with U.S. export control laws and
<add> other applicable export and import laws. You agree to notify us if you
<add> become aware of any circumstance which would make any of the foregoing
<add> representations inaccurate in any respect. We may publicly disclose your
<add> participation in the project, including the fact that you have signed the SCA.
<add>
<add>6. This SCA is governed by the laws of the State of California and applicable
<add>U.S. Federal law. Any choice of law rules will not apply.
<add>
<add>7. Please place an “x” on one of the applicable statement below. Please do NOT
<add>mark both statements:
<add>
<add> * [x] I am signing on behalf of myself as an individual and no other person
<add> or entity, including my employer, has or will have rights with respect to my
<add> contributions.
<add>
<add> * [] I am signing on behalf of my employer or a legal entity and I have the
<add> actual authority to contractually bind that entity.
<add>
<add>## Contributor Details
<add>
<add>| Field | Entry |
<add>|------------------------------- | -------------------- |
<add>| Name | Gavriel Loria |
<add>| Company name (if applicable) | |
<add>| Title or role (if applicable) | |
<add>| Date | Nov 29, 2018 |
<add>| GitHub username | gavrieltal |
<add>| Website (optional) | |
<ide><path>examples/training/train_textcat.py
<ide> def load_data(limit=0, split=0.8):
<ide>
<ide> def evaluate(tokenizer, textcat, texts, cats):
<ide> docs = (tokenizer(text) for text in texts)
<del> tp = 1e-8 # True positives
<add> tp = 0.0 # True positives
<ide> fp = 1e-8 # False positives
<ide> fn = 1e-8 # False negatives
<del> tn = 1e-8 # True negatives
<add> tn = 0.0 # True negatives
<ide> for i, doc in enumerate(textcat.pipe(docs)):
<ide> gold = cats[i]
<ide> for label, score in doc.cats.items(): | 2 |
Text | Text | add changelog entry | 36720af42995c8bac06ea7187e2c5768f89c2783 | <ide><path>actionpack/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<add>* Add backtrace to development routing error page. *Richard Schneeman*
<add>
<ide> * Replace `include_seconds` boolean argument with `:include_seconds => true` option
<ide> in `distance_of_time_in_words` and `time_ago_in_words` signature. *Dmitriy Kiriyenko*
<ide> | 1 |
Ruby | Ruby | fix delete_all when chained with joins | 6f6c2909dcf32fca71ccc645a36469864b97894a | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
<ide> def sanitize_limit(limit)
<ide> # on mysql (even when aliasing the tables), but mysql allows using JOIN directly in
<ide> # an UPDATE statement, so in the mysql adapters we redefine this to do that.
<ide> def join_to_update(update, select) #:nodoc:
<del> subselect = select.clone
<del> subselect.projections = [update.key]
<add> key = update.key
<add> subselect = subquery_for(key, select)
<ide>
<del> update.where update.key.in(subselect)
<add> update.where key.in(subselect)
<add> end
<add>
<add> def join_to_delete(delete, select, key) #:nodoc:
<add> subselect = subquery_for(key, select)
<add>
<add> delete.where key.in(subselect)
<ide> end
<ide>
<ide> protected
<add>
<add> # Return a subquery for the given key using the join information.
<add> def subquery_for(key, select)
<add> subselect = select.clone
<add> subselect.projections = [key]
<add> subselect
<add> end
<add>
<ide> # Returns an array of record hashes with the column names as keys and
<ide> # column values as values.
<ide> def select(sql, name = nil, binds = [])
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
<ide> def release_savepoint
<ide>
<ide> # In the simple case, MySQL allows us to place JOINs directly into the UPDATE
<ide> # query. However, this does not allow for LIMIT, OFFSET and ORDER. To support
<del> # these, we must use a subquery. However, MySQL is too stupid to create a
<del> # temporary table for this automatically, so we have to give it some prompting
<del> # in the form of a subsubquery. Ugh!
<add> # these, we must use a subquery.
<ide> def join_to_update(update, select) #:nodoc:
<ide> if select.limit || select.offset || select.orders.any?
<del> subsubselect = select.clone
<del> subsubselect.projections = [update.key]
<del>
<del> subselect = Arel::SelectManager.new(select.engine)
<del> subselect.project Arel.sql(update.key.name)
<del> subselect.from subsubselect.as('__active_record_temp')
<del>
<del> update.where update.key.in(subselect)
<add> super
<ide> else
<ide> update.table select.source
<ide> update.wheres = select.constraints
<ide> def limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key)
<ide>
<ide> protected
<ide>
<add> # MySQL is too stupid to create a temporary table for use subquery, so we have
<add> # to give it some prompting in the form of a subsubquery. Ugh!
<add> def subquery_for(key, select)
<add> subsubselect = select.clone
<add> subsubselect.projections = [key]
<add>
<add> subselect = Arel::SelectManager.new(select.engine)
<add> subselect.project Arel.sql(key.name)
<add> subselect.from subsubselect.as('__active_record_temp')
<add> end
<add>
<ide> def add_index_length(option_strings, column_names, options = {})
<ide> if options.is_a?(Hash) && length = options[:length]
<ide> case length
<ide><path>activerecord/lib/active_record/relation.rb
<ide> def delete_all(conditions = nil)
<ide> if conditions
<ide> where(conditions).delete_all
<ide> else
<del> statement = arel.compile_delete
<del> affected = @klass.connection.delete(statement, 'SQL', bind_values)
<add> stmt = Arel::DeleteManager.new(arel.engine)
<add> stmt.from(table)
<add>
<add> if joins_values.any?
<add> @klass.connection.join_to_delete(stmt, arel, table[primary_key])
<add> else
<add> stmt.wheres = arel.constraints
<add> end
<add>
<add> affected = @klass.connection.delete(stmt, 'SQL', bind_values)
<ide>
<ide> reset
<ide> affected
<ide><path>activerecord/test/cases/persistence_test.rb
<ide> require 'models/parrot'
<ide> require 'models/minivan'
<ide> require 'models/person'
<add>require 'models/pet'
<add>require 'models/toy'
<ide> require 'rexml/document'
<ide> require 'active_support/core_ext/exception'
<ide>
<ide> class PersistencesTest < ActiveRecord::TestCase
<ide>
<del> fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, 'warehouse-things', :authors, :categorizations, :categories, :posts, :minivans
<add> fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, 'warehouse-things', :authors, :categorizations, :categories, :posts, :minivans, :pets, :toys
<ide>
<ide> # Oracle UPDATE does not support ORDER BY
<ide> unless current_adapter?(:OracleAdapter)
<ide> def test_delete_all
<ide> assert_equal Topic.count, Topic.delete_all
<ide> end
<ide>
<add> def test_delete_all_with_joins_and_where_part_is_hash
<add> where_args = {:toys => {:name => 'Bone'}}
<add> count = Pet.joins(:toys).where(where_args).count
<add>
<add> assert_equal count, 1
<add> assert_equal count, Pet.joins(:toys).where(where_args).delete_all
<add> end
<add>
<add> def test_delete_all_with_joins_and_where_part_is_not_hash
<add> where_args = ['toys.name = ?', 'Bone']
<add> count = Pet.joins(:toys).where(where_args).count
<add>
<add> assert_equal count, 1
<add> assert_equal count, Pet.joins(:toys).where(where_args).delete_all
<add> end
<add>
<ide> def test_update_by_condition
<ide> Topic.update_all "content = 'bulk updated!'", ["approved = ?", true]
<ide> assert_equal "Have a nice day", Topic.find(1).content | 4 |
Javascript | Javascript | remove unused var from child-process-fork | 7b0cf87101407f43e2ba7e76572adac8cf501238 | <ide><path>test/parallel/test-child-process-fork.js
<ide> var args = ['foo', 'bar'];
<ide> var n = fork(common.fixturesDir + '/child-process-spawn-node.js', args);
<ide> assert.deepStrictEqual(args, ['foo', 'bar']);
<ide>
<del>var messageCount = 0;
<del>
<ide> n.on('message', function(m) {
<ide> console.log('PARENT got message:', m);
<ide> assert.ok(m.foo);
<del> messageCount++;
<ide> });
<ide>
<ide> // https://github.com/joyent/node/issues/2355 - JSON.stringify(undefined) | 1 |
Javascript | Javascript | update workers for `next export` | 61b8b7323e089c8cc0372ce0f32402c8d70096f8 | <ide><path>packages/next/export/index.js
<ide> import { cpus } from 'os'
<del>import { fork } from 'child_process'
<del>import { recursiveCopy } from '../lib/recursive-copy'
<add>import chalk from 'chalk'
<add>import Worker from 'jest-worker'
<add>import { promisify } from 'util'
<ide> import mkdirpModule from 'mkdirp'
<ide> import { resolve, join } from 'path'
<add>import { API_ROUTE } from '../lib/constants'
<ide> import { existsSync, readFileSync } from 'fs'
<del>import chalk from 'chalk'
<add>import createProgress from 'tty-aware-progress'
<add>import { recursiveCopy } from '../lib/recursive-copy'
<add>import { recursiveDelete } from '../lib/recursive-delete'
<add>import { formatAmpMessages } from '../build/output/index'
<ide> import loadConfig, {
<ide> isTargetLikeServerless
<ide> } from '../next-server/server/config'
<ide> import {
<ide> CLIENT_PUBLIC_FILES_PATH,
<ide> CLIENT_STATIC_FILES_PATH
<ide> } from '../next-server/lib/constants'
<del>import createProgress from 'tty-aware-progress'
<del>import { promisify } from 'util'
<del>import { recursiveDelete } from '../lib/recursive-delete'
<del>import { API_ROUTE } from '../lib/constants'
<del>import { formatAmpMessages } from '../build/output/index'
<ide>
<ide> const mkdirp = promisify(mkdirpModule)
<ide>
<ide> export default async function (dir, options, configuration) {
<ide>
<ide> dir = resolve(dir)
<ide> const nextConfig = configuration || loadConfig(PHASE_EXPORT, dir)
<del> const concurrency = options.concurrency || 10
<ide> const threads = options.threads || Math.max(cpus().length - 1, 1)
<ide> const distDir = join(dir, nextConfig.distDir)
<ide> const subFolders = nextConfig.exportTrailingSlash
<ide> export default async function (dir, options, configuration) {
<ide> nextExport: true
<ide> }
<ide>
<del> log(
<del> ` launching ${threads} threads with concurrency of ${concurrency} per thread`
<del> )
<add> log(` launching ${threads} workers`)
<ide> const exportPathMap = await nextConfig.exportPathMap(defaultPathMap, {
<ide> dev: false,
<ide> dir,
<ide> export default async function (dir, options, configuration) {
<ide>
<ide> const progress = !options.silent && createProgress(filteredPaths.length)
<ide>
<del> const chunks = filteredPaths.reduce((result, route, i) => {
<del> const worker = i % threads
<del> if (!result[worker]) {
<del> result[worker] = { paths: [], pathMap: {} }
<del> }
<del> result[worker].pathMap[route] = exportPathMap[route]
<del> result[worker].paths.push(route)
<del>
<del> if (options.sprPages && options.sprPages.has(route)) {
<del> result[worker].pathMap[route].sprPage = true
<del> }
<del> return result
<del> }, [])
<del>
<ide> const ampValidations = {}
<ide> let hadValidationError = false
<ide>
<ide> export default async function (dir, options, configuration) {
<ide> }
<ide> })
<ide> }
<del> const workers = new Set()
<add>
<add> const worker = new Worker(require.resolve('./worker'), {
<add> maxRetries: 0,
<add> numWorkers: threads,
<add> enableWorkerThreads: true,
<add> exposedMethods: ['default']
<add> })
<add>
<add> worker.getStdout().pipe(process.stdout)
<add> worker.getStderr().pipe(process.stderr)
<add>
<add> let renderError = false
<ide>
<ide> await Promise.all(
<del> chunks.map(
<del> chunk =>
<del> new Promise((resolve, reject) => {
<del> const worker = fork(require.resolve('./worker'), [], {
<del> env: process.env
<del> })
<del> workers.add(worker)
<del> worker.send({
<del> distDir,
<del> buildId,
<del> exportPaths: chunk.paths,
<del> exportPathMap: chunk.pathMap,
<del> outDir,
<del> renderOpts,
<del> serverRuntimeConfig,
<del> concurrency,
<del> subFolders,
<del> serverless: isTargetLikeServerless(nextConfig.target)
<del> })
<del> worker.on('message', ({ type, payload }) => {
<del> if (type === 'progress' && progress) {
<del> progress()
<del> } else if (type === 'error') {
<del> reject(payload)
<del> } else if (type === 'done') {
<del> resolve()
<del> } else if (type === 'amp-validation') {
<del> ampValidations[payload.page] = payload.result
<del> hadValidationError =
<del> hadValidationError || payload.result.errors.length
<del> }
<del> })
<del> })
<del> )
<add> filteredPaths.map(async path => {
<add> const result = await worker.default({
<add> path,
<add> pathMap: exportPathMap[path],
<add> distDir,
<add> buildId,
<add> outDir,
<add> renderOpts,
<add> serverRuntimeConfig,
<add> subFolders,
<add> serverless: isTargetLikeServerless(nextConfig.target)
<add> })
<add>
<add> for (const validation of result.ampValidations || []) {
<add> const { page, result } = validation
<add> ampValidations[page] = result
<add> hadValidationError |=
<add> Array.isArray(result && result.errors) && result.errors.length > 0
<add> }
<add> renderError |= result.error
<add> if (progress) progress()
<add> })
<ide> )
<ide>
<del> workers.forEach(worker => worker.kill())
<add> worker.end()
<ide>
<ide> if (Object.keys(ampValidations).length) {
<ide> console.log(formatAmpMessages(ampValidations))
<ide> export default async function (dir, options, configuration) {
<ide> )
<ide> }
<ide>
<add> if (renderError) {
<add> throw new Error(`Export encountered errors`)
<add> }
<ide> // Add an empty line to the console for the better readability.
<ide> log('')
<ide> }
<ide><path>packages/next/export/worker.js
<ide> import { promisify } from 'util'
<ide> import { extname, join, dirname, sep } from 'path'
<ide> import { renderToHTML } from '../next-server/server/render'
<ide> import { writeFile, access } from 'fs'
<del>import { Sema } from 'async-sema'
<ide> import AmpHtmlValidator from 'amphtml-validator'
<ide> import { loadComponents } from '../next-server/server/load-components'
<ide> import { isDynamicRoute } from '../next-server/lib/router/utils/is-dynamic'
<ide> import { getRouteMatcher } from '../next-server/lib/router/utils/route-matcher'
<ide> import { getRouteRegex } from '../next-server/lib/router/utils/route-regex'
<ide>
<ide> const envConfig = require('../next-server/lib/runtime-config')
<del>const mkdirp = promisify(mkdirpModule)
<ide> const writeFileP = promisify(writeFile)
<add>const mkdirp = promisify(mkdirpModule)
<ide> const accessP = promisify(access)
<ide>
<ide> global.__NEXT_DATA__ = {
<ide> nextExport: true
<ide> }
<ide>
<del>process.on(
<del> 'message',
<del> async ({
<del> distDir,
<del> buildId,
<del> exportPaths,
<del> exportPathMap,
<del> outDir,
<del> renderOpts,
<del> serverRuntimeConfig,
<del> concurrency,
<del> subFolders,
<del> serverless
<del> }) => {
<del> const sema = new Sema(concurrency, { capacity: exportPaths.length })
<del> try {
<del> const work = async path => {
<del> await sema.acquire()
<del> let { query = {} } = exportPathMap[path]
<del> const { page, sprPage } = exportPathMap[path]
<del> const filePath = path === '/' ? '/index' : path
<del> const ampPath = `${filePath}.amp`
<del>
<del> // Check if the page is a specified dynamic route
<del> if (isDynamicRoute(page) && page !== path) {
<del> const params = getRouteMatcher(getRouteRegex(page))(path)
<del> if (params) {
<del> query = {
<del> ...query,
<del> ...params
<del> }
<del> } else {
<del> throw new Error(
<del> `The provided export path '${path}' doesn't match the '${page}' page.\nRead more: https://err.sh/zeit/next.js/export-path-mismatch`
<del> )
<del> }
<del> }
<add>export default async function ({
<add> path,
<add> pathMap,
<add> distDir,
<add> buildId,
<add> outDir,
<add> renderOpts,
<add> serverRuntimeConfig,
<add> subFolders,
<add> serverless
<add>}) {
<add> let results = {
<add> ampValidations: []
<add> }
<ide>
<del> const headerMocks = {
<del> headers: {},
<del> getHeader: () => ({}),
<del> setHeader: () => {},
<del> hasHeader: () => false,
<del> removeHeader: () => {},
<del> getHeaderNames: () => []
<add> try {
<add> let { query = {} } = pathMap
<add> const { page, sprPage } = pathMap
<add> const filePath = path === '/' ? '/index' : path
<add> const ampPath = `${filePath}.amp`
<add>
<add> // Check if the page is a specified dynamic route
<add> if (isDynamicRoute(page) && page !== path) {
<add> const params = getRouteMatcher(getRouteRegex(page))(path)
<add> if (params) {
<add> query = {
<add> ...query,
<add> ...params
<ide> }
<add> } else {
<add> throw new Error(
<add> `The provided export path '${path}' doesn't match the '${page}' page.\nRead more: https://err.sh/zeit/next.js/export-path-mismatch`
<add> )
<add> }
<add> }
<ide>
<del> const req = {
<del> url: path,
<del> ...headerMocks
<del> }
<del> const res = {
<del> ...headerMocks
<del> }
<add> const headerMocks = {
<add> headers: {},
<add> getHeader: () => ({}),
<add> setHeader: () => {},
<add> hasHeader: () => false,
<add> removeHeader: () => {},
<add> getHeaderNames: () => []
<add> }
<ide>
<del> if (sprPage && isDynamicRoute(page)) {
<del> query._nextPreviewSkeleton = 1
<del> // pass via `req` to avoid adding code to serverless bundle
<del> req.url +=
<del> (req.url.includes('?') ? '&' : '?') + '_nextPreviewSkeleton=1'
<del> }
<add> const req = {
<add> url: path,
<add> ...headerMocks
<add> }
<add> const res = {
<add> ...headerMocks
<add> }
<ide>
<del> envConfig.setConfig({
<del> serverRuntimeConfig,
<del> publicRuntimeConfig: renderOpts.runtimeConfig
<del> })
<add> if (sprPage && isDynamicRoute(page)) {
<add> query._nextPreviewSkeleton = 1
<add> // pass via `req` to avoid adding code to serverless bundle
<add> req.url += (req.url.includes('?') ? '&' : '?') + '_nextPreviewSkeleton=1'
<add> }
<ide>
<del> let htmlFilename = `${filePath}${sep}index.html`
<del> if (!subFolders) htmlFilename = `${filePath}.html`
<del>
<del> const pageExt = extname(page)
<del> const pathExt = extname(path)
<del> // Make sure page isn't a folder with a dot in the name e.g. `v1.2`
<del> if (pageExt !== pathExt && pathExt !== '') {
<del> // If the path has an extension, use that as the filename instead
<del> htmlFilename = path
<del> } else if (path === '/') {
<del> // If the path is the root, just use index.html
<del> htmlFilename = 'index.html'
<del> }
<add> envConfig.setConfig({
<add> serverRuntimeConfig,
<add> publicRuntimeConfig: renderOpts.runtimeConfig
<add> })
<add>
<add> let htmlFilename = `${filePath}${sep}index.html`
<add> if (!subFolders) htmlFilename = `${filePath}.html`
<add>
<add> const pageExt = extname(page)
<add> const pathExt = extname(path)
<add> // Make sure page isn't a folder with a dot in the name e.g. `v1.2`
<add> if (pageExt !== pathExt && pathExt !== '') {
<add> // If the path has an extension, use that as the filename instead
<add> htmlFilename = path
<add> } else if (path === '/') {
<add> // If the path is the root, just use index.html
<add> htmlFilename = 'index.html'
<add> }
<ide>
<del> const baseDir = join(outDir, dirname(htmlFilename))
<del> const htmlFilepath = join(outDir, htmlFilename)
<add> const baseDir = join(outDir, dirname(htmlFilename))
<add> const htmlFilepath = join(outDir, htmlFilename)
<add>
<add> await mkdirp(baseDir)
<add> let html
<add> let curRenderOpts = {}
<add> let renderMethod = renderToHTML
<add>
<add> if (serverless) {
<add> renderMethod = require(join(
<add> distDir,
<add> 'serverless/pages',
<add> (page === '/' ? 'index' : page) + '.js'
<add> )).renderReqToHTML
<add> const result = await renderMethod(req, res, true)
<add> curRenderOpts = result.renderOpts
<add> html = result.html
<add> } else {
<add> const components = await loadComponents(
<add> distDir,
<add> buildId,
<add> page,
<add> serverless
<add> )
<add>
<add> if (typeof components.Component === 'string') {
<add> html = components.Component
<add> } else {
<add> curRenderOpts = { ...components, ...renderOpts, ampPath }
<add> html = await renderMethod(req, res, page, query, curRenderOpts)
<add> }
<add> }
<ide>
<del> await mkdirp(baseDir)
<del> let html
<del> let curRenderOpts = {}
<del> let renderMethod = renderToHTML
<add> const validateAmp = async (html, page) => {
<add> const validator = await AmpHtmlValidator.getInstance()
<add> const result = validator.validateString(html)
<add> const errors = result.errors.filter(e => e.severity === 'ERROR')
<add> const warnings = result.errors.filter(e => e.severity !== 'ERROR')
<add>
<add> if (warnings.length || errors.length) {
<add> results.ampValidations.push({
<add> page,
<add> result: {
<add> errors,
<add> warnings
<add> }
<add> })
<add> }
<add> }
<ide>
<add> if (curRenderOpts.inAmpMode) {
<add> await validateAmp(html, path)
<add> } else if (curRenderOpts.hybridAmp) {
<add> // we need to render the AMP version
<add> let ampHtmlFilename = `${ampPath}${sep}index.html`
<add> if (!subFolders) {
<add> ampHtmlFilename = `${ampPath}.html`
<add> }
<add> const ampBaseDir = join(outDir, dirname(ampHtmlFilename))
<add> const ampHtmlFilepath = join(outDir, ampHtmlFilename)
<add>
<add> try {
<add> await accessP(ampHtmlFilepath)
<add> } catch (_) {
<add> // make sure it doesn't exist from manual mapping
<add> let ampHtml
<ide> if (serverless) {
<del> renderMethod = require(join(
<del> distDir,
<del> 'serverless/pages',
<del> (page === '/' ? 'index' : page) + '.js'
<del> )).renderReqToHTML
<del> const result = await renderMethod(req, res, true)
<del> curRenderOpts = result.renderOpts
<del> html = result.html
<add> req.url += (req.url.includes('?') ? '&' : '?') + 'amp=1'
<add> ampHtml = (await renderMethod(req, res, true)).html
<ide> } else {
<del> const components = await loadComponents(
<del> distDir,
<del> buildId,
<add> ampHtml = await renderMethod(
<add> req,
<add> res,
<ide> page,
<del> serverless
<add> { ...query, amp: 1 },
<add> curRenderOpts
<ide> )
<del>
<del> if (typeof components.Component === 'string') {
<del> html = components.Component
<del> } else {
<del> curRenderOpts = { ...components, ...renderOpts, ampPath }
<del> html = await renderMethod(req, res, page, query, curRenderOpts)
<del> }
<ide> }
<ide>
<del> const validateAmp = async (html, page) => {
<del> const validator = await AmpHtmlValidator.getInstance()
<del> const result = validator.validateString(html)
<del> const errors = result.errors.filter(e => e.severity === 'ERROR')
<del> const warnings = result.errors.filter(e => e.severity !== 'ERROR')
<del>
<del> if (warnings.length || errors.length) {
<del> process.send({
<del> type: 'amp-validation',
<del> payload: {
<del> page,
<del> result: {
<del> errors,
<del> warnings
<del> }
<del> }
<del> })
<del> }
<del> }
<del>
<del> if (curRenderOpts.inAmpMode) {
<del> await validateAmp(html, path)
<del> } else if (curRenderOpts.hybridAmp) {
<del> // we need to render the AMP version
<del> let ampHtmlFilename = `${ampPath}${sep}index.html`
<del> if (!subFolders) {
<del> ampHtmlFilename = `${ampPath}.html`
<del> }
<del> const ampBaseDir = join(outDir, dirname(ampHtmlFilename))
<del> const ampHtmlFilepath = join(outDir, ampHtmlFilename)
<del>
<del> try {
<del> await accessP(ampHtmlFilepath)
<del> } catch (_) {
<del> // make sure it doesn't exist from manual mapping
<del> let ampHtml
<del> if (serverless) {
<del> req.url += (req.url.includes('?') ? '&' : '?') + 'amp=1'
<del> ampHtml = (await renderMethod(req, res, true)).html
<del> } else {
<del> ampHtml = await renderMethod(
<del> req,
<del> res,
<del> page,
<del> { ...query, amp: 1 },
<del> curRenderOpts
<del> )
<del> }
<del>
<del> await validateAmp(ampHtml, page + '?amp=1')
<del> await mkdirp(ampBaseDir)
<del> await writeFileP(ampHtmlFilepath, ampHtml, 'utf8')
<del> }
<del> }
<del>
<del> await writeFileP(htmlFilepath, html, 'utf8')
<del> process.send({ type: 'progress' })
<del> sema.release()
<add> await validateAmp(ampHtml, page + '?amp=1')
<add> await mkdirp(ampBaseDir)
<add> await writeFileP(ampHtmlFilepath, ampHtml, 'utf8')
<ide> }
<del> await Promise.all(exportPaths.map(work))
<del> process.send({ type: 'done' })
<del> } catch (err) {
<del> console.error(err)
<del> process.send({ type: 'error', payload: err })
<ide> }
<add> await writeFileP(htmlFilepath, html, 'utf8')
<add> return results
<add> } catch (error) {
<add> console.error(`\nError occurred prerendering ${path}:`, error)
<add> return { ...results, error: true }
<ide> }
<del>)
<add>}
<ide><path>test/integration/handles-export-errors/pages/index copy 10.js
<add>// eslint-disable-next-line
<add>export default () => hello.world
<ide><path>test/integration/handles-export-errors/pages/index copy 11.js
<add>// eslint-disable-next-line
<add>export default () => hello.world
<ide><path>test/integration/handles-export-errors/pages/index copy 12.js
<add>// eslint-disable-next-line
<add>export default () => hello.world
<ide><path>test/integration/handles-export-errors/pages/index copy 13.js
<add>// eslint-disable-next-line
<add>export default () => hello.world
<ide><path>test/integration/handles-export-errors/pages/index copy 2.js
<add>// eslint-disable-next-line
<add>export default () => hello.world
<ide><path>test/integration/handles-export-errors/pages/index copy 3.js
<add>// eslint-disable-next-line
<add>export default () => hello.world
<ide><path>test/integration/handles-export-errors/pages/index copy 4.js
<add>// eslint-disable-next-line
<add>export default () => hello.world
<ide><path>test/integration/handles-export-errors/pages/index copy 5.js
<add>// eslint-disable-next-line
<add>export default () => hello.world
<ide><path>test/integration/handles-export-errors/pages/index copy 6.js
<add>// eslint-disable-next-line
<add>export default () => hello.world
<ide><path>test/integration/handles-export-errors/pages/index copy 7.js
<add>// eslint-disable-next-line
<add>export default () => hello.world
<ide><path>test/integration/handles-export-errors/pages/index copy 8.js
<add>// eslint-disable-next-line
<add>export default () => hello.world
<ide><path>test/integration/handles-export-errors/pages/index copy 9.js
<add>// eslint-disable-next-line
<add>export default () => hello.world
<ide><path>test/integration/handles-export-errors/pages/index copy.js
<add>// eslint-disable-next-line
<add>export default () => hello.world
<ide><path>test/integration/handles-export-errors/pages/index.js
<add>// eslint-disable-next-line
<add>export default () => hello.world
<ide><path>test/integration/handles-export-errors/test/index.test.js
<add>/* eslint-env jest */
<add>/* global jasmine */
<add>import path from 'path'
<add>import { nextBuild } from 'next-test-utils'
<add>
<add>jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
<add>const appDir = path.join(__dirname, '..')
<add>
<add>describe('Handles Errors During Export', () => {
<add> it('Does not crash workers', async () => {
<add> const { stdout, stderr } = await nextBuild(appDir, [], {
<add> stdout: true,
<add> stderr: true
<add> })
<add>
<add> expect(stdout + stderr).not.toMatch(/ERR_IPC_CHANNEL_CLOSED/)
<add> })
<add>}) | 17 |
Javascript | Javascript | remove test case 0 from tls-cnnic-whitelist | 1d72434c8b80607078bf83c415307be811a6cd95 | <ide><path>test/parallel/test-tls-cnnic-whitelist.js
<ide> function loadPEM(n) {
<ide> }
<ide>
<ide> const testCases = [
<del> { // Test 0: for the check of a cert not in the whitelist.
<del> // agent7-cert.pem is issued by the fake CNNIC root CA so that its
<del> // hash is not listed in the whitelist.
<del> // fake-cnnic-root-cert has the same subject name as the original
<del> // rootCA.
<del> serverOpts: {
<del> key: loadPEM('agent7-key'),
<del> cert: loadPEM('agent7-cert')
<del> },
<del> clientOpts: {
<del> port: undefined,
<del> rejectUnauthorized: true,
<del> ca: [loadPEM('fake-cnnic-root-cert')]
<del> },
<del> errorCode: 'CERT_HAS_EXPIRED'
<del> },
<ide> // Test 1: for the fix of node#2061
<ide> // agent6-cert.pem is signed by intermediate cert of ca3.
<ide> // The server has a cert chain of agent6->ca3->ca1(root) but | 1 |
Javascript | Javascript | reduce the memory usage of the operator list | f4942b11f8ed58d9376898a67cc05efc98c4e563 | <ide><path>src/core/core.js
<ide> var Page = (function PageClosure() {
<ide> var annotations = datas[1];
<ide>
<ide> if (annotations.length === 0) {
<del> PartialEvaluator.optimizeQueue(pageOpList);
<ide> pageOpList.flush(true);
<ide> promise.resolve(pageOpList);
<ide> return;
<ide> var Page = (function PageClosure() {
<ide> var annotationsReadyPromise = Annotation.appendToOperatorList(
<ide> annotations, pageOpList, pdfManager, partialEvaluator);
<ide> annotationsReadyPromise.then(function () {
<del> PartialEvaluator.optimizeQueue(pageOpList);
<ide> pageOpList.flush(true);
<ide> promise.resolve(pageOpList);
<ide> }, reject);
<ide><path>src/core/evaluator.js
<ide> isStream, isString, JpegStream, Lexer, Metrics, Name, Parser,
<ide> Pattern, PDFImage, PDFJS, serifFonts, stdFontMap, symbolsFonts,
<ide> TilingPattern, TODO, warn, Util, Promise,
<del> RefSetCache, isRef, TextRenderingMode, CMapFactory */
<add> RefSetCache, isRef, TextRenderingMode, CMapFactory, OPS */
<ide>
<ide> 'use strict';
<ide>
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> // If variableArgs === false: exactly `numArgs` expected
<ide> var OP_MAP = {
<ide> // Graphic state
<del> w: { fnName: 'setLineWidth', numArgs: 1, variableArgs: false },
<del> J: { fnName: 'setLineCap', numArgs: 1, variableArgs: false },
<del> j: { fnName: 'setLineJoin', numArgs: 1, variableArgs: false },
<del> M: { fnName: 'setMiterLimit', numArgs: 1, variableArgs: false },
<del> d: { fnName: 'setDash', numArgs: 2, variableArgs: false },
<del> ri: { fnName: 'setRenderingIntent', numArgs: 1, variableArgs: false },
<del> i: { fnName: 'setFlatness', numArgs: 1, variableArgs: false },
<del> gs: { fnName: 'setGState', numArgs: 1, variableArgs: false },
<del> q: { fnName: 'save', numArgs: 0, variableArgs: false },
<del> Q: { fnName: 'restore', numArgs: 0, variableArgs: false },
<del> cm: { fnName: 'transform', numArgs: 6, variableArgs: false },
<add> w: { id: OPS.setLineWidth, numArgs: 1, variableArgs: false },
<add> J: { id: OPS.setLineCap, numArgs: 1, variableArgs: false },
<add> j: { id: OPS.setLineJoin, numArgs: 1, variableArgs: false },
<add> M: { id: OPS.setMiterLimit, numArgs: 1, variableArgs: false },
<add> d: { id: OPS.setDash, numArgs: 2, variableArgs: false },
<add> ri: { id: OPS.setRenderingIntent, numArgs: 1, variableArgs: false },
<add> i: { id: OPS.setFlatness, numArgs: 1, variableArgs: false },
<add> gs: { id: OPS.setGState, numArgs: 1, variableArgs: false },
<add> q: { id: OPS.save, numArgs: 0, variableArgs: false },
<add> Q: { id: OPS.restore, numArgs: 0, variableArgs: false },
<add> cm: { id: OPS.transform, numArgs: 6, variableArgs: false },
<ide>
<ide> // Path
<del> m: { fnName: 'moveTo', numArgs: 2, variableArgs: false },
<del> l: { fnName: 'lineTo', numArgs: 2, variableArgs: false },
<del> c: { fnName: 'curveTo', numArgs: 6, variableArgs: false },
<del> v: { fnName: 'curveTo2', numArgs: 4, variableArgs: false },
<del> y: { fnName: 'curveTo3', numArgs: 4, variableArgs: false },
<del> h: { fnName: 'closePath', numArgs: 0, variableArgs: false },
<del> re: { fnName: 'rectangle', numArgs: 4, variableArgs: false },
<del> S: { fnName: 'stroke', numArgs: 0, variableArgs: false },
<del> s: { fnName: 'closeStroke', numArgs: 0, variableArgs: false },
<del> f: { fnName: 'fill', numArgs: 0, variableArgs: false },
<del> F: { fnName: 'fill', numArgs: 0, variableArgs: false },
<del> 'f*': { fnName: 'eoFill', numArgs: 0, variableArgs: false },
<del> B: { fnName: 'fillStroke', numArgs: 0, variableArgs: false },
<del> 'B*': { fnName: 'eoFillStroke', numArgs: 0, variableArgs: false },
<del> b: { fnName: 'closeFillStroke', numArgs: 0, variableArgs: false },
<del> 'b*': { fnName: 'closeEOFillStroke', numArgs: 0, variableArgs: false },
<del> n: { fnName: 'endPath', numArgs: 0, variableArgs: false },
<add> m: { id: OPS.moveTo, numArgs: 2, variableArgs: false },
<add> l: { id: OPS.lineTo, numArgs: 2, variableArgs: false },
<add> c: { id: OPS.curveTo, numArgs: 6, variableArgs: false },
<add> v: { id: OPS.curveTo2, numArgs: 4, variableArgs: false },
<add> y: { id: OPS.curveTo3, numArgs: 4, variableArgs: false },
<add> h: { id: OPS.closePath, numArgs: 0, variableArgs: false },
<add> re: { id: OPS.rectangle, numArgs: 4, variableArgs: false },
<add> S: { id: OPS.stroke, numArgs: 0, variableArgs: false },
<add> s: { id: OPS.closeStroke, numArgs: 0, variableArgs: false },
<add> f: { id: OPS.fill, numArgs: 0, variableArgs: false },
<add> F: { id: OPS.fill, numArgs: 0, variableArgs: false },
<add> 'f*': { id: OPS.eoFill, numArgs: 0, variableArgs: false },
<add> B: { id: OPS.fillStroke, numArgs: 0, variableArgs: false },
<add> 'B*': { id: OPS.eoFillStroke, numArgs: 0, variableArgs: false },
<add> b: { id: OPS.closeFillStroke, numArgs: 0, variableArgs: false },
<add> 'b*': { id: OPS.closeEOFillStroke, numArgs: 0, variableArgs: false },
<add> n: { id: OPS.endPath, numArgs: 0, variableArgs: false },
<ide>
<ide> // Clipping
<del> W: { fnName: 'clip', numArgs: 0, variableArgs: false },
<del> 'W*': { fnName: 'eoClip', numArgs: 0, variableArgs: false },
<add> W: { id: OPS.clip, numArgs: 0, variableArgs: false },
<add> 'W*': { id: OPS.eoClip, numArgs: 0, variableArgs: false },
<ide>
<ide> // Text
<del> BT: { fnName: 'beginText', numArgs: 0, variableArgs: false },
<del> ET: { fnName: 'endText', numArgs: 0, variableArgs: false },
<del> Tc: { fnName: 'setCharSpacing', numArgs: 1, variableArgs: false },
<del> Tw: { fnName: 'setWordSpacing', numArgs: 1, variableArgs: false },
<del> Tz: { fnName: 'setHScale', numArgs: 1, variableArgs: false },
<del> TL: { fnName: 'setLeading', numArgs: 1, variableArgs: false },
<del> Tf: { fnName: 'setFont', numArgs: 2, variableArgs: false },
<del> Tr: { fnName: 'setTextRenderingMode', numArgs: 1, variableArgs: false },
<del> Ts: { fnName: 'setTextRise', numArgs: 1, variableArgs: false },
<del> Td: { fnName: 'moveText', numArgs: 2, variableArgs: false },
<del> TD: { fnName: 'setLeadingMoveText', numArgs: 2, variableArgs: false },
<del> Tm: { fnName: 'setTextMatrix', numArgs: 6, variableArgs: false },
<del> 'T*': { fnName: 'nextLine', numArgs: 0, variableArgs: false },
<del> Tj: { fnName: 'showText', numArgs: 1, variableArgs: false },
<del> TJ: { fnName: 'showSpacedText', numArgs: 1, variableArgs: false },
<del> '\'': { fnName: 'nextLineShowText', numArgs: 1, variableArgs: false },
<del> '"': { fnName: 'nextLineSetSpacingShowText', numArgs: 3,
<add> BT: { id: OPS.beginText, numArgs: 0, variableArgs: false },
<add> ET: { id: OPS.endText, numArgs: 0, variableArgs: false },
<add> Tc: { id: OPS.setCharSpacing, numArgs: 1, variableArgs: false },
<add> Tw: { id: OPS.setWordSpacing, numArgs: 1, variableArgs: false },
<add> Tz: { id: OPS.setHScale, numArgs: 1, variableArgs: false },
<add> TL: { id: OPS.setLeading, numArgs: 1, variableArgs: false },
<add> Tf: { id: OPS.setFont, numArgs: 2, variableArgs: false },
<add> Tr: { id: OPS.setTextRenderingMode, numArgs: 1, variableArgs: false },
<add> Ts: { id: OPS.setTextRise, numArgs: 1, variableArgs: false },
<add> Td: { id: OPS.moveText, numArgs: 2, variableArgs: false },
<add> TD: { id: OPS.setLeadingMoveText, numArgs: 2, variableArgs: false },
<add> Tm: { id: OPS.setTextMatrix, numArgs: 6, variableArgs: false },
<add> 'T*': { id: OPS.nextLine, numArgs: 0, variableArgs: false },
<add> Tj: { id: OPS.showText, numArgs: 1, variableArgs: false },
<add> TJ: { id: OPS.showSpacedText, numArgs: 1, variableArgs: false },
<add> '\'': { id: OPS.nextLineShowText, numArgs: 1, variableArgs: false },
<add> '"': { id: OPS.nextLineSetSpacingShowText, numArgs: 3,
<ide> variableArgs: false },
<ide>
<ide> // Type3 fonts
<del> d0: { fnName: 'setCharWidth', numArgs: 2, variableArgs: false },
<del> d1: { fnName: 'setCharWidthAndBounds', numArgs: 6, variableArgs: false },
<add> d0: { id: OPS.setCharWidth, numArgs: 2, variableArgs: false },
<add> d1: { id: OPS.setCharWidthAndBounds, numArgs: 6, variableArgs: false },
<ide>
<ide> // Color
<del> CS: { fnName: 'setStrokeColorSpace', numArgs: 1, variableArgs: false },
<del> cs: { fnName: 'setFillColorSpace', numArgs: 1, variableArgs: false },
<del> SC: { fnName: 'setStrokeColor', numArgs: 4, variableArgs: true },
<del> SCN: { fnName: 'setStrokeColorN', numArgs: 33, variableArgs: true },
<del> sc: { fnName: 'setFillColor', numArgs: 4, variableArgs: true },
<del> scn: { fnName: 'setFillColorN', numArgs: 33, variableArgs: true },
<del> G: { fnName: 'setStrokeGray', numArgs: 1, variableArgs: false },
<del> g: { fnName: 'setFillGray', numArgs: 1, variableArgs: false },
<del> RG: { fnName: 'setStrokeRGBColor', numArgs: 3, variableArgs: false },
<del> rg: { fnName: 'setFillRGBColor', numArgs: 3, variableArgs: false },
<del> K: { fnName: 'setStrokeCMYKColor', numArgs: 4, variableArgs: false },
<del> k: { fnName: 'setFillCMYKColor', numArgs: 4, variableArgs: false },
<add> CS: { id: OPS.setStrokeColorSpace, numArgs: 1, variableArgs: false },
<add> cs: { id: OPS.setFillColorSpace, numArgs: 1, variableArgs: false },
<add> SC: { id: OPS.setStrokeColor, numArgs: 4, variableArgs: true },
<add> SCN: { id: OPS.setStrokeColorN, numArgs: 33, variableArgs: true },
<add> sc: { id: OPS.setFillColor, numArgs: 4, variableArgs: true },
<add> scn: { id: OPS.setFillColorN, numArgs: 33, variableArgs: true },
<add> G: { id: OPS.setStrokeGray, numArgs: 1, variableArgs: false },
<add> g: { id: OPS.setFillGray, numArgs: 1, variableArgs: false },
<add> RG: { id: OPS.setStrokeRGBColor, numArgs: 3, variableArgs: false },
<add> rg: { id: OPS.setFillRGBColor, numArgs: 3, variableArgs: false },
<add> K: { id: OPS.setStrokeCMYKColor, numArgs: 4, variableArgs: false },
<add> k: { id: OPS.setFillCMYKColor, numArgs: 4, variableArgs: false },
<ide>
<ide> // Shading
<del> sh: { fnName: 'shadingFill', numArgs: 1, variableArgs: false },
<add> sh: { id: OPS.shadingFill, numArgs: 1, variableArgs: false },
<ide>
<ide> // Images
<del> BI: { fnName: 'beginInlineImage', numArgs: 0, variableArgs: false },
<del> ID: { fnName: 'beginImageData', numArgs: 0, variableArgs: false },
<del> EI: { fnName: 'endInlineImage', numArgs: 1, variableArgs: false },
<add> BI: { id: OPS.beginInlineImage, numArgs: 0, variableArgs: false },
<add> ID: { id: OPS.beginImageData, numArgs: 0, variableArgs: false },
<add> EI: { id: OPS.endInlineImage, numArgs: 1, variableArgs: false },
<ide>
<ide> // XObjects
<del> Do: { fnName: 'paintXObject', numArgs: 1, variableArgs: false },
<del> MP: { fnName: 'markPoint', numArgs: 1, variableArgs: false },
<del> DP: { fnName: 'markPointProps', numArgs: 2, variableArgs: false },
<del> BMC: { fnName: 'beginMarkedContent', numArgs: 1, variableArgs: false },
<del> BDC: { fnName: 'beginMarkedContentProps', numArgs: 2, variableArgs: false },
<del> EMC: { fnName: 'endMarkedContent', numArgs: 0, variableArgs: false },
<add> Do: { id: OPS.paintXObject, numArgs: 1, variableArgs: false },
<add> MP: { id: OPS.markPoint, numArgs: 1, variableArgs: false },
<add> DP: { id: OPS.markPointProps, numArgs: 2, variableArgs: false },
<add> BMC: { id: OPS.beginMarkedContent, numArgs: 1, variableArgs: false },
<add> BDC: { id: OPS.beginMarkedContentProps, numArgs: 2,
<add> variableArgs: false },
<add> EMC: { id: OPS.endMarkedContent, numArgs: 0, variableArgs: false },
<ide>
<ide> // Compatibility
<del> BX: { fnName: 'beginCompat', numArgs: 0, variableArgs: false },
<del> EX: { fnName: 'endCompat', numArgs: 0, variableArgs: false },
<add> BX: { id: OPS.beginCompat, numArgs: 0, variableArgs: false },
<add> EX: { id: OPS.endCompat, numArgs: 0, variableArgs: false },
<ide>
<ide> // (reserved partial commands for the lexer)
<ide> BM: null,
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> // There is also a group colorspace, but since we put everything in
<ide> // RGB I'm not sure we need it.
<ide> }
<del> operatorList.addOp('beginGroup', [groupOptions]);
<add> operatorList.addOp(OPS.beginGroup, [groupOptions]);
<ide> }
<ide>
<del> operatorList.addOp('paintFormXObjectBegin', [matrix, bbox]);
<add> operatorList.addOp(OPS.paintFormXObjectBegin, [matrix, bbox]);
<ide>
<ide> this.getOperatorList(xobj, xobj.dict.get('Resources') || resources,
<ide> operatorList);
<del> operatorList.addOp('paintFormXObjectEnd', []);
<add> operatorList.addOp(OPS.paintFormXObjectEnd, []);
<ide>
<ide> if (group) {
<del> operatorList.addOp('endGroup', [groupOptions]);
<add> operatorList.addOp(OPS.endGroup, [groupOptions]);
<ide> }
<ide> },
<ide>
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> var decode = dict.get('Decode', 'D');
<ide> var inverseDecode = !!decode && decode[0] > 0;
<ide>
<del> operatorList.addOp('paintImageMaskXObject',
<add> operatorList.addOp(OPS.paintImageMaskXObject,
<ide> [PDFImage.createMask(imgArray, width, height,
<ide> inverseDecode)]
<ide> );
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> var imageObj = new PDFImage(this.xref, resources, image,
<ide> inline, null, null);
<ide> var imgData = imageObj.getImageData();
<del> operatorList.addOp('paintInlineImageXObject', [imgData]);
<add> operatorList.addOp(OPS.paintInlineImageXObject, [imgData]);
<ide> return;
<ide> }
<ide>
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> if (!softMask && !mask && image instanceof JpegStream &&
<ide> image.isNativelySupported(this.xref, resources)) {
<ide> // These JPEGs don't need any more processing so we can just send it.
<del> operatorList.addOp('paintJpegXObject', args);
<add> operatorList.addOp(OPS.paintJpegXObject, args);
<ide> this.handler.send(
<ide> 'obj', [objId, this.pageIndex, 'JpegStream', image.getIR()]);
<ide> return;
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> self.handler.send('obj', [objId, self.pageIndex, 'Image', imgData]);
<ide> }, self.handler, self.xref, resources, image, inline);
<ide>
<del> operatorList.addOp('paintImageXObject', args);
<add> operatorList.addOp(OPS.paintImageXObject, args);
<ide> },
<ide>
<ide> handleTilingType: function PartialEvaluator_handleTilingType(
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> setGStateForKey(gStateObj, key, value);
<ide> }
<ide>
<del> operatorList.addOp('setGState', [gStateObj]);
<add> operatorList.addOp(OPS.setGState, [gStateObj]);
<ide> },
<ide>
<ide> loadFont: function PartialEvaluator_loadFont(fontName, font, xref,
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> continue;
<ide> }
<ide>
<del> var fn = opSpec.fnName;
<add> var fn = opSpec.id;
<ide>
<ide> // Validate the number of arguments for the command
<ide> if (opSpec.variableArgs) {
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> var loadedName = self.handleSetFont(resources, args, null,
<ide> operatorList);
<ide> operatorList.addDependency(loadedName);
<del> fn = 'setFont';
<add> fn = OPS.setFont;
<ide> args[0] = loadedName;
<ide> } else if (cmd == 'EI') {
<ide> self.buildPaintImageXObject(resources, args[0], true, operatorList);
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide>
<ide> switch (fn) {
<ide> // Parse the ColorSpace data to a raw format.
<del> case 'setFillColorSpace':
<del> case 'setStrokeColorSpace':
<add> case OPS.setFillColorSpace:
<add> case OPS.setStrokeColorSpace:
<ide> args = [ColorSpace.parseToIR(args[0], xref, resources)];
<ide> break;
<del> case 'shadingFill':
<add> case OPS.shadingFill:
<ide> var shadingRes = resources.get('Shading');
<ide> if (!shadingRes)
<ide> error('No shading resource found');
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> shading, null, xref, resources);
<ide> var patternIR = shadingFill.getIR();
<ide> args = [patternIR];
<del> fn = 'shadingFill';
<add> fn = OPS.shadingFill;
<ide> break;
<del> case 'setGState':
<add> case OPS.setGState:
<ide> var dictName = args[0];
<ide> var extGState = resources.get('ExtGState');
<ide>
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> PartialEvaluator.optimizeQueue =
<ide> function PartialEvaluator_optimizeQueue(queue) {
<ide>
<add> function squash(array, index, howMany, element) {
<add> if (isArray(array)) {
<add> array.splice(index, howMany, element);
<add> } else {
<add> // Replace the element.
<add> array[index] = element;
<add> // Shift everything after the element up.
<add> var sub = array.subarray(index + howMany);
<add> array.set(sub, index + 1);
<add> }
<add> }
<add>
<ide> var fnArray = queue.fnArray, argsArray = queue.argsArray;
<ide> // grouping paintInlineImageXObject's into paintInlineImageXObjectGroup
<ide> // searching for (save, transform, paintInlineImageXObject, restore)+
<ide> var MIN_IMAGES_IN_INLINE_IMAGES_BLOCK = 10;
<ide> var MAX_IMAGES_IN_INLINE_IMAGES_BLOCK = 200;
<ide> var MAX_WIDTH = 1000;
<ide> var IMAGE_PADDING = 1;
<del> for (var i = 0, ii = fnArray.length; i < ii; i++) {
<del> if (fnArray[i] === 'paintInlineImageXObject' &&
<del> fnArray[i - 2] === 'save' && fnArray[i - 1] === 'transform' &&
<del> fnArray[i + 1] === 'restore') {
<add> for (var i = 0, ii = argsArray.length; i < ii; i++) {
<add> if (fnArray[i] === OPS.paintInlineImageXObject &&
<add> fnArray[i - 2] === OPS.save && fnArray[i - 1] === OPS.transform &&
<add> fnArray[i + 1] === OPS.restore) {
<ide> var j = i - 2;
<ide> for (i += 2; i < ii && fnArray[i - 4] === fnArray[i]; i++) {
<ide> }
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> }
<ide> }
<ide> // replacing queue items
<del> fnArray.splice(j, count * 4, ['paintInlineImageXObjectGroup']);
<add> squash(fnArray, j, count * 4, OPS.paintInlineImageXObjectGroup);
<ide> argsArray.splice(j, count * 4,
<ide> [{width: imgWidth, height: imgHeight, data: imgData}, map]);
<ide> i = j;
<del> ii = fnArray.length;
<add> ii = argsArray.length;
<ide> }
<ide> }
<ide> // grouping paintImageMaskXObject's into paintImageMaskXObjectGroup
<ide> // searching for (save, transform, paintImageMaskXObject, restore)+
<ide> var MIN_IMAGES_IN_MASKS_BLOCK = 10;
<ide> var MAX_IMAGES_IN_MASKS_BLOCK = 100;
<del> for (var i = 0, ii = fnArray.length; i < ii; i++) {
<del> if (fnArray[i] === 'paintImageMaskXObject' &&
<del> fnArray[i - 2] === 'save' && fnArray[i - 1] === 'transform' &&
<del> fnArray[i + 1] === 'restore') {
<add> for (var i = 0, ii = argsArray.length; i < ii; i++) {
<add> if (fnArray[i] === OPS.paintImageMaskXObject &&
<add> fnArray[i - 2] === OPS.save && fnArray[i - 1] === OPS.transform &&
<add> fnArray[i + 1] === OPS.restore) {
<ide> var j = i - 2;
<ide> for (i += 2; i < ii && fnArray[i - 4] === fnArray[i]; i++) {
<ide> }
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> height: maskParams.height, transform: transform});
<ide> }
<ide> // replacing queue items
<del> fnArray.splice(j, count * 4, ['paintImageMaskXObjectGroup']);
<add> squash(fnArray, j, count * 4, OPS.paintImageMaskXObjectGroup);
<ide> argsArray.splice(j, count * 4, [images]);
<ide> i = j;
<del> ii = fnArray.length;
<add> ii = argsArray.length;
<ide> }
<ide> }
<ide> };
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> return PartialEvaluator;
<ide> })();
<ide>
<del>
<ide> var OperatorList = (function OperatorListClosure() {
<ide> var CHUNK_SIZE = 100;
<ide>
<ide> function OperatorList(messageHandler, pageIndex) {
<ide> this.messageHandler = messageHandler;
<del> this.fnArray = [];
<add> // When there isn't a message handler the fn array needs to be able to grow
<add> // since we can't flush the operators.
<add> if (messageHandler) {
<add> this.fnArray = new Uint8Array(CHUNK_SIZE);
<add> } else {
<add> this.fnArray = [];
<add> }
<ide> this.argsArray = [];
<ide> this.dependencies = {},
<ide> this.pageIndex = pageIndex;
<add> this.fnIndex = 0;
<ide> }
<ide>
<ide> OperatorList.prototype = {
<ide>
<add> get length() {
<add> return this.argsArray.length;
<add> },
<add>
<ide> addOp: function(fn, args) {
<del> this.fnArray.push(fn);
<del> this.argsArray.push(args);
<del> if (this.messageHandler && this.fnArray.length >= CHUNK_SIZE) {
<del> this.flush();
<add> if (this.messageHandler) {
<add> this.fnArray[this.fnIndex++] = fn;
<add> this.argsArray.push(args);
<add> if (this.fnIndex >= CHUNK_SIZE) {
<add> this.flush();
<add> }
<add> } else {
<add> this.fnArray.push(fn);
<add> this.argsArray.push(args);
<ide> }
<ide> },
<ide>
<ide> var OperatorList = (function OperatorListClosure() {
<ide> return;
<ide> }
<ide> this.dependencies[dependency] = true;
<del> this.addOp('dependency', [dependency]);
<add> this.addOp(OPS.dependency, [dependency]);
<ide> },
<ide>
<ide> addDependencies: function(dependencies) {
<ide> var OperatorList = (function OperatorListClosure() {
<ide> },
<ide>
<ide> addOpList: function(opList) {
<del> Util.concatenateToArray(this.fnArray, opList.fnArray);
<del> Util.concatenateToArray(this.argsArray, opList.argsArray);
<ide> Util.extendObj(this.dependencies, opList.dependencies);
<add> for (var i = 0, ii = opList.length; i < ii; i++) {
<add> this.addOp(opList.fnArray[i], opList.argsArray[i]);
<add> }
<ide> },
<ide>
<ide> getIR: function() {
<ide> return {
<ide> fnArray: this.fnArray,
<del> argsArray: this.argsArray
<add> argsArray: this.argsArray,
<add> length: this.length
<ide> };
<ide> },
<ide>
<ide> var OperatorList = (function OperatorListClosure() {
<ide> operatorList: {
<ide> fnArray: this.fnArray,
<ide> argsArray: this.argsArray,
<del> lastChunk: lastChunk
<add> lastChunk: lastChunk,
<add> length: this.length
<ide> },
<ide> pageIndex: this.pageIndex
<ide> });
<ide> this.dependencies = [];
<del> this.fnArray = [];
<add> this.fnIndex = 0;
<ide> this.argsArray = [];
<ide> }
<ide> };
<ide><path>src/display/api.js
<ide> var PDFPageProxy = (function PDFPageProxyClosure() {
<ide> */
<ide> _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk) {
<ide> // Add the new chunk to the current operator list.
<del> Util.concatenateToArray(this.operatorList.fnArray,
<del> operatorListChunk.fnArray);
<del> Util.concatenateToArray(this.operatorList.argsArray,
<del> operatorListChunk.argsArray);
<add> for (var i = 0, ii = operatorListChunk.length; i < ii; i++) {
<add> this.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
<add> this.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
<add> }
<ide> this.operatorList.lastChunk = operatorListChunk.lastChunk;
<ide>
<ide> // Notify all the rendering tasks there are more operators to be consumed.
<ide> var InternalRenderTask = (function InternalRenderTaskClosure() {
<ide> this.operatorListIdx,
<ide> this._continue.bind(this),
<ide> this.stepper);
<del> if (this.operatorListIdx === this.operatorList.fnArray.length) {
<add> if (this.operatorListIdx === this.operatorList.argsArray.length) {
<ide> this.running = false;
<ide> if (this.operatorList.lastChunk) {
<ide> this.gfx.endDrawing();
<ide><path>src/display/canvas.js
<ide> /* globals ColorSpace, DeviceCmykCS, DeviceGrayCS, DeviceRgbCS, error,
<ide> FONT_IDENTITY_MATRIX, IDENTITY_MATRIX, ImageData, isArray, isNum,
<ide> Pattern, TilingPattern, TODO, Util, warn, assert, info,
<del> TextRenderingMode */
<add> TextRenderingMode, OPS */
<ide>
<ide> 'use strict';
<ide>
<ide> var CanvasGraphics = (function CanvasGraphicsClosure() {
<ide>
<ide> var commonObjs = this.commonObjs;
<ide> var objs = this.objs;
<del> var fnName;
<add> var fnId;
<ide> var slowCommands = this.slowCommands;
<ide>
<ide> while (true) {
<ide> var CanvasGraphics = (function CanvasGraphicsClosure() {
<ide> return i;
<ide> }
<ide>
<del> fnName = fnArray[i];
<add> fnId = fnArray[i];
<ide>
<del> if (fnName !== 'dependency') {
<del> this[fnName].apply(this, argsArray[i]);
<add> if (fnId !== OPS.dependency) {
<add> this[fnId].apply(this, argsArray[i]);
<ide> } else {
<ide> var deps = argsArray[i];
<ide> for (var n = 0, nn = deps.length; n < nn; n++) {
<ide> var CanvasGraphics = (function CanvasGraphicsClosure() {
<ide> // If the execution took longer then a certain amount of time, shedule
<ide> // to continue exeution after a short delay.
<ide> // However, this is only possible if a 'continueCallback' is passed in.
<del> if (continueCallback && slowCommands[fnName] && Date.now() > endTime) {
<add> if (continueCallback && slowCommands[fnId] && Date.now() > endTime) {
<ide> setTimeout(continueCallback, 0);
<ide> return i;
<ide> }
<ide> var CanvasGraphics = (function CanvasGraphicsClosure() {
<ide> }
<ide> };
<ide>
<add> for (var op in OPS) {
<add> CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
<add> }
<add>
<ide> return CanvasGraphics;
<ide> })();
<ide>
<ide><path>src/shared/annotation.js
<ide> */
<ide> /* globals Util, isDict, isName, stringToPDFString, TODO, Dict, Stream,
<ide> stringToBytes, PDFJS, isWorker, assert, NotImplementedException,
<del> Promise, isArray, ObjectLoader, isValidUrl, OperatorList */
<add> Promise, isArray, ObjectLoader, isValidUrl, OperatorList, OPS */
<ide>
<ide> 'use strict';
<ide>
<ide> var Annotation = (function AnnotationClosure() {
<ide>
<ide> resourcesPromise.then(function(resources) {
<ide> var opList = new OperatorList();
<del> opList.addOp('beginAnnotation', [data.rect, transform, matrix]);
<add> opList.addOp(OPS.beginAnnotation, [data.rect, transform, matrix]);
<ide> evaluator.getOperatorList(this.appearance, resources, opList);
<del> opList.addOp('endAnnotation', []);
<add> opList.addOp(OPS.endAnnotation, []);
<ide> promise.resolve(opList);
<ide> }.bind(this));
<ide>
<ide> var Annotation = (function AnnotationClosure() {
<ide> annotationPromises.push(annotations[i].getOperatorList(partialEvaluator));
<ide> }
<ide> Promise.all(annotationPromises).then(function(datas) {
<del> opList.addOp('beginAnnotations', []);
<add> opList.addOp(OPS.beginAnnotations, []);
<ide> for (var i = 0, n = datas.length; i < n; ++i) {
<ide> var annotOpList = datas[i];
<ide> opList.addOpList(annotOpList);
<ide> }
<del> opList.addOp('endAnnotations', []);
<add> opList.addOp(OPS.endAnnotations, []);
<ide> annotationsReadyPromise.resolve();
<ide> }, reject);
<ide>
<ide> var TextWidgetAnnotation = (function TextWidgetAnnotationClosure() {
<ide> data.rgb = [0, 0, 0];
<ide> // TODO THIS DOESN'T MAKE ANY SENSE SINCE THE fnArray IS EMPTY!
<ide> for (var i = 0, n = fnArray.length; i < n; ++i) {
<del> var fnName = appearanceFnArray[i];
<add> var fnId = appearanceFnArray[i];
<ide> var args = appearanceArgsArray[i];
<ide>
<del> if (fnName === 'setFont') {
<add> if (fnId === OPS.setFont) {
<ide> data.fontRefName = args[0];
<ide> var size = args[1];
<ide> if (size < 0) {
<ide> var TextWidgetAnnotation = (function TextWidgetAnnotationClosure() {
<ide> data.fontDirection = 1;
<ide> data.fontSize = size;
<ide> }
<del> } else if (fnName === 'setFillRGBColor') {
<add> } else if (fnId === OPS.setFillRGBColor) {
<ide> data.rgb = args;
<del> } else if (fnName === 'setFillGray') {
<add> } else if (fnId === OPS.setFillGray) {
<ide> var rgbValue = args[0] * 255;
<ide> data.rgb = [rgbValue, rgbValue, rgbValue];
<ide> }
<ide><path>src/shared/util.js
<ide> if (!globalScope.PDFJS) {
<ide>
<ide> globalScope.PDFJS.pdfBug = false;
<ide>
<add>// All the possible operations for an operator list.
<add>var OPS = PDFJS.OPS = {
<add> // Intentially start from 1 so it is easy to spot bad operators that will be
<add> // 0's.
<add> dependency: 1,
<add> setLineWidth: 2,
<add> setLineCap: 3,
<add> setLineJoin: 4,
<add> setMiterLimit: 5,
<add> setDash: 6,
<add> setRenderingIntent: 7,
<add> setFlatness: 8,
<add> setGState: 9,
<add> save: 10,
<add> restore: 11,
<add> transform: 12,
<add> moveTo: 13,
<add> lineTo: 14,
<add> curveTo: 15,
<add> curveTo2: 16,
<add> curveTo3: 17,
<add> closePath: 18,
<add> rectangle: 19,
<add> stroke: 20,
<add> closeStroke: 21,
<add> fill: 22,
<add> eoFill: 23,
<add> fillStroke: 24,
<add> eoFillStroke: 25,
<add> closeFillStroke: 26,
<add> closeEOFillStroke: 27,
<add> endPath: 28,
<add> clip: 29,
<add> eoClip: 30,
<add> beginText: 31,
<add> endText: 32,
<add> setCharSpacing: 33,
<add> setWordSpacing: 34,
<add> setHScale: 35,
<add> setLeading: 36,
<add> setFont: 37,
<add> setTextRenderingMode: 38,
<add> setTextRise: 39,
<add> moveText: 40,
<add> setLeadingMoveText: 41,
<add> setTextMatrix: 42,
<add> nextLine: 43,
<add> showText: 44,
<add> showSpacedText: 45,
<add> nextLineShowText: 46,
<add> nextLineSetSpacingShowText: 47,
<add> setCharWidth: 48,
<add> setCharWidthAndBounds: 49,
<add> setStrokeColorSpace: 50,
<add> setFillColorSpace: 51,
<add> setStrokeColor: 52,
<add> setStrokeColorN: 53,
<add> setFillColor: 54,
<add> setFillColorN: 55,
<add> setStrokeGray: 56,
<add> setFillGray: 57,
<add> setStrokeRGBColor: 58,
<add> setFillRGBColor: 59,
<add> setStrokeCMYKColor: 60,
<add> setFillCMYKColor: 61,
<add> shadingFill: 62,
<add> beginInlineImage: 63,
<add> beginImageData: 64,
<add> endInlineImage: 65,
<add> paintXObject: 66,
<add> markPoint: 67,
<add> markPointProps: 68,
<add> beginMarkedContent: 69,
<add> beginMarkedContentProps: 70,
<add> endMarkedContent: 71,
<add> beginCompat: 72,
<add> endCompat: 73,
<add> paintFormXObjectBegin: 74,
<add> paintFormXObjectEnd: 75,
<add> beginGroup: 76,
<add> endGroup: 77,
<add> beginAnnotations: 78,
<add> endAnnotations: 79,
<add> beginAnnotation: 80,
<add> endAnnotation: 81,
<add> paintJpegXObject: 82,
<add> paintImageMaskXObject: 83,
<add> paintImageMaskXObjectGroup: 84,
<add> paintImageXObject: 85,
<add> paintInlineImageXObject: 86,
<add> paintInlineImageXObjectGroup: 87
<add>};
<ide>
<ide> // Use only for debugging purposes. This should not be used in any code that is
<ide> // in mozilla master.
<ide><path>test/unit/evaluator_spec.js
<ide> /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
<ide> /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
<del>/* globals expect, it, describe, PartialEvaluator, StringStream */
<add>/* globals expect, it, describe, PartialEvaluator, StringStream, OPS */
<ide>
<ide> 'use strict';
<ide>
<ide> describe('evaluator', function() {
<ide> var result = evaluator.getOperatorList(stream, new ResourcesMock());
<ide> expect(!!result.fnArray && !!result.argsArray).toEqual(true);
<ide> expect(result.fnArray.length).toEqual(1);
<del> expect(result.fnArray[0]).toEqual('save');
<add> expect(result.fnArray[0]).toEqual(OPS.save);
<ide> expect(result.argsArray[0].length).toEqual(0);
<ide> });
<ide>
<ide> describe('evaluator', function() {
<ide> var result = evaluator.getOperatorList(stream, new ResourcesMock());
<ide> expect(!!result.fnArray && !!result.argsArray).toEqual(true);
<ide> expect(result.fnArray.length).toEqual(1);
<del> expect(result.fnArray[0]).toEqual('restore');
<add> expect(result.fnArray[0]).toEqual(OPS.restore);
<ide> });
<ide>
<ide> it('should handle two glued operations', function() {
<ide> describe('evaluator', function() {
<ide> var result = evaluator.getOperatorList(stream, resources);
<ide> expect(!!result.fnArray && !!result.argsArray).toEqual(true);
<ide> expect(result.fnArray.length).toEqual(2);
<del> expect(result.fnArray[0]).toEqual('paintXObject');
<del> expect(result.fnArray[1]).toEqual('restore');
<add> expect(result.fnArray[0]).toEqual(OPS.paintXObject);
<add> expect(result.fnArray[1]).toEqual(OPS.restore);
<ide> });
<ide>
<ide> it('should handle tree glued operations', function() {
<ide> describe('evaluator', function() {
<ide> var result = evaluator.getOperatorList(stream, new ResourcesMock());
<ide> expect(!!result.fnArray && !!result.argsArray).toEqual(true);
<ide> expect(result.fnArray.length).toEqual(3);
<del> expect(result.fnArray[0]).toEqual('save');
<del> expect(result.fnArray[1]).toEqual('save');
<del> expect(result.fnArray[2]).toEqual('save');
<add> expect(result.fnArray[0]).toEqual(OPS.save);
<add> expect(result.fnArray[1]).toEqual(OPS.save);
<add> expect(result.fnArray[2]).toEqual(OPS.save);
<ide> });
<ide>
<ide> it('should handle three glued operations #2', function() {
<ide> describe('evaluator', function() {
<ide> var result = evaluator.getOperatorList(stream, resources);
<ide> expect(!!result.fnArray && !!result.argsArray).toEqual(true);
<ide> expect(result.fnArray.length).toEqual(3);
<del> expect(result.fnArray[0]).toEqual('eoFillStroke');
<del> expect(result.fnArray[1]).toEqual('fillStroke');
<del> expect(result.fnArray[2]).toEqual('eoFill');
<add> expect(result.fnArray[0]).toEqual(OPS.eoFillStroke);
<add> expect(result.fnArray[1]).toEqual(OPS.fillStroke);
<add> expect(result.fnArray[2]).toEqual(OPS.eoFill);
<ide> });
<ide>
<ide> it('should handle glued operations and operands', function() {
<ide> describe('evaluator', function() {
<ide> var result = evaluator.getOperatorList(stream, new ResourcesMock());
<ide> expect(!!result.fnArray && !!result.argsArray).toEqual(true);
<ide> expect(result.fnArray.length).toEqual(2);
<del> expect(result.fnArray[0]).toEqual('save');
<del> expect(result.fnArray[1]).toEqual('setTextRise');
<add> expect(result.fnArray[0]).toEqual(OPS.save);
<add> expect(result.fnArray[1]).toEqual(OPS.setTextRise);
<ide> expect(result.argsArray.length).toEqual(2);
<ide> expect(result.argsArray[1].length).toEqual(1);
<ide> expect(result.argsArray[1][0]).toEqual(5);
<ide> describe('evaluator', function() {
<ide> var result = evaluator.getOperatorList(stream, new ResourcesMock());
<ide> expect(!!result.fnArray && !!result.argsArray).toEqual(true);
<ide> expect(result.fnArray.length).toEqual(3);
<del> expect(result.fnArray[0]).toEqual('setFlatness');
<del> expect(result.fnArray[1]).toEqual('setRenderingIntent');
<del> expect(result.fnArray[2]).toEqual('save');
<add> expect(result.fnArray[0]).toEqual(OPS.setFlatness);
<add> expect(result.fnArray[1]).toEqual(OPS.setRenderingIntent);
<add> expect(result.fnArray[2]).toEqual(OPS.save);
<ide> expect(result.argsArray.length).toEqual(3);
<ide> expect(result.argsArray[0].length).toEqual(1);
<ide> expect(result.argsArray[0][0]).toEqual(true);
<ide> describe('evaluator', function() {
<ide> var result = evaluator.getOperatorList(stream, new ResourcesMock());
<ide> expect(result.argsArray[0][0]).toEqual(5);
<ide> expect(result.argsArray[0][1]).toEqual(1);
<del> expect(result.fnArray[0]).toEqual('setCharWidth');
<add> expect(result.fnArray[0]).toEqual(OPS.setCharWidth);
<ide> });
<ide> it('should execute if too many arguments', function() {
<ide> var evaluator = new PartialEvaluator(new PdfManagerMock(),
<ide> describe('evaluator', function() {
<ide> expect(result.argsArray[0][0]).toEqual(5);
<ide> expect(result.argsArray[0][1]).toEqual(1);
<ide> expect(result.argsArray[0][2]).toEqual(4);
<del> expect(result.fnArray[0]).toEqual('setCharWidth');
<add> expect(result.fnArray[0]).toEqual(OPS.setCharWidth);
<ide> });
<ide> it('should skip if too few arguments', function() {
<ide> var evaluator = new PartialEvaluator(new PdfManagerMock(),
<ide><path>web/debugger.js
<ide> var Stepper = (function StepperClosure() {
<ide> return out;
<ide> }
<ide>
<add> var opMap = null;
<add>
<ide> var glyphCommands = {
<ide> 'showText': 0,
<ide> 'showSpacedText': 0,
<ide> var Stepper = (function StepperClosure() {
<ide> headerRow.appendChild(c('th', 'args'));
<ide> panel.appendChild(content);
<ide> this.table = table;
<add> if (!opMap) {
<add> opMap = Object.create(null);
<add> for (var key in PDFJS.OPS) {
<add> opMap[PDFJS.OPS[key]] = key;
<add> }
<add> }
<ide> },
<ide> updateOperatorList: function updateOperatorList(operatorList) {
<ide> var self = this;
<ide> var Stepper = (function StepperClosure() {
<ide> breakCell.appendChild(cbox);
<ide> line.appendChild(breakCell);
<ide> line.appendChild(c('td', i.toString()));
<del> var fn = operatorList.fnArray[i];
<add> var fn = opMap[operatorList.fnArray[i]];
<ide> var decArgs = args;
<ide> if (fn in glyphCommands) {
<ide> var glyphIndex = glyphCommands[fn]; | 8 |
PHP | PHP | use array_merge_recursive in input class | 98fa907805f24a90d0394e6a15b032c8a5fd8f2a | <ide><path>laravel/input.php
<ide> class Input {
<ide> */
<ide> public static function all()
<ide> {
<del> $input = array_merge(static::get(), static::query(), static::file());
<add> $input = array_merge_recursive(static::get(), static::query(), static::file());
<ide>
<ide> unset($input[Request::spoofer]);
<ide> | 1 |
Text | Text | fix positional/option in cli types | 83c1b919a7f35452a23a1016fd862e6034107cfb | <ide><path>website/docs/api/cli.md
<ide> $ python -m spacy info [model] [--markdown] [--silent] [--exclude]
<ide>
<ide> | Name | Description |
<ide> | ------------------------------------------------ | --------------------------------------------------------------------------------------------- |
<del>| `model` | A trained pipeline, i.e. package name or path (optional). ~~Optional[str] \(positional)~~ |
<add>| `model` | A trained pipeline, i.e. package name or path (optional). ~~Optional[str] \(option)~~ |
<ide> | `--markdown`, `-md` | Print information as Markdown. ~~bool (flag)~~ |
<ide> | `--silent`, `-s` <Tag variant="new">2.0.12</Tag> | Don't print anything, just return the values. ~~bool (flag)~~ |
<ide> | `--exclude`, `-e` | Comma-separated keys to exclude from the print-out. Defaults to `"labels"`. ~~Optional[str]~~ |
<ide> $ python -m spacy convert [input_file] [output_dir] [--converter] [--file-type]
<ide> | Name | Description |
<ide> | ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
<ide> | `input_file` | Input file. ~~Path (positional)~~ |
<del>| `output_dir` | Output directory for converted file. Defaults to `"-"`, meaning data will be written to `stdout`. ~~Optional[Path] \(positional)~~ |
<add>| `output_dir` | Output directory for converted file. Defaults to `"-"`, meaning data will be written to `stdout`. ~~Optional[Path] \(option)~~ |
<ide> | `--converter`, `-c` <Tag variant="new">2</Tag> | Name of converter to use (see below). ~~str (option)~~ |
<ide> | `--file-type`, `-t` <Tag variant="new">2.1</Tag> | Type of file to create. Either `spacy` (default) for binary [`DocBin`](/api/docbin) data or `json` for v2.x JSON format. ~~str (option)~~ |
<ide> | `--n-sents`, `-n` | Number of sentences per document. Supported for: `conll`, `conllu`, `iob`, `ner` ~~int (option)~~ |
<ide> $ python -m spacy debug profile [model] [inputs] [--n-texts]
<ide> | Name | Description |
<ide> | ----------------- | ---------------------------------------------------------------------------------- |
<ide> | `model` | A loadable spaCy pipeline (package name or path). ~~str (positional)~~ |
<del>| `inputs` | Optional path to input file, or `-` for standard input. ~~Path (positional)~~ |
<add>| `inputs` | Path to input file, or `-` for standard input. ~~Path (positional)~~ |
<ide> | `--n-texts`, `-n` | Maximum number of texts to use if available. Defaults to `10000`. ~~int (option)~~ |
<ide> | `--help`, `-h` | Show help message and available arguments. ~~bool (flag)~~ |
<ide> | **PRINTS** | Profiling information for the pipeline. |
<ide> $ python -m spacy project dvc [project_dir] [workflow] [--force] [--verbose]
<ide> > $ python -m spacy project dvc all
<ide> > ```
<ide>
<del>| Name | Description |
<del>| ----------------- | ----------------------------------------------------------------------------------------------------------------- |
<del>| `project_dir` | Path to project directory. Defaults to current working directory. ~~Path (positional)~~ |
<del>| `workflow` | Name of workflow defined in `project.yml`. Defaults to first workflow if not set. ~~Optional[str] \(positional)~~ |
<del>| `--force`, `-F` | Force-updating config file. ~~bool (flag)~~ |
<del>| `--verbose`, `-V` | Print more output generated by DVC. ~~bool (flag)~~ |
<del>| `--help`, `-h` | Show help message and available arguments. ~~bool (flag)~~ |
<del>| **CREATES** | A `dvc.yaml` file in the project directory, based on the steps defined in the given workflow. |
<add>| Name | Description |
<add>| ----------------- | ------------------------------------------------------------------------------------------------------------- |
<add>| `project_dir` | Path to project directory. Defaults to current working directory. ~~Path (positional)~~ |
<add>| `workflow` | Name of workflow defined in `project.yml`. Defaults to first workflow if not set. ~~Optional[str] \(option)~~ |
<add>| `--force`, `-F` | Force-updating config file. ~~bool (flag)~~ |
<add>| `--verbose`, `-V` | Print more output generated by DVC. ~~bool (flag)~~ |
<add>| `--help`, `-h` | Show help message and available arguments. ~~bool (flag)~~ |
<add>| **CREATES** | A `dvc.yaml` file in the project directory, based on the steps defined in the given workflow. |
<ide>
<ide> ## ray {#ray new="3"}
<ide>
<ide> $ python -m spacy ray train [config_path] [--code] [--output] [--n-workers] [--a
<ide> | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
<ide> | `config_path` | Path to [training config](/api/data-formats#config) file containing all settings and hyperparameters. ~~Path (positional)~~ |
<ide> | `--code`, `-c` | Path to Python file with additional code to be imported. Allows [registering custom functions](/usage/training#custom-functions) for new architectures. ~~Optional[Path] \(option)~~ |
<del>| `--output`, `-o` | Directory or remote storage URL for saving trained pipeline. The directory will be created if it doesn't exist. ~~Optional[Path] \(positional)~~ |
<add>| `--output`, `-o` | Directory or remote storage URL for saving trained pipeline. The directory will be created if it doesn't exist. ~~Optional[Path] \(option)~~ |
<ide> | `--n-workers`, `-n` | The number of workers. Defaults to `1`. ~~int (option)~~ |
<ide> | `--address`, `-a` | Optional address of the Ray cluster. If not set (default), Ray will run locally. ~~Optional[str] \(option)~~ |
<ide> | `--gpu-id`, `-g` | GPU ID or `-1` for CPU. Defaults to `-1`. ~~int (option)~~ | | 1 |
Python | Python | fix typo in docstring of bitwise_or | 952ae80c9e780100a0fa017fe8ef0fe988ba4ad2 | <ide><path>numpy/core/code_generators/ufunc_docstrings.py
<ide> def add_newdoc(place, name, doc):
<ide>
<ide> Examples
<ide> --------
<del> The number 13 has the binaray representation ``00001101``. Likewise,
<add> The number 13 has the binary representation ``00001101``. Likewise,
<ide> 16 is represented by ``00010000``. The bit-wise OR of 13 and 16 is
<ide> then ``000111011``, or 29:
<ide> | 1 |
Javascript | Javascript | add ref to integer | eaa08062f317a439ec655a231cee948ead8ae7dd | <ide><path>tools/doc/type-parser.js
<ide> const jsDocUrl = 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/' +
<ide> 'Reference/Global_Objects/';
<ide> const jsPrimitiveUrl = 'https://developer.mozilla.org/en-US/docs/Web/' +
<ide> 'JavaScript/Data_structures';
<del>const jsPrimitives = [
<del> 'Number', 'String', 'Boolean', 'Null', 'Symbol'
<del>];
<add>const jsPrimitives = {
<add> 'Integer': 'Number', // this is for extending
<add> 'Number': 'Number',
<add> 'String': 'String',
<add> 'Boolean': 'Boolean',
<add> 'Null': 'Null',
<add> 'Symbol': 'Symbol'
<add>};
<ide> const jsGlobalTypes = [
<del> 'Error', 'Object', 'Function', 'Array', 'Uint8Array',
<add> 'Error', 'Object', 'Function', 'Array', 'TypedArray', 'Uint8Array',
<ide> 'Uint16Array', 'Uint32Array', 'Int8Array', 'Int16Array', 'Int32Array',
<ide> 'Uint8ClampedArray', 'Float32Array', 'Float64Array', 'Date', 'RegExp',
<ide> 'ArrayBuffer', 'DataView', 'Promise', 'EvalError', 'RangeError',
<ide> module.exports = {
<ide> typeText = typeText.trim();
<ide> if (typeText) {
<ide> let typeUrl = null;
<del> if (jsPrimitives.indexOf(typeText) !== -1) {
<del> typeUrl = jsPrimitiveUrl + '#' + typeText + '_type';
<add> const primitive = jsPrimitives[typeText];
<add> if (primitive !== undefined) {
<add> typeUrl = `${jsPrimitiveUrl}#${primitive}_type`;
<ide> } else if (jsGlobalTypes.indexOf(typeText) !== -1) {
<ide> typeUrl = jsDocUrl + typeText;
<ide> } else if (typeMap[typeText]) { | 1 |
Javascript | Javascript | fix removealllisteners() for stream.readable | 9f4bf4ca43bc40f68a05c87081a9bae8736515b1 | <ide><path>lib/_stream_readable.js
<ide> Readable.prototype.removeListener = function(ev, fn) {
<ide> };
<ide>
<ide> Readable.prototype.removeAllListeners = function(ev) {
<del> const res = Stream.prototype.removeAllListeners.call(this, ev);
<add> const res = Stream.prototype.removeAllListeners.apply(this, arguments);
<ide>
<ide> if (ev === 'readable' || ev === undefined) {
<ide> // We need to check if there is someone still listening to
<ide><path>test/parallel/test-stream-readable-event.js
<ide> const Readable = require('stream').Readable;
<ide> assert.deepStrictEqual(result, expected);
<ide> }));
<ide> }
<add>
<add>{
<add> // #20923
<add> const r = new Readable();
<add> r._read = function() {
<add> // actually doing thing here
<add> };
<add> r.on('data', function() {});
<add>
<add> r.removeAllListeners();
<add>
<add> assert.strictEqual(r.eventNames().length, 0);
<add>} | 2 |
Mixed | Text | add extends to derived classes | 5c9209bc4d9f5e7da78eb03824ad27add5324bc8 | <ide><path>doc/api/assert.md
<ide> lenient legacy mode.
<ide>
<ide> ## Class: assert.AssertionError
<ide>
<del>A subclass of `Error` that indicates the failure of an assertion. All errors
<del>thrown by the `assert` module will be instances of the `AssertionError` class.
<add>* Extends: {errors.Error}
<add>
<add>Indicates the failure of an assertion. All errors thrown by the `assert` module
<add>will be instances of the `AssertionError` class.
<ide>
<ide> ### new assert.AssertionError(options)
<ide> <!-- YAML
<ide><path>doc/api/errors.md
<ide> cases. If [domains][] are enabled, or a handler has been registered with
<ide>
<ide> <!--type=class-->
<ide>
<del>A generic JavaScript `Error` object that does not denote any specific
<add>A generic JavaScript {Error} object that does not denote any specific
<ide> circumstance of why the error occurred. `Error` objects capture a "stack trace"
<ide> detailing the point in the code at which the `Error` was instantiated, and may
<ide> provide a text description of the error.
<ide> loop tick.
<ide>
<ide> ## Class: AssertionError
<ide>
<del>A subclass of `Error` that indicates the failure of an assertion. For details,
<del>see [`Class: assert.AssertionError`][].
<add>* Extends: {errors.Error}
<add>
<add>Indicates the failure of an assertion. For details, see
<add>[`Class: assert.AssertionError`][].
<ide>
<ide> ## Class: RangeError
<ide>
<del>A subclass of `Error` that indicates that a provided argument was not within the
<del>set or range of acceptable values for a function; whether that is a numeric
<del>range, or outside the set of options for a given function parameter.
<add>* Extends: {errors.Error}
<add>
<add>Indicates that a provided argument was not within the set or range of
<add>acceptable values for a function; whether that is a numeric range, or
<add>outside the set of options for a given function parameter.
<ide>
<ide> ```js
<ide> require('net').connect(-1);
<ide> of argument validation.
<ide>
<ide> ## Class: ReferenceError
<ide>
<del>A subclass of `Error` that indicates that an attempt is being made to access a
<del>variable that is not defined. Such errors commonly indicate typos in code, or
<del>an otherwise broken program.
<add>* Extends: {errors.Error}
<add>
<add>Indicates that an attempt is being made to access a variable that is not
<add>defined. Such errors commonly indicate typos in code, or an otherwise broken
<add>program.
<ide>
<ide> While client code may generate and propagate these errors, in practice, only V8
<ide> will do so.
<ide> or its dependencies.
<ide>
<ide> ## Class: SyntaxError
<ide>
<del>A subclass of `Error` that indicates that a program is not valid JavaScript.
<del>These errors may only be generated and propagated as a result of code
<del>evaluation. Code evaluation may happen as a result of `eval`, `Function`,
<del>`require`, or [vm][]. These errors are almost always indicative of a broken
<del>program.
<add>* Extends: {errors.Error}
<add>
<add>Indicates that a program is not valid JavaScript. These errors may only be
<add>generated and propagated as a result of code evaluation. Code evaluation may
<add>happen as a result of `eval`, `Function`, `require`, or [vm][]. These errors
<add>are almost always indicative of a broken program.
<ide>
<ide> ```js
<ide> try {
<ide> they may only be caught by other contexts.
<ide>
<ide> ## Class: SystemError
<ide>
<add>* Extends: {errors.Error}
<add>
<ide> Node.js generates system errors when exceptions occur within its runtime
<ide> environment. These usually occur when an application violates an operating
<ide> system constraint. For example, a system error will occur if an application
<ide> program. For a comprehensive list, see the [`errno`(3) man page][].
<ide>
<ide> ## Class: TypeError
<ide>
<del>A subclass of `Error` that indicates that a provided argument is not an
<del>allowable type. For example, passing a function to a parameter which expects a
<del>string would be considered a `TypeError`.
<add>* Extends {errors.Error}
<add>
<add>Indicates that a provided argument is not an allowable type. For example,
<add>passing a function to a parameter which expects a string would be considered
<add>a `TypeError`.
<ide>
<ide> ```js
<ide> require('url').parse(() => { });
<ide><path>tools/doc/type-parser.js
<ide> const customTypesMap = {
<ide>
<ide> 'Domain': 'domain.html#domain_class_domain',
<ide>
<add> 'errors.Error': 'errors.html#errors_class_error',
<add>
<ide> 'import.meta': 'esm.html#esm_import_meta',
<ide>
<ide> 'EventEmitter': 'events.html#events_class_eventemitter', | 3 |
Python | Python | use model_dir inside of load_model | c19b83f6ae42634d6b2a1403bebf328edcd61de6 | <ide><path>examples/training/load_ner.py
<ide> def load_model(model_dir):
<ide> with (model_dir / 'vocab' / 'strings.json').open('r', encoding='utf8') as file_:
<ide> nlp.vocab.strings.load(file_)
<ide> nlp.vocab.load_lexemes(model_dir / 'vocab' / 'lexemes.bin')
<del> ner = EntityRecognizer.load(pathlib.Path("ner"), nlp.vocab, require=True)
<add> ner = EntityRecognizer.load(model_dir, nlp.vocab, require=True)
<ide> return (nlp, ner)
<ide>
<ide> (nlp, ner) = load_model('ner') | 1 |
Mixed | Javascript | add rm method | 4e9f3cc6fe7147128c2e837ff94d18dd8778e6fc | <ide><path>doc/api/errors.md
<ide> added: v14.0.0
<ide> Used when a feature that is not available
<ide> to the current platform which is running Node.js is used.
<ide>
<add><a id="ERR_FS_EISDIR"></a>
<add>### `ERR_FS_EISDIR`
<add>
<add>Path is a directory.
<add>
<ide> <a id="ERR_FS_FILE_TOO_LARGE"></a>
<ide> ### `ERR_FS_FILE_TOO_LARGE`
<ide>
<ide><path>doc/api/fs.md
<ide> changes:
<ide> * `options` {Object}
<ide> * `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
<ide> `EPERM` error is encountered, Node.js will retry the operation with a linear
<del> backoff wait of `retryDelay` ms longer on each try. This option represents
<del> the number of retries. This option is ignored if the `recursive` option is
<del> not `true`. **Default:** `0`.
<add> backoff wait of `retryDelay` milliseconds longer on each try. This option
<add> represents the number of retries. This option is ignored if the `recursive`
<add> option is not `true`. **Default:** `0`.
<ide> * `recursive` {boolean} If `true`, perform a recursive directory removal. In
<ide> recursive mode, errors are not reported if `path` does not exist, and
<ide> operations are retried on failure. **Default:** `false`.
<ide> changes:
<ide> * `options` {Object}
<ide> * `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
<ide> `EPERM` error is encountered, Node.js will retry the operation with a linear
<del> backoff wait of `retryDelay` ms longer on each try. This option represents
<del> the number of retries. This option is ignored if the `recursive` option is
<del> not `true`. **Default:** `0`.
<add> backoff wait of `retryDelay` milliseconds longer on each try. This option
<add> represents the number of retries. This option is ignored if the `recursive`
<add> option is not `true`. **Default:** `0`.
<ide> * `recursive` {boolean} If `true`, perform a recursive directory removal. In
<ide> recursive mode, errors are not reported if `path` does not exist, and
<ide> operations are retried on failure. **Default:** `false`.
<ide> that represent files will be deleted. The permissive behavior of the
<ide> `recursive` option is deprecated, `ENOTDIR` and `ENOENT` will be thrown in
<ide> the future.
<ide>
<add>## `fs.rm(path[, options], callback)`
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>* `path` {string|Buffer|URL}
<add>* `options` {Object}
<add> * `force` don't error on nonexistent path
<add> * `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
<add> `EPERM` error is encountered, Node.js will retry the operation with a linear
<add> backoff wait of `retryDelay` milliseconds longer on each try. This option
<add> represents the number of retries. This option is ignored if the `recursive`
<add> option is not `true`. **Default:** `0`.
<add> * `recursive` {boolean} If `true`, perform a recursive removal. In
<add> recursive mode operations are retried on failure. **Default:** `false`.
<add> * `retryDelay` {integer} The amount of time in milliseconds to wait between
<add> retries. This option is ignored if the `recursive` option is not `true`.
<add> **Default:** `100`.
<add>* `callback` {Function}
<add> * `err` {Error}
<add>
<add>Asynchronously removes files and directories (modeled on the standard POSIX `rm`
<add>utility). No arguments other than a possible exception are given to the
<add>completion callback.
<add>
<add>## `fs.rmSync(path[, options])`
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>* `path` {string|Buffer|URL}
<add>* `options` {Object}
<add> * `force` Ignore errors
<add> * `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
<add> `EPERM` error is encountered, Node.js will retry the operation with a linear
<add> backoff wait of `retryDelay` milliseconds longer on each try. This option
<add> represents the number of retries. This option is ignored if the `recursive`
<add> option is not `true`. **Default:** `0`.
<add> * `recursive` {boolean} If `true`, perform a recursive directory removal. In
<add> recursive mode operations are retried on failure. **Default:** `false`.
<add> * `retryDelay` {integer} The amount of time in milliseconds to wait between
<add> retries. This option is ignored if the `recursive` option is not `true`.
<add> **Default:** `100`.
<add>
<add>Synchronously removes files and directories (modeled on the standard POSIX `rm`
<add>utility). Returns `undefined`.
<add>
<ide> ## `fs.stat(path[, options], callback)`
<ide> <!-- YAML
<ide> added: v0.0.2
<ide> changes:
<ide> * `options` {Object}
<ide> * `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
<ide> `EPERM` error is encountered, Node.js will retry the operation with a linear
<del> backoff wait of `retryDelay` ms longer on each try. This option represents
<del> the number of retries. This option is ignored if the `recursive` option is
<del> not `true`. **Default:** `0`.
<add> backoff wait of `retryDelay` milliseconds longer on each try. This option
<add> represents the number of retries. This option is ignored if the `recursive`
<add> option is not `true`. **Default:** `0`.
<ide> * `recursive` {boolean} If `true`, perform a recursive directory removal. In
<ide> recursive mode, errors are not reported if `path` does not exist, and
<ide> operations are retried on failure. **Default:** `false`.
<ide> that represent files will be deleted. The permissive behavior of the
<ide> `recursive` option is deprecated, `ENOTDIR` and `ENOENT` will be thrown in
<ide> the future.
<ide>
<add>## `fsPromises.rm(path[, options])`
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>* `path` {string|Buffer|URL}
<add>* `options` {Object}
<add> * `force` Ignore errors
<add> * `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
<add> `EPERM` error is encountered, Node.js will retry the operation with a linear
<add> backoff wait of `retryDelay` milliseconds longer on each try. This option
<add> represents the number of retries. This option is ignored if the `recursive`
<add> option is not `true`. **Default:** `0`.
<add> * `recursive` {boolean} If `true`, perform a recursive directory removal. In
<add> recursive mode operations are retried on failure. **Default:** `false`.
<add> * `retryDelay` {integer} The amount of time in milliseconds to wait between
<add> retries. This option is ignored if the `recursive` option is not `true`.
<add> **Default:** `100`.
<add>
<add>Synchronously removes files and directories (modeled on the standard POSIX `rm`
<add>utility). Resolves the `Promise` with no arguments on success.
<add>
<ide> ### `fsPromises.stat(path[, options])`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide><path>lib/fs.js
<ide> const {
<ide> validateOffsetLengthRead,
<ide> validateOffsetLengthWrite,
<ide> validatePath,
<add> validateRmOptions,
<add> validateRmOptionsSync,
<ide> validateRmdirOptions,
<ide> validateStringAfterArrayBufferView,
<ide> warnOnNonPortableTemplate
<ide> function rmdir(path, options, callback) {
<ide>
<ide> callback = makeCallback(callback);
<ide> path = pathModule.toNamespacedPath(getValidatedPath(path));
<del> options = validateRmdirOptions(options);
<ide>
<del> if (options.recursive) {
<del> lazyLoadRimraf();
<del> return rimraf(path, options, callback);
<del> }
<add> if (options && options.recursive) {
<add> options = validateRmOptions(
<add> path,
<add> { ...options, force: true },
<add> (err, options) => {
<add> if (err) {
<add> return callback(err);
<add> }
<ide>
<del> const req = new FSReqCallback();
<del> req.oncomplete = callback;
<del> binding.rmdir(path, req);
<add> lazyLoadRimraf();
<add> return rimraf(path, options, callback);
<add> });
<add>
<add> } else {
<add> options = validateRmdirOptions(options);
<add> const req = new FSReqCallback();
<add> req.oncomplete = callback;
<add> return binding.rmdir(path, req);
<add> }
<ide> }
<ide>
<ide> function rmdirSync(path, options) {
<ide> path = getValidatedPath(path);
<del> options = validateRmdirOptions(options);
<ide>
<del> if (options.recursive) {
<add> if (options && options.recursive) {
<add> options = validateRmOptionsSync(path, { ...options, force: true });
<ide> lazyLoadRimraf();
<ide> return rimrafSync(pathModule.toNamespacedPath(path), options);
<ide> }
<ide>
<add> options = validateRmdirOptions(options);
<ide> const ctx = { path };
<ide> binding.rmdir(pathModule.toNamespacedPath(path), undefined, ctx);
<del> handleErrorFromBinding(ctx);
<add> return handleErrorFromBinding(ctx);
<add>}
<add>
<add>function rm(path, options, callback) {
<add> if (typeof options === 'function') {
<add> callback = options;
<add> options = undefined;
<add> }
<add>
<add> validateRmOptions(path, options, (err, options) => {
<add> if (err) {
<add> return callback(err);
<add> }
<add> lazyLoadRimraf();
<add> return rimraf(pathModule.toNamespacedPath(path), options, callback);
<add> });
<add>}
<add>
<add>function rmSync(path, options) {
<add> options = validateRmOptionsSync(path, options);
<add>
<add> lazyLoadRimraf();
<add> return rimrafSync(pathModule.toNamespacedPath(path), options);
<ide> }
<ide>
<ide> function fdatasync(fd, callback) {
<ide> module.exports = fs = {
<ide> realpathSync,
<ide> rename,
<ide> renameSync,
<add> rm,
<add> rmSync,
<ide> rmdir,
<ide> rmdirSync,
<ide> stat,
<ide><path>lib/internal/errors.js
<ide> E('ERR_FEATURE_UNAVAILABLE_ON_PLATFORM',
<ide> 'The feature %s is unavailable on the current platform' +
<ide> ', which is being used to run Node.js',
<ide> TypeError);
<add>E('ERR_FS_EISDIR', 'Path is a directory', SystemError);
<ide> E('ERR_FS_FILE_TOO_LARGE', 'File size (%s) is greater than 2 GB', RangeError);
<ide> E('ERR_FS_INVALID_SYMLINK_TYPE',
<ide> 'Symlink type must be one of "dir", "file", or "junction". Received "%s"',
<ide><path>lib/internal/fs/promises.js
<ide> const {
<ide> validateBufferArray,
<ide> validateOffsetLengthRead,
<ide> validateOffsetLengthWrite,
<add> validateRmOptions,
<ide> validateRmdirOptions,
<ide> validateStringAfterArrayBufferView,
<ide> warnOnNonPortableTemplate
<ide> const {
<ide> } = require('internal/worker/js_transferable');
<ide>
<ide> const getDirectoryEntriesPromise = promisify(getDirents);
<add>const validateRmOptionsPromise = promisify(validateRmOptions);
<ide>
<ide> class FileHandle extends JSTransferable {
<ide> constructor(filehandle) {
<ide> async function ftruncate(handle, len = 0) {
<ide> return binding.ftruncate(handle.fd, len, kUsePromises);
<ide> }
<ide>
<add>async function rm(path, options) {
<add> path = pathModule.toNamespacedPath(getValidatedPath(path));
<add> options = await validateRmOptionsPromise(path, options);
<add> return rimrafPromises(path, options);
<add>}
<add>
<ide> async function rmdir(path, options) {
<ide> path = pathModule.toNamespacedPath(getValidatedPath(path));
<ide> options = validateRmdirOptions(options);
<ide> module.exports = {
<ide> opendir: promisify(opendir),
<ide> rename,
<ide> truncate,
<add> rm,
<ide> rmdir,
<ide> mkdir,
<ide> readdir,
<ide><path>lib/internal/fs/utils.js
<ide> const {
<ide> const { Buffer } = require('buffer');
<ide> const {
<ide> codes: {
<add> ERR_FS_EISDIR,
<ide> ERR_FS_INVALID_SYMLINK_TYPE,
<ide> ERR_INVALID_ARG_TYPE,
<ide> ERR_INVALID_ARG_VALUE,
<ide> function warnOnNonPortableTemplate(template) {
<ide> }
<ide> }
<ide>
<add>const defaultRmOptions = {
<add> recursive: false,
<add> force: false,
<add> retryDelay: 100,
<add> maxRetries: 0
<add>};
<add>
<ide> const defaultRmdirOptions = {
<ide> retryDelay: 100,
<ide> maxRetries: 0,
<ide> recursive: false,
<ide> };
<ide>
<del>const validateRmdirOptions = hideStackFrames((options) => {
<del> if (options === undefined)
<del> return defaultRmdirOptions;
<del> if (options === null || typeof options !== 'object')
<del> throw new ERR_INVALID_ARG_TYPE('options', 'object', options);
<add>const validateRmOptions = hideStackFrames((path, options, callback) => {
<add> try {
<add> options = validateRmdirOptions(options, defaultRmOptions);
<add> } catch (err) {
<add> return callback(err);
<add> }
<ide>
<del> options = { ...defaultRmdirOptions, ...options };
<add> if (typeof options.force !== 'boolean')
<add> return callback(
<add> new ERR_INVALID_ARG_TYPE('force', 'boolean', options.force)
<add> );
<ide>
<del> if (typeof options.recursive !== 'boolean')
<del> throw new ERR_INVALID_ARG_TYPE('recursive', 'boolean', options.recursive);
<add> lazyLoadFs().stat(path, (err, stats) => {
<add> if (err && err.code === 'ENOENT') {
<add> if (options.force) {
<add> return callback(null, options);
<add> }
<add> return callback(err, options);
<add> }
<add>
<add> if (err) {
<add> return callback(err);
<add> }
<add>
<add> if (stats.isDirectory() && !options.recursive) {
<add> return callback(new ERR_FS_EISDIR({
<add> code: 'EISDIR',
<add> message: 'is a directory',
<add> path,
<add> syscall: 'rm',
<add> errno: -21
<add> }));
<add> }
<add> return callback(null, options);
<add> });
<add>});
<ide>
<del> validateInt32(options.retryDelay, 'retryDelay', 0);
<del> validateUint32(options.maxRetries, 'maxRetries');
<add>const validateRmOptionsSync = hideStackFrames((path, options) => {
<add> options = validateRmdirOptions(options, defaultRmOptions);
<add>
<add> if (typeof options.force !== 'boolean')
<add> throw new ERR_INVALID_ARG_TYPE('force', 'boolean', options.force);
<add>
<add> try {
<add> const stats = lazyLoadFs().statSync(path);
<add>
<add> if (stats.isDirectory() && !options.recursive) {
<add> throw new ERR_FS_EISDIR({
<add> code: 'EISDIR',
<add> message: 'is a directory',
<add> path,
<add> syscall: 'rm',
<add> errno: -21
<add> });
<add> }
<add> } catch (err) {
<add> if (err.code !== 'ENOENT') {
<add> throw err;
<add> } else if (err.code === 'ENOENT' && !options.force) {
<add> throw err;
<add> }
<add> }
<ide>
<ide> return options;
<ide> });
<ide>
<add>const validateRmdirOptions = hideStackFrames(
<add> (options, defaults = defaultRmdirOptions) => {
<add> if (options === undefined)
<add> return defaults;
<add> if (options === null || typeof options !== 'object')
<add> throw new ERR_INVALID_ARG_TYPE('options', 'object', options);
<add>
<add> options = { ...defaults, ...options };
<add>
<add> if (typeof options.recursive !== 'boolean')
<add> throw new ERR_INVALID_ARG_TYPE('recursive', 'boolean', options.recursive);
<add>
<add> validateInt32(options.retryDelay, 'retryDelay', 0);
<add> validateUint32(options.maxRetries, 'maxRetries');
<add>
<add> return options;
<add> });
<add>
<ide> const getValidMode = hideStackFrames((mode, type) => {
<ide> let min = kMinimumAccessMode;
<ide> let max = kMaximumAccessMode;
<ide> module.exports = {
<ide> validateOffsetLengthRead,
<ide> validateOffsetLengthWrite,
<ide> validatePath,
<add> validateRmOptions,
<add> validateRmOptionsSync,
<ide> validateRmdirOptions,
<ide> validateStringAfterArrayBufferView,
<ide> warnOnNonPortableTemplate
<ide><path>test/common/tmpdir.js
<ide> const fs = require('fs');
<ide> const path = require('path');
<ide> const { isMainThread } = require('worker_threads');
<ide>
<del>function rimrafSync(pathname) {
<del> fs.rmdirSync(pathname, { maxRetries: 3, recursive: true });
<add>function rmSync(pathname) {
<add> fs.rmSync(pathname, { maxRetries: 3, recursive: true, force: true });
<ide> }
<ide>
<ide> const testRoot = process.env.NODE_TEST_DIR ?
<ide> const tmpPath = path.join(testRoot, tmpdirName);
<ide>
<ide> let firstRefresh = true;
<ide> function refresh() {
<del> rimrafSync(this.path);
<add> rmSync(this.path);
<ide> fs.mkdirSync(this.path);
<ide>
<ide> if (firstRefresh) {
<ide> function onexit() {
<ide> process.chdir(testRoot);
<ide>
<ide> try {
<del> rimrafSync(tmpPath);
<add> rmSync(tmpPath);
<ide> } catch (e) {
<ide> console.error('Can\'t clean tmpdir:', tmpPath);
<ide>
<ide><path>test/parallel/test-fs-rm.js
<add>// Flags: --expose-internals
<add>'use strict';
<add>const common = require('../common');
<add>const tmpdir = require('../common/tmpdir');
<add>const assert = require('assert');
<add>const fs = require('fs');
<add>const path = require('path');
<add>const { validateRmOptionsSync } = require('internal/fs/utils');
<add>
<add>tmpdir.refresh();
<add>
<add>let count = 0;
<add>const nextDirPath = (name = 'rm') =>
<add> path.join(tmpdir.path, `${name}-${count++}`);
<add>
<add>function makeNonEmptyDirectory(depth, files, folders, dirname, createSymLinks) {
<add> fs.mkdirSync(dirname, { recursive: true });
<add> fs.writeFileSync(path.join(dirname, 'text.txt'), 'hello', 'utf8');
<add>
<add> const options = { flag: 'wx' };
<add>
<add> for (let f = files; f > 0; f--) {
<add> fs.writeFileSync(path.join(dirname, `f-${depth}-${f}`), '', options);
<add> }
<add>
<add> if (createSymLinks) {
<add> // Valid symlink
<add> fs.symlinkSync(
<add> `f-${depth}-1`,
<add> path.join(dirname, `link-${depth}-good`),
<add> 'file'
<add> );
<add>
<add> // Invalid symlink
<add> fs.symlinkSync(
<add> 'does-not-exist',
<add> path.join(dirname, `link-${depth}-bad`),
<add> 'file'
<add> );
<add> }
<add>
<add> // File with a name that looks like a glob
<add> fs.writeFileSync(path.join(dirname, '[a-z0-9].txt'), '', options);
<add>
<add> depth--;
<add> if (depth <= 0) {
<add> return;
<add> }
<add>
<add> for (let f = folders; f > 0; f--) {
<add> fs.mkdirSync(
<add> path.join(dirname, `folder-${depth}-${f}`),
<add> { recursive: true }
<add> );
<add> makeNonEmptyDirectory(
<add> depth,
<add> files,
<add> folders,
<add> path.join(dirname, `d-${depth}-${f}`),
<add> createSymLinks
<add> );
<add> }
<add>}
<add>
<add>function removeAsync(dir) {
<add> // Removal should fail without the recursive option.
<add> fs.rm(dir, common.mustCall((err) => {
<add> assert.strictEqual(err.syscall, 'rm');
<add>
<add> // Removal should fail without the recursive option set to true.
<add> fs.rm(dir, { recursive: false }, common.mustCall((err) => {
<add> assert.strictEqual(err.syscall, 'rm');
<add>
<add> // Recursive removal should succeed.
<add> fs.rm(dir, { recursive: true }, common.mustCall((err) => {
<add> assert.ifError(err);
<add>
<add> // Attempted removal should fail now because the directory is gone.
<add> fs.rm(dir, common.mustCall((err) => {
<add> assert.strictEqual(err.syscall, 'stat');
<add> }));
<add> }));
<add> }));
<add> }));
<add>}
<add>
<add>// Test the asynchronous version
<add>{
<add> // Create a 4-level folder hierarchy including symlinks
<add> let dir = nextDirPath();
<add> makeNonEmptyDirectory(4, 10, 2, dir, true);
<add> removeAsync(dir);
<add>
<add> // Create a 2-level folder hierarchy without symlinks
<add> dir = nextDirPath();
<add> makeNonEmptyDirectory(2, 10, 2, dir, false);
<add> removeAsync(dir);
<add>
<add> // Create a flat folder including symlinks
<add> dir = nextDirPath();
<add> makeNonEmptyDirectory(1, 10, 2, dir, true);
<add> removeAsync(dir);
<add>
<add> // Should fail if target does not exist
<add> fs.rm(
<add> path.join(tmpdir.path, 'noexist.txt'),
<add> { recursive: true },
<add> common.mustCall((err) => {
<add> assert.strictEqual(err.code, 'ENOENT');
<add> })
<add> );
<add>
<add> // Should delete a file
<add> const filePath = path.join(tmpdir.path, 'rm-async-file.txt');
<add> fs.writeFileSync(filePath, '');
<add> fs.rm(filePath, { recursive: true }, common.mustCall((err) => {
<add> try {
<add> assert.strictEqual(err, null);
<add> assert.strictEqual(fs.existsSync(filePath), false);
<add> } finally {
<add> fs.rmSync(filePath, { force: true });
<add> }
<add> }));
<add>}
<add>
<add>// Test the synchronous version.
<add>{
<add> const dir = nextDirPath();
<add> makeNonEmptyDirectory(4, 10, 2, dir, true);
<add>
<add> // Removal should fail without the recursive option set to true.
<add> assert.throws(() => {
<add> fs.rmSync(dir);
<add> }, { syscall: 'rm' });
<add> assert.throws(() => {
<add> fs.rmSync(dir, { recursive: false });
<add> }, { syscall: 'rm' });
<add>
<add> // Should fail if target does not exist
<add> assert.throws(() => {
<add> fs.rmSync(path.join(tmpdir.path, 'noexist.txt'), { recursive: true });
<add> }, {
<add> code: 'ENOENT',
<add> name: 'Error',
<add> message: /^ENOENT: no such file or directory, stat/
<add> });
<add>
<add> // Should delete a file
<add> const filePath = path.join(tmpdir.path, 'rm-file.txt');
<add> fs.writeFileSync(filePath, '');
<add>
<add> try {
<add> fs.rmSync(filePath, { recursive: true });
<add> } finally {
<add> fs.rmSync(filePath, { force: true });
<add> }
<add>
<add> // Recursive removal should succeed.
<add> fs.rmSync(dir, { recursive: true });
<add>
<add> // Attempted removal should fail now because the directory is gone.
<add> assert.throws(() => fs.rmSync(dir), { syscall: 'stat' });
<add>}
<add>
<add>// Test the Promises based version.
<add>(async () => {
<add> const dir = nextDirPath();
<add> makeNonEmptyDirectory(4, 10, 2, dir, true);
<add>
<add> // Removal should fail without the recursive option set to true.
<add> assert.rejects(fs.promises.rm(dir), { syscall: 'rm' });
<add> assert.rejects(fs.promises.rm(dir, { recursive: false }), {
<add> syscall: 'rm'
<add> });
<add>
<add> // Recursive removal should succeed.
<add> await fs.promises.rm(dir, { recursive: true });
<add>
<add> // Attempted removal should fail now because the directory is gone.
<add> assert.rejects(fs.promises.rm(dir), { syscall: 'stat' });
<add>
<add> // Should fail if target does not exist
<add> assert.rejects(fs.promises.rm(
<add> path.join(tmpdir.path, 'noexist.txt'),
<add> { recursive: true }
<add> ), {
<add> code: 'ENOENT',
<add> name: 'Error',
<add> message: /^ENOENT: no such file or directory, stat/
<add> });
<add>
<add> // Should not fail if target does not exist and force option is true
<add> fs.promises.rm(path.join(tmpdir.path, 'noexist.txt'), { force: true });
<add>
<add> // Should delete file
<add> const filePath = path.join(tmpdir.path, 'rm-promises-file.txt');
<add> fs.writeFileSync(filePath, '');
<add>
<add> try {
<add> await fs.promises.rm(filePath, { recursive: true });
<add> } finally {
<add> fs.rmSync(filePath, { force: true });
<add> }
<add>})().then(common.mustCall());
<add>
<add>// Test input validation.
<add>{
<add> const dir = nextDirPath();
<add> makeNonEmptyDirectory(4, 10, 2, dir, true);
<add> const filePath = (path.join(tmpdir.path, 'rm-args-file.txt'));
<add> fs.writeFileSync(filePath, '');
<add>
<add> const defaults = {
<add> retryDelay: 100,
<add> maxRetries: 0,
<add> recursive: false,
<add> force: false
<add> };
<add> const modified = {
<add> retryDelay: 953,
<add> maxRetries: 5,
<add> recursive: true,
<add> force: false
<add> };
<add>
<add> assert.deepStrictEqual(validateRmOptionsSync(filePath), defaults);
<add> assert.deepStrictEqual(validateRmOptionsSync(filePath, {}), defaults);
<add> assert.deepStrictEqual(validateRmOptionsSync(filePath, modified), modified);
<add> assert.deepStrictEqual(validateRmOptionsSync(filePath, {
<add> maxRetries: 99
<add> }), {
<add> retryDelay: 100,
<add> maxRetries: 99,
<add> recursive: false,
<add> force: false
<add> });
<add>
<add> [null, 'foo', 5, NaN].forEach((bad) => {
<add> assert.throws(() => {
<add> validateRmOptionsSync(filePath, bad);
<add> }, {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> name: 'TypeError',
<add> message: /^The "options" argument must be of type object\./
<add> });
<add> });
<add>
<add> [undefined, null, 'foo', Infinity, function() {}].forEach((bad) => {
<add> assert.throws(() => {
<add> validateRmOptionsSync(filePath, { recursive: bad });
<add> }, {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> name: 'TypeError',
<add> message: /^The "recursive" argument must be of type boolean\./
<add> });
<add> });
<add>
<add> [undefined, null, 'foo', Infinity, function() {}].forEach((bad) => {
<add> assert.throws(() => {
<add> validateRmOptionsSync(filePath, { force: bad });
<add> }, {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> name: 'TypeError',
<add> message: /^The "force" argument must be of type boolean\./
<add> });
<add> });
<add>
<add> assert.throws(() => {
<add> validateRmOptionsSync(filePath, { retryDelay: -1 });
<add> }, {
<add> code: 'ERR_OUT_OF_RANGE',
<add> name: 'RangeError',
<add> message: /^The value of "retryDelay" is out of range\./
<add> });
<add>
<add> assert.throws(() => {
<add> validateRmOptionsSync(filePath, { maxRetries: -1 });
<add> }, {
<add> code: 'ERR_OUT_OF_RANGE',
<add> name: 'RangeError',
<add> message: /^The value of "maxRetries" is out of range\./
<add> });
<add>}
<ide><path>test/parallel/test-policy-parse-integrity.js
<ide> function hash(algo, body) {
<ide> }
<ide>
<ide> const tmpdirPath = path.join(tmpdir.path, 'test-policy-parse-integrity');
<del>fs.rmdirSync(tmpdirPath, { maxRetries: 3, recursive: true });
<add>fs.rmSync(tmpdirPath, { maxRetries: 3, recursive: true, force: true });
<ide> fs.mkdirSync(tmpdirPath, { recursive: true });
<ide>
<ide> const policyFilepath = path.join(tmpdirPath, 'policy');
<ide><path>test/pummel/test-policy-integrity.js
<ide> function drainQueue() {
<ide> `deletable-policy-${testId}.json`
<ide> );
<ide> const cliPolicy = willDeletePolicy ? tmpPolicyPath : policyPath;
<del> fs.rmdirSync(configDirPath, { maxRetries: 3, recursive: true });
<add> fs.rmSync(configDirPath, { maxRetries: 3, recursive: true, force: true });
<ide> fs.mkdirSync(configDirPath, { recursive: true });
<ide> const manifest = {
<ide> onerror: onError,
<ide> function drainQueue() {
<ide> console.log(`stderr: ${Buffer.concat(stderr)}`);
<ide> throw e;
<ide> }
<del> fs.rmdirSync(configDirPath, { maxRetries: 3, recursive: true });
<add> fs.rmSync(configDirPath, { maxRetries: 3, recursive: true, force: true });
<ide> drainQueue();
<ide> });
<ide> } | 10 |
Ruby | Ruby | use prepare-hermes-for-build in cocoapods | aaa01f77106f891696d9ec508e2ee71111a6af2a | <ide><path>scripts/react_native_pods.rb
<ide> def use_react_native! (options={})
<ide> end
<ide>
<ide> if hermes_enabled
<add> system("(cd #{prefix} && node scripts/hermes/prepare-hermes-for-build)")
<ide> pod 'React-hermes', :path => "#{prefix}/ReactCommon/hermes"
<del> hermes_source_path = downloadAndConfigureHermesSource(prefix)
<del> pod 'hermes-engine', :path => "#{hermes_source_path}/hermes-engine.podspec"
<add> pod 'hermes-engine', :path => "#{prefix}/sdks/hermes/hermes-engine.podspec"
<ide> pod 'libevent', '~> 2.1.12'
<ide> end
<ide>
<ide> def use_react_native_codegen!(spec, options={})
<ide> }
<ide> end
<ide>
<del>def downloadAndConfigureHermesSource(react_native_path)
<del> hermes_tarball_base_url = "https://github.com/facebook/hermes/tarball/"
<del> sdks_dir = "#{react_native_path}/sdks"
<del> download_dir = "#{sdks_dir}/download"
<del> hermes_dir = "#{sdks_dir}/hermes"
<del> hermes_tag_file = "#{sdks_dir}/.hermesversion"
<del> system("mkdir -p #{hermes_dir} #{download_dir}")
<del>
<del> if (File.exist?(hermes_tag_file))
<del> hermes_tag = File.read(hermes_tag_file).strip
<del> else
<del> hermes_tag = "main"
<del> end
<del>
<del> hermes_tarball_url = hermes_tarball_base_url + hermes_tag
<del> hermes_tag_sha = %x[git ls-remote https://github.com/facebook/hermes #{hermes_tag} | cut -f 1].strip
<del> hermes_tarball_path = "#{download_dir}/hermes-#{hermes_tag_sha}.tar.gz"
<del>
<del> if (!File.exist?(hermes_tarball_path))
<del> Pod::UI.puts "[Hermes] Downloading Hermes source code..."
<del> system("curl #{hermes_tarball_url} -Lo #{hermes_tarball_path}")
<del> end
<del> Pod::UI.puts "[Hermes] Extracting Hermes tarball (#{hermes_tag_sha.slice(0,6)})"
<del> system("tar -zxf #{hermes_tarball_path} --strip-components=1 --directory #{hermes_dir}")
<del>
<del> # Use React Native's own scripts to build Hermes
<del> system("cp #{sdks_dir}/hermes-engine/hermes-engine.podspec #{hermes_dir}/hermes-engine.podspec")
<del> system("cp #{sdks_dir}/hermes-engine/utils/* #{hermes_dir}/utils/.")
<del>
<del> hermes_dir
<del>end
<del>
<ide> # This provides a post_install workaround for build issues related Xcode 12.5 and Apple Silicon (M1) machines.
<ide> # Call this in the app's main Podfile's post_install hook.
<ide> # See https://github.com/facebook/react-native/issues/31480#issuecomment-902912841 for more context. | 1 |
Javascript | Javascript | add additional ssg transform test | 05ba91d3ba50d097a5c3ec59c971778e6b8d0fc0 | <ide><path>test/unit/babel-plugin-next-ssg-transform.test.js
<ide> describe('babel plugin (next-ssg-transform)', () => {
<ide> )
<ide> })
<ide>
<add> it('should remove re-exported variable declarations (safe)', () => {
<add> const output = babel(trim`
<add> const unstable_getStaticPaths = () => {
<add> return []
<add> }, a = 2
<add>
<add> export { unstable_getStaticPaths }
<add>
<add> export default function Test() {
<add> return <div />
<add> }
<add> `)
<add>
<add> expect(output).toMatchInlineSnapshot(
<add> `"const a=2;const __NEXT_COMP=function Test(){return __jsx(\\"div\\",null);};__NEXT_COMP.__NEXT_SPR=true export default __NEXT_COMP;"`
<add> )
<add> })
<add>
<ide> it('should remove re-exported function declarations', () => {
<ide> const output = babel(trim`
<ide> function unstable_getStaticPaths() { | 1 |
Text | Text | fix nits in esm.md | 9d21b0395cc248a0e5537a11cc84f61919eccca6 | <ide><path>doc/api/esm.md
<ide> from `data:text/javascript,import "./foo";` will fail to resolve since there
<ide> is no concept of relative resolution for `data:` URLs. An example of a `data:`
<ide> URLs being used is:
<ide>
<del>```mjs
<del>import 'data:text/javascript,console.log("hello!");'
<del>import _ from 'data:application/json,"world!"'
<add>```js
<add>import 'data:text/javascript,console.log("hello!");';
<add>import _ from 'data:application/json,"world!"';
<ide> ```
<ide>
<ide> ## import.meta
<ide> $ node --experimental-modules --es-module-specifier-resolution=node index
<ide> success!
<ide> ```
<ide>
<add>[CommonJS]: modules.html
<add>[ECMAScript-modules implementation]: https://github.com/nodejs/modules/blob/master/doc/plan-for-new-modules-implementation.md
<add>[ES Module Integration Proposal for Web Assembly]: https://github.com/webassembly/esm-integration
<add>[Node.js EP for ES Modules]: https://github.com/nodejs/node-eps/blob/master/002-es-modules.md
<ide> [Terminology]: #esm_terminology
<add>[WHATWG JSON modules specification]: https://html.spec.whatwg.org/#creating-a-json-module-script
<ide> [`data:` URLs]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
<ide> [`export`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export
<del>[`import`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
<ide> [`import()`]: #esm_import-expressions
<ide> [`import.meta.url`]: #esm_import_meta
<add>[`import`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
<ide> [`module.createRequire()`]: modules.html#modules_module_createrequire_filename
<del>[CommonJS]: modules.html
<del>[ECMAScript-modules implementation]: https://github.com/nodejs/modules/blob/master/doc/plan-for-new-modules-implementation.md
<del>[Node.js EP for ES Modules]: https://github.com/nodejs/node-eps/blob/master/002-es-modules.md
<del>[special scheme]: https://url.spec.whatwg.org/#special-scheme
<del>[WHATWG JSON modules specification]: https://html.spec.whatwg.org/#creating-a-json-module-script
<del>[ES Module Integration Proposal for Web Assembly]: https://github.com/webassembly/esm-integration
<ide> [dynamic instantiate hook]: #esm_dynamic_instantiate_hook
<add>[special scheme]: https://url.spec.whatwg.org/#special-scheme
<ide> [the official standard format]: https://tc39.github.io/ecma262/#sec-modules | 1 |
Text | Text | add release notes for v1.2.30 | 83bc2479675fd1e0e023c5be1dbcbeb2e2932c6d | <ide><path>CHANGELOG.md
<add><a name="1.2.30"></a>
<add># 1.2.30 patronal-resurrection (2016-07-21)
<add>
<add>
<add>_**Note:** This release contains some security fixes that required breaking changes. Since the
<add>legacy 1.2.x branch is the only version branch that supports IE8, it was necessary to introduce a
<add>couple of low-impact breaking changes in a patch release - something we generally avoid - in order
<add>to make the fixes available to people that still need IE8 support._
<add>
<add>## Bug Fixes
<add>
<add>- **$compile:**
<add> - secure `link[href]` as a `RESOURCE_URL`s in `$sce`
<add> ([f35f334b](https://github.com/angular/angular.js/commit/f35f334bd3197585bdf034f4b6d9ffa3122dac62),
<add> [#14687](https://github.com/angular/angular.js/issues/14687))
<add> - properly sanitize `xlink:href` attribute interoplation
<add> ([f2fa1ed8](https://github.com/angular/angular.js/commit/f2fa1ed83d18d4e79a36f8c0db1c2524d762e513),
<add> [2687c261](https://github.com/angular/angular.js/commit/2687c26140585d9e3716f9f559390f5d8d598fdf))
<add>- **ngSanitize:** blacklist the attribute `usemap` as it can be used as a security exploit
<add> ([ac0d5286](https://github.com/angular/angular.js/commit/ac0d5286b8931633d774080d6396fb4825d8be33),
<add> [#14903](https://github.com/angular/angular.js/issues/14903))
<add>- **ngAnimate:** do not use event.timeStamp anymore for time tracking
<add> ([8d83b563](https://github.com/angular/angular.js/commit/8d83b5633471c847d58f337426fe069797dd49d9),
<add> [#13494](https://github.com/angular/angular.js/issues/13494), [#13495](https://github.com/angular/angular.js/issues/13495))
<add>
<add>
<add>## Breaking Changes
<add>
<add>- **$compile:** due to [f35f334b](https://github.com/angular/angular.js/commit/f35f334bd3197585bdf034f4b6d9ffa3122dac62),
<add>
<add>`link[href]` attributes are now protected via `$sce`, which prevents interpolated values that fail
<add>the `RESOURCE_URL` context tests from being used in interpolation. For example if the application is
<add>running at `https://mydomain.org/` then the following will fail:
<add>
<add>```html
<add><link rel="stylesheet" href="{{ 'https://otherdomain.org/unsafe.css' }}" />
<add>```
<add>
<add>By default, `RESOURCE_URL` safe URLs are only allowed from the same domain and protocol as the
<add>application document. To use URLs from other domains and/or protocols, you may either whitelist them
<add>using `$sceDelegateProvider.resourceUrlWhitelist(...)` or wrap them into a trusted value by calling
<add>`$sce.trustAsResourceUrl(url)`.
<add>
<add>- **ngSanitize:** due to [234053fc](https://github.com/angular/angular.js/commit/234053fc9ad90e0d05be7e8359c6af66be94c094),
<add>
<add>The `$sanitize` service will now remove instances of the `usemap` attribute from any elements passed
<add>to it.
<add>
<add>This attribute is used to reference another element by `name` or `id`. Since the `name` and `id`
<add>attributes are already blacklisted, a sanitized `usemap` attribute could only reference unsanitized
<add>content, which is a security risk.
<add>
<add>
<ide> <a name="1.5.7"></a>
<ide> # 1.5.7 hexagonal-circumvolution (2016-06-15)
<ide>
<ide> changes section for more information
<ide>
<ide> - **ngSanitize:** due to [234053fc](https://github.com/angular/angular.js/commit/234053fc9ad90e0d05be7e8359c6af66be94c094),
<ide>
<del>The `$sanitize` service will now remove instances of the `usemap` attribute from any elements passed to it.
<add>The `$sanitize` service will now remove instances of the `usemap` attribute from any elements passed
<add>to it.
<ide>
<ide> This attribute is used to reference another element by `name` or `id`. Since the `name` and `id`
<ide> attributes are already blacklisted, a sanitized `usemap` attribute could only reference unsanitized | 1 |
Python | Python | get a better error when check_copies fails | 4ba248748f779b6eb1317734a2493307b3c26431 | <ide><path>tests/test_utils_check_copies.py
<ide> def check_copy_consistency(self, comment, class_name, class_code, overwrite_resu
<ide> with open(fname, "w") as f:
<ide> f.write(code)
<ide> if overwrite_result is None:
<del> self.assertTrue(check_copies.is_copy_consistent(fname))
<add> self.assertTrue(len(check_copies.is_copy_consistent(fname)) == 0)
<ide> else:
<ide> check_copies.is_copy_consistent(f.name, overwrite=True)
<ide> with open(fname, "r") as f:
<ide><path>utils/check_copies.py
<ide> def is_copy_consistent(filename, overwrite=False):
<ide> """
<ide> with open(filename, "r", encoding="utf-8") as f:
<ide> lines = f.readlines()
<del> found_diff = False
<add> diffs = []
<ide> line_index = 0
<ide> # Not a foor loop cause `lines` is going to change (if `overwrite=True`).
<ide> while line_index < len(lines):
<ide> def is_copy_consistent(filename, overwrite=False):
<ide>
<ide> # Test for a diff and act accordingly.
<ide> if observed_code != theoretical_code:
<del> found_diff = True
<add> diffs.append([object_name, start_index])
<ide> if overwrite:
<ide> lines = lines[:start_index] + [theoretical_code] + lines[line_index:]
<ide> line_index = start_index + 1
<ide>
<del> if overwrite and found_diff:
<add> if overwrite and len(diffs) > 0:
<ide> # Warn the user a file has been modified.
<ide> print(f"Detected changes, rewriting {filename}.")
<ide> with open(filename, "w", encoding="utf-8") as f:
<ide> f.writelines(lines)
<del> return not found_diff
<add> return diffs
<ide>
<ide>
<ide> def check_copies(overwrite: bool = False):
<ide> all_files = glob.glob(os.path.join(TRANSFORMERS_PATH, "**/*.py"), recursive=True)
<ide> diffs = []
<ide> for filename in all_files:
<del> consistent = is_copy_consistent(filename, overwrite)
<del> if not consistent:
<del> diffs.append(filename)
<add> new_diffs = is_copy_consistent(filename, overwrite)
<add> diffs += [f"- {filename}: copy does not match {d[0]} at line {d[1]}" for d in new_diffs]
<ide> if not overwrite and len(diffs) > 0:
<ide> diff = "\n".join(diffs)
<ide> raise Exception(
<del> "Found copy inconsistencies in the following files:\n"
<add> "Found the follwing copy inconsistencies:\n"
<ide> + diff
<ide> + "\nRun `make fix-copies` or `python utils/check_copies --fix_and_overwrite` to fix them."
<ide> ) | 2 |
Mixed | Javascript | make params in writing methods optional | c100f9ad295b3d930cc47b9b4d91abd34ce93973 | <ide><path>doc/api/fs.md
<ide> added: v10.0.0
<ide> Change the file system timestamps of the object referenced by the {FileHandle}
<ide> then resolves the promise with no arguments upon success.
<ide>
<del>#### `filehandle.write(buffer[, offset[, length[, position]]])`
<add>#### `filehandle.write(buffer, offset[, length[, position]])`
<ide>
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> changes:
<ide>
<ide> * `buffer` {Buffer|TypedArray|DataView}
<ide> * `offset` {integer} The start position from within `buffer` where the data
<del> to write begins. **Default:** `0`
<add> to write begins.
<ide> * `length` {integer} The number of bytes from `buffer` to write. **Default:**
<ide> `buffer.byteLength - offset`
<ide> * `position` {integer|null} The offset from the beginning of the file where the
<ide> On Linux, positional writes do not work when the file is opened in append mode.
<ide> The kernel ignores the position argument and always appends the data to
<ide> the end of the file.
<ide>
<add>#### `filehandle.write(buffer[, options])`
<add>
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>* `buffer` {Buffer|TypedArray|DataView}
<add>* `options` {Object}
<add> * `offset` {integer} **Default:** `0`
<add> * `length` {integer} **Default:** `buffer.byteLength - offset`
<add> * `position` {integer} **Default:** `null`
<add>* Returns: {Promise}
<add>
<add>Write `buffer` to the file.
<add>
<add>Similar to the above `filehandle.write` function, this version takes an
<add>optional `options` object. If no `options` object is specified, it will
<add>default with the above values.
<add>
<ide> #### `filehandle.write(string[, position[, encoding]])`
<ide>
<ide> <!-- YAML
<ide> This happens when:
<ide> * the file is deleted, followed by a restore
<ide> * the file is renamed and then renamed a second time back to its original name
<ide>
<del>### `fs.write(fd, buffer[, offset[, length[, position]]], callback)`
<add>### `fs.write(fd, buffer, offset[, length[, position]], callback)`
<ide>
<ide> <!-- YAML
<ide> added: v0.0.2
<ide> On Linux, positional writes don't work when the file is opened in append mode.
<ide> The kernel ignores the position argument and always appends the data to
<ide> the end of the file.
<ide>
<add>### `fs.write(fd, buffer[, options], callback)`
<add>
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>* `fd` {integer}
<add>* `buffer` {Buffer|TypedArray|DataView}
<add>* `options` {Object}
<add> * `offset` {integer} **Default:** `0`
<add> * `length` {integer} **Default:** `buffer.byteLength - offset`
<add> * `position` {integer} **Default:** `null`
<add>* `callback` {Function}
<add> * `err` {Error}
<add> * `bytesWritten` {integer}
<add> * `buffer` {Buffer|TypedArray|DataView}
<add>
<add>Write `buffer` to the file specified by `fd`.
<add>
<add>Similar to the above `fs.write` function, this version takes an
<add>optional `options` object. If no `options` object is specified, it will
<add>default with the above values.
<add>
<ide> ### `fs.write(fd, string[, position[, encoding]], callback)`
<ide>
<ide> <!-- YAML
<ide> for more details.
<ide> For detailed information, see the documentation of the asynchronous version of
<ide> this API: [`fs.writeFile()`][].
<ide>
<del>### `fs.writeSync(fd, buffer[, offset[, length[, position]]])`
<add>### `fs.writeSync(fd, buffer, offset[, length[, position]])`
<ide>
<ide> <!-- YAML
<ide> added: v0.1.21
<ide> changes:
<ide> For detailed information, see the documentation of the asynchronous version of
<ide> this API: [`fs.write(fd, buffer...)`][].
<ide>
<add>### `fs.writeSync(fd, buffer[, options])`
<add>
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>* `fd` {integer}
<add>* `buffer` {Buffer|TypedArray|DataView}
<add>* `options` {Object}
<add> * `offset` {integer} **Default:** `0`
<add> * `length` {integer} **Default:** `buffer.byteLength - offset`
<add> * `position` {integer} **Default:** `null`
<add>* Returns: {number} The number of bytes written.
<add>
<add>For detailed information, see the documentation of the asynchronous version of
<add>this API: [`fs.write(fd, buffer...)`][].
<add>
<ide> ### `fs.writeSync(fd, string[, position[, encoding]])`
<ide>
<ide> <!-- YAML
<ide><path>lib/fs.js
<ide> function read(fd, buffer, offsetOrOptions, length, position, callback) {
<ide> ({
<ide> offset = 0,
<ide> length = buffer.byteLength - offset,
<del> position = null
<add> position = null,
<ide> } = params ?? ObjectCreate(null));
<ide> }
<ide>
<ide> function readSync(fd, buffer, offset, length, position) {
<ide> ({
<ide> offset = 0,
<ide> length = buffer.byteLength - offset,
<del> position = null
<add> position = null,
<ide> } = options);
<ide> }
<ide>
<ide> function readvSync(fd, buffers, position) {
<ide> * Writes `buffer` to the specified `fd` (file descriptor).
<ide> * @param {number} fd
<ide> * @param {Buffer | TypedArray | DataView | string | object} buffer
<del> * @param {number} [offset]
<add> * @param {number | object} [offsetOrOptions]
<ide> * @param {number} [length]
<ide> * @param {number | null} [position]
<ide> * @param {(
<ide> function readvSync(fd, buffers, position) {
<ide> * ) => any} callback
<ide> * @returns {void}
<ide> */
<del>function write(fd, buffer, offset, length, position, callback) {
<add>function write(fd, buffer, offsetOrOptions, length, position, callback) {
<ide> function wrapper(err, written) {
<ide> // Retain a reference to buffer so that it can't be GC'ed too soon.
<ide> callback(err, written || 0, buffer);
<ide> }
<ide>
<ide> fd = getValidatedFd(fd);
<ide>
<add> let offset = offsetOrOptions;
<ide> if (isArrayBufferView(buffer)) {
<ide> callback = maybeCallback(callback || position || length || offset);
<add>
<add> if (typeof offset === 'object') {
<add> ({
<add> offset = 0,
<add> length = buffer.byteLength - offset,
<add> position = null,
<add> } = offsetOrOptions ?? ObjectCreate(null));
<add> }
<add>
<ide> if (offset == null || typeof offset === 'function') {
<ide> offset = 0;
<ide> } else {
<ide> ObjectDefineProperty(write, internalUtil.customPromisifyArgs,
<ide> * specified `fd` (file descriptor).
<ide> * @param {number} fd
<ide> * @param {Buffer | TypedArray | DataView | string} buffer
<del> * @param {number} [offset]
<del> * @param {number} [length]
<del> * @param {number | null} [position]
<add> * @param {{
<add> * offset?: number;
<add> * length?: number;
<add> * position?: number | null;
<add> * }} [offsetOrOptions]
<ide> * @returns {number}
<ide> */
<del>function writeSync(fd, buffer, offset, length, position) {
<add>function writeSync(fd, buffer, offsetOrOptions, length, position) {
<ide> fd = getValidatedFd(fd);
<ide> const ctx = {};
<ide> let result;
<add>
<add> let offset = offsetOrOptions;
<ide> if (isArrayBufferView(buffer)) {
<add> if (typeof offset === 'object') {
<add> ({
<add> offset = 0,
<add> length = buffer.byteLength - offset,
<add> position = null
<add> } = offsetOrOptions ?? ObjectCreate(null));
<add> }
<ide> if (position === undefined)
<ide> position = null;
<ide> if (offset == null) {
<ide><path>lib/internal/fs/promises.js
<ide> async function readv(handle, buffers, position) {
<ide> return { bytesRead, buffers };
<ide> }
<ide>
<del>async function write(handle, buffer, offset, length, position) {
<add>async function write(handle, buffer, offsetOrOptions, length, position) {
<ide> if (buffer?.byteLength === 0)
<ide> return { bytesWritten: 0, buffer };
<ide>
<add> let offset = offsetOrOptions;
<ide> if (isArrayBufferView(buffer)) {
<add> if (typeof offset === 'object') {
<add> ({
<add> offset = 0,
<add> length = buffer.byteLength - offset,
<add> position = null
<add> } = offsetOrOptions ?? ObjectCreate(null));
<add> }
<add>
<ide> if (offset == null) {
<ide> offset = 0;
<ide> } else {
<ide><path>test/parallel/test-fs-promises-write-optional-params.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>
<add>// This test ensures that filehandle.write accepts "named parameters" object
<add>// and doesn't interpret objects as strings
<add>
<add>const assert = require('assert');
<add>const fsPromises = require('fs').promises;
<add>const path = require('path');
<add>const tmpdir = require('../common/tmpdir');
<add>
<add>tmpdir.refresh();
<add>
<add>const dest = path.resolve(tmpdir.path, 'tmp.txt');
<add>const buffer = Buffer.from('zyx');
<add>
<add>async function testInvalid(dest, expectedCode, ...params) {
<add> let fh;
<add> try {
<add> fh = await fsPromises.open(dest, 'w+');
<add> await assert.rejects(
<add> fh.write(...params),
<add> { code: expectedCode });
<add> } finally {
<add> await fh?.close();
<add> }
<add>}
<add>
<add>async function testValid(dest, buffer, options) {
<add> let fh;
<add> try {
<add> fh = await fsPromises.open(dest, 'w+');
<add> const writeResult = await fh.write(buffer, options);
<add> const writeBufCopy = Uint8Array.prototype.slice.call(writeResult.buffer);
<add>
<add> const readResult = await fh.read(buffer, options);
<add> const readBufCopy = Uint8Array.prototype.slice.call(readResult.buffer);
<add>
<add> assert.ok(writeResult.bytesWritten >= readResult.bytesRead);
<add> if (options.length !== undefined && options.length !== null) {
<add> assert.strictEqual(writeResult.bytesWritten, options.length);
<add> }
<add> if (options.offset === undefined || options.offset === 0) {
<add> assert.deepStrictEqual(writeBufCopy, readBufCopy);
<add> }
<add> assert.deepStrictEqual(writeResult.buffer, readResult.buffer);
<add> } finally {
<add> await fh?.close();
<add> }
<add>}
<add>
<add>(async () => {
<add> // Test if first argument is not wrongly interpreted as ArrayBufferView|string
<add> for (const badBuffer of [
<add> undefined, null, true, 42, 42n, Symbol('42'), NaN, [], () => {},
<add> Promise.resolve(new Uint8Array(1)),
<add> {},
<add> { buffer: 'amNotParam' },
<add> { string: 'amNotParam' },
<add> { buffer: new Uint8Array(1).buffer },
<add> new Date(),
<add> new String('notPrimitive'),
<add> { toString() { return 'amObject'; } },
<add> { [Symbol.toPrimitive]: (hint) => 'amObject' },
<add> ]) {
<add> await testInvalid(dest, 'ERR_INVALID_ARG_TYPE', badBuffer, {});
<add> }
<add>
<add> // First argument (buffer or string) is mandatory
<add> await testInvalid(dest, 'ERR_INVALID_ARG_TYPE');
<add>
<add> // Various invalid options
<add> await testInvalid(dest, 'ERR_OUT_OF_RANGE', buffer, { length: 5 });
<add> await testInvalid(dest, 'ERR_OUT_OF_RANGE', buffer, { offset: 5 });
<add> await testInvalid(dest, 'ERR_OUT_OF_RANGE', buffer, { length: 1, offset: 3 });
<add> await testInvalid(dest, 'ERR_OUT_OF_RANGE', buffer, { length: -1 });
<add> await testInvalid(dest, 'ERR_OUT_OF_RANGE', buffer, { offset: -1 });
<add> await testInvalid(dest, 'ERR_INVALID_ARG_TYPE', buffer, { offset: false });
<add> await testInvalid(dest, 'ERR_INVALID_ARG_TYPE', buffer, { offset: true });
<add>
<add> // Test compatibility with filehandle.read counterpart
<add> for (const options of [
<add> {},
<add> { length: 1 },
<add> { position: 5 },
<add> { length: 1, position: 5 },
<add> { length: 1, position: -1, offset: 2 },
<add> { length: null },
<add> { position: null },
<add> { offset: 1 },
<add> ]) {
<add> await testValid(dest, buffer, options);
<add> }
<add>})().then(common.mustCall());
<ide><path>test/parallel/test-fs-write-optional-params.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>
<add>// This test ensures that fs.write accepts "named parameters" object
<add>// and doesn't interpret objects as strings
<add>
<add>const assert = require('assert');
<add>const fs = require('fs');
<add>const path = require('path');
<add>const tmpdir = require('../common/tmpdir');
<add>const util = require('util');
<add>
<add>tmpdir.refresh();
<add>
<add>const destInvalid = path.resolve(tmpdir.path, 'rwopt_invalid');
<add>const buffer = Buffer.from('zyx');
<add>
<add>function testInvalidCb(fd, expectedCode, buffer, options, callback) {
<add> assert.throws(
<add> () => fs.write(fd, buffer, options, common.mustNotCall()),
<add> { code: expectedCode }
<add> );
<add> callback(0);
<add>}
<add>
<add>function testValidCb(buffer, options, index, callback) {
<add> const dest = path.resolve(tmpdir.path, `rwopt_valid_${index}`);
<add> fs.open(dest, 'w+', common.mustSucceed((fd) => {
<add> fs.write(fd, buffer, options, common.mustSucceed((bytesWritten, bufferWritten) => {
<add> const writeBufCopy = Uint8Array.prototype.slice.call(bufferWritten);
<add>
<add> fs.read(fd, buffer, options, common.mustSucceed((bytesRead, bufferRead) => {
<add> const readBufCopy = Uint8Array.prototype.slice.call(bufferRead);
<add>
<add> assert.ok(bytesWritten >= bytesRead);
<add> if (options.length !== undefined && options.length !== null) {
<add> assert.strictEqual(bytesWritten, options.length);
<add> }
<add> if (options.offset === undefined || options.offset === 0) {
<add> assert.deepStrictEqual(writeBufCopy, readBufCopy);
<add> }
<add> assert.deepStrictEqual(bufferWritten, bufferRead);
<add> fs.close(fd, common.mustSucceed(callback));
<add> }));
<add> }));
<add> }));
<add>}
<add>
<add>// Promisify to reduce flakiness
<add>const testInvalid = util.promisify(testInvalidCb);
<add>const testValid = util.promisify(testValidCb);
<add>
<add>async function runTests(fd) {
<add> // Test if first argument is not wrongly interpreted as ArrayBufferView|string
<add> for (const badBuffer of [
<add> undefined, null, true, 42, 42n, Symbol('42'), NaN, [], () => {},
<add> Promise.resolve(new Uint8Array(1)),
<add> {},
<add> { buffer: 'amNotParam' },
<add> { string: 'amNotParam' },
<add> { buffer: new Uint8Array(1).buffer },
<add> new Date(),
<add> new String('notPrimitive'),
<add> { [Symbol.toPrimitive]: (hint) => 'amObject' },
<add>
<add> // TODO(LiviaMedeiros): add the following after DEP0162 EOL
<add> // { toString() { return 'amObject'; } },
<add> ]) {
<add> await testInvalid(fd, 'ERR_INVALID_ARG_TYPE', badBuffer, {});
<add> }
<add>
<add> // First argument (buffer or string) is mandatory
<add> await testInvalid(fd, 'ERR_INVALID_ARG_TYPE', undefined, undefined);
<add>
<add> // Various invalid options
<add> await testInvalid(fd, 'ERR_OUT_OF_RANGE', buffer, { length: 5 });
<add> await testInvalid(fd, 'ERR_OUT_OF_RANGE', buffer, { offset: 5 });
<add> await testInvalid(fd, 'ERR_OUT_OF_RANGE', buffer, { length: 1, offset: 3 });
<add> await testInvalid(fd, 'ERR_OUT_OF_RANGE', buffer, { length: -1 });
<add> await testInvalid(fd, 'ERR_OUT_OF_RANGE', buffer, { offset: -1 });
<add> await testInvalid(fd, 'ERR_INVALID_ARG_TYPE', buffer, { offset: false });
<add> await testInvalid(fd, 'ERR_INVALID_ARG_TYPE', buffer, { offset: true });
<add>
<add> // Test compatibility with fs.read counterpart
<add> for (const [ index, options ] of [
<add> {},
<add> { length: 1 },
<add> { position: 5 },
<add> { length: 1, position: 5 },
<add> { length: 1, position: -1, offset: 2 },
<add> { length: null },
<add> { position: null },
<add> { offset: 1 },
<add> ].entries()) {
<add> await testValid(buffer, options, index);
<add> }
<add>}
<add>
<add>fs.open(destInvalid, 'w+', common.mustSucceed(async (fd) => {
<add> runTests(fd).then(common.mustCall(() => fs.close(fd, common.mustSucceed())));
<add>}));
<ide><path>test/parallel/test-fs-write-sync-optional-params.js
<add>'use strict';
<add>
<add>require('../common');
<add>
<add>// This test ensures that fs.writeSync accepts "named parameters" object
<add>// and doesn't interpret objects as strings
<add>
<add>const assert = require('assert');
<add>const fs = require('fs');
<add>const path = require('path');
<add>const tmpdir = require('../common/tmpdir');
<add>
<add>tmpdir.refresh();
<add>
<add>const dest = path.resolve(tmpdir.path, 'tmp.txt');
<add>const buffer = Buffer.from('zyx');
<add>
<add>function testInvalid(dest, expectedCode, ...bufferAndOptions) {
<add> let fd;
<add> try {
<add> fd = fs.openSync(dest, 'w+');
<add> assert.throws(
<add> () => fs.writeSync(fd, ...bufferAndOptions),
<add> { code: expectedCode });
<add> } finally {
<add> if (fd != null) fs.closeSync(fd);
<add> }
<add>}
<add>
<add>function testValid(dest, buffer, options) {
<add> let fd;
<add> try {
<add> fd = fs.openSync(dest, 'w+');
<add> const bytesWritten = fs.writeSync(fd, buffer, options);
<add> const bytesRead = fs.readSync(fd, buffer, options);
<add>
<add> assert.ok(bytesWritten >= bytesRead);
<add> if (options.length !== undefined && options.length !== null) {
<add> assert.strictEqual(bytesWritten, options.length);
<add> }
<add> } finally {
<add> if (fd != null) fs.closeSync(fd);
<add> }
<add>}
<add>
<add>{
<add> // Test if second argument is not wrongly interpreted as string or options
<add> for (const badBuffer of [
<add> undefined, null, true, 42, 42n, Symbol('42'), NaN, [], () => {},
<add> {},
<add> { buffer: 'amNotParam' },
<add> { string: 'amNotParam' },
<add> { buffer: new Uint8Array(1) },
<add> { buffer: new Uint8Array(1).buffer },
<add> Promise.resolve(new Uint8Array(1)),
<add> new Date(),
<add> new String('notPrimitive'),
<add> { toString() { return 'amObject'; } },
<add> { [Symbol.toPrimitive]: (hint) => 'amObject' },
<add> ]) {
<add> testInvalid(dest, 'ERR_INVALID_ARG_TYPE', badBuffer);
<add> }
<add>
<add> // First argument (buffer or string) is mandatory
<add> testInvalid(dest, 'ERR_INVALID_ARG_TYPE');
<add>
<add> // Various invalid options
<add> testInvalid(dest, 'ERR_OUT_OF_RANGE', buffer, { length: 5 });
<add> testInvalid(dest, 'ERR_OUT_OF_RANGE', buffer, { offset: 5 });
<add> testInvalid(dest, 'ERR_OUT_OF_RANGE', buffer, { length: 1, offset: 3 });
<add> testInvalid(dest, 'ERR_OUT_OF_RANGE', buffer, { length: -1 });
<add> testInvalid(dest, 'ERR_OUT_OF_RANGE', buffer, { offset: -1 });
<add> testInvalid(dest, 'ERR_INVALID_ARG_TYPE', buffer, { offset: false });
<add> testInvalid(dest, 'ERR_INVALID_ARG_TYPE', buffer, { offset: true });
<add>
<add> // Test compatibility with fs.readSync counterpart with reused options
<add> for (const options of [
<add> {},
<add> { length: 1 },
<add> { position: 5 },
<add> { length: 1, position: 5 },
<add> { length: 1, position: -1, offset: 2 },
<add> { length: null },
<add> { position: null },
<add> { offset: 1 },
<add> ]) {
<add> testValid(dest, buffer, options);
<add> }
<add>} | 6 |
Mixed | Text | add an option `end_at` to `find_in_batches` | 3dc432068b295504be938e7d4d67bc628edbf850 | <ide><path>activerecord/CHANGELOG.md
<add>* `find_in_batches` now accepts an `:end_at` parameter that complements the `:start`
<add> parameter to specify where to stop batch processing.
<add>
<add> *Vipul A M*
<add>
<ide> * Fix rounding problem for PostgreSQL timestamp column.
<ide>
<ide> If timestamp column have the precision, it need to format according to
<ide><path>activerecord/lib/active_record/relation/batches.rb
<ide> module Batches
<ide> #
<ide> # ==== Options
<ide> # * <tt>:batch_size</tt> - Specifies the size of the batch. Default to 1000.
<del> # * <tt>:start</tt> - Specifies the primary key value to start from.
<add> # * <tt>:start</tt> - Specifies the primary key value to start from, inclusive of the value.
<add> # * <tt>:end_at</tt> - Specifies the primary key value to end at, inclusive of the value.
<ide> # This is especially useful if you want multiple workers dealing with
<ide> # the same processing queue. You can make worker 1 handle all the records
<ide> # between id 0 and 10,000 and worker 2 handle from 10,000 and beyond
<del> # (by setting the +:start+ option on that worker).
<add> # (by setting the +:start+ and +:end_at+ option on each worker).
<ide> #
<ide> # # Let's process for a batch of 2000 records, skipping the first 2000 rows
<ide> # Person.find_each(start: 2000, batch_size: 2000) do |person|
<ide> module Batches
<ide> #
<ide> # NOTE: You can't set the limit either, that's used to control
<ide> # the batch sizes.
<del> def find_each(start: nil, batch_size: 1000)
<add> def find_each(start: nil, end_at: nil, batch_size: 1000)
<ide> if block_given?
<del> find_in_batches(start: start, batch_size: batch_size) do |records|
<add> find_in_batches(start: start, end_at: end_at, batch_size: batch_size) do |records|
<ide> records.each { |record| yield record }
<ide> end
<ide> else
<del> enum_for(:find_each, start: start, batch_size: batch_size) do
<del> start ? where(table[primary_key].gteq(start)).size : size
<add> enum_for(:find_each, start: start, end_at: end_at, batch_size: batch_size) do
<add> relation = self
<add> apply_limits(relation, start, end_at).size
<ide> end
<ide> end
<ide> end
<ide> def find_each(start: nil, batch_size: 1000)
<ide> #
<ide> # ==== Options
<ide> # * <tt>:batch_size</tt> - Specifies the size of the batch. Default to 1000.
<del> # * <tt>:start</tt> - Specifies the primary key value to start from.
<add> # * <tt>:start</tt> - Specifies the primary key value to start from, inclusive of the value.
<add> # * <tt>:end_at</tt> - Specifies the primary key value to end at, inclusive of the value.
<ide> # This is especially useful if you want multiple workers dealing with
<ide> # the same processing queue. You can make worker 1 handle all the records
<ide> # between id 0 and 10,000 and worker 2 handle from 10,000 and beyond
<del> # (by setting the +:start+ option on that worker).
<add> # (by setting the +:start+ and +:end_at+ option on each worker).
<ide> #
<ide> # # Let's process the next 2000 records
<ide> # Person.find_in_batches(start: 2000, batch_size: 2000) do |group|
<ide> def find_each(start: nil, batch_size: 1000)
<ide> #
<ide> # NOTE: You can't set the limit either, that's used to control
<ide> # the batch sizes.
<del> def find_in_batches(start: nil, batch_size: 1000)
<add> def find_in_batches(start: nil, end_at: nil, batch_size: 1000)
<ide> relation = self
<ide>
<ide> unless block_given?
<del> return to_enum(:find_in_batches, start: start, batch_size: batch_size) do
<del> total = start ? where(table[primary_key].gteq(start)).size : size
<add> return to_enum(:find_in_batches, start: start, end_at: end_at, batch_size: batch_size) do
<add> total = apply_limits(relation, start, end_at).size
<ide> (total - 1).div(batch_size) + 1
<ide> end
<ide> end
<ide> def find_in_batches(start: nil, batch_size: 1000)
<ide> end
<ide>
<ide> relation = relation.reorder(batch_order).limit(batch_size)
<del> records = start ? relation.where(table[primary_key].gteq(start)).to_a : relation.to_a
<add> relation = apply_limits(relation, start, end_at)
<add> records = relation.to_a
<ide>
<ide> while records.any?
<ide> records_size = records.size
<ide> def find_in_batches(start: nil, batch_size: 1000)
<ide>
<ide> private
<ide>
<add> def apply_limits(relation, start, end_at)
<add> relation = relation.where(table[primary_key].gteq(start)) if start
<add> relation = relation.where(table[primary_key].lteq(end_at)) if end_at
<add> relation
<add> end
<add>
<ide> def batch_order
<ide> "#{quoted_table_name}.#{quoted_primary_key} ASC"
<ide> end
<ide><path>activerecord/test/cases/batches_test.rb
<ide> def test_find_in_batches_should_start_from_the_start_option
<ide> end
<ide> end
<ide>
<add> def test_find_in_batches_should_end_at_the_end_option
<add> assert_queries(6) do
<add> Post.find_in_batches(batch_size: 1, end_at: 5) do |batch|
<add> assert_kind_of Array, batch
<add> assert_kind_of Post, batch.first
<add> end
<add> end
<add> end
<add>
<ide> def test_find_in_batches_shouldnt_execute_query_unless_needed
<ide> assert_queries(2) do
<ide> Post.find_in_batches(:batch_size => @total) {|batch| assert_kind_of Array, batch }
<ide><path>guides/source/active_record_querying.md
<ide> end
<ide>
<ide> Another example would be if you wanted multiple workers handling the same processing queue. You could have each worker handle 10000 records by setting the appropriate `:start` option on each worker.
<ide>
<add>**`:end_at`**
<add>
<add>Similar to the `:start` option, `:end_at` allows you to configure the last ID of the sequence whenever the highest ID is not the one you need.
<add>This would be useful, for example, if you wanted to run a batch process, using a subset of records based on `:start` and `:end_at`
<add>
<add>For example, to send newsletters only to users with the primary key starting from 2000 upto 10000 and to retrieve them in batches of 1000:
<add>
<add>```ruby
<add>User.find_each(start: 2000, end_at: 10000, batch_size: 5000) do |user|
<add> NewsMailer.weekly(user).deliver_now
<add>end
<add>```
<add>
<ide> #### `find_in_batches`
<ide>
<ide> The `find_in_batches` method is similar to `find_each`, since both retrieve batches of records. The difference is that `find_in_batches` yields _batches_ to the block as an array of models, instead of individually. The following example will yield to the supplied block an array of up to 1000 invoices at a time, with the final block containing any remaining invoices:
<ide> end
<ide>
<ide> ##### Options for `find_in_batches`
<ide>
<del>The `find_in_batches` method accepts the same `:batch_size` and `:start` options as `find_each`.
<add>The `find_in_batches` method accepts the same `:batch_size`, `:start` and `:end_at` options as `find_each`.
<ide>
<ide> Conditions
<ide> ---------- | 4 |
Python | Python | document the method tofile() | 2e6688521aabe7a03fd980e226f7088abb71a307 | <ide><path>numpy/add_newdocs.py
<ide>
<ide>
<ide> add_newdoc('numpy.core.multiarray', 'ndarray', ('tofile',
<del> """a.tofile(fid, sep="") -> None. Write the data to a file.
<add> """a.tofile(fid, sep="", format="%s") -> None. Write the data to a file.
<add>
<add> Required arguments:
<add> file -- an open file object or a filename
<add>
<add> Keyword arguments:
<add> sep -- separator for text output. Write binary if empty (default "")
<add> format -- format string for text file output (default "%s")
<add>
<add> A convenience function for quick storage of array data. Information on
<add> endianess and precision is lost, so this method is not a good choice for
<add> files intended to archive data or transport data between machines with
<add> different endianess. Some of these problems can be overcome by outputting
<add> text files at the expense of speed and file size.
<add>
<add> If 'sep' is empty this method is equivalent to file.write(a.tostring()). If
<add> 'sep' is not empty each data item is converted to the nearest Python type
<add> and formatted using "format"%item. The resulting strings are written to the
<add> file separated by the contents of 'sep'.
<ide>
<ide> """))
<ide> | 1 |
PHP | PHP | fix lazycollection#takeuntiltimeout | aac0da02132d38cff8fe9ff6aee5f9b0ca689a18 | <ide><path>src/Illuminate/Collections/LazyCollection.php
<ide> public function takeUntilTimeout(DateTimeInterface $timeout)
<ide> $timeout = $timeout->getTimestamp();
<ide>
<ide> return new static(function () use ($timeout) {
<del> $iterator = $this->getIterator();
<del>
<del> if (! $iterator->valid() || $this->now() > $timeout) {
<add> if ($this->now() >= $timeout) {
<ide> return;
<ide> }
<ide>
<del> yield $iterator->key() => $iterator->current();
<del>
<del> while ($iterator->valid() && $this->now() < $timeout) {
<del> $iterator->next();
<add> foreach ($this as $key => $value) {
<add> yield $key => $value;
<ide>
<del> yield $iterator->key() => $iterator->current();
<add> if ($this->now() >= $timeout) {
<add> break;
<add> }
<ide> }
<ide> });
<ide> }
<ide><path>tests/Support/SupportLazyCollectionIsLazyTest.php
<ide> namespace Illuminate\Tests\Support;
<ide>
<ide> use Exception;
<add>use Illuminate\Support\Carbon;
<ide> use Illuminate\Support\ItemNotFoundException;
<ide> use Illuminate\Support\LazyCollection;
<ide> use Illuminate\Support\MultipleItemsFoundException;
<add>use Mockery as m;
<ide> use PHPUnit\Framework\TestCase;
<ide> use stdClass;
<ide>
<ide> public function testTakeUntilIsLazy()
<ide> });
<ide> }
<ide>
<add> public function testTakeUntilTimeoutIsLazy()
<add> {
<add> tap(m::mock(LazyCollection::class.'[now]')->times(100), function ($mock) {
<add> $this->assertDoesNotEnumerateCollection($mock, function ($mock) {
<add> $timeout = Carbon::now();
<add>
<add> $results = $mock
<add> ->tap(function ($collection) use ($mock, $timeout) {
<add> tap($collection)
<add> ->mockery_init($mock->mockery_getContainer())
<add> ->shouldAllowMockingProtectedMethods()
<add> ->shouldReceive('now')
<add> ->times(1)
<add> ->andReturn(
<add> $timeout->getTimestamp()
<add> );
<add> })
<add> ->takeUntilTimeout($timeout)
<add> ->all();
<add> });
<add> });
<add>
<add> tap(m::mock(LazyCollection::class.'[now]')->times(100), function ($mock) {
<add> $this->assertEnumeratesCollection($mock, 1, function ($mock) {
<add> $timeout = Carbon::now();
<add>
<add> $results = $mock
<add> ->tap(function ($collection) use ($mock, $timeout) {
<add> tap($collection)
<add> ->mockery_init($mock->mockery_getContainer())
<add> ->shouldAllowMockingProtectedMethods()
<add> ->shouldReceive('now')
<add> ->times(2)
<add> ->andReturn(
<add> (clone $timeout)->sub(1, 'minute')->getTimestamp(),
<add> $timeout->getTimestamp()
<add> );
<add> })
<add> ->takeUntilTimeout($timeout)
<add> ->all();
<add> });
<add> });
<add>
<add> tap(m::mock(LazyCollection::class.'[now]')->times(100), function ($mock) {
<add> $this->assertEnumeratesCollectionOnce($mock, function ($mock) {
<add> $timeout = Carbon::now();
<add>
<add> $results = $mock
<add> ->tap(function ($collection) use ($mock, $timeout) {
<add> tap($collection)
<add> ->mockery_init($mock->mockery_getContainer())
<add> ->shouldAllowMockingProtectedMethods()
<add> ->shouldReceive('now')
<add> ->times(100)
<add> ->andReturn(
<add> (clone $timeout)->sub(1, 'minute')->getTimestamp()
<add> );
<add> })
<add> ->takeUntilTimeout($timeout)
<add> ->all();
<add> });
<add> });
<add>
<add> m::close();
<add> }
<add>
<ide> public function testTakeWhileIsLazy()
<ide> {
<ide> $this->assertDoesNotEnumerate(function ($collection) {
<ide><path>tests/Support/SupportLazyCollectionTest.php
<ide> public function testTakeUntilTimeout()
<ide> m::close();
<ide> }
<ide>
<del> public function testTakeUntilTimeoutWithPastTimeout()
<del> {
<del> $timeout = Carbon::now()->subMinute();
<del>
<del> $mock = m::mock(LazyCollection::class.'[now]');
<del>
<del> $results = $mock
<del> ->times(10)
<del> ->tap(function ($collection) use ($mock, $timeout) {
<del> tap($collection)
<del> ->mockery_init($mock->mockery_getContainer())
<del> ->shouldAllowMockingProtectedMethods()
<del> ->shouldReceive('now')
<del> ->times(1)
<del> ->andReturn(
<del> (clone $timeout)->add(1, 'minute')->getTimestamp(),
<del> );
<del> })
<del> ->takeUntilTimeout($timeout)
<del> ->all();
<del>
<del> $this->assertSame([], $results);
<del>
<del> m::close();
<del> }
<del>
<ide> public function testTapEach()
<ide> {
<ide> $data = LazyCollection::times(10); | 3 |
Javascript | Javascript | preserve cursor pos | c07edd90f5bfb4edb98b57e76e56742e08142b91 | <ide><path>lib/_debugger.js
<ide> Interface.prototype.childPrint = function(text) {
<ide> }).map(function(chunk) {
<ide> return '< ' + chunk;
<ide> }).join('\n'));
<del> this.repl.displayPrompt();
<add> this.repl.displayPrompt(true);
<ide> };
<ide>
<ide> // Errors formatting
<ide><path>lib/readline.js
<ide> Interface.prototype.setPrompt = function(prompt, length) {
<ide> };
<ide>
<ide>
<del>Interface.prototype.prompt = function() {
<add>Interface.prototype.prompt = function(preserveCursor) {
<ide> if (this.enabled) {
<del> this.cursor = 0;
<add> if (!preserveCursor) this.cursor = 0;
<ide> this._refreshLine();
<ide> } else {
<ide> this.output.write(this._prompt);
<ide><path>lib/repl.js
<ide> REPLServer.prototype.resetContext = function(force) {
<ide> this.context = context;
<ide> };
<ide>
<del>REPLServer.prototype.displayPrompt = function() {
<add>REPLServer.prototype.displayPrompt = function(preserveCursor) {
<ide> this.rli.setPrompt(this.bufferedCommand.length ?
<ide> '...' + new Array(this.lines.level.length).join('..') + ' ' :
<ide> this.prompt);
<del> this.rli.prompt();
<add> this.rli.prompt(preserveCursor);
<ide> };
<ide>
<ide> | 3 |
PHP | PHP | fix most coding standards in test/case/view | f5804cb4caca2dc3f98e42fa64c4de35055bc17d | <ide><path>lib/Cake/Test/Case/View/Helper/CacheHelperTest.php
<ide> public function cache_parsing() {
<ide> $this->set('batman', 'bruce wayne');
<ide> $this->set('spiderman', 'peter parker');
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function setUp() {
<ide> Configure::write('Cache.check', true);
<ide> Configure::write('Cache.disable', false);
<ide> App::build(array(
<del> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View'. DS)
<add> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
<ide> ), App::RESET);
<ide> }
<ide>
<ide> public function testCacheActionArray() {
<ide> $this->assertTrue(file_exists($filename));
<ide> @unlink($filename);
<ide>
<del>
<ide> $this->Controller->cache_parsing();
<ide> $this->Controller->cacheAction = array(
<ide> 'cache_parsing' => 21600
<ide> public function testCacheActionArray() {
<ide> $this->assertTrue(file_exists($filename));
<ide> @unlink($filename);
<ide>
<del>
<ide> $this->Controller->cache_parsing();
<ide> $this->Controller->request->addParams(array(
<ide> 'controller' => 'cache_test',
<ide><path>lib/Cake/Test/Case/View/Helper/FormHelperTest.php
<ide> class ContactTagsContact extends CakeTestModel {
<ide> public function setSchema($schema) {
<ide> $this->_schema = $schema;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function schema($field = false) {
<ide> unset($this->_schema['id']);
<ide> return $this->_schema;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function beforeValidate($options = array()) {
<ide> $this->invalidate('openid_not_registered');
<ide> return true;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function beforeValidate($options = array()) {
<ide> $this->invalidate('email');
<ide> return false;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function beforeValidate($options = array()) {
<ide> $this->invalidate('city');
<ide> return false;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function beforeValidate($options = array()) {
<ide> $this->invalidate('description');
<ide> return false;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function tearDown() {
<ide> Configure::write('Security.salt', $this->oldSalt);
<ide> }
<ide>
<del>
<del>
<ide> /**
<ide> * testFormCreateWithSecurity method
<ide> *
<ide> public function testSecurityButtonNestedNamed() {
<ide> $this->assertEquals(array('Address.button'), $result);
<ide> }
<ide>
<del>
<ide> /**
<ide> * Test that submit inputs created with foo[bar] name attributes are unlocked correctly.
<ide> *
<ide> public function testUnlockFieldRemovingFromFields() {
<ide> */
<ide> public function testTagIsInvalid() {
<ide> $Contact = ClassRegistry::getObject('Contact');
<del> $Contact->validationErrors[0]['email'] = array('Please provide an email');
<add> $Contact->validationErrors[0]['email'] = array('Please provide an email');
<ide>
<ide> $this->Form->setEntity('Contact.0.email');
<ide> $result = $this->Form->tagIsInvalid();
<ide> public function testTagIsInvalid() {
<ide> */
<ide> public function testPasswordValidation() {
<ide> $Contact = ClassRegistry::getObject('Contact');
<del> $Contact->validationErrors['password'] = array('Please provide a password');
<add> $Contact->validationErrors['password'] = array('Please provide a password');
<ide>
<ide> $result = $this->Form->input('Contact.password');
<ide> $expected = array(
<ide> public function testInputSelectType() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del>
<ide> $this->View->viewVars['users'] = array('value' => 'good', 'other' => 'bad');
<ide> $this->Form->request->data = array('Model' => array('user_id' => 'value'));
<ide>
<ide> public function testDateTimeLabelIdMatchesFirstInput() {
<ide> $this->assertContains('label for="ModelDateYear"', $result);
<ide> }
<ide>
<del>
<ide> /**
<ide> * testMonth method
<ide> *
<ide> public function testHour() {
<ide> $result = $this->Form->hour('Model.field', true, array('value' => 'now'));
<ide> $thisHour = date('H');
<ide> $optValue = date('G');
<del> $this->assertRegExp('/<option value="' . $thisHour . '" selected="selected">'. $optValue .'<\/option>/', $result);
<add> $this->assertRegExp('/<option value="' . $thisHour . '" selected="selected">' . $optValue . '<\/option>/', $result);
<ide> }
<ide>
<ide> /**
<ide> public function testButton() {
<ide>
<ide> $result = $this->Form->button('No type', array('type' => false));
<ide> $this->assertTags($result, array('button' => array(), 'No type', '/button'));
<del>
<add>
<ide> $result = $this->Form->button('Upload Text', array('onClick' => "$('#postAddForm').ajaxSubmit({target: '#postTextUpload', url: '/posts/text'});return false;'", 'escape' => false));
<ide> $this->assertNotRegExp('/\&039/', $result);
<ide> }
<ide> public function testCreate() {
<ide> '/div'
<ide> );
<ide> $this->assertTags($result, $expected);
<del>
<ide> }
<ide>
<ide> /**
<ide> public function testCreateCustomRoute() {
<ide> */
<ide> public function testCreateWithInputDefaults() {
<ide> $this->Form->create('User', array(
<del> 'inputDefaults' => array('div' => false, 'label' => false, 'error' => array('attributes'=>array('wrap' => 'small', 'class' => 'error')))
<del> ));
<add> 'inputDefaults' => array(
<add> 'div' => false,
<add> 'label' => false,
<add> 'error' => array('attributes' => array('wrap' => 'small', 'class' => 'error'))
<add> )
<add> ));
<ide> $result = $this->Form->input('username');
<ide> $expected = array(
<ide> 'input' => array('type' => 'text', 'name' => 'data[User][username]', 'id' => 'UserUsername')
<ide> public function testCreateWithInputDefaults() {
<ide> '/div'
<ide> );
<ide> $this->assertTags($result, $expected);
<del>
<add>
<ide> $User = ClassRegistry::getObject('User');
<ide> $User->validationErrors['username'] = array('empty');
<ide> $result = $this->Form->input('username', array('div' => true, 'label' => 'username', 'error' => array('empty' => __('Required'))));
<ide> public function testFormMagicInput() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del>
<ide> extract($this->dateRegex);
<ide> $now = strtotime('now');
<ide>
<ide><path>lib/Cake/Test/Case/View/Helper/HtmlHelperTest.php
<ide> class TheHtmlTestController extends Controller {
<ide> }
<ide>
<ide> class TestHtmlHelper extends HtmlHelper {
<add>
<ide> /**
<ide> * expose a method as public
<ide> *
<ide> public function setUp() {
<ide> $this->Html->request->webroot = '';
<ide>
<ide> App::build(array(
<del> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin'. DS)
<add> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
<ide> ));
<ide>
<ide> Configure::write('Asset.timestamp', false);
<ide> public function testImageTagWithTheme() {
<ide> $File = new File($testfile, true);
<ide>
<ide> App::build(array(
<del> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View'. DS)
<add> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
<ide> ));
<ide> Configure::write('Asset.timestamp', true);
<ide> Configure::write('debug', 1);
<ide> public function testImageTagWithTheme() {
<ide> */
<ide> public function testThemeAssetsInMainWebrootPath() {
<ide> App::build(array(
<del> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View'. DS)
<add> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
<ide> ));
<ide> $webRoot = Configure::read('App.www_root');
<ide> Configure::write('App.www_root', CAKE . 'Test' . DS . 'test_app' . DS . 'webroot' . DS);
<ide> public function testScript() {
<ide> 'script' => array('type' => 'text/javascript', 'src' => 'js/jquery-1.3.2.js', 'defer' => 'defer', 'encoding' => 'utf-8')
<ide> );
<ide> $this->assertTags($result, $expected);
<del>
<ide> }
<ide>
<del> /**
<add>/**
<ide> * test that plugin scripts added with uses() are only ever included once.
<ide> * test script tag generation with plugin syntax
<ide> *
<ide> public function testScriptInTheme() {
<ide> $File = new File($testfile, true);
<ide>
<ide> App::build(array(
<del> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View'. DS)
<add> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
<ide> ));
<ide>
<ide> $this->Html->webroot = '/';
<ide> public function testScriptBlock() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del>
<ide> $this->View->expects($this->at(0))
<ide> ->method('append')
<ide> ->with('script', $this->matchesRegularExpression('/window\.foo\s\=\s2;/'));
<ide> public function testScriptStartAndScriptEnd() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del>
<ide> $result = $this->Html->scriptStart(array('safe' => false));
<ide> $this->assertNull($result);
<ide> echo 'this is some javascript';
<ide> public function testBreadcrumb() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del>
<ide> $this->Html->addCrumb('Fourth', null);
<ide>
<ide> $result = $this->Html->getCrumbs();
<ide> public function testMeta() {
<ide> $this->assertTags($result, array('meta' => array('name' => 'keywords', 'content' => 'these, are, some, meta, keywords')));
<ide> $this->assertRegExp('/\s+\/>$/', $result);
<ide>
<del>
<ide> $result = $this->Html->meta('description', 'this is the meta description');
<ide> $this->assertTags($result, array('meta' => array('name' => 'description', 'content' => 'this is the meta description')));
<ide>
<ide> $result = $this->Html->meta(array('name' => 'ROBOTS', 'content' => 'ALL'));
<ide> $this->assertTags($result, array('meta' => array('name' => 'ROBOTS', 'content' => 'ALL')));
<del>
<del>
<ide> }
<ide>
<ide> /**
<ide> public function testCrumbList() {
<ide> /**
<ide> * Test getCrumbList startText
<ide> */
<del> public function testCrumbListFirstLink() {
<del> $this->Html->addCrumb('First', '#first');
<del> $this->Html->addCrumb('Second', '#second');
<del>
<del> $result = $this->Html->getCrumbList(null, 'Home');
<del> $this->assertTags(
<del> $result,
<del> array(
<del> '<ul',
<del> array('li' => array('class' => 'first')),
<del> array('a' => array('href' => '/')), 'Home', '/a',
<del> '/li',
<del> '<li',
<del> array('a' => array('href' => '#first')), 'First', '/a',
<del> '/li',
<del> array('li' => array('class' => 'last')),
<del> array('a' => array('href' => '#second')), 'Second', '/a',
<del> '/li',
<del> '/ul'
<del> )
<del> );
<del>
<del> $result = $this->Html->getCrumbList(null, array('url' => '/home', 'text' => '<img src="/home.png" />', 'escape' => false));
<del> $this->assertTags(
<del> $result,
<del> array(
<del> '<ul',
<del> array('li' => array('class' => 'first')),
<del> array('a' => array('href' => '/home')), 'img' => array('src' => '/home.png'), '/a',
<del> '/li',
<del> '<li',
<del> array('a' => array('href' => '#first')), 'First', '/a',
<del> '/li',
<del> array('li' => array('class' => 'last')),
<del> array('a' => array('href' => '#second')), 'Second', '/a',
<del> '/li',
<del> '/ul'
<del> )
<del> );
<del> }
<add> public function testCrumbListFirstLink() {
<add> $this->Html->addCrumb('First', '#first');
<add> $this->Html->addCrumb('Second', '#second');
<add>
<add> $result = $this->Html->getCrumbList(null, 'Home');
<add> $this->assertTags(
<add> $result,
<add> array(
<add> '<ul',
<add> array('li' => array('class' => 'first')),
<add> array('a' => array('href' => '/')), 'Home', '/a',
<add> '/li',
<add> '<li',
<add> array('a' => array('href' => '#first')), 'First', '/a',
<add> '/li',
<add> array('li' => array('class' => 'last')),
<add> array('a' => array('href' => '#second')), 'Second', '/a',
<add> '/li',
<add> '/ul'
<add> )
<add> );
<add>
<add> $result = $this->Html->getCrumbList(null, array('url' => '/home', 'text' => '<img src="/home.png" />', 'escape' => false));
<add> $this->assertTags(
<add> $result,
<add> array(
<add> '<ul',
<add> array('li' => array('class' => 'first')),
<add> array('a' => array('href' => '/home')), 'img' => array('src' => '/home.png'), '/a',
<add> '/li',
<add> '<li',
<add> array('a' => array('href' => '#first')), 'First', '/a',
<add> '/li',
<add> array('li' => array('class' => 'last')),
<add> array('a' => array('href' => '#second')), 'Second', '/a',
<add> '/li',
<add> '/ul'
<add> )
<add> );
<add> }
<ide>
<ide> /**
<ide> * testLoadConfig method
<ide> public function testCrumbListFirstLink() {
<ide> */
<ide>
<ide> public function testLoadConfig() {
<del> $path = CAKE . 'Test' . DS . 'test_app' . DS . 'Config'. DS;
<add> $path = CAKE . 'Test' . DS . 'test_app' . DS . 'Config' . DS;
<ide>
<ide> $result = $this->Html->loadConfig('htmlhelper_tags', $path);
<ide> $expected = array(
<ide> public function testLoadConfigWrongFile() {
<ide> * @expectedException ConfigureException
<ide> */
<ide> public function testLoadConfigWrongReader() {
<del> $path = CAKE . 'Test' . DS . 'test_app' . DS . 'Config'. DS;
<add> $path = CAKE . 'Test' . DS . 'test_app' . DS . 'Config' . DS;
<ide> $result = $this->Html->loadConfig(array('htmlhelper_tags', 'wrong_reader'), $path);
<ide> }
<ide>
<ide><path>lib/Cake/Test/Case/View/Helper/JqueryEngineHelperTest.php
<ide> App::uses('View', 'View');
<ide>
<ide> class JqueryEngineHelperTest extends CakeTestCase {
<add>
<ide> /**
<ide> * setUp
<ide> *
<ide><path>lib/Cake/Test/Case/View/Helper/JsHelperTest.php
<ide> App::uses('ClassRegistry', 'Utility');
<ide>
<ide> class JsEncodingObject {
<add>
<ide> protected $_title = 'Old thing';
<ide>
<ide> private $__noshow = 'Never ever';
<add>
<ide> }
<ide>
<ide> class OptionEngineHelper extends JsBaseEngineHelper {
<add>
<ide> protected $_optionMap = array(
<ide> 'request' => array(
<ide> 'complete' => 'success',
<ide> public function testParseOptions($options, $safe = array()) {
<ide> return $this->_parseOptions($options, $safe);
<ide> }
<ide>
<del> public function get($selector) {}
<del> public function event($type, $callback, $options = array()) {}
<del> public function domReady($functionBody) {}
<del> public function each($callback) {}
<del> public function effect($name, $options = array()) {}
<del> public function request($url, $options = array()) {}
<del> public function drag($options = array()) {}
<del> public function drop($options = array()) {}
<del> public function sortable($options = array()) {}
<del> public function slider($options = array()) {}
<del> public function serializeForm($options = array()) {}
<add> public function get($selector) {
<add> }
<add>
<add> public function event($type, $callback, $options = array()) {
<add> }
<add>
<add> public function domReady($functionBody) {
<add> }
<add>
<add> public function each($callback) {
<add> }
<add>
<add> public function effect($name, $options = array()) {
<add> }
<add>
<add> public function request($url, $options = array()) {
<add> }
<add>
<add> public function drag($options = array()) {
<add> }
<add>
<add> public function drop($options = array()) {
<add> }
<add>
<add> public function sortable($options = array()) {
<add> }
<add>
<add> public function slider($options = array()) {
<add> }
<add>
<add> public function serializeForm($options = array()) {
<add> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function serializeForm($options = array()) {}
<ide> * @package Cake.Test.Case.View.Helper
<ide> */
<ide> class JsHelperTest extends CakeTestCase {
<add>
<ide> /**
<ide> * Regexp for CDATA start block
<ide> *
<ide> class JsHelperTest extends CakeTestCase {
<ide> */
<ide> public $cDataEnd = 'preg:/[^\]]*\]\]\>[\s\r\n]*/';
<ide>
<del>
<ide> /**
<ide> * setUp method
<ide> *
<ide> public function testSetVarsAtTopOfBufferedScripts() {
<ide> $this->assertEquals($result[1], 'alert("hey you!");');
<ide> $this->assertEquals($result[2], 'confirm("Are you sure?");');
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function testSetVarsAtTopOfBufferedScripts() {
<ide> * @package Cake.Test.Case.View.Helper
<ide> */
<ide> class JsBaseEngineTest extends CakeTestCase {
<add>
<ide> /**
<ide> * setUp method
<ide> *
<ide> public function testRedirect() {
<ide> * @return void
<ide> */
<ide> public function testObject() {
<del>
<ide> $object = array('title' => 'New thing', 'indexes' => array(5, 6, 7, 8));
<ide> $result = $this->JsEngine->object($object);
<ide> $expected = '{"title":"New thing","indexes":[5,6,7,8]}';
<ide><path>lib/Cake/Test/Case/View/Helper/MootoolsEngineHelperTest.php
<ide> App::uses('MootoolsEngineHelper', 'View/Helper');
<ide>
<ide> class MootoolsEngineHelperTest extends CakeTestCase {
<add>
<ide> /**
<ide> * setUp
<ide> *
<ide><path>lib/Cake/Test/Case/View/Helper/NumberHelperTest.php
<ide> public function tearDown() {
<ide> unset($this->View);
<ide> }
<ide>
<del>
<ide> /**
<ide> * test CakeNumber class methods are called correctly
<ide> */
<ide><path>lib/Cake/Test/Case/View/Helper/PaginatorHelperTest.php
<ide> public function testSortLinks() {
<ide> $result = $this->Paginator->sort('title', 'Title', array('direction' => 'asc'));
<ide> $this->assertRegExp('/\/accounts\/index\/param\/page:1\/sort:title\/direction:asc" class="desc">Title<\/a>$/', $result);
<ide>
<del>
<ide> $this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
<ide> $this->Paginator->request->params['paging']['Article']['options']['sort'] = null;
<ide> $result = $this->Paginator->sort('title', 'Title', array('direction' => 'asc'));
<ide> $this->assertRegExp('/\/accounts\/index\/param\/page:1\/sort:title\/direction:desc" class="asc">Title<\/a>$/', $result);
<ide>
<del>
<ide> $this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
<ide> $this->Paginator->request->params['paging']['Article']['options']['sort'] = null;
<ide> $result = $this->Paginator->sort('title', 'Title', array('direction' => 'desc'));
<ide> public function testSortLinksUsingDotNotation() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del>
<ide> $this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
<ide> $result = $this->Paginator->sort('Article.title', 'Title');
<ide> $expected = array(
<ide> public function testNumbers() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del>
<ide> $this->Paginator->request->params['paging'] = array(
<ide> 'Client' => array(
<ide> 'page' => 14,
<ide> public function testNumbers() {
<ide> array('span' => array('class' => 'page-link')), array('a' => array('href' => '/index/page:9')), '9', '/a', '/span',
<ide> );
<ide> $this->assertTags($result, $expected);
<del>
<add>
<ide> $result = $this->Paginator->numbers(array('first' => 1, 'currentClass' => 'active'));
<ide> $expected = array(
<ide> array('span' => array()), array('a' => array('href' => '/index/page:1')), '1', '/a', '/span',
<ide> public function testNumbers() {
<ide> array('span' => array()), array('a' => array('href' => '/index/page:9')), '9', '/a', '/span',
<ide> );
<ide> $this->assertTags($result, $expected);
<del>
<add>
<ide> $result = $this->Paginator->numbers(array('first' => 1, 'class' => 'page-link', 'currentClass' => 'active'));
<ide> $expected = array(
<ide> array('span' => array('class' => 'page-link')), array('a' => array('href' => '/index/page:1')), '1', '/a', '/span',
<ide> public function testNumbers() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del>
<ide> $this->Paginator->request->params['paging'] = array(
<ide> 'Client' => array(
<ide> 'page' => 4895,
<ide><path>lib/Cake/Test/Case/View/Helper/PrototypeEngineHelperTest.php
<ide> App::uses('PrototypeEngineHelper', 'View/Helper');
<ide>
<ide> class PrototypeEngineHelperTest extends CakeTestCase {
<add>
<ide> /**
<ide> * setUp
<ide> *
<ide><path>lib/Cake/Test/Case/View/Helper/RssHelperTest.php
<ide> public function testItem() {
<ide> 'url' => 'http://example.com/foo?a=1&b=2',
<ide> 'convertEntities' => false
<ide> ),
<del> 'description' => array(
<add> 'description' => array(
<ide> 'value' => 'descriptive words',
<ide> 'cdata' => true,
<ide> ),
<ide><path>lib/Cake/Test/Case/View/Helper/SessionHelperTest.php
<ide> public function testFlash() {
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> App::build(array(
<del> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View'. DS)
<add> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
<ide> ));
<ide> $result = $this->Session->flash('notification');
<ide> $result = str_replace("\r\n", "\n", $result);
<ide> public function testFlashAttributes() {
<ide> */
<ide> public function testFlashElementInAttrs() {
<ide> App::build(array(
<del> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View'. DS)
<add> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
<ide> ));
<ide> $result = $this->Session->flash('flash', array(
<ide> 'element' => 'session_helper',
<ide> public function testFlashElementInAttrs() {
<ide> */
<ide> public function testFlashWithPluginElement() {
<ide> App::build(array(
<del> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin'. DS)
<add> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
<ide> ));
<ide> CakePlugin::load('TestPlugin');
<ide>
<ide><path>lib/Cake/Test/Case/View/HelperCollectionTest.php
<ide> class HtmlAliasHelper extends HtmlHelper {
<ide> }
<ide>
<ide> class HelperCollectionTest extends CakeTestCase {
<add>
<ide> /**
<ide> * setUp
<ide> *
<ide><path>lib/Cake/Test/Case/View/HelperTest.php
<ide> public function schema($field = false) {
<ide> );
<ide> return $this->_schema;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function schema($field = false) {
<ide> );
<ide> return $this->_schema;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function schema($field = false) {
<ide> );
<ide> return $this->_schema;
<ide> }
<add>
<ide> }
<ide>
<ide> class TestHelper extends Helper {
<add>
<ide> /**
<ide> * Helpers for this helper.
<ide> *
<ide> class TestHelper extends Helper {
<ide> public function parseAttributes($options, $exclude = null, $insertBefore = ' ', $insertAfter = null) {
<ide> return $this->_parseAttributes($options, $exclude, $insertBefore, $insertAfter);
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function testAssetUrl() {
<ide> * @return void
<ide> */
<ide> public function testAssetTimestampPluginsAndThemes() {
<del> $_timestamp = Configure::read('Asset.timestamp');
<add> $timestamp = Configure::read('Asset.timestamp');
<ide> Configure::write('Asset.timestamp', 'force');
<ide> App::build(array(
<ide> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS),
<ide> ));
<del> CakePlugin::load(array('TestPlugin'));;
<add> CakePlugin::load(array('TestPlugin'));
<ide>
<ide> $result = $this->Helper->assetTimestamp('/test_plugin/css/test_plugin_asset.css');
<ide> $this->assertRegExp('#/test_plugin/css/test_plugin_asset.css\?[0-9]+$#', $result, 'Missing timestamp plugin');
<ide> public function testAssetTimestampPluginsAndThemes() {
<ide> $this->assertRegExp('#/theme/test_theme/js/non_existant.js\?$#', $result, 'No error on missing file');
<ide>
<ide> App::build();
<del> Configure::write('Asset.timestamp', $_timestamp);
<add> Configure::write('Asset.timestamp', $timestamp);
<ide> }
<ide>
<ide> /**
<ide> public function testMultiDimensionalField() {
<ide>
<ide> $this->Helper->request->data['My']['title'] = 'My Title';
<ide> $result = $this->Helper->value('My.title');
<del> $this->assertEquals($result,'My Title');
<add> $this->assertEquals($result, 'My Title');
<ide> }
<ide>
<ide> public function testWebrootPaths() {
<ide> public function testWebrootPaths() {
<ide> $this->Helper->theme = 'test_theme';
<ide>
<ide> App::build(array(
<del> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View'. DS)
<add> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
<ide> ));
<ide>
<ide> $result = $this->Helper->webroot('/img/cake.power.gif');
<ide> public function testThatHelperHelpersAreNotAttached() {
<ide> */
<ide> public function testLazyLoadingUsesReferences() {
<ide> $Helper = new TestHelper($this->View);
<del> $result1 = $Helper->Html;
<del> $result2 = $Helper->Html;
<add> $resultA = $Helper->Html;
<add> $resultB = $Helper->Html;
<ide>
<del> $result1->testprop = 1;
<del> $this->assertEquals($result1->testprop, $result2->testprop);
<add> $resultA->testprop = 1;
<add> $this->assertEquals($resultA->testprop, $resultB->testprop);
<ide> }
<add>
<ide> }
<ide><path>lib/Cake/Test/Case/View/JsonViewTest.php
<ide> public function testRenderWithoutViewMultiple() {
<ide> $View = new JsonView($Controller);
<ide> $output = $View->render(false);
<ide>
<del> $this->assertIdentical(json_encode(array('no' =>$data['no'], 'user' => $data['user'])), $output);
<add> $this->assertIdentical(json_encode(array('no' => $data['no'], 'user' => $data['user'])), $output);
<ide> $this->assertIdentical('application/json', $Response->type());
<ide> }
<ide>
<ide><path>lib/Cake/Test/Case/View/MediaViewTest.php
<ide> public function testRenderNotFound() {
<ide> */
<ide> public function testRender() {
<ide> $this->MediaView->viewVars = array(
<del> 'path' => CAKE . 'Test' . DS . 'test_app' . DS . 'Vendor' . DS .'css' . DS,
<add> 'path' => CAKE . 'Test' . DS . 'test_app' . DS . 'Vendor' . DS . 'css' . DS,
<ide> 'id' => 'test_asset.css',
<ide> 'extension' => 'css',
<ide> );
<ide> public function testRenderWithUnknownFileTypeGeneric() {
<ide> $currentUserAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
<ide> $_SERVER['HTTP_USER_AGENT'] = 'Some generic browser';
<ide> $this->MediaView->viewVars = array(
<del> 'path' => CAKE . 'Test' . DS . 'test_app' . DS . 'Config' . DS,
<add> 'path' => CAKE . 'Test' . DS . 'test_app' . DS . 'Config' . DS,
<ide> 'id' => 'no_section.ini',
<ide> 'extension' => 'ini',
<ide> );
<ide> public function testRenderWithUnknownFileTypeOpera() {
<ide> $currentUserAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
<ide> $_SERVER['HTTP_USER_AGENT'] = 'Opera/9.80 (Windows NT 6.0; U; en) Presto/2.8.99 Version/11.10';
<ide> $this->MediaView->viewVars = array(
<del> 'path' => CAKE . 'Test' . DS . 'test_app' . DS . 'Config' . DS,
<add> 'path' => CAKE . 'Test' . DS . 'test_app' . DS . 'Config' . DS,
<ide> 'id' => 'no_section.ini',
<ide> 'extension' => 'ini',
<ide> );
<ide> public function testRenderWithUnknownFileTypeIE() {
<ide> $currentUserAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
<ide> $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; Media Center PC 4.0; SLCC1; .NET CLR 3.0.04320)';
<ide> $this->MediaView->viewVars = array(
<del> 'path' => CAKE . 'Test' . DS . 'test_app' . DS . 'Config' . DS,
<add> 'path' => CAKE . 'Test' . DS . 'test_app' . DS . 'Config' . DS,
<ide> 'id' => 'no_section.ini',
<ide> 'extension' => 'ini',
<ide> 'name' => 'config'
<ide> public function testRenderWithUnknownFileTypeIE() {
<ide> */
<ide> public function testConnectionAborted() {
<ide> $this->MediaView->viewVars = array(
<del> 'path' => CAKE . 'Test' . DS . 'test_app' . DS . 'Vendor' . DS .'css' . DS,
<add> 'path' => CAKE . 'Test' . DS . 'test_app' . DS . 'Vendor' . DS . 'css' . DS,
<ide> 'id' => 'test_asset.css',
<ide> 'extension' => 'css',
<ide> );
<ide> public function testConnectionAborted() {
<ide> */
<ide> public function testConnectionAbortedOnBuffering() {
<ide> $this->MediaView->viewVars = array(
<del> 'path' => CAKE . 'Test' . DS . 'test_app' . DS . 'Vendor' . DS .'css' . DS,
<add> 'path' => CAKE . 'Test' . DS . 'test_app' . DS . 'Vendor' . DS . 'css' . DS,
<ide> 'id' => 'test_asset.css',
<ide> 'extension' => 'css',
<ide> );
<ide> public function testConnectionAbortedOnBuffering() {
<ide> */
<ide> public function testRenderUpperExtension() {
<ide> $this->MediaView->viewVars = array(
<del> 'path' => CAKE . 'Test' . DS . 'test_app' . DS . 'Vendor' . DS .'img' . DS,
<add> 'path' => CAKE . 'Test' . DS . 'test_app' . DS . 'Vendor' . DS . 'img' . DS,
<ide> 'id' => 'test_2.JPG',
<ide> 'extension' => 'JPG',
<ide> );
<ide> public function testRenderUpperExtension() {
<ide> */
<ide> public function testRenderExtensionNotSet() {
<ide> $this->MediaView->viewVars = array(
<del> 'path' => CAKE . 'Test' . DS . 'test_app' . DS . 'Vendor' . DS .'img' . DS,
<add> 'path' => CAKE . 'Test' . DS . 'test_app' . DS . 'Vendor' . DS . 'img' . DS,
<ide> 'id' => 'test_2.JPG',
<ide> );
<ide>
<ide><path>lib/Cake/Test/Case/View/ScaffoldViewTest.php
<ide> class TestScaffoldView extends ScaffoldView {
<ide> public function testGetFilename($action) {
<ide> return $this->_getViewFileName($action);
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function testGetViewFilename() {
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = $ScaffoldView->testGetFilename('admin_edit');
<del> $expected =CAKE . 'View' . DS . 'Scaffolds' . DS . 'form.ctp';
<add> $expected = CAKE . 'View' . DS . 'Scaffolds' . DS . 'form.ctp';
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = $ScaffoldView->testGetFilename('admin_add');
<ide> public function testGetViewFilename() {
<ide>
<ide> $ScaffoldView = new TestScaffoldView($Controller);
<ide> $result = $ScaffoldView->testGetFilename('admin_edit');
<del> $expected = CAKE . 'Test' . DS . 'test_app' .DS . 'View' . DS . 'Posts' . DS . 'scaffold.form.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Posts' . DS . 'scaffold.form.ctp';
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = $ScaffoldView->testGetFilename('edit');
<del> $expected = CAKE . 'Test' . DS . 'test_app' .DS . 'View' . DS . 'Posts' . DS . 'scaffold.form.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Posts' . DS . 'scaffold.form.ctp';
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $Controller = new ScaffoldViewMockController($this->request);
<ide> public function testGetViewFilename() {
<ide>
<ide> $ScaffoldView = new TestScaffoldView($Controller);
<ide> $result = $ScaffoldView->testGetFilename('admin_add');
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin'
<del> . DS .'TestPlugin' . DS . 'View' . DS . 'Tests' . DS . 'scaffold.form.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' .
<add> DS . 'TestPlugin' . DS . 'View' . DS . 'Tests' . DS . 'scaffold.form.ctp';
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = $ScaffoldView->testGetFilename('add');
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin'
<del> . DS .'TestPlugin' . DS . 'View' . DS . 'Tests' . DS . 'scaffold.form.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' .
<add> DS . 'TestPlugin' . DS . 'View' . DS . 'Tests' . DS . 'scaffold.form.ctp';
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> Configure::write('Routing.prefixes', $_admin);
<ide> public function testGetViewFileNameWithTheme() {
<ide> $ScaffoldView = new TestScaffoldView($this->Controller);
<ide>
<ide> $result = $ScaffoldView->testGetFilename('index');
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS
<del> . 'Themed' . DS . 'TestTheme' . DS . 'Posts' . DS . 'scaffold.index.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS .
<add> 'Themed' . DS . 'TestTheme' . DS . 'Posts' . DS . 'scaffold.index.ctp';
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<ide><path>lib/Cake/Test/Case/View/ThemeViewTest.php
<ide> public function index() {
<ide> $test3 = 'even more data';
<ide> $this->set(compact('test2', 'test3'));
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function setUp() {
<ide> $this->ThemeView = new ThemeView($this->PostsController);
<ide> App::build(array(
<ide> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS),
<del> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View'. DS)
<add> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
<ide> ));
<ide> App::objects('plugins', null, false);
<ide> CakePlugin::load(array('TestPlugin'));
<ide> public function testPluginThemedGetTemplate() {
<ide> $this->Controller->theme = 'TestTheme';
<ide>
<ide> $ThemeView = new TestTheme2View($this->Controller);
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Plugin' . DS . 'TestPlugin' . DS . 'Tests' . DS .'index.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Plugin' . DS . 'TestPlugin' . DS . 'Tests' . DS . 'index.ctp';
<ide> $result = $ThemeView->getViewFileName('index');
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Plugin' . DS . 'TestPlugin' . DS . 'Layouts' . DS .'plugin_default.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Plugin' . DS . 'TestPlugin' . DS . 'Layouts' . DS . 'plugin_default.ctp';
<ide> $result = $ThemeView->getLayoutFileName('plugin_default');
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Layouts' . DS .'default.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Layouts' . DS . 'default.ctp';
<ide> $result = $ThemeView->getLayoutFileName('default');
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide> public function testGetTemplate() {
<ide>
<ide> $ThemeView = new TestTheme2View($this->Controller);
<ide> $ThemeView->theme = 'TestTheme';
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS .'Pages' . DS .'home.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Pages' . DS . 'home.ctp';
<ide> $result = $ThemeView->getViewFileName('home');
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Posts' . DS .'index.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Posts' . DS . 'index.ctp';
<ide> $result = $ThemeView->getViewFileName('/Posts/index');
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Layouts' . DS .'default.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Layouts' . DS . 'default.ctp';
<ide> $result = $ThemeView->getLayoutFileName();
<ide> $this->assertEquals($expected, $result);
<ide>
<ide><path>lib/Cake/Test/Case/View/ViewTest.php
<ide> public function nocache_multiple_element() {
<ide> $this->set('foo', 'this is foo var');
<ide> $this->set('bar', 'this is bar var');
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function index() {
<ide> $test3 = 'even more data';
<ide> $this->set(compact('test2', 'test3'));
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function render_($___viewFn, $___dataForView, $loadHelpers = true, $cache
<ide> public function scripts() {
<ide> return $this->_scripts;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function beforeLayout($viewFile) {
<ide> public function afterLayout($layoutFile) {
<ide> $this->_View->output .= 'modified in the afterlife';
<ide> }
<add>
<ide> }
<ide>
<ide>
<ide> public function setUp() {
<ide>
<ide> App::build(array(
<ide> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS),
<del> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View'. DS)
<add> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
<ide> ), App::RESET);
<ide> App::objects('plugins', null, false);
<ide>
<ide> public function tearDown() {
<ide> unset($this->ThemeView);
<ide> unset($this->ThemePostsController);
<ide> unset($this->ThemeController);
<del>
<ide> }
<add>
<ide> /**
<ide> * testGetTemplate method
<ide> *
<ide> public function testGetTemplate() {
<ide>
<ide> $ThemeView = new TestThemeView($this->Controller);
<ide> $ThemeView->theme = 'TestTheme';
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS .'Pages' . DS .'home.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Pages' . DS . 'home.ctp';
<ide> $result = $ThemeView->getViewFileName('home');
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Posts' . DS .'index.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Posts' . DS . 'index.ctp';
<ide> $result = $ThemeView->getViewFileName('/Posts/index');
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Layouts' . DS .'default.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Layouts' . DS . 'default.ctp';
<ide> $result = $ThemeView->getLayoutFileName();
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> public function testPluginGetTemplate() {
<ide>
<ide> $View = new TestView($this->Controller);
<ide>
<del> $expected = CakePlugin::path('TestPlugin') . 'View' . DS .'Tests' . DS .'index.ctp';
<add> $expected = CakePlugin::path('TestPlugin') . 'View' . DS . 'Tests' . DS . 'index.ctp';
<ide> $result = $View->getViewFileName('index');
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $expected = CakePlugin::path('TestPlugin') . 'View' . DS . 'Layouts' . DS .'default.ctp';
<add> $expected = CakePlugin::path('TestPlugin') . 'View' . DS . 'Layouts' . DS . 'default.ctp';
<ide> $result = $View->getLayoutFileName();
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide> public function testPluginThemedGetTemplate() {
<ide> $this->Controller->theme = 'TestTheme';
<ide>
<ide> $ThemeView = new TestThemeView($this->Controller);
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Plugin' . DS . 'TestPlugin' . DS . 'Tests' . DS .'index.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Plugin' . DS . 'TestPlugin' . DS . 'Tests' . DS . 'index.ctp';
<ide> $result = $ThemeView->getViewFileName('index');
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Plugin' . DS . 'TestPlugin' . DS . 'Layouts' . DS .'plugin_default.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Plugin' . DS . 'TestPlugin' . DS . 'Layouts' . DS . 'plugin_default.ctp';
<ide> $result = $ThemeView->getLayoutFileName('plugin_default');
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Layouts' . DS .'default.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Layouts' . DS . 'default.ctp';
<ide> $result = $ThemeView->getLayoutFileName('default');
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide> public function testCamelCasePluginGetTemplate() {
<ide> $View = new TestView($this->Controller);
<ide> App::build(array(
<ide> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS),
<del> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View'. DS)
<add> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
<ide> ));
<ide>
<ide> $pluginPath = CakePlugin::path('TestPlugin');
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS .'TestPlugin' . DS . 'View' . DS .'Tests' . DS .'index.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS . 'TestPlugin' . DS . 'View' . DS . 'Tests' . DS . 'index.ctp';
<ide> $result = $View->getViewFileName('index');
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $expected = $pluginPath. 'View' . DS . 'Layouts' . DS .'default.ctp';
<add> $expected = $pluginPath . 'View' . DS . 'Layouts' . DS . 'default.ctp';
<ide> $result = $View->getLayoutFileName();
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide> public function testGetViewFileNames() {
<ide>
<ide> $View = new TestView($this->Controller);
<ide>
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS .'Pages' . DS .'home.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Pages' . DS . 'home.ctp';
<ide> $result = $View->getViewFileName('home');
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS .'Posts' . DS .'index.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Posts' . DS . 'index.ctp';
<ide> $result = $View->getViewFileName('/Posts/index');
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS .'Posts' . DS .'index.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Posts' . DS . 'index.ctp';
<ide> $result = $View->getViewFileName('../Posts/index');
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS .'Pages' . DS .'page.home.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Pages' . DS . 'page.home.ctp';
<ide> $result = $View->getViewFileName('page.home');
<ide> $this->assertEquals($expected, $result, 'Should not ruin files with dots.');
<ide>
<ide> CakePlugin::load('TestPlugin');
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS .'Pages' . DS .'home.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Pages' . DS . 'home.ctp';
<ide> $result = $View->getViewFileName('TestPlugin.home');
<ide> $this->assertEquals($expected, $result, 'Plugin is missing the view, cascade to app.');
<ide>
<ide> $View->viewPath = 'Tests';
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS . 'TestPlugin' . DS . 'View' . DS .'Tests' . DS .'index.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS . 'TestPlugin' . DS . 'View' . DS . 'Tests' . DS . 'index.ctp';
<ide> $result = $View->getViewFileName('TestPlugin.index');
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide> public function testGetLayoutFileName() {
<ide>
<ide> $View = new TestView($this->Controller);
<ide>
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Layouts' . DS .'default.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Layouts' . DS . 'default.ctp';
<ide> $result = $View->getLayoutFileName();
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> public function testGetLayoutFileNamePlugin() {
<ide> $View = new TestView($this->Controller);
<ide> CakePlugin::load('TestPlugin');
<ide>
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS . 'TestPlugin' . DS . 'View' . DS . 'Layouts' . DS .'default.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS . 'TestPlugin' . DS . 'View' . DS . 'Layouts' . DS . 'default.ctp';
<ide> $result = $View->getLayoutFileName('TestPlugin.default');
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $View->plugin = 'TestPlugin';
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS . 'TestPlugin' . DS . 'View' . DS . 'Layouts' . DS .'default.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS . 'TestPlugin' . DS . 'View' . DS . 'Layouts' . DS . 'default.ctp';
<ide> $result = $View->getLayoutFileName('default');
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide> public function testViewFileName() {
<ide> $result = $View->getViewFileName('../Themed/TestTheme/Posts/index');
<ide> $this->assertRegExp('/Themed(\/|\\\)TestTheme(\/|\\\)Posts(\/|\\\)index.ctp/', $result);
<ide>
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS .'Posts' . DS .'index.ctp';
<add> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Posts' . DS . 'index.ctp';
<ide> $result = $View->getViewFileName('../Posts/index');
<ide> $this->assertEquals($expected, $result);
<del>
<ide> }
<ide>
<ide> /**
<ide> public function testRenderStrippingNoCacheTagsOnlyCacheCheck() {
<ide> $this->assertNotRegExp('/cake:nocache/', $result);
<ide> }
<ide>
<del>/**
<del> * testRenderNocache method
<del> *
<del> * @return void
<del> */
<del>
<del>/* This is a new test case for a pending enhancement
<del> public function testRenderNocache() {
<del> $this->PostsController->helpers = array('Cache', 'Html');
<del> $this->PostsController->constructClasses();
<del> $this->PostsController->cacheAction = 21600;
<del> $this->PostsController->here = '/posts/nocache_multiple_element';
<del> $this->PostsController->action = 'nocache_multiple_element';
<del> $this->PostsController->nocache_multiple_element();
<del> Configure::write('Cache.check', true);
<del> Configure::write('Cache.disable', false);
<del>
<del> $filename = CACHE . 'views' . DS . 'posts_nocache_multiple_element.php';
<del>
<del> $View = new TestView($this->PostsController);
<del> $View->render();
<del>
<del> ob_start();
<del> $View->renderCache($filename, getMicroTime());
<del> $result = ob_get_clean();
<del> @unlink($filename);
<del>
<del> $this->assertRegExp('/php echo \$foo;/', $result);
<del> $this->assertRegExp('/php echo \$bar;/', $result);
<del> $this->assertRegExp('/php \$barfoo = \'in sub2\';/', $result);
<del> $this->assertRegExp('/php echo \$barfoo;/', $result);
<del> $this->assertRegExp('/printing: "in sub2"/', $result);
<del> $this->assertRegExp('/php \$foobar = \'in sub1\';/', $result);
<del> $this->assertRegExp('/php echo \$foobar;/', $result);
<del> $this->assertRegExp('/printing: "in sub1"/', $result);
<del> }
<del>*/
<del>
<ide> /**
<ide> * testSet method
<ide> *
<ide><path>lib/Cake/Test/Case/View/XmlViewTest.php
<ide> public function testRenderWithoutViewMultiple() {
<ide> $output = $View->render(false);
<ide>
<ide> $expected = array(
<del> 'response' => array('no' =>$data['no'], 'user' => $data['user'])
<add> 'response' => array('no' => $data['no'], 'user' => $data['user'])
<ide> );
<ide> $this->assertIdentical(Xml::build($expected)->asXML(), $output);
<ide> $this->assertIdentical('application/xml', $Response->type()); | 19 |
Javascript | Javascript | add assertions to zero length buffer test | 927661f8ace022a0f77a35ea76dffb5bb21b188d | <ide><path>test/parallel/test-buffer-slice.js
<ide> assert.equal(buf.slice('0', '-111'), '');
<ide>
<ide> // try to slice a zero length Buffer
<ide> // see https://github.com/joyent/node/issues/5881
<del>Buffer.alloc(0).slice(0, 1);
<add>assert.doesNotThrow(() => Buffer.alloc(0).slice(0, 1));
<add>assert.strictEqual(Buffer.alloc(0).slice(0, 1).length, 0);
<ide>
<ide> {
<ide> // Single argument slice | 1 |
Python | Python | add upsampling layer tests | 84909a49c2c58d7cda893897c183067acc0794ef | <ide><path>tests/auto/keras/layers/test_convolutional.py
<ide> def test_convolution_1d(self):
<ide> for subsample_length in [1, 3]:
<ide> for W_regularizer in [None, 'l2']:
<ide> for b_regularizer in [None, 'l2']:
<del> layer = convolutional.Convolution1D(
<del> input_dim, nb_filter, filter_length, weights=weight,
<del> border_mode=border_mode, W_regularizer=W_regularizer,
<del> b_regularizer=b_regularizer, subsample_length=subsample_length)
<add> for act_regularizer in [None, 'l2']:
<add> layer = convolutional.Convolution1D(
<add> input_dim, nb_filter, filter_length, weights=weight,
<add> border_mode=border_mode, W_regularizer=W_regularizer,
<add> b_regularizer=b_regularizer, activity_regularizer=act_regularizer,
<add> subsample_length=subsample_length)
<ide>
<ide> layer.input = theano.shared(value=input)
<ide> for train in [True, False]:
<ide> def test_convolution_2d(self):
<ide> for subsample in [(1, 1), (2, 3)]:
<ide> for W_regularizer in [None, 'l2']:
<ide> for b_regularizer in [None, 'l2']:
<del> layer = convolutional.Convolution2D(
<del> nb_filter, stack_size, nb_row, nb_col, weights=weight,
<del> border_mode=border_mode, W_regularizer=W_regularizer,
<del> b_regularizer=b_regularizer, subsample=subsample)
<add> for act_regularizer in [None, 'l2']:
<add> layer = convolutional.Convolution2D(
<add> nb_filter, stack_size, nb_row, nb_col, weights=weight,
<add> border_mode=border_mode, W_regularizer=W_regularizer,
<add> b_regularizer=b_regularizer, activity_regularizer=act_regularizer,
<add> subsample=subsample)
<ide>
<del> layer.input = theano.shared(value=input)
<del> for train in [True, False]:
<del> out = layer.get_output(train).eval()
<del> if border_mode == 'same' and subsample == (1, 1):
<del> assert out.shape[2:] == input.shape[2:]
<add> layer.input = theano.shared(value=input)
<add> for train in [True, False]:
<add> out = layer.get_output(train).eval()
<add> if border_mode == 'same' and subsample == (1, 1):
<add> assert out.shape[2:] == input.shape[2:]
<ide>
<del> config = layer.get_config()
<add> config = layer.get_config()
<ide>
<ide> def test_maxpooling_2d(self):
<ide> nb_samples = 9
<ide> def test_zero_padding_2d(self):
<ide>
<ide> config = layer.get_config()
<ide>
<add> def test_upsample_1d(self):
<add> nb_samples = 9
<add>
<add> nb_steps = 7
<add> input_dim = 10
<add>
<add> input = np.ones((nb_samples, nb_steps, input_dim))
<add> for length in [2,3,9]:
<add> layer = convolutional.UpSample1D(length=length)
<add> layer.input = theano.shared(value=input)
<add> for train in [True, False]:
<add> out = layer.get_output(train).eval()
<add> assert out.shape[1] == length*nb_steps
<add>
<add> config = layer.get_config()
<add>
<add> def test_upsample_2d(self):
<add> nb_samples = 9
<add>
<add> stack_size = 7
<add> input_nb_row = 11
<add> input_nb_col = 12
<add>
<add> input = np.ones((nb_samples, stack_size, input_nb_row, input_nb_col))
<add>
<add> for length_row in [2,3,9]:
<add> for length_col in [2,3,9]:
<add> layer = convolutional.UpSample2D(size=(length_row,length_col))
<add> layer.input = theano.shared(value=input)
<add> for train in [True, False]:
<add> out = layer.get_output(train).eval()
<add> assert out.shape[2] == length_row*input_nb_row
<add> assert out.shape[3] == length_col*input_nb_col
<add>
<add> config = layer.get_config()
<add>
<ide> if __name__ == '__main__':
<ide> unittest.main() | 1 |
Javascript | Javascript | update jquery code | 98a1c9fd05bbcfdf7c8b50377ce7c76e7ae9b480 | <ide><path>tests/jquery-1.7.1.js
<ide> /*!
<del> * jQuery JavaScript Library v1.7.1
<add> * jQuery JavaScript Library v1.7.2
<ide> * http://jquery.com/
<ide> *
<ide> * Copyright 2011, John Resig
<ide> * Copyright 2011, The Dojo Foundation
<ide> * Released under the MIT, BSD, and GPL Licenses.
<ide> *
<del> * Date: Mon Nov 21 21:11:03 2011 -0500
<add> * Date: Wed Mar 21 12:46:34 2012 -0700
<ide> */
<ide> (function( window, undefined ) {
<ide>
<ide> jQuery.fn = jQuery.prototype = {
<ide> selector: "",
<ide>
<ide> // The current version of jQuery being used
<del> jquery: "1.7.1",
<add> jquery: "1.7.2",
<ide>
<ide> // The default length of a jQuery object is 0
<ide> length: 0,
<ide> jQuery.extend({
<ide> return jQuery.type(obj) === "array";
<ide> },
<ide>
<del> // A crude way of determining if an object is a window
<ide> isWindow: function( obj ) {
<del> return obj && typeof obj === "object" && "setInterval" in obj;
<add> return obj != null && obj == obj.window;
<ide> },
<ide>
<ide> isNumeric: function( obj ) {
<ide> jQuery.extend({
<ide>
<ide> // Cross-browser xml parsing
<ide> parseXML: function( data ) {
<add> if ( typeof data !== "string" || !data ) {
<add> return null;
<add> }
<ide> var xml, tmp;
<ide> try {
<ide> if ( window.DOMParser ) { // Standard
<ide> jQuery.extend({
<ide>
<ide> // Mutifunctional method to get and set values to a collection
<ide> // The value/s can optionally be executed if it's a function
<del> access: function( elems, key, value, exec, fn, pass ) {
<del> var length = elems.length;
<add> access: function( elems, fn, key, value, chainable, emptyGet, pass ) {
<add> var exec,
<add> bulk = key == null,
<add> i = 0,
<add> length = elems.length;
<ide>
<del> // Setting many attributes
<del> if ( typeof key === "object" ) {
<del> for ( var k in key ) {
<del> jQuery.access( elems, k, key[k], exec, fn, value );
<add> // Sets many values
<add> if ( key && typeof key === "object" ) {
<add> for ( i in key ) {
<add> jQuery.access( elems, fn, i, key[i], 1, emptyGet, value );
<ide> }
<del> return elems;
<del> }
<add> chainable = 1;
<ide>
<del> // Setting one attribute
<del> if ( value !== undefined ) {
<add> // Sets one value
<add> } else if ( value !== undefined ) {
<ide> // Optionally, function values get executed if exec is true
<del> exec = !pass && exec && jQuery.isFunction(value);
<add> exec = pass === undefined && jQuery.isFunction( value );
<add>
<add> if ( bulk ) {
<add> // Bulk operations only iterate when executing function values
<add> if ( exec ) {
<add> exec = fn;
<add> fn = function( elem, key, value ) {
<add> return exec.call( jQuery( elem ), value );
<add> };
<add>
<add> // Otherwise they run against the entire set
<add> } else {
<add> fn.call( elems, value );
<add> fn = null;
<add> }
<add> }
<ide>
<del> for ( var i = 0; i < length; i++ ) {
<del> fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
<add> if ( fn ) {
<add> for (; i < length; i++ ) {
<add> fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
<add> }
<ide> }
<ide>
<del> return elems;
<add> chainable = 1;
<ide> }
<ide>
<del> // Getting an attribute
<del> return length ? fn( elems[0], key ) : undefined;
<add> return chainable ?
<add> elems :
<add>
<add> // Gets
<add> bulk ?
<add> fn.call( elems ) :
<add> length ? fn( elems[0], key ) : emptyGet;
<ide> },
<ide>
<ide> now: function() {
<ide> jQuery.Callbacks = function( flags ) {
<ide> stack = [],
<ide> // Last fire value (for non-forgettable lists)
<ide> memory,
<add> // Flag to know if list was already fired
<add> fired,
<ide> // Flag to know if list is currently firing
<ide> firing,
<ide> // First callback to fire (used internally by add and fireWith)
<ide> jQuery.Callbacks = function( flags ) {
<ide> fire = function( context, args ) {
<ide> args = args || [];
<ide> memory = !flags.memory || [ context, args ];
<add> fired = true;
<ide> firing = true;
<ide> firingIndex = firingStart || 0;
<ide> firingStart = 0;
<ide> jQuery.Callbacks = function( flags ) {
<ide> },
<ide> // To know if the callbacks have already been called at least once
<ide> fired: function() {
<del> return !!memory;
<add> return !!fired;
<ide> }
<ide> };
<ide>
<ide> jQuery.support = (function() {
<ide> select,
<ide> opt,
<ide> input,
<del> marginDiv,
<ide> fragment,
<ide> tds,
<ide> events,
<ide> jQuery.support = (function() {
<ide> noCloneEvent: true,
<ide> inlineBlockNeedsLayout: false,
<ide> shrinkWrapBlocks: false,
<del> reliableMarginRight: true
<add> reliableMarginRight: true,
<add> pixelMargin: true
<ide> };
<ide>
<add> // jQuery.boxModel DEPRECATED in 1.3, use jQuery.support.boxModel instead
<add> jQuery.boxModel = support.boxModel = (document.compatMode === "CSS1Compat");
<add>
<ide> // Make sure checked status is properly cloned
<ide> input.checked = true;
<ide> support.noCloneChecked = input.cloneNode( true ).checked;
<ide> jQuery.support = (function() {
<ide> support.radioValue = input.value === "t";
<ide>
<ide> input.setAttribute("checked", "checked");
<add>
<add> // #11217 - WebKit loses check when the name is after the checked attribute
<add> input.setAttribute( "name", "t" );
<add>
<ide> div.appendChild( input );
<ide> fragment = document.createDocumentFragment();
<ide> fragment.appendChild( div.lastChild );
<ide> jQuery.support = (function() {
<ide> fragment.removeChild( input );
<ide> fragment.appendChild( div );
<ide>
<del> div.innerHTML = "";
<del>
<del> // Check if div with explicit width and no margin-right incorrectly
<del> // gets computed margin-right based on width of container. For more
<del> // info see bug #3333
<del> // Fails in WebKit before Feb 2011 nightlies
<del> // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
<del> if ( window.getComputedStyle ) {
<del> marginDiv = document.createElement( "div" );
<del> marginDiv.style.width = "0";
<del> marginDiv.style.marginRight = "0";
<del> div.style.width = "2px";
<del> div.appendChild( marginDiv );
<del> support.reliableMarginRight =
<del> ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0;
<del> }
<del>
<ide> // Technique from Juriy Zaytsev
<ide> // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
<ide> // We only care about the case where non-standard event systems
<ide> // are used, namely in IE. Short-circuiting here helps us to
<ide> // avoid an eval call (in setAttribute) which can cause CSP
<ide> // to go haywire. See: https://developer.mozilla.org/en/Security/CSP
<ide> if ( div.attachEvent ) {
<del> for( i in {
<add> for ( i in {
<ide> submit: 1,
<ide> change: 1,
<ide> focusin: 1
<ide> jQuery.support = (function() {
<ide> fragment.removeChild( div );
<ide>
<ide> // Null elements to avoid leaks in IE
<del> fragment = select = opt = marginDiv = div = input = null;
<add> fragment = select = opt = div = input = null;
<ide>
<ide> // Run tests that need a body at doc ready
<ide> jQuery(function() {
<ide> var container, outer, inner, table, td, offsetSupport,
<del> conMarginTop, ptlm, vb, style, html,
<add> marginDiv, conMarginTop, style, html, positionTopLeftWidthHeight,
<add> paddingMarginBorderVisibility, paddingMarginBorder,
<ide> body = document.getElementsByTagName("body")[0];
<ide>
<ide> if ( !body ) {
<ide> jQuery.support = (function() {
<ide> }
<ide>
<ide> conMarginTop = 1;
<del> ptlm = "position:absolute;top:0;left:0;width:1px;height:1px;margin:0;";
<del> vb = "visibility:hidden;border:0;";
<del> style = "style='" + ptlm + "border:5px solid #000;padding:0;'";
<del> html = "<div " + style + "><div></div></div>" +
<del> "<table " + style + " cellpadding='0' cellspacing='0'>" +
<add> paddingMarginBorder = "padding:0;margin:0;border:";
<add> positionTopLeftWidthHeight = "position:absolute;top:0;left:0;width:1px;height:1px;";
<add> paddingMarginBorderVisibility = paddingMarginBorder + "0;visibility:hidden;";
<add> style = "style='" + positionTopLeftWidthHeight + paddingMarginBorder + "5px solid #000;";
<add> html = "<div " + style + "display:block;'><div style='" + paddingMarginBorder + "0;display:block;overflow:hidden;'></div></div>" +
<add> "<table " + style + "' cellpadding='0' cellspacing='0'>" +
<ide> "<tr><td></td></tr></table>";
<ide>
<ide> container = document.createElement("div");
<del> container.style.cssText = vb + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px";
<add> container.style.cssText = paddingMarginBorderVisibility + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px";
<ide> body.insertBefore( container, body.firstChild );
<ide>
<ide> // Construct the test element
<ide> jQuery.support = (function() {
<ide> // display:none (it is still safe to use offsets if a parent element is
<ide> // hidden; don safety goggles and see bug #4512 for more information).
<ide> // (only IE 8 fails this test)
<del> div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";
<add> div.innerHTML = "<table><tr><td style='" + paddingMarginBorder + "0;display:none'></td><td>t</td></tr></table>";
<ide> tds = div.getElementsByTagName( "td" );
<ide> isSupported = ( tds[ 0 ].offsetHeight === 0 );
<ide>
<ide> jQuery.support = (function() {
<ide> // (IE <= 8 fail this test)
<ide> support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
<ide>
<del> // Figure out if the W3C box model works as expected
<del> div.innerHTML = "";
<del> div.style.width = div.style.paddingLeft = "1px";
<del> jQuery.boxModel = support.boxModel = div.offsetWidth === 2;
<add> // Check if div with explicit width and no margin-right incorrectly
<add> // gets computed margin-right based on width of container. For more
<add> // info see bug #3333
<add> // Fails in WebKit before Feb 2011 nightlies
<add> // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
<add> if ( window.getComputedStyle ) {
<add> div.innerHTML = "";
<add> marginDiv = document.createElement( "div" );
<add> marginDiv.style.width = "0";
<add> marginDiv.style.marginRight = "0";
<add> div.style.width = "2px";
<add> div.appendChild( marginDiv );
<add> support.reliableMarginRight =
<add> ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0;
<add> }
<ide>
<ide> if ( typeof div.style.zoom !== "undefined" ) {
<ide> // Check if natively block-level elements act like inline-block
<ide> // elements when setting their display to 'inline' and giving
<ide> // them layout
<ide> // (IE < 8 does this)
<add> div.innerHTML = "";
<add> div.style.width = div.style.padding = "1px";
<add> div.style.border = 0;
<add> div.style.overflow = "hidden";
<ide> div.style.display = "inline";
<ide> div.style.zoom = 1;
<del> support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 );
<add> support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
<ide>
<ide> // Check if elements with layout shrink-wrap their children
<ide> // (IE 6 does this)
<del> div.style.display = "";
<del> div.innerHTML = "<div style='width:4px;'></div>";
<del> support.shrinkWrapBlocks = ( div.offsetWidth !== 2 );
<add> div.style.display = "block";
<add> div.style.overflow = "visible";
<add> div.innerHTML = "<div style='width:5px;'></div>";
<add> support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
<ide> }
<ide>
<del> div.style.cssText = ptlm + vb;
<add> div.style.cssText = positionTopLeftWidthHeight + paddingMarginBorderVisibility;
<ide> div.innerHTML = html;
<ide>
<ide> outer = div.firstChild;
<ide> jQuery.support = (function() {
<ide> offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 );
<ide> offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop );
<ide>
<add> if ( window.getComputedStyle ) {
<add> div.style.marginTop = "1%";
<add> support.pixelMargin = ( window.getComputedStyle( div, null ) || { marginTop: 0 } ).marginTop !== "1%";
<add> }
<add>
<add> if ( typeof container.style.zoom !== "undefined" ) {
<add> container.style.zoom = 1;
<add> }
<add>
<ide> body.removeChild( container );
<del> div = container = null;
<add> marginDiv = div = container = null;
<ide>
<ide> jQuery.extend( support, offsetSupport );
<ide> });
<ide> jQuery.extend({
<ide>
<ide> jQuery.fn.extend({
<ide> data: function( key, value ) {
<del> var parts, attr, name,
<add> var parts, part, attr, name, l,
<add> elem = this[0],
<add> i = 0,
<ide> data = null;
<ide>
<del> if ( typeof key === "undefined" ) {
<add> // Gets all values
<add> if ( key === undefined ) {
<ide> if ( this.length ) {
<del> data = jQuery.data( this[0] );
<add> data = jQuery.data( elem );
<ide>
<del> if ( this[0].nodeType === 1 && !jQuery._data( this[0], "parsedAttrs" ) ) {
<del> attr = this[0].attributes;
<del> for ( var i = 0, l = attr.length; i < l; i++ ) {
<add> if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
<add> attr = elem.attributes;
<add> for ( l = attr.length; i < l; i++ ) {
<ide> name = attr[i].name;
<ide>
<ide> if ( name.indexOf( "data-" ) === 0 ) {
<ide> name = jQuery.camelCase( name.substring(5) );
<ide>
<del> dataAttr( this[0], name, data[ name ] );
<add> dataAttr( elem, name, data[ name ] );
<ide> }
<ide> }
<del> jQuery._data( this[0], "parsedAttrs", true );
<add> jQuery._data( elem, "parsedAttrs", true );
<ide> }
<ide> }
<ide>
<ide> return data;
<add> }
<ide>
<del> } else if ( typeof key === "object" ) {
<add> // Sets multiple values
<add> if ( typeof key === "object" ) {
<ide> return this.each(function() {
<ide> jQuery.data( this, key );
<ide> });
<ide> }
<ide>
<del> parts = key.split(".");
<add> parts = key.split( ".", 2 );
<ide> parts[1] = parts[1] ? "." + parts[1] : "";
<add> part = parts[1] + "!";
<ide>
<del> if ( value === undefined ) {
<del> data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
<add> return jQuery.access( this, function( value ) {
<ide>
<del> // Try to fetch any internally stored data first
<del> if ( data === undefined && this.length ) {
<del> data = jQuery.data( this[0], key );
<del> data = dataAttr( this[0], key, data );
<del> }
<add> if ( value === undefined ) {
<add> data = this.triggerHandler( "getData" + part, [ parts[0] ] );
<ide>
<del> return data === undefined && parts[1] ?
<del> this.data( parts[0] ) :
<del> data;
<add> // Try to fetch any internally stored data first
<add> if ( data === undefined && elem ) {
<add> data = jQuery.data( elem, key );
<add> data = dataAttr( elem, key, data );
<add> }
<ide>
<del> } else {
<del> return this.each(function() {
<del> var self = jQuery( this ),
<del> args = [ parts[0], value ];
<add> return data === undefined && parts[1] ?
<add> this.data( parts[0] ) :
<add> data;
<add> }
<ide>
<del> self.triggerHandler( "setData" + parts[1] + "!", args );
<add> parts[1] = value;
<add> this.each(function() {
<add> var self = jQuery( this );
<add>
<add> self.triggerHandler( "setData" + part, parts );
<ide> jQuery.data( this, key, value );
<del> self.triggerHandler( "changeData" + parts[1] + "!", args );
<add> self.triggerHandler( "changeData" + part, parts );
<ide> });
<del> }
<add> }, null, value, arguments.length > 1, null, false );
<ide> },
<ide>
<ide> removeData: function( key ) {
<ide> function dataAttr( elem, key, data ) {
<ide> data = data === "true" ? true :
<ide> data === "false" ? false :
<ide> data === "null" ? null :
<del> jQuery.isNumeric( data ) ? parseFloat( data ) :
<add> jQuery.isNumeric( data ) ? +data :
<ide> rbrace.test( data ) ? jQuery.parseJSON( data ) :
<ide> data;
<ide> } catch( e ) {}
<ide> jQuery.extend({
<ide>
<ide> jQuery.fn.extend({
<ide> queue: function( type, data ) {
<add> var setter = 2;
<add>
<ide> if ( typeof type !== "string" ) {
<ide> data = type;
<ide> type = "fx";
<add> setter--;
<ide> }
<ide>
<del> if ( data === undefined ) {
<add> if ( arguments.length < setter ) {
<ide> return jQuery.queue( this[0], type );
<ide> }
<del> return this.each(function() {
<del> var queue = jQuery.queue( this, type, data );
<ide>
<del> if ( type === "fx" && queue[0] !== "inprogress" ) {
<del> jQuery.dequeue( this, type );
<del> }
<del> });
<add> return data === undefined ?
<add> this :
<add> this.each(function() {
<add> var queue = jQuery.queue( this, type, data );
<add>
<add> if ( type === "fx" && queue[0] !== "inprogress" ) {
<add> jQuery.dequeue( this, type );
<add> }
<add> });
<ide> },
<ide> dequeue: function( type ) {
<ide> return this.each(function() {
<ide> jQuery.fn.extend({
<ide> }
<ide> }
<ide> resolve();
<del> return defer.promise();
<add> return defer.promise( object );
<ide> }
<ide> });
<ide>
<ide> var rclass = /[\n\t\r]/g,
<ide>
<ide> jQuery.fn.extend({
<ide> attr: function( name, value ) {
<del> return jQuery.access( this, name, value, true, jQuery.attr );
<add> return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
<ide> },
<ide>
<ide> removeAttr: function( name ) {
<ide> jQuery.fn.extend({
<ide> },
<ide>
<ide> prop: function( name, value ) {
<del> return jQuery.access( this, name, value, true, jQuery.prop );
<add> return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
<ide> },
<ide>
<ide> removeProp: function( name ) {
<ide> jQuery.fn.extend({
<ide>
<ide> if ( !arguments.length ) {
<ide> if ( elem ) {
<del> hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ];
<add> hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
<ide>
<ide> if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
<ide> return ret;
<ide> jQuery.fn.extend({
<ide> });
<ide> }
<ide>
<del> hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ];
<add> hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
<ide>
<ide> // If set returns undefined, fall back to normal setting
<ide> if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
<ide> jQuery.extend({
<ide> },
<ide>
<ide> removeAttr: function( elem, value ) {
<del> var propName, attrNames, name, l,
<add> var propName, attrNames, name, l, isBool,
<ide> i = 0;
<ide>
<ide> if ( value && elem.nodeType === 1 ) {
<ide> jQuery.extend({
<ide>
<ide> if ( name ) {
<ide> propName = jQuery.propFix[ name ] || name;
<add> isBool = rboolean.test( name );
<ide>
<ide> // See #9699 for explanation of this approach (setting first, then removal)
<del> jQuery.attr( elem, name, "" );
<add> // Do not do this for boolean attributes (see #10870)
<add> if ( !isBool ) {
<add> jQuery.attr( elem, name, "" );
<add> }
<ide> elem.removeAttribute( getSetAttribute ? name : propName );
<ide>
<ide> // Set corresponding property to false for boolean attributes
<del> if ( rboolean.test( name ) && propName in elem ) {
<add> if ( isBool && propName in elem ) {
<ide> elem[ propName ] = false;
<ide> }
<ide> }
<ide> if ( !getSetAttribute ) {
<ide>
<ide> fixSpecified = {
<ide> name: true,
<del> id: true
<add> id: true,
<add> coords: true
<ide> };
<ide>
<ide> // Use this for any attribute in IE6/7
<ide> jQuery.each([ "radio", "checkbox" ], function() {
<ide>
<ide> var rformElems = /^(?:textarea|input|select)$/i,
<ide> rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/,
<del> rhoverHack = /\bhover(\.\S+)?\b/,
<add> rhoverHack = /(?:^|\s)hover(\.\S+)?\b/,
<ide> rkeyEvent = /^key/,
<ide> rmouseEvent = /^(?:mouse|contextmenu)|click/,
<ide> rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
<ide> jQuery.event = {
<ide> if ( handler.handler ) {
<ide> handleObjIn = handler;
<ide> handler = handleObjIn.handler;
<add> selector = handleObjIn.selector;
<ide> }
<ide>
<ide> // Make sure that the handler has a unique ID, used to find/remove it later
<ide> jQuery.event = {
<ide> handler: handler,
<ide> guid: handler.guid,
<ide> selector: selector,
<del> quick: quickParse( selector ),
<add> quick: selector && quickParse( selector ),
<ide> namespace: namespaces.join(".")
<ide> }, handleObjIn );
<ide>
<ide> jQuery.event = {
<ide> delegateCount = handlers.delegateCount,
<ide> args = [].slice.call( arguments, 0 ),
<ide> run_all = !event.exclusive && !event.namespace,
<add> special = jQuery.event.special[ event.type ] || {},
<ide> handlerQueue = [],
<ide> i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related;
<ide>
<ide> // Use the fix-ed jQuery.Event rather than the (read-only) native event
<ide> args[0] = event;
<ide> event.delegateTarget = this;
<ide>
<add> // Call the preDispatch hook for the mapped type, and let it bail if desired
<add> if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
<add> return;
<add> }
<add>
<ide> // Determine handlers that should run if there are delegated events
<del> // Avoid disabled elements in IE (#6911) and non-left-click bubbling in Firefox (#3861)
<del> if ( delegateCount && !event.target.disabled && !(event.button && event.type === "click") ) {
<add> // Avoid non-left-click bubbling in Firefox (#3861)
<add> if ( delegateCount && !(event.button && event.type === "click") ) {
<ide>
<ide> // Pregenerate a single jQuery object for reuse with .is()
<ide> jqcur = jQuery(this);
<ide> jqcur.context = this.ownerDocument || this;
<ide>
<ide> for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
<del> selMatch = {};
<del> matches = [];
<del> jqcur[0] = cur;
<del> for ( i = 0; i < delegateCount; i++ ) {
<del> handleObj = handlers[ i ];
<del> sel = handleObj.selector;
<del>
<del> if ( selMatch[ sel ] === undefined ) {
<del> selMatch[ sel ] = (
<del> handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel )
<del> );
<add>
<add> // Don't process events on disabled elements (#6911, #8165)
<add> if ( cur.disabled !== true ) {
<add> selMatch = {};
<add> matches = [];
<add> jqcur[0] = cur;
<add> for ( i = 0; i < delegateCount; i++ ) {
<add> handleObj = handlers[ i ];
<add> sel = handleObj.selector;
<add>
<add> if ( selMatch[ sel ] === undefined ) {
<add> selMatch[ sel ] = (
<add> handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel )
<add> );
<add> }
<add> if ( selMatch[ sel ] ) {
<add> matches.push( handleObj );
<add> }
<ide> }
<del> if ( selMatch[ sel ] ) {
<del> matches.push( handleObj );
<add> if ( matches.length ) {
<add> handlerQueue.push({ elem: cur, matches: matches });
<ide> }
<ide> }
<del> if ( matches.length ) {
<del> handlerQueue.push({ elem: cur, matches: matches });
<del> }
<ide> }
<ide> }
<ide>
<ide> jQuery.event = {
<ide> }
<ide> }
<ide>
<add> // Call the postDispatch hook for the mapped type
<add> if ( special.postDispatch ) {
<add> special.postDispatch.call( this, event );
<add> }
<add>
<ide> return event.result;
<ide> },
<ide>
<ide> if ( !jQuery.support.submitBubbles ) {
<ide> form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
<ide> if ( form && !form._submit_attached ) {
<ide> jQuery.event.add( form, "submit._submit", function( event ) {
<del> // If form was submitted by the user, bubble the event up the tree
<del> if ( this.parentNode && !event.isTrigger ) {
<del> jQuery.event.simulate( "submit", this.parentNode, event, true );
<del> }
<add> event._submit_bubble = true;
<ide> });
<ide> form._submit_attached = true;
<ide> }
<ide> });
<ide> // return undefined since we don't need an event listener
<ide> },
<add>
<add> postDispatch: function( event ) {
<add> // If form was submitted by the user, bubble the event up the tree
<add> if ( event._submit_bubble ) {
<add> delete event._submit_bubble;
<add> if ( this.parentNode && !event.isTrigger ) {
<add> jQuery.event.simulate( "submit", this.parentNode, event, true );
<add> }
<add> }
<add> },
<ide>
<ide> teardown: function() {
<ide> // Only need this for delegated form submit events
<ide> jQuery.fn.extend({
<ide> // Types can be a map of types/handlers
<ide> if ( typeof types === "object" ) {
<ide> // ( types-Object, selector, data )
<del> if ( typeof selector !== "string" ) {
<add> if ( typeof selector !== "string" ) { // && selector != null
<ide> // ( types-Object, data )
<del> data = selector;
<add> data = data || selector;
<ide> selector = undefined;
<ide> }
<ide> for ( type in types ) {
<ide> jQuery.fn.extend({
<ide> });
<ide> },
<ide> one: function( types, selector, data, fn ) {
<del> return this.on.call( this, types, selector, data, fn, 1 );
<add> return this.on( types, selector, data, fn, 1 );
<ide> },
<ide> off: function( types, selector, fn ) {
<ide> if ( types && types.preventDefault && types.handleObj ) {
<ide> // ( event ) dispatched jQuery.Event
<ide> var handleObj = types.handleObj;
<ide> jQuery( types.delegateTarget ).off(
<del> handleObj.namespace? handleObj.type + "." + handleObj.namespace : handleObj.type,
<add> handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
<ide> handleObj.selector,
<ide> handleObj.handler
<ide> );
<ide> var Sizzle = function( selector, context, results, seed ) {
<ide> if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
<ide> return [];
<ide> }
<del>
<add>
<ide> if ( !selector || typeof selector !== "string" ) {
<ide> return results;
<ide> }
<ide> var Sizzle = function( selector, context, results, seed ) {
<ide> contextXML = Sizzle.isXML( context ),
<ide> parts = [],
<ide> soFar = selector;
<del>
<add>
<ide> // Reset the position of the chunker regexp (start from head)
<ide> do {
<ide> chunker.exec( "" );
<ide> m = chunker.exec( soFar );
<ide>
<ide> if ( m ) {
<ide> soFar = m[3];
<del>
<add>
<ide> parts.push( m[1] );
<del>
<add>
<ide> if ( m[2] ) {
<ide> extra = m[3];
<ide> break;
<ide> var Sizzle = function( selector, context, results, seed ) {
<ide> if ( Expr.relative[ selector ] ) {
<ide> selector += parts.shift();
<ide> }
<del>
<add>
<ide> set = posProcess( selector, set, seed );
<ide> }
<ide> }
<ide> Sizzle.find = function( expr, context, isXML ) {
<ide>
<ide> for ( i = 0, len = Expr.order.length; i < len; i++ ) {
<ide> type = Expr.order[i];
<del>
<add>
<ide> if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
<ide> left = match[1];
<ide> match.splice( 1, 1 );
<ide> var getText = Sizzle.getText = function( elem ) {
<ide> ret = "";
<ide>
<ide> if ( nodeType ) {
<del> if ( nodeType === 1 || nodeType === 9 ) {
<add> if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
<ide> // Use textContent || innerText for elements
<ide> if ( typeof elem.textContent === 'string' ) {
<ide> return elem.textContent;
<ide> var Expr = Sizzle.selectors = {
<ide>
<ide> ATTR: function( match, curLoop, inplace, result, not, isXML ) {
<ide> var name = match[1] = match[1].replace( rBackslash, "" );
<del>
<add>
<ide> if ( !isXML && Expr.attrMap[name] ) {
<ide> match[1] = Expr.attrMap[name];
<ide> }
<ide> var Expr = Sizzle.selectors = {
<ide> } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
<ide> return true;
<ide> }
<del>
<add>
<ide> return match;
<ide> },
<ide>
<ide> var Expr = Sizzle.selectors = {
<ide> return match;
<ide> }
<ide> },
<del>
<add>
<ide> filters: {
<ide> enabled: function( elem ) {
<ide> return elem.disabled === false && elem.type !== "hidden";
<ide> var Expr = Sizzle.selectors = {
<ide> checked: function( elem ) {
<ide> return elem.checked === true;
<ide> },
<del>
<add>
<ide> selected: function( elem ) {
<ide> // Accessing this property makes selected-by-default
<ide> // options in Safari work properly
<ide> if ( elem.parentNode ) {
<ide> elem.parentNode.selectedIndex;
<ide> }
<del>
<add>
<ide> return elem.selected === true;
<ide> },
<ide>
<ide> var Expr = Sizzle.selectors = {
<ide>
<ide> text: function( elem ) {
<ide> var attr = elem.getAttribute( "type" ), type = elem.type;
<del> // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
<add> // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
<ide> // use getAttribute instead to test this case
<ide> return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null );
<ide> },
<ide> var Expr = Sizzle.selectors = {
<ide> switch ( type ) {
<ide> case "only":
<ide> case "first":
<del> while ( (node = node.previousSibling) ) {
<del> if ( node.nodeType === 1 ) {
<del> return false;
<add> while ( (node = node.previousSibling) ) {
<add> if ( node.nodeType === 1 ) {
<add> return false;
<ide> }
<ide> }
<ide>
<del> if ( type === "first" ) {
<del> return true;
<add> if ( type === "first" ) {
<add> return true;
<ide> }
<ide>
<ide> node = elem;
<ide>
<add> /* falls through */
<ide> case "last":
<del> while ( (node = node.nextSibling) ) {
<del> if ( node.nodeType === 1 ) {
<del> return false;
<add> while ( (node = node.nextSibling) ) {
<add> if ( node.nodeType === 1 ) {
<add> return false;
<ide> }
<ide> }
<ide>
<ide> var Expr = Sizzle.selectors = {
<ide> if ( first === 1 && last === 0 ) {
<ide> return true;
<ide> }
<del>
<add>
<ide> doneName = match[0];
<ide> parent = elem.parentNode;
<del>
<add>
<ide> if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) {
<ide> count = 0;
<del>
<add>
<ide> for ( node = parent.firstChild; node; node = node.nextSibling ) {
<ide> if ( node.nodeType === 1 ) {
<ide> node.nodeIndex = ++count;
<ide> }
<del> }
<add> }
<ide>
<ide> parent[ expando ] = doneName;
<ide> }
<del>
<add>
<ide> diff = elem.nodeIndex - last;
<ide>
<ide> if ( first === 0 ) {
<ide> var Expr = Sizzle.selectors = {
<ide> TAG: function( elem, match ) {
<ide> return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match;
<ide> },
<del>
<add>
<ide> CLASS: function( elem, match ) {
<ide> return (" " + (elem.className || elem.getAttribute("class")) + " ")
<ide> .indexOf( match ) > -1;
<ide> for ( var type in Expr.match ) {
<ide> Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
<ide> Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
<ide> }
<add>// Expose origPOS
<add>// "global" as in regardless of relation to brackets/parens
<add>Expr.match.globalPOS = origPOS;
<ide>
<ide> var makeArray = function( array, results ) {
<ide> array = Array.prototype.slice.call( array, 0 );
<ide> var makeArray = function( array, results ) {
<ide> results.push.apply( results, array );
<ide> return results;
<ide> }
<del>
<add>
<ide> return array;
<ide> };
<ide>
<ide> if ( document.querySelectorAll ) {
<ide> if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
<ide> return;
<ide> }
<del>
<add>
<ide> Sizzle = function( query, context, extra, seed ) {
<ide> context = context || document;
<ide>
<ide> if ( document.querySelectorAll ) {
<ide> if ( !seed && !Sizzle.isXML(context) ) {
<ide> // See if we find a selector to speed up
<ide> var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
<del>
<add>
<ide> if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
<ide> // Speed-up: Sizzle("TAG")
<ide> if ( match[1] ) {
<ide> return makeArray( context.getElementsByTagName( query ), extra );
<del>
<add>
<ide> // Speed-up: Sizzle(".CLASS")
<ide> } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
<ide> return makeArray( context.getElementsByClassName( match[2] ), extra );
<ide> }
<ide> }
<del>
<add>
<ide> if ( context.nodeType === 9 ) {
<ide> // Speed-up: Sizzle("body")
<ide> // The body element only exists once, optimize finding it
<ide> if ( query === "body" && context.body ) {
<ide> return makeArray( [ context.body ], extra );
<del>
<add>
<ide> // Speed-up: Sizzle("#ID")
<ide> } else if ( match && match[3] ) {
<ide> var elem = context.getElementById( match[3] );
<ide> if ( document.querySelectorAll ) {
<ide> if ( elem.id === match[3] ) {
<ide> return makeArray( [ elem ], extra );
<ide> }
<del>
<add>
<ide> } else {
<ide> return makeArray( [], extra );
<ide> }
<ide> }
<del>
<add>
<ide> try {
<ide> return makeArray( context.querySelectorAll(query), extra );
<ide> } catch(qsaError) {}
<ide> if ( document.querySelectorAll ) {
<ide> }
<ide> }
<ide> }
<del>
<add>
<ide> return oldSizzle(query, context, extra, seed);
<ide> };
<ide>
<ide> if ( document.querySelectorAll ) {
<ide> // This should fail with an exception
<ide> // Gecko does not error, returns false instead
<ide> matches.call( document.documentElement, "[test!='']:sizzle" );
<del>
<add>
<ide> } catch( pseudoError ) {
<ide> pseudoWorks = true;
<ide> }
<ide> if ( document.querySelectorAll ) {
<ide> expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
<ide>
<ide> if ( !Sizzle.isXML( node ) ) {
<del> try {
<add> try {
<ide> if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
<ide> var ret = matches.call( node, expr );
<ide>
<ide> if ( document.querySelectorAll ) {
<ide> if ( div.getElementsByClassName("e").length === 1 ) {
<ide> return;
<ide> }
<del>
<add>
<ide> Expr.order.splice(1, 0, "CLASS");
<ide> Expr.find.CLASS = function( match, context, isXML ) {
<ide> if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
<ide> function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
<ide>
<ide> if ( elem ) {
<ide> var match = false;
<del>
<add>
<ide> elem = elem[dir];
<ide>
<ide> while ( elem ) {
<ide> if ( document.documentElement.contains ) {
<ide>
<ide> Sizzle.isXML = function( elem ) {
<ide> // documentElement is verified for cases where it doesn't yet exist
<del> // (such as loading iframes in IE - #4833)
<add> // (such as loading iframes in IE - #4833)
<ide> var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
<ide>
<ide> return documentElement ? documentElement.nodeName !== "HTML" : false;
<ide> var runtil = /Until$/,
<ide> rmultiselector = /,/,
<ide> isSimple = /^.[^:#\[\.,]*$/,
<ide> slice = Array.prototype.slice,
<del> POS = jQuery.expr.match.POS,
<add> POS = jQuery.expr.match.globalPOS,
<ide> // methods guaranteed to produce a unique set when starting from a unique set
<ide> guaranteedUnique = {
<ide> children: true,
<ide> jQuery.fn.extend({
<ide> },
<ide>
<ide> is: function( selector ) {
<del> return !!selector && (
<add> return !!selector && (
<ide> typeof selector === "string" ?
<ide> // If this is a positional selector, check membership in the returned set
<ide> // so $("p:first").is("p:last") won't return true for a doc with two "p".
<del> POS.test( selector ) ?
<add> POS.test( selector ) ?
<ide> jQuery( selector, this.context ).index( this[0] ) >= 0 :
<ide> jQuery.filter( selector, this ).length > 0 :
<ide> this.filter( selector ).length > 0 );
<ide> },
<ide>
<ide> closest: function( selectors, context ) {
<ide> var ret = [], i, l, cur = this[0];
<del>
<add>
<ide> // Array (deprecated as of jQuery 1.7)
<ide> if ( jQuery.isArray( selectors ) ) {
<ide> var level = 1;
<ide> jQuery.each({
<ide> return jQuery.dir( elem, "previousSibling", until );
<ide> },
<ide> siblings: function( elem ) {
<del> return jQuery.sibling( elem.parentNode.firstChild, elem );
<add> return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
<ide> },
<ide> children: function( elem ) {
<ide> return jQuery.sibling( elem.firstChild );
<ide> function createSafeFragment( document ) {
<ide> return safeFrag;
<ide> }
<ide>
<del>var nodeNames = "abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|" +
<add>var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
<ide> "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
<ide> rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
<ide> rleadingWhitespace = /^\s+/,
<ide> var nodeNames = "abbr|article|aside|audio|canvas|datalist|details|figcaption|fig
<ide> rhtml = /<|&#?\w+;/,
<ide> rnoInnerhtml = /<(?:script|style)/i,
<ide> rnocache = /<(?:script|object|embed|option|style)/i,
<del> rnoshimcache = new RegExp("<(?:" + nodeNames + ")", "i"),
<add> rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
<ide> // checked="checked" or checked
<ide> rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
<ide> rscriptType = /\/(java|ecma)script/i,
<ide> if ( !jQuery.support.htmlSerialize ) {
<ide> }
<ide>
<ide> jQuery.fn.extend({
<del> text: function( text ) {
<del> if ( jQuery.isFunction(text) ) {
<del> return this.each(function(i) {
<del> var self = jQuery( this );
<del>
<del> self.text( text.call(this, i, self.text()) );
<del> });
<del> }
<del>
<del> if ( typeof text !== "object" && text !== undefined ) {
<del> return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
<del> }
<del>
<del> return jQuery.text( this );
<add> text: function( value ) {
<add> return jQuery.access( this, function( value ) {
<add> return value === undefined ?
<add> jQuery.text( this ) :
<add> this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
<add> }, null, value, arguments.length );
<ide> },
<ide>
<ide> wrapAll: function( html ) {
<ide> jQuery.fn.extend({
<ide> },
<ide>
<ide> html: function( value ) {
<del> if ( value === undefined ) {
<del> return this[0] && this[0].nodeType === 1 ?
<del> this[0].innerHTML.replace(rinlinejQuery, "") :
<del> null;
<add> return jQuery.access( this, function( value ) {
<add> var elem = this[0] || {},
<add> i = 0,
<add> l = this.length;
<ide>
<del> // See if we can take a shortcut and just use innerHTML
<del> } else if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
<del> (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
<del> !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
<add> if ( value === undefined ) {
<add> return elem.nodeType === 1 ?
<add> elem.innerHTML.replace( rinlinejQuery, "" ) :
<add> null;
<add> }
<ide>
<del> value = value.replace(rxhtmlTag, "<$1></$2>");
<ide>
<del> try {
<del> for ( var i = 0, l = this.length; i < l; i++ ) {
<del> // Remove element nodes and prevent memory leaks
<del> if ( this[i].nodeType === 1 ) {
<del> jQuery.cleanData( this[i].getElementsByTagName("*") );
<del> this[i].innerHTML = value;
<del> }
<del> }
<add> if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
<add> ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
<add> !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
<ide>
<del> // If using innerHTML throws an exception, use the fallback method
<del> } catch(e) {
<del> this.empty().append( value );
<del> }
<add> value = value.replace( rxhtmlTag, "<$1></$2>" );
<ide>
<del> } else if ( jQuery.isFunction( value ) ) {
<del> this.each(function(i){
<del> var self = jQuery( this );
<add> try {
<add> for (; i < l; i++ ) {
<add> // Remove element nodes and prevent memory leaks
<add> elem = this[i] || {};
<add> if ( elem.nodeType === 1 ) {
<add> jQuery.cleanData( elem.getElementsByTagName( "*" ) );
<add> elem.innerHTML = value;
<add> }
<add> }
<ide>
<del> self.html( value.call(this, i, self.html()) );
<del> });
<add> elem = 0;
<ide>
<del> } else {
<del> this.empty().append( value );
<del> }
<add> // If using innerHTML throws an exception, use the fallback method
<add> } catch(e) {}
<add> }
<ide>
<del> return this;
<add> if ( elem ) {
<add> this.empty().append( value );
<add> }
<add> }, null, value, arguments.length );
<ide> },
<ide>
<ide> replaceWith: function( value ) {
<ide> jQuery.fn.extend({
<ide> }
<ide>
<ide> if ( scripts.length ) {
<del> jQuery.each( scripts, evalScript );
<add> jQuery.each( scripts, function( i, elem ) {
<add> if ( elem.src ) {
<add> jQuery.ajax({
<add> type: "GET",
<add> global: false,
<add> url: elem.src,
<add> async: false,
<add> dataType: "script"
<add> });
<add> } else {
<add> jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) );
<add> }
<add>
<add> if ( elem.parentNode ) {
<add> elem.parentNode.removeChild( elem );
<add> }
<add> });
<ide> }
<ide> }
<ide>
<ide> function cloneCopyEvent( src, dest ) {
<ide>
<ide> for ( type in events ) {
<ide> for ( i = 0, l = events[ type ].length; i < l; i++ ) {
<del> jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data );
<add> jQuery.event.add( dest, type, events[ type ][ i ] );
<ide> }
<ide> }
<ide> }
<ide> function cloneFixAttributes( src, dest ) {
<ide> // cloning other types of input fields
<ide> } else if ( nodeName === "input" || nodeName === "textarea" ) {
<ide> dest.defaultValue = src.defaultValue;
<add>
<add> // IE blanks contents when cloning scripts
<add> } else if ( nodeName === "script" && dest.text !== src.text ) {
<add> dest.text = src.text;
<ide> }
<ide>
<ide> // Event data gets referenced instead of copied if the expando
<ide> // gets copied too
<ide> dest.removeAttribute( jQuery.expando );
<add>
<add> // Clear flags for bubbling special change/submit events, they must
<add> // be reattached when the newly cloned events are first activated
<add> dest.removeAttribute( "_submit_attached" );
<add> dest.removeAttribute( "_change_attached" );
<ide> }
<ide>
<ide> jQuery.buildFragment = function( args, nodes, scripts ) {
<ide> jQuery.extend({
<ide> destElements,
<ide> i,
<ide> // IE<=8 does not properly clone detached, unknown element nodes
<del> clone = jQuery.support.html5Clone || !rnoshimcache.test( "<" + elem.nodeName ) ?
<add> clone = jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ?
<ide> elem.cloneNode( true ) :
<ide> shimCloneNode( elem );
<ide>
<ide> jQuery.extend({
<ide> },
<ide>
<ide> clean: function( elems, context, fragment, scripts ) {
<del> var checkScriptType;
<add> var checkScriptType, script, j,
<add> ret = [];
<ide>
<ide> context = context || document;
<ide>
<ide> jQuery.extend({
<ide> context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
<ide> }
<ide>
<del> var ret = [], j;
<del>
<ide> for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
<ide> if ( typeof elem === "number" ) {
<ide> elem += "";
<ide> jQuery.extend({
<ide> var tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(),
<ide> wrap = wrapMap[ tag ] || wrapMap._default,
<ide> depth = wrap[0],
<del> div = context.createElement("div");
<add> div = context.createElement("div"),
<add> safeChildNodes = safeFragment.childNodes,
<add> remove;
<ide>
<ide> // Append wrapper element to unknown element safe doc fragment
<ide> if ( context === document ) {
<ide> jQuery.extend({
<ide> }
<ide>
<ide> elem = div.childNodes;
<add>
<add> // Clear elements from DocumentFragment (safeFragment or otherwise)
<add> // to avoid hoarding elements. Fixes #11356
<add> if ( div ) {
<add> div.parentNode.removeChild( div );
<add>
<add> // Guard against -1 index exceptions in FF3.6
<add> if ( safeChildNodes.length > 0 ) {
<add> remove = safeChildNodes[ safeChildNodes.length - 1 ];
<add>
<add> if ( remove && remove.parentNode ) {
<add> remove.parentNode.removeChild( remove );
<add> }
<add> }
<add> }
<ide> }
<ide> }
<ide>
<ide> jQuery.extend({
<ide> return !elem.type || rscriptType.test( elem.type );
<ide> };
<ide> for ( i = 0; ret[i]; i++ ) {
<del> if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
<del> scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
<add> script = ret[i];
<add> if ( scripts && jQuery.nodeName( script, "script" ) && (!script.type || rscriptType.test( script.type )) ) {
<add> scripts.push( script.parentNode ? script.parentNode.removeChild( script ) : script );
<ide>
<ide> } else {
<del> if ( ret[i].nodeType === 1 ) {
<del> var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType );
<add> if ( script.nodeType === 1 ) {
<add> var jsTags = jQuery.grep( script.getElementsByTagName( "script" ), checkScriptType );
<ide>
<ide> ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
<ide> }
<del> fragment.appendChild( ret[i] );
<add> fragment.appendChild( script );
<ide> }
<ide> }
<ide> }
<ide> jQuery.extend({
<ide> }
<ide> });
<ide>
<del>function evalScript( i, elem ) {
<del> if ( elem.src ) {
<del> jQuery.ajax({
<del> url: elem.src,
<del> async: false,
<del> dataType: "script"
<del> });
<del> } else {
<del> jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) );
<del> }
<del>
<del> if ( elem.parentNode ) {
<del> elem.parentNode.removeChild( elem );
<del> }
<del>}
<del>
<ide>
<ide>
<ide>
<ide> var ralpha = /alpha\([^)]*\)/i,
<ide> ropacity = /opacity=([^)]*)/,
<ide> // fixed for IE9, see #8346
<ide> rupper = /([A-Z]|^ms)/g,
<del> rnumpx = /^-?\d+(?:px)?$/i,
<del> rnum = /^-?\d/,
<add> rnum = /^[\-+]?(?:\d*\.)?\d+$/i,
<add> rnumnonpx = /^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i,
<ide> rrelNum = /^([\-+])=([\-+.\de]+)/,
<add> rmargin = /^margin/,
<ide>
<ide> cssShow = { position: "absolute", visibility: "hidden", display: "block" },
<del> cssWidth = [ "Left", "Right" ],
<del> cssHeight = [ "Top", "Bottom" ],
<add>
<add> // order is important!
<add> cssExpand = [ "Top", "Right", "Bottom", "Left" ],
<add>
<ide> curCSS,
<ide>
<ide> getComputedStyle,
<ide> currentStyle;
<ide>
<ide> jQuery.fn.css = function( name, value ) {
<del> // Setting 'undefined' is a no-op
<del> if ( arguments.length === 2 && value === undefined ) {
<del> return this;
<del> }
<del>
<del> return jQuery.access( this, name, value, true, function( elem, name, value ) {
<add> return jQuery.access( this, function( elem, name, value ) {
<ide> return value !== undefined ?
<ide> jQuery.style( elem, name, value ) :
<ide> jQuery.css( elem, name );
<del> });
<add> }, name, value, arguments.length > 1 );
<ide> };
<ide>
<ide> jQuery.extend({
<ide> jQuery.extend({
<ide> get: function( elem, computed ) {
<ide> if ( computed ) {
<ide> // We should always get a number back from opacity
<del> var ret = curCSS( elem, "opacity", "opacity" );
<add> var ret = curCSS( elem, "opacity" );
<ide> return ret === "" ? "1" : ret;
<ide>
<ide> } else {
<ide> jQuery.extend({
<ide>
<ide> // A method for quickly swapping in/out CSS properties to get correct calculations
<ide> swap: function( elem, options, callback ) {
<del> var old = {};
<add> var old = {},
<add> ret, name;
<ide>
<ide> // Remember the old values, and insert the new ones
<del> for ( var name in options ) {
<add> for ( name in options ) {
<ide> old[ name ] = elem.style[ name ];
<ide> elem.style[ name ] = options[ name ];
<ide> }
<ide>
<del> callback.call( elem );
<add> ret = callback.call( elem );
<ide>
<ide> // Revert the old values
<ide> for ( name in options ) {
<ide> elem.style[ name ] = old[ name ];
<ide> }
<add>
<add> return ret;
<ide> }
<ide> });
<ide>
<del>// DEPRECATED, Use jQuery.css() instead
<add>// DEPRECATED in 1.3, Use jQuery.css() instead
<ide> jQuery.curCSS = jQuery.css;
<ide>
<del>jQuery.each(["height", "width"], function( i, name ) {
<del> jQuery.cssHooks[ name ] = {
<del> get: function( elem, computed, extra ) {
<del> var val;
<del>
<del> if ( computed ) {
<del> if ( elem.offsetWidth !== 0 ) {
<del> return getWH( elem, name, extra );
<del> } else {
<del> jQuery.swap( elem, cssShow, function() {
<del> val = getWH( elem, name, extra );
<del> });
<del> }
<del>
<del> return val;
<del> }
<del> },
<del>
<del> set: function( elem, value ) {
<del> if ( rnumpx.test( value ) ) {
<del> // ignore negative width and height values #1599
<del> value = parseFloat( value );
<del>
<del> if ( value >= 0 ) {
<del> return value + "px";
<del> }
<del>
<del> } else {
<del> return value;
<del> }
<del> }
<del> };
<del>});
<del>
<del>if ( !jQuery.support.opacity ) {
<del> jQuery.cssHooks.opacity = {
<del> get: function( elem, computed ) {
<del> // IE uses filters for opacity
<del> return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
<del> ( parseFloat( RegExp.$1 ) / 100 ) + "" :
<del> computed ? "1" : "";
<del> },
<del>
<del> set: function( elem, value ) {
<del> var style = elem.style,
<del> currentStyle = elem.currentStyle,
<del> opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
<del> filter = currentStyle && currentStyle.filter || style.filter || "";
<del>
<del> // IE has trouble with opacity if it does not have layout
<del> // Force it by setting the zoom level
<del> style.zoom = 1;
<del>
<del> // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
<del> if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) {
<del>
<del> // Setting style.filter to null, "" & " " still leave "filter:" in the cssText
<del> // if "filter:" is present at all, clearType is disabled, we want to avoid this
<del> // style.removeAttribute is IE Only, but so apparently is this code path...
<del> style.removeAttribute( "filter" );
<del>
<del> // if there there is no filter style applied in a css rule, we are done
<del> if ( currentStyle && !currentStyle.filter ) {
<del> return;
<del> }
<del> }
<del>
<del> // otherwise, set new filter values
<del> style.filter = ralpha.test( filter ) ?
<del> filter.replace( ralpha, opacity ) :
<del> filter + " " + opacity;
<del> }
<del> };
<del>}
<del>
<del>jQuery(function() {
<del> // This hook cannot be added until DOM ready because the support test
<del> // for it is not run until after DOM ready
<del> if ( !jQuery.support.reliableMarginRight ) {
<del> jQuery.cssHooks.marginRight = {
<del> get: function( elem, computed ) {
<del> // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
<del> // Work around by temporarily setting element display to inline-block
<del> var ret;
<del> jQuery.swap( elem, { "display": "inline-block" }, function() {
<del> if ( computed ) {
<del> ret = curCSS( elem, "margin-right", "marginRight" );
<del> } else {
<del> ret = elem.style.marginRight;
<del> }
<del> });
<del> return ret;
<del> }
<del> };
<del> }
<del>});
<del>
<ide> if ( document.defaultView && document.defaultView.getComputedStyle ) {
<ide> getComputedStyle = function( elem, name ) {
<del> var ret, defaultView, computedStyle;
<add> var ret, defaultView, computedStyle, width,
<add> style = elem.style;
<ide>
<ide> name = name.replace( rupper, "-$1" ).toLowerCase();
<ide>
<ide> if ( (defaultView = elem.ownerDocument.defaultView) &&
<ide> (computedStyle = defaultView.getComputedStyle( elem, null )) ) {
<add>
<ide> ret = computedStyle.getPropertyValue( name );
<ide> if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
<ide> ret = jQuery.style( elem, name );
<ide> }
<ide> }
<ide>
<add> // A tribute to the "awesome hack by Dean Edwards"
<add> // WebKit uses "computed value (percentage if specified)" instead of "used value" for margins
<add> // which is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
<add> if ( !jQuery.support.pixelMargin && computedStyle && rmargin.test( name ) && rnumnonpx.test( ret ) ) {
<add> width = style.width;
<add> style.width = ret;
<add> ret = computedStyle.width;
<add> style.width = width;
<add> }
<add>
<ide> return ret;
<ide> };
<ide> }
<ide> if ( document.documentElement.currentStyle ) {
<ide>
<ide> // Avoid setting ret to empty string here
<ide> // so we don't default to auto
<del> if ( ret === null && style && (uncomputed = style[ name ]) ) {
<add> if ( ret == null && style && (uncomputed = style[ name ]) ) {
<ide> ret = uncomputed;
<ide> }
<ide>
<ide> if ( document.documentElement.currentStyle ) {
<ide>
<ide> // If we're not dealing with a regular pixel number
<ide> // but a number that has a weird ending, we need to convert it to pixels
<del> if ( !rnumpx.test( ret ) && rnum.test( ret ) ) {
<add> if ( rnumnonpx.test( ret ) ) {
<ide>
<ide> // Remember the original values
<ide> left = style.left;
<ide> if ( document.documentElement.currentStyle ) {
<ide> if ( rsLeft ) {
<ide> elem.runtimeStyle.left = elem.currentStyle.left;
<ide> }
<del> style.left = name === "fontSize" ? "1em" : ( ret || 0 );
<add> style.left = name === "fontSize" ? "1em" : ret;
<ide> ret = style.pixelLeft + "px";
<ide>
<ide> // Revert the changed values
<ide> if ( document.documentElement.currentStyle ) {
<ide>
<ide> curCSS = getComputedStyle || currentStyle;
<ide>
<del>function getWH( elem, name, extra ) {
<add>function getWidthOrHeight( elem, name, extra ) {
<ide>
<ide> // Start with offset property
<ide> var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
<del> which = name === "width" ? cssWidth : cssHeight,
<del> i = 0,
<del> len = which.length;
<add> i = name === "width" ? 1 : 0,
<add> len = 4;
<ide>
<ide> if ( val > 0 ) {
<ide> if ( extra !== "border" ) {
<del> for ( ; i < len; i++ ) {
<add> for ( ; i < len; i += 2 ) {
<ide> if ( !extra ) {
<del> val -= parseFloat( jQuery.css( elem, "padding" + which[ i ] ) ) || 0;
<add> val -= parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0;
<ide> }
<ide> if ( extra === "margin" ) {
<del> val += parseFloat( jQuery.css( elem, extra + which[ i ] ) ) || 0;
<add> val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ] ) ) || 0;
<ide> } else {
<del> val -= parseFloat( jQuery.css( elem, "border" + which[ i ] + "Width" ) ) || 0;
<add> val -= parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
<ide> }
<ide> }
<ide> }
<ide> function getWH( elem, name, extra ) {
<ide> }
<ide>
<ide> // Fall back to computed then uncomputed css if necessary
<del> val = curCSS( elem, name, name );
<add> val = curCSS( elem, name );
<ide> if ( val < 0 || val == null ) {
<del> val = elem.style[ name ] || 0;
<add> val = elem.style[ name ];
<ide> }
<add>
<add> // Computed unit is not pixels. Stop here and return.
<add> if ( rnumnonpx.test(val) ) {
<add> return val;
<add> }
<add>
<ide> // Normalize "", auto, and prepare for extra
<ide> val = parseFloat( val ) || 0;
<ide>
<ide> // Add padding, border, margin
<ide> if ( extra ) {
<del> for ( ; i < len; i++ ) {
<del> val += parseFloat( jQuery.css( elem, "padding" + which[ i ] ) ) || 0;
<add> for ( ; i < len; i += 2 ) {
<add> val += parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0;
<ide> if ( extra !== "padding" ) {
<del> val += parseFloat( jQuery.css( elem, "border" + which[ i ] + "Width" ) ) || 0;
<add> val += parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
<ide> }
<ide> if ( extra === "margin" ) {
<del> val += parseFloat( jQuery.css( elem, extra + which[ i ] ) ) || 0;
<add> val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ]) ) || 0;
<ide> }
<ide> }
<ide> }
<ide>
<ide> return val + "px";
<ide> }
<ide>
<add>jQuery.each([ "height", "width" ], function( i, name ) {
<add> jQuery.cssHooks[ name ] = {
<add> get: function( elem, computed, extra ) {
<add> if ( computed ) {
<add> if ( elem.offsetWidth !== 0 ) {
<add> return getWidthOrHeight( elem, name, extra );
<add> } else {
<add> return jQuery.swap( elem, cssShow, function() {
<add> return getWidthOrHeight( elem, name, extra );
<add> });
<add> }
<add> }
<add> },
<add>
<add> set: function( elem, value ) {
<add> return rnum.test( value ) ?
<add> value + "px" :
<add> value;
<add> }
<add> };
<add>});
<add>
<add>if ( !jQuery.support.opacity ) {
<add> jQuery.cssHooks.opacity = {
<add> get: function( elem, computed ) {
<add> // IE uses filters for opacity
<add> return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
<add> ( parseFloat( RegExp.$1 ) / 100 ) + "" :
<add> computed ? "1" : "";
<add> },
<add>
<add> set: function( elem, value ) {
<add> var style = elem.style,
<add> currentStyle = elem.currentStyle,
<add> opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
<add> filter = currentStyle && currentStyle.filter || style.filter || "";
<add>
<add> // IE has trouble with opacity if it does not have layout
<add> // Force it by setting the zoom level
<add> style.zoom = 1;
<add>
<add> // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
<add> if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) {
<add>
<add> // Setting style.filter to null, "" & " " still leave "filter:" in the cssText
<add> // if "filter:" is present at all, clearType is disabled, we want to avoid this
<add> // style.removeAttribute is IE Only, but so apparently is this code path...
<add> style.removeAttribute( "filter" );
<add>
<add> // if there there is no filter style applied in a css rule, we are done
<add> if ( currentStyle && !currentStyle.filter ) {
<add> return;
<add> }
<add> }
<add>
<add> // otherwise, set new filter values
<add> style.filter = ralpha.test( filter ) ?
<add> filter.replace( ralpha, opacity ) :
<add> filter + " " + opacity;
<add> }
<add> };
<add>}
<add>
<add>jQuery(function() {
<add> // This hook cannot be added until DOM ready because the support test
<add> // for it is not run until after DOM ready
<add> if ( !jQuery.support.reliableMarginRight ) {
<add> jQuery.cssHooks.marginRight = {
<add> get: function( elem, computed ) {
<add> // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
<add> // Work around by temporarily setting element display to inline-block
<add> return jQuery.swap( elem, { "display": "inline-block" }, function() {
<add> if ( computed ) {
<add> return curCSS( elem, "margin-right" );
<add> } else {
<add> return elem.style.marginRight;
<add> }
<add> });
<add> }
<add> };
<add> }
<add>});
<add>
<ide> if ( jQuery.expr && jQuery.expr.filters ) {
<ide> jQuery.expr.filters.hidden = function( elem ) {
<ide> var width = elem.offsetWidth,
<ide> if ( jQuery.expr && jQuery.expr.filters ) {
<ide> };
<ide> }
<ide>
<add>// These hooks are used by animate to expand properties
<add>jQuery.each({
<add> margin: "",
<add> padding: "",
<add> border: "Width"
<add>}, function( prefix, suffix ) {
<add>
<add> jQuery.cssHooks[ prefix + suffix ] = {
<add> expand: function( value ) {
<add> var i,
<add>
<add> // assumes a single number if not a string
<add> parts = typeof value === "string" ? value.split(" ") : [ value ],
<add> expanded = {};
<add>
<add> for ( i = 0; i < 4; i++ ) {
<add> expanded[ prefix + cssExpand[ i ] + suffix ] =
<add> parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
<add> }
<add>
<add> return expanded;
<add> }
<add> };
<add>});
<add>
<ide>
<ide>
<ide>
<ide> jQuery.extend({
<ide> isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
<ide> global: true,
<ide> type: "GET",
<del> contentType: "application/x-www-form-urlencoded",
<add> contentType: "application/x-www-form-urlencoded; charset=UTF-8",
<ide> processData: true,
<ide> async: true,
<ide> /*
<ide> jQuery.extend({
<ide> // Apply prefilters
<ide> inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
<ide>
<del> // If request was aborted inside a prefiler, stop there
<add> // If request was aborted inside a prefilter, stop there
<ide> if ( state === 2 ) {
<ide> return false;
<ide> }
<ide> function buildParams( prefix, obj, traditional, add ) {
<ide> // a server error. Possible fixes are to modify rack's
<ide> // deserialization algorithm or to provide an option or flag
<ide> // to force array serialization to be shallow.
<del> buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
<add> buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
<ide> }
<ide> });
<ide>
<del> } else if ( !traditional && obj != null && typeof obj === "object" ) {
<add> } else if ( !traditional && jQuery.type( obj ) === "object" ) {
<ide> // Serialize object item.
<ide> for ( var name in obj ) {
<ide> buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
<ide> jQuery.ajaxSetup({
<ide> // Detect, normalize options and install callbacks for jsonp requests
<ide> jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
<ide>
<del> var inspectData = s.contentType === "application/x-www-form-urlencoded" &&
<del> ( typeof s.data === "string" );
<add> var inspectData = ( typeof s.data === "string" ) && /^application\/x\-www\-form\-urlencoded/.test( s.contentType );
<ide>
<ide> if ( s.dataTypes[ 0 ] === "jsonp" ||
<ide> s.jsonp !== false && ( jsre.test( s.url ) ||
<ide> if ( jQuery.support.ajax ) {
<ide> if ( xml && xml.documentElement /* #4958 */ ) {
<ide> responses.xml = xml;
<ide> }
<del> responses.text = xhr.responseText;
<add>
<add> // When requesting binary data, IE6-9 will throw an exception
<add> // on any attempt to access responseText (#11426)
<add> try {
<add> responses.text = xhr.responseText;
<add> } catch( _ ) {
<add> }
<ide>
<ide> // Firefox throws an exception when accessing
<ide> // statusText for faulty cross-domain requests
<ide> jQuery.fn.extend({
<ide> // Set elements which have been overridden with display: none
<ide> // in a stylesheet to whatever the default browser style is
<ide> // for such an element
<del> if ( display === "" && jQuery.css(elem, "display") === "none" ) {
<add> if ( (display === "" && jQuery.css(elem, "display") === "none") ||
<add> !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
<ide> jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) );
<ide> }
<ide> }
<ide> jQuery.fn.extend({
<ide> var opt = jQuery.extend( {}, optall ),
<ide> isElement = this.nodeType === 1,
<ide> hidden = isElement && jQuery(this).is(":hidden"),
<del> name, val, p, e,
<add> name, val, p, e, hooks, replace,
<ide> parts, start, end, unit,
<ide> method;
<ide>
<ide> // will store per property easing and be used to determine when an animation is complete
<ide> opt.animatedProperties = {};
<ide>
<add> // first pass over propertys to expand / normalize
<ide> for ( p in prop ) {
<del>
<del> // property name normalization
<ide> name = jQuery.camelCase( p );
<ide> if ( p !== name ) {
<ide> prop[ name ] = prop[ p ];
<ide> delete prop[ p ];
<ide> }
<ide>
<del> val = prop[ name ];
<add> if ( ( hooks = jQuery.cssHooks[ name ] ) && "expand" in hooks ) {
<add> replace = hooks.expand( prop[ name ] );
<add> delete prop[ name ];
<ide>
<add> // not quite $.extend, this wont overwrite keys already present.
<add> // also - reusing 'p' from above because we have the correct "name"
<add> for ( p in replace ) {
<add> if ( ! ( p in prop ) ) {
<add> prop[ p ] = replace[ p ];
<add> }
<add> }
<add> }
<add> }
<add>
<add> for ( name in prop ) {
<add> val = prop[ name ];
<ide> // easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
<ide> if ( jQuery.isArray( val ) ) {
<ide> opt.animatedProperties[ name ] = val[ 1 ];
<ide> jQuery.extend({
<ide> },
<ide>
<ide> easing: {
<del> linear: function( p, n, firstNum, diff ) {
<del> return firstNum + diff * p;
<add> linear: function( p ) {
<add> return p;
<ide> },
<del> swing: function( p, n, firstNum, diff ) {
<del> return ( ( -Math.cos( p*Math.PI ) / 2 ) + 0.5 ) * diff + firstNum;
<add> swing: function( p ) {
<add> return ( -Math.cos( p*Math.PI ) / 2 ) + 0.5;
<ide> }
<ide> },
<ide>
<ide> jQuery.fx.prototype = {
<ide> t.queue = this.options.queue;
<ide> t.elem = this.elem;
<ide> t.saveState = function() {
<del> if ( self.options.hide && jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) {
<del> jQuery._data( self.elem, "fxshow" + self.prop, self.start );
<add> if ( jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) {
<add> if ( self.options.hide ) {
<add> jQuery._data( self.elem, "fxshow" + self.prop, self.start );
<add> } else if ( self.options.show ) {
<add> jQuery._data( self.elem, "fxshow" + self.prop, self.end );
<add> }
<ide> }
<ide> };
<ide>
<ide> jQuery.extend( jQuery.fx, {
<ide> }
<ide> });
<ide>
<del>// Adds width/height step functions
<del>// Do not set anything below 0
<del>jQuery.each([ "width", "height" ], function( i, prop ) {
<del> jQuery.fx.step[ prop ] = function( fx ) {
<del> jQuery.style( fx.elem, prop, Math.max(0, fx.now) + fx.unit );
<del> };
<add>// Ensure props that can't be negative don't go there on undershoot easing
<add>jQuery.each( fxAttrs.concat.apply( [], fxAttrs ), function( i, prop ) {
<add> // exclude marginTop, marginLeft, marginBottom and marginRight from this list
<add> if ( prop.indexOf( "margin" ) ) {
<add> jQuery.fx.step[ prop ] = function( fx ) {
<add> jQuery.style( fx.elem, prop, Math.max(0, fx.now) + fx.unit );
<add> };
<add> }
<ide> });
<ide>
<ide> if ( jQuery.expr && jQuery.expr.filters ) {
<ide> function defaultDisplay( nodeName ) {
<ide> // document to it; WebKit & Firefox won't allow reusing the iframe document.
<ide> if ( !iframeDoc || !iframe.createElement ) {
<ide> iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
<del> iframeDoc.write( ( document.compatMode === "CSS1Compat" ? "<!doctype html>" : "" ) + "<html><body>" );
<add> iframeDoc.write( ( jQuery.support.boxModel ? "<!doctype html>" : "" ) + "<html><body>" );
<ide> iframeDoc.close();
<ide> }
<ide>
<ide> function defaultDisplay( nodeName ) {
<ide>
<ide>
<ide>
<del>var rtable = /^t(?:able|d|h)$/i,
<add>var getOffset,
<add> rtable = /^t(?:able|d|h)$/i,
<ide> rroot = /^(?:body|html)$/i;
<ide>
<ide> if ( "getBoundingClientRect" in document.documentElement ) {
<del> jQuery.fn.offset = function( options ) {
<del> var elem = this[0], box;
<del>
<del> if ( options ) {
<del> return this.each(function( i ) {
<del> jQuery.offset.setOffset( this, options, i );
<del> });
<del> }
<del>
<del> if ( !elem || !elem.ownerDocument ) {
<del> return null;
<del> }
<del>
<del> if ( elem === elem.ownerDocument.body ) {
<del> return jQuery.offset.bodyOffset( elem );
<del> }
<del>
<add> getOffset = function( elem, doc, docElem, box ) {
<ide> try {
<ide> box = elem.getBoundingClientRect();
<ide> } catch(e) {}
<ide>
<del> var doc = elem.ownerDocument,
<del> docElem = doc.documentElement;
<del>
<ide> // Make sure we're not dealing with a disconnected DOM node
<ide> if ( !box || !jQuery.contains( docElem, elem ) ) {
<ide> return box ? { top: box.top, left: box.left } : { top: 0, left: 0 };
<ide> }
<ide>
<ide> var body = doc.body,
<del> win = getWindow(doc),
<add> win = getWindow( doc ),
<ide> clientTop = docElem.clientTop || body.clientTop || 0,
<ide> clientLeft = docElem.clientLeft || body.clientLeft || 0,
<ide> scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop,
<ide> if ( "getBoundingClientRect" in document.documentElement ) {
<ide> };
<ide>
<ide> } else {
<del> jQuery.fn.offset = function( options ) {
<del> var elem = this[0];
<del>
<del> if ( options ) {
<del> return this.each(function( i ) {
<del> jQuery.offset.setOffset( this, options, i );
<del> });
<del> }
<del>
<del> if ( !elem || !elem.ownerDocument ) {
<del> return null;
<del> }
<del>
<del> if ( elem === elem.ownerDocument.body ) {
<del> return jQuery.offset.bodyOffset( elem );
<del> }
<del>
<add> getOffset = function( elem, doc, docElem ) {
<ide> var computedStyle,
<ide> offsetParent = elem.offsetParent,
<ide> prevOffsetParent = elem,
<del> doc = elem.ownerDocument,
<del> docElem = doc.documentElement,
<ide> body = doc.body,
<ide> defaultView = doc.defaultView,
<ide> prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
<ide> if ( "getBoundingClientRect" in document.documentElement ) {
<ide> };
<ide> }
<ide>
<add>jQuery.fn.offset = function( options ) {
<add> if ( arguments.length ) {
<add> return options === undefined ?
<add> this :
<add> this.each(function( i ) {
<add> jQuery.offset.setOffset( this, options, i );
<add> });
<add> }
<add>
<add> var elem = this[0],
<add> doc = elem && elem.ownerDocument;
<add>
<add> if ( !doc ) {
<add> return null;
<add> }
<add>
<add> if ( elem === doc.body ) {
<add> return jQuery.offset.bodyOffset( elem );
<add> }
<add>
<add> return getOffset( elem, doc, doc.documentElement );
<add>};
<add>
<ide> jQuery.offset = {
<ide>
<ide> bodyOffset: function( body ) {
<ide> jQuery.fn.extend({
<ide>
<ide>
<ide> // Create scrollLeft and scrollTop methods
<del>jQuery.each( ["Left", "Top"], function( i, name ) {
<del> var method = "scroll" + name;
<add>jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
<add> var top = /Y/.test( prop );
<ide>
<ide> jQuery.fn[ method ] = function( val ) {
<del> var elem, win;
<add> return jQuery.access( this, function( elem, method, val ) {
<add> var win = getWindow( elem );
<ide>
<del> if ( val === undefined ) {
<del> elem = this[ 0 ];
<del>
<del> if ( !elem ) {
<del> return null;
<add> if ( val === undefined ) {
<add> return win ? (prop in win) ? win[ prop ] :
<add> jQuery.support.boxModel && win.document.documentElement[ method ] ||
<add> win.document.body[ method ] :
<add> elem[ method ];
<ide> }
<ide>
<del> win = getWindow( elem );
<del>
<del> // Return the scroll offset
<del> return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
<del> jQuery.support.boxModel && win.document.documentElement[ method ] ||
<del> win.document.body[ method ] :
<del> elem[ method ];
<del> }
<del>
<del> // Set the scroll offset
<del> return this.each(function() {
<del> win = getWindow( this );
<del>
<ide> if ( win ) {
<ide> win.scrollTo(
<del> !i ? val : jQuery( win ).scrollLeft(),
<del> i ? val : jQuery( win ).scrollTop()
<add> !top ? val : jQuery( win ).scrollLeft(),
<add> top ? val : jQuery( win ).scrollTop()
<ide> );
<ide>
<ide> } else {
<del> this[ method ] = val;
<add> elem[ method ] = val;
<ide> }
<del> });
<add> }, method, val, arguments.length, null );
<ide> };
<ide> });
<ide>
<ide> function getWindow( elem ) {
<ide>
<ide>
<ide> // Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods
<del>jQuery.each([ "Height", "Width" ], function( i, name ) {
<del>
<del> var type = name.toLowerCase();
<add>jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
<add> var clientProp = "client" + name,
<add> scrollProp = "scroll" + name,
<add> offsetProp = "offset" + name;
<ide>
<ide> // innerHeight and innerWidth
<ide> jQuery.fn[ "inner" + name ] = function() {
<ide> jQuery.each([ "Height", "Width" ], function( i, name ) {
<ide> null;
<ide> };
<ide>
<del> jQuery.fn[ type ] = function( size ) {
<del> // Get window width or height
<del> var elem = this[0];
<del> if ( !elem ) {
<del> return size == null ? null : this;
<del> }
<add> jQuery.fn[ type ] = function( value ) {
<add> return jQuery.access( this, function( elem, type, value ) {
<add> var doc, docElemProp, orig, ret;
<ide>
<del> if ( jQuery.isFunction( size ) ) {
<del> return this.each(function( i ) {
<del> var self = jQuery( this );
<del> self[ type ]( size.call( this, i, self[ type ]() ) );
<del> });
<del> }
<add> if ( jQuery.isWindow( elem ) ) {
<add> // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
<add> doc = elem.document;
<add> docElemProp = doc.documentElement[ clientProp ];
<add> return jQuery.support.boxModel && docElemProp ||
<add> doc.body && doc.body[ clientProp ] || docElemProp;
<add> }
<ide>
<del> if ( jQuery.isWindow( elem ) ) {
<del> // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
<del> // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
<del> var docElemProp = elem.document.documentElement[ "client" + name ],
<del> body = elem.document.body;
<del> return elem.document.compatMode === "CSS1Compat" && docElemProp ||
<del> body && body[ "client" + name ] || docElemProp;
<del>
<del> // Get document width or height
<del> } else if ( elem.nodeType === 9 ) {
<del> // Either scroll[Width/Height] or offset[Width/Height], whichever is greater
<del> return Math.max(
<del> elem.documentElement["client" + name],
<del> elem.body["scroll" + name], elem.documentElement["scroll" + name],
<del> elem.body["offset" + name], elem.documentElement["offset" + name]
<del> );
<add> // Get document width or height
<add> if ( elem.nodeType === 9 ) {
<add> // Either scroll[Width/Height] or offset[Width/Height], whichever is greater
<add> doc = elem.documentElement;
<ide>
<del> // Get or set width or height on the element
<del> } else if ( size === undefined ) {
<del> var orig = jQuery.css( elem, type ),
<del> ret = parseFloat( orig );
<add> // when a window > document, IE6 reports a offset[Width/Height] > client[Width/Height]
<add> // so we can't use max, as it'll choose the incorrect offset[Width/Height]
<add> // instead we use the correct client[Width/Height]
<add> // support:IE6
<add> if ( doc[ clientProp ] >= doc[ scrollProp ] ) {
<add> return doc[ clientProp ];
<add> }
<add>
<add> return Math.max(
<add> elem.body[ scrollProp ], doc[ scrollProp ],
<add> elem.body[ offsetProp ], doc[ offsetProp ]
<add> );
<add> }
<ide>
<del> return jQuery.isNumeric( ret ) ? ret : orig;
<add> // Get width or height on the element
<add> if ( value === undefined ) {
<add> orig = jQuery.css( elem, type );
<add> ret = parseFloat( orig );
<add> return jQuery.isNumeric( ret ) ? ret : orig;
<add> }
<ide>
<del> // Set the width or height on the element (default to pixels if value is unitless)
<del> } else {
<del> return this.css( type, typeof size === "string" ? size : size + "px" );
<del> }
<add> // Set the width or height on the element
<add> jQuery( elem ).css( type, value );
<add> }, type, value, arguments.length, null );
<ide> };
<del>
<ide> });
<ide>
<ide> | 1 |
Python | Python | raise error for negative arc indices (closes ) | cc76a26fe815b400794964b383df4cd81f564f2f | <ide><path>spacy/displacy/render.py
<ide> from .templates import TPL_DEP_SVG, TPL_DEP_WORDS, TPL_DEP_ARCS, TPL_ENTS
<ide> from .templates import TPL_ENT, TPL_ENT_RTL, TPL_FIGURE, TPL_TITLE, TPL_PAGE
<ide> from ..util import minify_html, escape_html, get_entry_points
<add>from ..errors import Errors
<add>
<ide>
<ide> DEFAULT_LANG = "en"
<ide> DEFAULT_DIR = "ltr"
<ide> def render_arrow(self, label, start, end, direction, i):
<ide> i (int): Unique ID, typically arrow index.
<ide> RETURNS (unicode): Rendered SVG markup.
<ide> """
<add> if start < 0 or end < 0:
<add> error_args = dict(start=start, end=end, label=label, dir=direction)
<add> raise ValueError(Errors.E156.format(**error_args))
<ide> level = self.levels.index(end - start) + 1
<ide> x_start = self.offset_x + start * self.distance + self.arrow_spacing
<ide> if self.direction == "rtl":
<ide><path>spacy/errors.py
<ide> class Errors(object):
<ide> E154 = ("Either the `nlp` model or the `vocab` should be specified.")
<ide> E155 = ("The `nlp` object should have access to pre-trained word vectors, cf. "
<ide> "https://spacy.io/usage/models#languages.")
<add> E156 = ("Can't render negative values for dependency arc start or end. "
<add> "Make sure that you're passing in absolute token indices, not "
<add> "relative token offsets.\nstart: {start}, end: {end}, label: "
<add> "{label}, direction: {dir}")
<ide>
<ide>
<ide> @add_codes
<ide><path>spacy/tests/test_displacy.py
<ide>
<ide> import pytest
<ide> from spacy import displacy
<add>from spacy.displacy.render import DependencyRenderer
<ide> from spacy.tokens import Span
<ide> from spacy.lang.fa import Persian
<ide>
<ide> def test_displacy_parse_deps(en_vocab):
<ide> ]
<ide>
<ide>
<add>def test_displacy_invalid_arcs():
<add> renderer = DependencyRenderer()
<add> words = [{"text": "This", "tag": "DET"}, {"text": "is", "tag": "VERB"}]
<add> arcs = [
<add> {"start": 0, "end": 1, "label": "nsubj", "dir": "left"},
<add> {"start": -1, "end": 2, "label": "det", "dir": "left"},
<add> ]
<add> with pytest.raises(ValueError):
<add> renderer.render([{"words": words, "arcs": arcs}])
<add>
<add>
<ide> def test_displacy_spans(en_vocab):
<ide> """Test that displaCy can render Spans."""
<ide> doc = get_doc(en_vocab, words=["But", "Google", "is", "starting", "from", "behind"]) | 3 |
PHP | PHP | add second param | 1c75bf80888bbd5c76950395cbded1db5c6d607d | <ide><path>src/Illuminate/Foundation/Testing/TestResponse.php
<ide> public function assertExactJson(array $data)
<ide> * Assert that the response has a given JSON structure.
<ide> *
<ide> * @param array|null $structure
<add> * @param array|null $responseData
<ide> * @return $this
<ide> */
<del> public function assertJsonStructure(array $structure = null)
<add> public function assertJsonStructure(array $structure = null, $responseData = null)
<ide> {
<ide> if (is_null($structure)) {
<ide> return $this->assertJson();
<ide> }
<ide>
<del> $responseData = $this->decodeResponseJson();
<add> if (is_null($responseData)) {
<add> $responseData = $this->decodeResponseJson();
<add> }
<ide>
<ide> foreach ($structure as $key => $value) {
<ide> if (is_array($value) && $key === '*') { | 1 |
Go | Go | add fast path for userns | 67aa418df26f850be34b0536a3e32ba218d71bec | <ide><path>daemon/graphdriver/overlay2/check.go
<ide> import (
<ide> "path/filepath"
<ide> "syscall"
<ide>
<add> "github.com/containerd/containerd/sys"
<ide> "github.com/docker/docker/pkg/system"
<ide> "github.com/pkg/errors"
<ide> "golang.org/x/sys/unix"
<ide> import (
<ide> // which copies up the opaque flag when copying up an opaque
<ide> // directory or the kernel enable CONFIG_OVERLAY_FS_REDIRECT_DIR.
<ide> // When these exist naive diff should be used.
<add>//
<add>// When running in a user namespace, returns errRunningInUserNS
<add>// immediately.
<ide> func doesSupportNativeDiff(d string) error {
<add> if sys.RunningInUserNS() {
<add> return errors.New("running in a user namespace")
<add> }
<add>
<ide> td, err := ioutil.TempDir(d, "opaque-bug-check")
<ide> if err != nil {
<ide> return err | 1 |
Python | Python | move export_base.py to oss | 0d3cab0c998cba761aaa38c2c65fa11b1988c219 | <ide><path>official/core/export_base.py
<add># Copyright 2021 The TensorFlow Authors. All Rights Reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add>
<add>"""Base class for model export."""
<add>
<add>import abc
<add>import functools
<add>from typing import Any, Dict, List, Optional, Text, Union
<add>
<add>import tensorflow as tf
<add>from tensorflow.python.saved_model.model_utils import export_utils
<add>
<add>
<add># TODO(hongkuny): add unit tests.
<add>class ExportModule(tf.Module, metaclass=abc.ABCMeta):
<add> """Base Export Module."""
<add>
<add> def __init__(self, params, model: tf.keras.Model, inference_step=None):
<add> super().__init__(name=None)
<add> self.model = model
<add> self.params = params
<add>
<add> if inference_step is not None:
<add> self.inference_step = functools.partial(inference_step, model=self.model)
<add> else:
<add> self.inference_step = functools.partial(
<add> self.model.__call__, training=False)
<add>
<add> @abc.abstractmethod
<add> def serve(self) -> Dict[str, tf.Tensor]:
<add> """The bare inference function which should run on all devices.
<add>
<add> Expecting tensors are passed in through keyword arguments. Returns a
<add> dictionary of tensors, when the keys will be used inside the SignatureDef.
<add> """
<add>
<add> @abc.abstractmethod
<add> def get_inference_signatures(
<add> self, function_keys: Dict[Text, Text]) -> Dict[str, Any]:
<add> """Get defined function signatures."""
<add>
<add>
<add>def export(export_module: ExportModule,
<add> function_keys: Union[List[Text], Dict[Text, Text]],
<add> export_savedmodel_dir: Text,
<add> checkpoint_path: Optional[Text] = None,
<add> timestamped: bool = True,
<add> save_options: Optional[tf.saved_model.SaveOptions] = None) -> Text:
<add> """Exports to SavedModel format.
<add>
<add> Args:
<add> export_module: a ExportModule with the keras Model and serving tf.functions.
<add> function_keys: a list of string keys to retrieve pre-defined serving
<add> signatures. The signaute keys will be set with defaults. If a dictionary
<add> is provided, the values will be used as signature keys.
<add> export_savedmodel_dir: Output saved model directory.
<add> checkpoint_path: Object-based checkpoint path or directory.
<add> timestamped: Whether to export the savedmodel to a timestamped directory.
<add> save_options: `SaveOptions` for `tf.saved_model.save`.
<add>
<add> Returns:
<add> The savedmodel directory path.
<add> """
<add> ckpt_dir_or_file = checkpoint_path
<add> if tf.io.gfile.isdir(ckpt_dir_or_file):
<add> ckpt_dir_or_file = tf.train.latest_checkpoint(ckpt_dir_or_file)
<add> if ckpt_dir_or_file:
<add> checkpoint = tf.train.Checkpoint(model=export_module.model)
<add> checkpoint.read(
<add> ckpt_dir_or_file).assert_existing_objects_matched().expect_partial()
<add> if isinstance(function_keys, list):
<add> if len(function_keys) == 1:
<add> function_keys = {
<add> function_keys[0]: tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY
<add> }
<add> else:
<add> raise ValueError(
<add> "If the function_keys is a list, it must contain a single element. %s"
<add> % function_keys)
<add>
<add> signatures = export_module.get_inference_signatures(function_keys)
<add> if timestamped:
<add> export_dir = export_utils.get_timestamped_export_dir(
<add> export_savedmodel_dir).decode("utf-8")
<add> else:
<add> export_dir = export_savedmodel_dir
<add> tf.saved_model.save(
<add> export_module, export_dir, signatures=signatures, options=save_options)
<add> return export_dir | 1 |
Ruby | Ruby | remove thread hack for ruby 1.9 | a856b3dc2cf6715c96d117996994e3eb092eae59 | <ide><path>activerecord/test/cases/transactions_test.rb
<ide> def test_rollback_when_saving_a_frozen_record
<ide> assert topic.frozen?, 'not frozen'
<ide> end
<ide>
<del> # The behavior of killed threads having a status of "aborting" was changed
<del> # in Ruby 2.0, so Thread#kill on 1.9 will prematurely commit the transaction
<del> # and there's nothing we can do about it.
<del> if !RUBY_VERSION.start_with?('1.9') && !in_memory_db?
<del> def test_rollback_when_thread_killed
<del> queue = Queue.new
<del> thread = Thread.new do
<del> Topic.transaction do
<del> @first.approved = true
<del> @second.approved = false
<del> @first.save
<add> def test_rollback_when_thread_killed
<add> queue = Queue.new
<add> thread = Thread.new do
<add> Topic.transaction do
<add> @first.approved = true
<add> @second.approved = false
<add> @first.save
<ide>
<del> queue.push nil
<del> sleep
<add> queue.push nil
<add> sleep
<ide>
<del> @second.save
<del> end
<add> @second.save
<ide> end
<add> end
<ide>
<del> queue.pop
<del> thread.kill
<del> thread.join
<add> queue.pop
<add> thread.kill
<add> thread.join
<ide>
<del> assert @first.approved?, "First should still be changed in the objects"
<del> assert [email protected]?, "Second should still be changed in the objects"
<add> assert @first.approved?, "First should still be changed in the objects"
<add> assert [email protected]?, "Second should still be changed in the objects"
<ide>
<del> assert !Topic.find(1).approved?, "First shouldn't have been approved"
<del> assert Topic.find(2).approved?, "Second should still be approved"
<del> end
<add> assert !Topic.find(1).approved?, "First shouldn't have been approved"
<add> assert Topic.find(2).approved?, "Second should still be approved"
<ide> end
<ide>
<ide> def test_restore_active_record_state_for_all_records_in_a_transaction | 1 |
Python | Python | replace \t by whitespace for readability | 4f748ee310048c1b4c100cc155399fbc8e6ad98c | <ide><path>numpy/f2py/cb_rules.py
<ide> jmp_buf #name#_jmpbuf;
<ide> /*typedef #rctype#(*#name#_typedef)(#optargs_td##args_td##strarglens_td##noargs#);*/
<ide> #static# #rctype# #callbackname# (#optargs##args##strarglens##noargs#) {
<del>\tPyTupleObject *capi_arglist = #name#_args_capi;
<del>\tPyObject *capi_return = NULL;
<del>\tPyObject *capi_tmp = NULL;
<del>\tPyObject *capi_arglist_list = NULL;
<del>\tint capi_j,capi_i = 0;
<del>\tint capi_longjmp_ok = 1;
<add> PyTupleObject *capi_arglist = #name#_args_capi;
<add> PyObject *capi_return = NULL;
<add> PyObject *capi_tmp = NULL;
<add> PyObject *capi_arglist_list = NULL;
<add> int capi_j,capi_i = 0;
<add> int capi_longjmp_ok = 1;
<ide> #decl#
<ide> #ifdef F2PY_REPORT_ATEXIT
<ide> f2py_cb_start_clock();
<ide> #endif
<del>\tCFUNCSMESS(\"cb:Call-back function #name# (maxnofargs=#maxnofargs#(-#nofoptargs#))\\n\");
<del>\tCFUNCSMESSPY(\"cb:#name#_capi=\",#name#_capi);
<del>\tif (#name#_capi==NULL) {
<del>\t\tcapi_longjmp_ok = 0;
<del>\t\t#name#_capi = PyObject_GetAttrString(#modulename#_module,\"#argname#\");
<del>\t}
<del>\tif (#name#_capi==NULL) {
<del>\t\tPyErr_SetString(#modulename#_error,\"cb: Callback #argname# not defined (as an argument or module #modulename# attribute).\\n\");
<del>\t\tgoto capi_fail;
<del>\t}
<del>\tif (F2PyCapsule_Check(#name#_capi)) {
<del>\t#name#_typedef #name#_cptr;
<del>\t#name#_cptr = F2PyCapsule_AsVoidPtr(#name#_capi);
<del>\t#returncptr#(*#name#_cptr)(#optargs_nm##args_nm##strarglens_nm#);
<del>\t#return#
<del>\t}
<del>\tif (capi_arglist==NULL) {
<del>\t\tcapi_longjmp_ok = 0;
<del>\t\tcapi_tmp = PyObject_GetAttrString(#modulename#_module,\"#argname#_extra_args\");
<del>\t\tif (capi_tmp) {
<del>\t\t\tcapi_arglist = (PyTupleObject *)PySequence_Tuple(capi_tmp);
<del>\t\t\tif (capi_arglist==NULL) {
<del>\t\t\t\tPyErr_SetString(#modulename#_error,\"Failed to convert #modulename#.#argname#_extra_args to tuple.\\n\");
<del>\t\t\t\tgoto capi_fail;
<del>\t\t\t}
<del>\t\t} else {
<del>\t\t\tPyErr_Clear();
<del>\t\t\tcapi_arglist = (PyTupleObject *)Py_BuildValue(\"()\");
<del>\t\t}
<del>\t}
<del>\tif (capi_arglist == NULL) {
<del>\t\tPyErr_SetString(#modulename#_error,\"Callback #argname# argument list is not set.\\n\");
<del>\t\tgoto capi_fail;
<del>\t}
<add> CFUNCSMESS(\"cb:Call-back function #name# (maxnofargs=#maxnofargs#(-#nofoptargs#))\\n\");
<add> CFUNCSMESSPY(\"cb:#name#_capi=\",#name#_capi);
<add> if (#name#_capi==NULL) {
<add> capi_longjmp_ok = 0;
<add> #name#_capi = PyObject_GetAttrString(#modulename#_module,\"#argname#\");
<add> }
<add> if (#name#_capi==NULL) {
<add> PyErr_SetString(#modulename#_error,\"cb: Callback #argname# not defined (as an argument or module #modulename# attribute).\\n\");
<add> goto capi_fail;
<add> }
<add> if (F2PyCapsule_Check(#name#_capi)) {
<add> #name#_typedef #name#_cptr;
<add> #name#_cptr = F2PyCapsule_AsVoidPtr(#name#_capi);
<add> #returncptr#(*#name#_cptr)(#optargs_nm##args_nm##strarglens_nm#);
<add> #return#
<add> }
<add> if (capi_arglist==NULL) {
<add> capi_longjmp_ok = 0;
<add> capi_tmp = PyObject_GetAttrString(#modulename#_module,\"#argname#_extra_args\");
<add> if (capi_tmp) {
<add> capi_arglist = (PyTupleObject *)PySequence_Tuple(capi_tmp);
<add> if (capi_arglist==NULL) {
<add> PyErr_SetString(#modulename#_error,\"Failed to convert #modulename#.#argname#_extra_args to tuple.\\n\");
<add> goto capi_fail;
<add> }
<add> } else {
<add> PyErr_Clear();
<add> capi_arglist = (PyTupleObject *)Py_BuildValue(\"()\");
<add> }
<add> }
<add> if (capi_arglist == NULL) {
<add> PyErr_SetString(#modulename#_error,\"Callback #argname# argument list is not set.\\n\");
<add> goto capi_fail;
<add> }
<ide> #setdims#
<ide> #ifdef PYPY_VERSION
<ide> #define CAPI_ARGLIST_SETITEM(idx, value) PyList_SetItem((PyObject *)capi_arglist_list, idx, value)
<del>\tcapi_arglist_list = PySequence_List(capi_arglist);
<del>\tif (capi_arglist_list == NULL) goto capi_fail;
<add> capi_arglist_list = PySequence_List(capi_arglist);
<add> if (capi_arglist_list == NULL) goto capi_fail;
<ide> #else
<ide> #define CAPI_ARGLIST_SETITEM(idx, value) PyTuple_SetItem((PyObject *)capi_arglist, idx, value)
<ide> #endif
<ide> #pyobjfrom#
<ide> #undef CAPI_ARGLIST_SETITEM
<ide> #ifdef PYPY_VERSION
<del>\tCFUNCSMESSPY(\"cb:capi_arglist=\",capi_arglist_list);
<add> CFUNCSMESSPY(\"cb:capi_arglist=\",capi_arglist_list);
<ide> #else
<del>\tCFUNCSMESSPY(\"cb:capi_arglist=\",capi_arglist);
<add> CFUNCSMESSPY(\"cb:capi_arglist=\",capi_arglist);
<ide> #endif
<del>\tCFUNCSMESS(\"cb:Call-back calling Python function #argname#.\\n\");
<add> CFUNCSMESS(\"cb:Call-back calling Python function #argname#.\\n\");
<ide> #ifdef F2PY_REPORT_ATEXIT
<ide> f2py_cb_start_call_clock();
<ide> #endif
<ide> #ifdef PYPY_VERSION
<del>\tcapi_return = PyObject_CallObject(#name#_capi,(PyObject *)capi_arglist_list);
<del>\tPy_DECREF(capi_arglist_list);
<del>\tcapi_arglist_list = NULL;
<add> capi_return = PyObject_CallObject(#name#_capi,(PyObject *)capi_arglist_list);
<add> Py_DECREF(capi_arglist_list);
<add> capi_arglist_list = NULL;
<ide> #else
<del>\tcapi_return = PyObject_CallObject(#name#_capi,(PyObject *)capi_arglist);
<add> capi_return = PyObject_CallObject(#name#_capi,(PyObject *)capi_arglist);
<ide> #endif
<ide> #ifdef F2PY_REPORT_ATEXIT
<ide> f2py_cb_stop_call_clock();
<ide> #endif
<del>\tCFUNCSMESSPY(\"cb:capi_return=\",capi_return);
<del>\tif (capi_return == NULL) {
<del>\t\tfprintf(stderr,\"capi_return is NULL\\n\");
<del>\t\tgoto capi_fail;
<del>\t}
<del>\tif (capi_return == Py_None) {
<del>\t\tPy_DECREF(capi_return);
<del>\t\tcapi_return = Py_BuildValue(\"()\");
<del>\t}
<del>\telse if (!PyTuple_Check(capi_return)) {
<del>\t\tcapi_return = Py_BuildValue(\"(N)\",capi_return);
<del>\t}
<del>\tcapi_j = PyTuple_Size(capi_return);
<del>\tcapi_i = 0;
<add> CFUNCSMESSPY(\"cb:capi_return=\",capi_return);
<add> if (capi_return == NULL) {
<add> fprintf(stderr,\"capi_return is NULL\\n\");
<add> goto capi_fail;
<add> }
<add> if (capi_return == Py_None) {
<add> Py_DECREF(capi_return);
<add> capi_return = Py_BuildValue(\"()\");
<add> }
<add> else if (!PyTuple_Check(capi_return)) {
<add> capi_return = Py_BuildValue(\"(N)\",capi_return);
<add> }
<add> capi_j = PyTuple_Size(capi_return);
<add> capi_i = 0;
<ide> #frompyobj#
<del>\tCFUNCSMESS(\"cb:#name#:successful\\n\");
<del>\tPy_DECREF(capi_return);
<add> CFUNCSMESS(\"cb:#name#:successful\\n\");
<add> Py_DECREF(capi_return);
<ide> #ifdef F2PY_REPORT_ATEXIT
<ide> f2py_cb_stop_clock();
<ide> #endif
<del>\tgoto capi_return_pt;
<add> goto capi_return_pt;
<ide> capi_fail:
<del>\tfprintf(stderr,\"Call-back #name# failed.\\n\");
<del>\tPy_XDECREF(capi_return);
<del>\tPy_XDECREF(capi_arglist_list);
<del>\tif (capi_longjmp_ok)
<del>\t\tlongjmp(#name#_jmpbuf,-1);
<add> fprintf(stderr,\"Call-back #name# failed.\\n\");
<add> Py_XDECREF(capi_return);
<add> Py_XDECREF(capi_arglist_list);
<add> if (capi_longjmp_ok)
<add> longjmp(#name#_jmpbuf,-1);
<ide> capi_return_pt:
<del>\t;
<add> ;
<ide> #return#
<ide> }
<ide> #endtitle#
<ide> 'latexdocstrcbs': '\\noindent Call-back functions:',
<ide> 'routnote': {hasnote: '--- #note#', l_not(hasnote): ''},
<ide> }, { # Function
<del> 'decl': '\t#ctype# return_value;',
<del> 'frompyobj': [{debugcapi: '\tCFUNCSMESS("cb:Getting return_value->");'},
<del> '\tif (capi_j>capi_i)\n\t\tGETSCALARFROMPYTUPLE(capi_return,capi_i++,&return_value,#ctype#,"#ctype#_from_pyobj failed in converting return_value of call-back function #name# to C #ctype#\\n");',
<add> 'decl': ' #ctype# return_value;',
<add> 'frompyobj': [{debugcapi: ' CFUNCSMESS("cb:Getting return_value->");'},
<add> ' if (capi_j>capi_i)\n GETSCALARFROMPYTUPLE(capi_return,capi_i++,&return_value,#ctype#,"#ctype#_from_pyobj failed in converting return_value of call-back function #name# to C #ctype#\\n");',
<ide> {debugcapi:
<del> '\tfprintf(stderr,"#showvalueformat#.\\n",return_value);'}
<add> ' fprintf(stderr,"#showvalueformat#.\\n",return_value);'}
<ide> ],
<ide> 'need': ['#ctype#_from_pyobj', {debugcapi: 'CFUNCSMESS'}, 'GETSCALARFROMPYTUPLE'],
<del> 'return': '\treturn return_value;',
<add> 'return': ' return return_value;',
<ide> '_check': l_and(isfunction, l_not(isstringfunction), l_not(iscomplexfunction))
<ide> },
<ide> { # String function
<del> 'pyobjfrom': {debugcapi: '\tfprintf(stderr,"debug-capi:cb:#name#:%d:\\n",return_value_len);'},
<add> 'pyobjfrom': {debugcapi: ' fprintf(stderr,"debug-capi:cb:#name#:%d:\\n",return_value_len);'},
<ide> 'args': '#ctype# return_value,int return_value_len',
<ide> 'args_nm': 'return_value,&return_value_len',
<ide> 'args_td': '#ctype# ,int',
<del> 'frompyobj': [{debugcapi: '\tCFUNCSMESS("cb:Getting return_value->\\"");'},
<del> """\tif (capi_j>capi_i)
<del>\t\tGETSTRFROMPYTUPLE(capi_return,capi_i++,return_value,return_value_len);""",
<add> 'frompyobj': [{debugcapi: ' CFUNCSMESS("cb:Getting return_value->\\"");'},
<add> """ if (capi_j>capi_i)
<add> GETSTRFROMPYTUPLE(capi_return,capi_i++,return_value,return_value_len);""",
<ide> {debugcapi:
<del> '\tfprintf(stderr,"#showvalueformat#\\".\\n",return_value);'}
<add> ' fprintf(stderr,"#showvalueformat#\\".\\n",return_value);'}
<ide> ],
<ide> 'need': ['#ctype#_from_pyobj', {debugcapi: 'CFUNCSMESS'},
<ide> 'string.h', 'GETSTRFROMPYTUPLE'],
<ide> """,
<ide> 'decl': """
<ide> #ifdef F2PY_CB_RETURNCOMPLEX
<del>\t#ctype# return_value;
<add> #ctype# return_value;
<ide> #endif
<ide> """,
<del> 'frompyobj': [{debugcapi: '\tCFUNCSMESS("cb:Getting return_value->");'},
<add> 'frompyobj': [{debugcapi: ' CFUNCSMESS("cb:Getting return_value->");'},
<ide> """\
<del>\tif (capi_j>capi_i)
<add> if (capi_j>capi_i)
<ide> #ifdef F2PY_CB_RETURNCOMPLEX
<del>\t\tGETSCALARFROMPYTUPLE(capi_return,capi_i++,&return_value,#ctype#,\"#ctype#_from_pyobj failed in converting return_value of call-back function #name# to C #ctype#\\n\");
<add> GETSCALARFROMPYTUPLE(capi_return,capi_i++,&return_value,#ctype#,\"#ctype#_from_pyobj failed in converting return_value of call-back function #name# to C #ctype#\\n\");
<ide> #else
<del>\t\tGETSCALARFROMPYTUPLE(capi_return,capi_i++,return_value,#ctype#,\"#ctype#_from_pyobj failed in converting return_value of call-back function #name# to C #ctype#\\n\");
<add> GETSCALARFROMPYTUPLE(capi_return,capi_i++,return_value,#ctype#,\"#ctype#_from_pyobj failed in converting return_value of call-back function #name# to C #ctype#\\n\");
<ide> #endif
<ide> """,
<ide> {debugcapi: """
<ide> #ifdef F2PY_CB_RETURNCOMPLEX
<del>\tfprintf(stderr,\"#showvalueformat#.\\n\",(return_value).r,(return_value).i);
<add> fprintf(stderr,\"#showvalueformat#.\\n\",(return_value).r,(return_value).i);
<ide> #else
<del>\tfprintf(stderr,\"#showvalueformat#.\\n\",(*return_value).r,(*return_value).i);
<add> fprintf(stderr,\"#showvalueformat#.\\n\",(*return_value).r,(*return_value).i);
<ide> #endif
<ide>
<ide> """}
<ide> ],
<ide> 'return': """
<ide> #ifdef F2PY_CB_RETURNCOMPLEX
<del>\treturn return_value;
<add> return return_value;
<ide> #else
<del>\treturn;
<add> return;
<ide> #endif
<ide> """,
<ide> 'need': ['#ctype#_from_pyobj', {debugcapi: 'CFUNCSMESS'},
<ide> 'strarglens_nm': {isstring: ',#varname_i#_cb_len'},
<ide> },
<ide> { # Scalars
<del> 'decl': {l_not(isintent_c): '\t#ctype# #varname_i#=(*#varname_i#_cb_capi);'},
<add> 'decl': {l_not(isintent_c): ' #ctype# #varname_i#=(*#varname_i#_cb_capi);'},
<ide> 'error': {l_and(isintent_c, isintent_out,
<ide> throw_error('intent(c,out) is forbidden for callback scalar arguments')):
<ide> ''},
<del> 'frompyobj': [{debugcapi: '\tCFUNCSMESS("cb:Getting #varname#->");'},
<add> 'frompyobj': [{debugcapi: ' CFUNCSMESS("cb:Getting #varname#->");'},
<ide> {isintent_out:
<del> '\tif (capi_j>capi_i)\n\t\tGETSCALARFROMPYTUPLE(capi_return,capi_i++,#varname_i#_cb_capi,#ctype#,"#ctype#_from_pyobj failed in converting argument #varname# of call-back function #name# to C #ctype#\\n");'},
<add> ' if (capi_j>capi_i)\n GETSCALARFROMPYTUPLE(capi_return,capi_i++,#varname_i#_cb_capi,#ctype#,"#ctype#_from_pyobj failed in converting argument #varname# of call-back function #name# to C #ctype#\\n");'},
<ide> {l_and(debugcapi, l_and(l_not(iscomplex), isintent_c)):
<del> '\tfprintf(stderr,"#showvalueformat#.\\n",#varname_i#);'},
<add> ' fprintf(stderr,"#showvalueformat#.\\n",#varname_i#);'},
<ide> {l_and(debugcapi, l_and(l_not(iscomplex), l_not( isintent_c))):
<del> '\tfprintf(stderr,"#showvalueformat#.\\n",*#varname_i#_cb_capi);'},
<add> ' fprintf(stderr,"#showvalueformat#.\\n",*#varname_i#_cb_capi);'},
<ide> {l_and(debugcapi, l_and(iscomplex, isintent_c)):
<del> '\tfprintf(stderr,"#showvalueformat#.\\n",(#varname_i#).r,(#varname_i#).i);'},
<add> ' fprintf(stderr,"#showvalueformat#.\\n",(#varname_i#).r,(#varname_i#).i);'},
<ide> {l_and(debugcapi, l_and(iscomplex, l_not( isintent_c))):
<del> '\tfprintf(stderr,"#showvalueformat#.\\n",(*#varname_i#_cb_capi).r,(*#varname_i#_cb_capi).i);'},
<add> ' fprintf(stderr,"#showvalueformat#.\\n",(*#varname_i#_cb_capi).r,(*#varname_i#_cb_capi).i);'},
<ide> ],
<ide> 'need': [{isintent_out: ['#ctype#_from_pyobj', 'GETSCALARFROMPYTUPLE']},
<ide> {debugcapi: 'CFUNCSMESS'}],
<ide> '_check': isscalar
<ide> }, {
<ide> 'pyobjfrom': [{isintent_in: """\
<del>\tif (#name#_nofargs>capi_i)
<del>\t\tif (CAPI_ARGLIST_SETITEM(capi_i++,pyobj_from_#ctype#1(#varname_i#)))
<del>\t\t\tgoto capi_fail;"""},
<add> if (#name#_nofargs>capi_i)
<add> if (CAPI_ARGLIST_SETITEM(capi_i++,pyobj_from_#ctype#1(#varname_i#)))
<add> goto capi_fail;"""},
<ide> {isintent_inout: """\
<del>\tif (#name#_nofargs>capi_i)
<del>\t\tif (CAPI_ARGLIST_SETITEM(capi_i++,pyarr_from_p_#ctype#1(#varname_i#_cb_capi)))
<del>\t\t\tgoto capi_fail;"""}],
<add> if (#name#_nofargs>capi_i)
<add> if (CAPI_ARGLIST_SETITEM(capi_i++,pyarr_from_p_#ctype#1(#varname_i#_cb_capi)))
<add> goto capi_fail;"""}],
<ide> 'need': [{isintent_in: 'pyobj_from_#ctype#1'},
<ide> {isintent_inout: 'pyarr_from_p_#ctype#1'},
<ide> {iscomplex: '#ctype#'}],
<ide> '_check': l_and(isscalar, isintent_nothide),
<ide> '_optional': ''
<ide> }, { # String
<del> 'frompyobj': [{debugcapi: '\tCFUNCSMESS("cb:Getting #varname#->\\"");'},
<del> """\tif (capi_j>capi_i)
<del>\t\tGETSTRFROMPYTUPLE(capi_return,capi_i++,#varname_i#,#varname_i#_cb_len);""",
<add> 'frompyobj': [{debugcapi: ' CFUNCSMESS("cb:Getting #varname#->\\"");'},
<add> """ if (capi_j>capi_i)
<add> GETSTRFROMPYTUPLE(capi_return,capi_i++,#varname_i#,#varname_i#_cb_len);""",
<ide> {debugcapi:
<del> '\tfprintf(stderr,"#showvalueformat#\\":%d:.\\n",#varname_i#,#varname_i#_cb_len);'},
<add> ' fprintf(stderr,"#showvalueformat#\\":%d:.\\n",#varname_i#,#varname_i#_cb_len);'},
<ide> ],
<ide> 'need': ['#ctype#', 'GETSTRFROMPYTUPLE',
<ide> {debugcapi: 'CFUNCSMESS'}, 'string.h'],
<ide> '_check': l_and(isstring, isintent_out)
<ide> }, {
<del> 'pyobjfrom': [{debugcapi: '\tfprintf(stderr,"debug-capi:cb:#varname#=\\"#showvalueformat#\\":%d:\\n",#varname_i#,#varname_i#_cb_len);'},
<add> 'pyobjfrom': [{debugcapi: ' fprintf(stderr,"debug-capi:cb:#varname#=\\"#showvalueformat#\\":%d:\\n",#varname_i#,#varname_i#_cb_len);'},
<ide> {isintent_in: """\
<del>\tif (#name#_nofargs>capi_i)
<del>\t\tif (CAPI_ARGLIST_SETITEM(capi_i++,pyobj_from_#ctype#1size(#varname_i#,#varname_i#_cb_len)))
<del>\t\t\tgoto capi_fail;"""},
<add> if (#name#_nofargs>capi_i)
<add> if (CAPI_ARGLIST_SETITEM(capi_i++,pyobj_from_#ctype#1size(#varname_i#,#varname_i#_cb_len)))
<add> goto capi_fail;"""},
<ide> {isintent_inout: """\
<del>\tif (#name#_nofargs>capi_i) {
<del>\t\tint #varname_i#_cb_dims[] = {#varname_i#_cb_len};
<del>\t\tif (CAPI_ARGLIST_SETITEM(capi_i++,pyarr_from_p_#ctype#1(#varname_i#,#varname_i#_cb_dims)))
<del>\t\t\tgoto capi_fail;
<del>\t}"""}],
<add> if (#name#_nofargs>capi_i) {
<add> int #varname_i#_cb_dims[] = {#varname_i#_cb_len};
<add> if (CAPI_ARGLIST_SETITEM(capi_i++,pyarr_from_p_#ctype#1(#varname_i#,#varname_i#_cb_dims)))
<add> goto capi_fail;
<add> }"""}],
<ide> 'need': [{isintent_in: 'pyobj_from_#ctype#1size'},
<ide> {isintent_inout: 'pyarr_from_p_#ctype#1'}],
<ide> '_check': l_and(isstring, isintent_nothide),
<ide> '_optional': ''
<ide> },
<ide> # Array ...
<ide> {
<del> 'decl': '\tnpy_intp #varname_i#_Dims[#rank#] = {#rank*[-1]#};',
<del> 'setdims': '\t#cbsetdims#;',
<add> 'decl': ' npy_intp #varname_i#_Dims[#rank#] = {#rank*[-1]#};',
<add> 'setdims': ' #cbsetdims#;',
<ide> '_check': isarray,
<ide> '_depend': ''
<ide> },
<ide> {
<del> 'pyobjfrom': [{debugcapi: '\tfprintf(stderr,"debug-capi:cb:#varname#\\n");'},
<add> 'pyobjfrom': [{debugcapi: ' fprintf(stderr,"debug-capi:cb:#varname#\\n");'},
<ide> {isintent_c: """\
<del>\tif (#name#_nofargs>capi_i) {
<del>\t\tint itemsize_ = #atype# == NPY_STRING ? 1 : 0;
<del>\t\t/*XXX: Hmm, what will destroy this array??? */
<del>\t\tPyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,#rank#,#varname_i#_Dims,#atype#,NULL,(char*)#varname_i#,itemsize_,NPY_ARRAY_CARRAY,NULL);
<add> if (#name#_nofargs>capi_i) {
<add> int itemsize_ = #atype# == NPY_STRING ? 1 : 0;
<add> /*XXX: Hmm, what will destroy this array??? */
<add> PyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,#rank#,#varname_i#_Dims,#atype#,NULL,(char*)#varname_i#,itemsize_,NPY_ARRAY_CARRAY,NULL);
<ide> """,
<ide> l_not(isintent_c): """\
<del>\tif (#name#_nofargs>capi_i) {
<del>\t\tint itemsize_ = #atype# == NPY_STRING ? 1 : 0;
<del>\t\t/*XXX: Hmm, what will destroy this array??? */
<del>\t\tPyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,#rank#,#varname_i#_Dims,#atype#,NULL,(char*)#varname_i#,itemsize_,NPY_ARRAY_FARRAY,NULL);
<add> if (#name#_nofargs>capi_i) {
<add> int itemsize_ = #atype# == NPY_STRING ? 1 : 0;
<add> /*XXX: Hmm, what will destroy this array??? */
<add> PyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,#rank#,#varname_i#_Dims,#atype#,NULL,(char*)#varname_i#,itemsize_,NPY_ARRAY_FARRAY,NULL);
<ide> """,
<ide> },
<ide> """
<del>\t\tif (tmp_arr==NULL)
<del>\t\t\tgoto capi_fail;
<del>\t\tif (CAPI_ARGLIST_SETITEM(capi_i++,(PyObject *)tmp_arr))
<del>\t\t\tgoto capi_fail;
<add> if (tmp_arr==NULL)
<add> goto capi_fail;
<add> if (CAPI_ARGLIST_SETITEM(capi_i++,(PyObject *)tmp_arr))
<add> goto capi_fail;
<ide> }"""],
<ide> '_check': l_and(isarray, isintent_nothide, l_or(isintent_in, isintent_inout)),
<ide> '_optional': '',
<ide> }, {
<del> 'frompyobj': [{debugcapi: '\tCFUNCSMESS("cb:Getting #varname#->");'},
<del> """\tif (capi_j>capi_i) {
<del>\t\tPyArrayObject *rv_cb_arr = NULL;
<del>\t\tif ((capi_tmp = PyTuple_GetItem(capi_return,capi_i++))==NULL) goto capi_fail;
<del>\t\trv_cb_arr = array_from_pyobj(#atype#,#varname_i#_Dims,#rank#,F2PY_INTENT_IN""",
<add> 'frompyobj': [{debugcapi: ' CFUNCSMESS("cb:Getting #varname#->");'},
<add> """ if (capi_j>capi_i) {
<add> PyArrayObject *rv_cb_arr = NULL;
<add> if ((capi_tmp = PyTuple_GetItem(capi_return,capi_i++))==NULL) goto capi_fail;
<add> rv_cb_arr = array_from_pyobj(#atype#,#varname_i#_Dims,#rank#,F2PY_INTENT_IN""",
<ide> {isintent_c: '|F2PY_INTENT_C'},
<ide> """,capi_tmp);
<del>\t\tif (rv_cb_arr == NULL) {
<del>\t\t\tfprintf(stderr,\"rv_cb_arr is NULL\\n\");
<del>\t\t\tgoto capi_fail;
<del>\t\t}
<del>\t\tMEMCOPY(#varname_i#,PyArray_DATA(rv_cb_arr),PyArray_NBYTES(rv_cb_arr));
<del>\t\tif (capi_tmp != (PyObject *)rv_cb_arr) {
<del>\t\t\tPy_DECREF(rv_cb_arr);
<del>\t\t}
<del>\t}""",
<del> {debugcapi: '\tfprintf(stderr,"<-.\\n");'},
<add> if (rv_cb_arr == NULL) {
<add> fprintf(stderr,\"rv_cb_arr is NULL\\n\");
<add> goto capi_fail;
<add> }
<add> MEMCOPY(#varname_i#,PyArray_DATA(rv_cb_arr),PyArray_NBYTES(rv_cb_arr));
<add> if (capi_tmp != (PyObject *)rv_cb_arr) {
<add> Py_DECREF(rv_cb_arr);
<add> }
<add> }""",
<add> {debugcapi: ' fprintf(stderr,"<-.\\n");'},
<ide> ],
<ide> 'need': ['MEMCOPY', {iscomplexarray: '#ctype#'}],
<ide> '_check': l_and(isarray, isintent_out) | 1 |
Ruby | Ruby | fix typo in spec | 564a06dfbb711a995558c64c55b353d1fdfcb473 | <ide><path>Library/Homebrew/test/utils/github_spec.rb
<ide> describe "::search_issues", :needs_network do
<ide> it "queries GitHub issues with the passed parameters" do
<ide> results = subject.search_issues("brew search", repo: "Homebrew/brew", author: "avetamine", is: "closed")
<del> expect(results.count).not_to be_empty
<add> expect(results).not_to be_empty
<ide> expect(results.last["title"]).to eq("brew search : 422 Unprocessable Entity")
<ide> end
<ide> end | 1 |
Javascript | Javascript | update example to use a module | e83c5ba68e9a154a28c7045042502af180623a00 | <ide><path>src/ng/directive/ngPluralize.js
<ide> * @param {number=} offset Offset to deduct from the total number.
<ide> *
<ide> * @example
<del> <example>
<add> <example module="pluralizeExample">
<ide> <file name="index.html">
<ide> <script>
<del> function Ctrl($scope) {
<del> $scope.person1 = 'Igor';
<del> $scope.person2 = 'Misko';
<del> $scope.personCount = 1;
<del> }
<add> angular.module('pluralizeExample', [])
<add> .controller('ExampleController', ['$scope', function($scope) {
<add> $scope.person1 = 'Igor';
<add> $scope.person2 = 'Misko';
<add> $scope.personCount = 1;
<add> }]);
<ide> </script>
<del> <div ng-controller="Ctrl">
<add> <div ng-controller="ExampleController">
<ide> Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
<ide> Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
<ide> Number of People:<input type="text" ng-model="personCount" value="1" /><br/> | 1 |
Python | Python | fix mobilenet bugs | 8040ad72dd488feac9843caca4f875186d3b75c1 | <ide><path>keras/applications/mobilenet.py
<ide> def MobileNet(input_shape=None,
<ide> '(pre-training on ImageNet).')
<ide>
<ide> if weights == 'imagenet' and include_top and classes != 1000:
<del> raise ValueError('If using `weights` as ImageNet with `include_top`'
<del> ' as true, `classes` should be 1000')
<add> raise ValueError('If using `weights` as ImageNet with `include_top` '
<add> 'as true, `classes` should be 1000')
<ide>
<del> if weights == 'imagenet' and depth_multiplier != 1:
<add> # Determine proper input shape.
<add> input_shape = _obtain_input_shape(input_shape,
<add> default_size=224,
<add> min_size=32,
<add> data_format=K.image_data_format(),
<add> include_top=include_top or weights)
<add> if K.image_data_format() == 'channels_last':
<add> row_axis, col_axis = (0, 1)
<add> else:
<add> row_axis, col_axis = (1, 2)
<add> rows = input_shape[row_axis]
<add> cols = input_shape[col_axis]
<add>
<add> if weights == 'imagenet':
<ide> if depth_multiplier != 1:
<ide> raise ValueError('If imagenet weights are being loaded, '
<ide> 'depth multiplier must be 1')
<ide> def MobileNet(input_shape=None,
<ide> 'alpha can be one of'
<ide> '`0.25`, `0.50`, `0.75` or `1.0` only.')
<ide>
<del> rows, cols = (0, 1) if K.image_data_format() == 'channels_last' else (1, 2)
<del> rows = int(input_shape[rows])
<del> cols = int(input_shape[cols])
<del>
<ide> if rows != cols or rows not in [128, 160, 192, 224]:
<del> raise ValueError('If imagenet weights are being loaded,'
<del> 'image must have a square shape (one of '
<add> raise ValueError('If imagenet weights are being loaded, '
<add> 'input must have a static square shape (one of '
<ide> '(128,128), (160,160), (192,192), or (224, 224)).'
<del> 'Image shape provided = (%d, %d)' % (rows, cols))
<add> ' Input shape provided = %s' % (input_shape,))
<ide>
<ide> if K.image_data_format() != 'channels_last':
<ide> warnings.warn('The MobileNet family of models is only available '
<ide> 'for the input data format "channels_last" '
<ide> '(width, height, channels). '
<ide> 'However your settings specify the default '
<del> 'data format "channels_first" (channels, width, height). '
<del> 'You should set `image_data_format="channels_last"` in your Keras '
<del> 'config located at ~/.keras/keras.json. '
<add> 'data format "channels_first" (channels, width, height).'
<add> ' You should set `image_data_format="channels_last"` '
<add> 'in your Keras config located at ~/.keras/keras.json. '
<ide> 'The model being returned right now will expect inputs '
<ide> 'to follow the "channels_last" data format.')
<ide> K.set_image_data_format('channels_last')
<ide> old_data_format = 'channels_first'
<ide> else:
<ide> old_data_format = None
<ide>
<del> # Determine proper input shape. Note, include_top is False by default, as
<del> # input shape can be anything larger than 32x32
<del> # and the same number of parameters will be used.
<del> input_shape = _obtain_input_shape(input_shape,
<del> default_size=224,
<del> min_size=32,
<del> data_format=K.image_data_format(),
<del> include_top=False)
<del>
<ide> if input_tensor is None:
<ide> img_input = Input(shape=input_shape)
<ide> else:
<ide> def MobileNet(input_shape=None,
<ide> else:
<ide> inputs = img_input
<ide>
<del> rows, cols = (0, 1) if K.image_data_format() == 'channels_last' else (1, 2)
<del> if input_shape[rows] is None:
<del> size = 'None'
<del> else:
<del> size = str(input_shape[rows])
<del>
<ide> # Create model.
<del> model = Model(inputs, x, name='mobilenet_%0.2f_%s' % (alpha, size))
<add> model = Model(inputs, x, name='mobilenet_%0.2f_%s' % (alpha, rows))
<ide>
<ide> # load weights
<ide> if weights == 'imagenet': | 1 |
Text | Text | add arabic translation for bash-chmod | 635d97d559b287a52e2f9d534b3fe96bfd760356 | <ide><path>guide/arabic/bash/bash-chmod/index.md
<add>---
<add>title: Bash chmod
<add>localeTitle: باش chmod
<add>---
<add>
<add>## ايعاز باش: chomd
<add>
<add>**يستخدم لتغير تصريح الملفات او المجلدات**
<add>
<add>مثال:
<add>
<add>`chmod u+x hello.py`
<add>
<add>يمنح المستخدم التصريح لتنفيذ الملف.
<add>
<add>### للمزيد من المعلومات:
<add>* [ويكيبيديا](https://ar.wikipedia.org/wiki/Chmod) | 1 |
PHP | PHP | avoid aliases. | 563af376828934fb796e400c9f69a0ef439d53c9 | <ide><path>src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php
<ide> public function withCount($relations)
<ide> // Finally we will add the proper result column alias to the query and run the subselect
<ide> // statement against the query builder. Then we will return the builder instance back
<ide> // to the developer for further constraint chaining that needs to take place on it.
<del> $column = isset($alias) ? $alias : snake_case($name.'_count');
<add> $column = isset($alias) ? $alias : Str::snake($name.'_count');
<ide>
<ide> $this->selectSub($query->toBase(), $column);
<ide> } | 1 |
Python | Python | build priority packages in separate processes pool | 2d3b63d14302187d5ca49d3fcb058832418eeeb2 | <ide><path>docs/build_docs.py
<ide> from rich.console import Console
<ide> from tabulate import tabulate
<ide>
<add>from airflow.utils.helpers import partition
<ide> from docs.exts.docs_build import dev_index_generator, lint_checks # pylint: disable=no-name-in-module
<ide> from docs.exts.docs_build.code_utils import CONSOLE_WIDTH, PROVIDER_INIT_FILE, TEXT_RED, TEXT_RESET
<ide> from docs.exts.docs_build.docs_builder import ( # pylint: disable=no-name-in-module
<ide> def main():
<ide> current_packages = process_package_filters(available_packages, package_filters)
<ide>
<ide> with with_group("Fetching inventories"):
<del> # Inventories that could not be retrieved should be retrieved first. This may mean this is a
<add> # Inventories that could not be retrieved should be built first. This may mean this is a
<ide> # new package.
<del> priority_packages = fetch_inventories()
<del> current_packages = sorted(current_packages, key=lambda d: -1 if d in priority_packages else 1)
<del>
<add> packages_without_inventories = fetch_inventories()
<add> normal_packages, priority_packages = partition(
<add> lambda d: d in packages_without_inventories, current_packages
<add> )
<add> normal_packages, priority_packages = list(normal_packages), list(priority_packages)
<ide> jobs = args.jobs if args.jobs != 0 else os.cpu_count()
<add>
<ide> with with_group(
<ide> f"Documentation will be built for {len(current_packages)} package(s) with {jobs} parallel jobs"
<ide> ):
<ide> def main():
<ide>
<ide> all_build_errors: Dict[Optional[str], List[DocBuildError]] = {}
<ide> all_spelling_errors: Dict[Optional[str], List[SpellingError]] = {}
<add> if priority_packages:
<add> # Build priority packages
<add> package_build_errors, package_spelling_errors = build_docs_for_packages(
<add> current_packages=priority_packages,
<add> docs_only=docs_only,
<add> spellcheck_only=spellcheck_only,
<add> for_production=for_production,
<add> jobs=jobs,
<add> verbose=args.verbose,
<add> )
<add> if package_build_errors:
<add> all_build_errors.update(package_build_errors)
<add> if package_spelling_errors:
<add> all_spelling_errors.update(package_spelling_errors)
<add>
<add> # Build normal packages
<add> # If only one inventory is missing, the remaining packages are correct. If we are missing
<add> # two or more inventories, it is better to try to build for all packages as the previous packages
<add> # may have failed as well.
<ide> package_build_errors, package_spelling_errors = build_docs_for_packages(
<del> current_packages=current_packages,
<add> current_packages=current_packages if len(priority_packages) > 1 else normal_packages,
<ide> docs_only=docs_only,
<ide> spellcheck_only=spellcheck_only,
<ide> for_production=for_production,
<ide> def main():
<ide> all_build_errors.update(package_build_errors)
<ide> if package_spelling_errors:
<ide> all_spelling_errors.update(package_spelling_errors)
<add>
<add> # Build documentation for some packages again if it can help them.
<ide> to_retry_packages = [
<ide> package_name
<ide> for package_name, errors in package_build_errors.items() | 1 |
Javascript | Javascript | use modern imports | 64d471600337222ac0a0ff07891140807c1b2471 | <ide><path>spec/git-repository-async-spec.js
<ide> 'use babel'
<ide>
<del>const fs = require('fs-plus')
<del>const path = require('path')
<del>const temp = require('temp')
<del>const Git = require('nodegit')
<add>import fs from 'fs-plus'
<add>import path from 'path'
<add>import temp from 'temp'
<add>import Git from 'nodegit'
<ide>
<del>const GitRepositoryAsync = require('../src/git-repository-async')
<del>const Project = require('../src/project')
<add>import {it, ffit, fffit, beforeEach, afterEach} from './async-spec-helpers'
<add>
<add>import GitRepositoryAsync from '../src/git-repository-async'
<add>import Project from '../src/project'
<ide>
<ide> temp.track()
<ide>
<ide> function copyRepository() {
<ide> return fs.realpathSync(workingDirPath)
<ide> }
<ide>
<del>function asyncIt(name, fn) {
<del> it(name, () => {
<del> waitsForPromise(fn)
<del> })
<del>}
<del>
<del>function fasyncIt(name, fn) {
<del> fit(name, () => {
<del> waitsForPromise(fn)
<del> })
<del>}
<del>
<del>function xasyncIt(name, fn) {
<del> xit(name, () => {
<del> waitsForPromise(fn)
<del> })
<del>}
<del>
<ide> describe('GitRepositoryAsync-js', () => {
<ide> let repo
<ide>
<ide> describe('GitRepositoryAsync-js', () => {
<ide> })
<ide>
<ide> describe('@open(path)', () => {
<del> asyncIt('repo is null when no repository is found', async () => {
<add> it('repo is null when no repository is found', async () => {
<ide> repo = GitRepositoryAsync.open(path.join(temp.dir, 'nogit.txt'))
<ide>
<ide> let threw = false
<ide> describe('GitRepositoryAsync-js', () => {
<ide> describe('.getPath()', () => {
<ide> xit('returns the repository path for a .git directory path')
<ide>
<del> asyncIt('returns the repository path for a repository path', async () => {
<add> it('returns the repository path for a repository path', async () => {
<ide> repo = openFixture('master.git')
<ide> let repoPath = await repo.getPath()
<ide> expect(repoPath).toBe(path.join(__dirname, 'fixtures', 'git', 'master.git'))
<ide> })
<ide> })
<ide>
<ide> describe('.isPathIgnored(path)', () => {
<del> asyncIt('resolves true for an ignored path', async () => {
<add> it('resolves true for an ignored path', async () => {
<ide> repo = openFixture('ignore.git')
<ide> let ignored = await repo.isPathIgnored('a.txt')
<ide> expect(ignored).toBeTruthy()
<ide> })
<ide>
<del> asyncIt('resolves false for a non-ignored path', async () => {
<add> it('resolves false for a non-ignored path', async () => {
<ide> repo = openFixture('ignore.git')
<ide> let ignored = await repo.isPathIgnored('b.txt')
<ide> expect(ignored).toBeFalsy()
<ide> describe('GitRepositoryAsync-js', () => {
<ide> })
<ide>
<ide> describe('when the path is unstaged', () => {
<del> asyncIt('resolves false if the path has not been modified', async () => {
<add> it('resolves false if the path has not been modified', async () => {
<ide> let modified = await repo.isPathModified(filePath)
<ide> expect(modified).toBeFalsy()
<ide> })
<ide>
<del> asyncIt('resolves true if the path is modified', async () => {
<add> it('resolves true if the path is modified', async () => {
<ide> fs.writeFileSync(filePath, "change")
<ide> let modified = await repo.isPathModified(filePath)
<ide> expect(modified).toBeTruthy()
<ide> })
<ide>
<del> asyncIt('resolves false if the path is new', async () => {
<add> it('resolves false if the path is new', async () => {
<ide> let modified = await repo.isPathModified(newPath)
<ide> expect(modified).toBeFalsy()
<ide> })
<ide>
<del> asyncIt('resolves false if the path is invalid', async () => {
<add> it('resolves false if the path is invalid', async () => {
<ide> let modified = await repo.isPathModified(emptyPath)
<ide> expect(modified).toBeFalsy()
<ide> })
<ide> describe('GitRepositoryAsync-js', () => {
<ide> })
<ide>
<ide> describe('when the path is unstaged', () => {
<del> asyncIt('returns true if the path is new', async () => {
<add> it('returns true if the path is new', async () => {
<ide> let isNew = await repo.isPathNew(newPath)
<ide> expect(isNew).toBeTruthy()
<ide> })
<ide>
<del> asyncIt("returns false if the path isn't new", async () => {
<add> it("returns false if the path isn't new", async () => {
<ide> let modified = await repo.isPathModified(newPath)
<ide> expect(modified).toBeFalsy()
<ide> })
<ide> describe('GitRepositoryAsync-js', () => {
<ide> filePath = path.join(workingDirPath, 'a.txt')
<ide> })
<ide>
<del> asyncIt('no longer reports a path as modified after checkout', async () => {
<add> it('no longer reports a path as modified after checkout', async () => {
<ide> let modified = await repo.isPathModified(filePath)
<ide> expect(modified).toBeFalsy()
<ide>
<ide> describe('GitRepositoryAsync-js', () => {
<ide> expect(modified).toBeFalsy()
<ide> })
<ide>
<del> asyncIt('restores the contents of the path to the original text', async () => {
<add> it('restores the contents of the path to the original text', async () => {
<ide> fs.writeFileSync(filePath, 'ch ch changes')
<ide> await repo.checkoutHead(filePath)
<ide> expect(fs.readFileSync(filePath, 'utf8')).toBe('')
<ide> })
<ide>
<del> asyncIt('fires a did-change-status event if the checkout completes successfully', async () => {
<add> it('fires a did-change-status event if the checkout completes successfully', async () => {
<ide> fs.writeFileSync(filePath, 'ch ch changes')
<ide>
<ide> await repo.getPathStatus(filePath)
<ide> describe('GitRepositoryAsync-js', () => {
<ide> filePath = path.join(workingDirectory, 'file.txt')
<ide> })
<ide>
<del> asyncIt('trigger a status-changed event when the new status differs from the last cached one', async () => {
<add> it('trigger a status-changed event when the new status differs from the last cached one', async () => {
<ide> let statusHandler = jasmine.createSpy("statusHandler")
<ide> repo.onDidChangeStatus(statusHandler)
<ide> fs.writeFileSync(filePath, '')
<ide> describe('GitRepositoryAsync-js', () => {
<ide> filePath = path.join(directoryPath, 'b.txt')
<ide> })
<ide>
<del> asyncIt('gets the status based on the files inside the directory', async () => {
<add> it('gets the status based on the files inside the directory', async () => {
<ide> await repo.checkoutHead(filePath)
<ide>
<ide> let result = await repo.getDirectoryStatus(directoryPath)
<ide> describe('GitRepositoryAsync-js', () => {
<ide> newPath = fs.absolute(newPath) // specs could be running under symbol path.
<ide> })
<ide>
<del> asyncIt('returns status information for all new and modified files', async () => {
<add> it('returns status information for all new and modified files', async () => {
<ide> fs.writeFileSync(modifiedPath, 'making this path modified')
<ide> await repo.refreshStatus()
<ide>
<ide> describe('GitRepositoryAsync-js', () => {
<ide> waitsForPromise(() => { return repository.refreshStatus() })
<ide> })
<ide>
<del> asyncIt('emits a status-changed event when a buffer is saved', async () => {
<add> it('emits a status-changed event when a buffer is saved', async () => {
<ide> let editor = await atom.workspace.open('other.txt')
<ide>
<ide> editor.insertNewline()
<ide> describe('GitRepositoryAsync-js', () => {
<ide> runs(() => expect(called).toEqual({path: editor.getPath(), pathStatus: 256}))
<ide> })
<ide>
<del> asyncIt('emits a status-changed event when a buffer is reloaded', async () => {
<add> it('emits a status-changed event when a buffer is reloaded', async () => {
<ide> let statusHandler = jasmine.createSpy('statusHandler')
<ide> let reloadHandler = jasmine.createSpy('reloadHandler')
<ide>
<ide> describe('GitRepositoryAsync-js', () => {
<ide> })
<ide> })
<ide>
<del> asyncIt("emits a status-changed event when a buffer's path changes", async () => {
<add> it("emits a status-changed event when a buffer's path changes", async () => {
<ide> let editor = await atom.workspace.open('other.txt')
<ide>
<ide> fs.writeFileSync(editor.getPath(), 'changed')
<ide> describe('GitRepositoryAsync-js', () => {
<ide> })
<ide> })
<ide>
<del> asyncIt('stops listening to the buffer when the repository is destroyed (regression)', async () => {
<add> it('stops listening to the buffer when the repository is destroyed (regression)', async () => {
<ide> let editor = await atom.workspace.open('other.txt')
<ide> atom.project.getRepositories()[0].destroy()
<ide> expect(() => editor.save()).not.toThrow()
<ide> describe('GitRepositoryAsync-js', () => {
<ide> if (project2) project2.destroy()
<ide> })
<ide>
<del> asyncIt('subscribes to all the serialized buffers in the project', async () => {
<add> it('subscribes to all the serialized buffers in the project', async () => {
<ide> await atom.workspace.open('file.txt')
<ide>
<ide> project2 = new Project({notificationManager: atom.notifications, packageManager: atom.packages, confirm: atom.confirm})
<ide><path>src/git-repository-async.js
<ide> 'use babel'
<ide>
<del>const fs = require('fs-plus')
<del>const Git = require('nodegit')
<del>const path = require('path')
<del>const {Emitter, CompositeDisposable} = require('event-kit')
<add>import fs from 'fs-plus'
<add>import Git from 'nodegit'
<add>import path from 'path'
<add>import {Emitter, CompositeDisposable} from 'event-kit'
<ide>
<ide> const modifiedStatusFlags = Git.Status.STATUS.WT_MODIFIED | Git.Status.STATUS.INDEX_MODIFIED | Git.Status.STATUS.WT_DELETED | Git.Status.STATUS.INDEX_DELETED | Git.Status.STATUS.WT_TYPECHANGE | Git.Status.STATUS.INDEX_TYPECHANGE
<ide> const newStatusFlags = Git.Status.STATUS.WT_NEW | Git.Status.STATUS.INDEX_NEW
<ide> const deletedStatusFlags = Git.Status.STATUS.WT_DELETED | Git.Status.STATUS.INDEX_DELETED
<ide> const indexStatusFlags = Git.Status.STATUS.INDEX_NEW | Git.Status.STATUS.INDEX_MODIFIED | Git.Status.STATUS.INDEX_DELETED | Git.Status.STATUS.INDEX_RENAMED | Git.Status.STATUS.INDEX_TYPECHANGE
<ide>
<ide> // Just using this for _.isEqual and _.object, we should impl our own here
<del>const _ = require('underscore-plus')
<add>import _ from 'underscore-plus'
<ide>
<ide> module.exports = class GitRepositoryAsync {
<ide> static open (path, options = {}) { | 2 |
Go | Go | fix race in restart loop | 752a0d6f34ee3c92dc877273c33b8cd0239fda71 | <ide><path>integration-cli/docker_cli_restart_test.go
<ide> func TestRestartWithVolumes(t *testing.T) {
<ide> logDone("restart - does not create a new volume on restart")
<ide> }
<ide>
<del>func TestRecordRestartPolicyNO(t *testing.T) {
<add>func TestRestartPolicyNO(t *testing.T) {
<ide> defer deleteAllContainers()
<ide>
<ide> cmd := exec.Command(dockerBinary, "run", "-d", "--restart=no", "busybox", "false")
<ide> func TestRecordRestartPolicyNO(t *testing.T) {
<ide> logDone("restart - recording restart policy name for --restart=no")
<ide> }
<ide>
<del>func TestRecordRestartPolicyAlways(t *testing.T) {
<add>func TestRestartPolicyAlways(t *testing.T) {
<ide> defer deleteAllContainers()
<ide>
<ide> cmd := exec.Command(dockerBinary, "run", "-d", "--restart=always", "busybox", "false")
<ide> func TestRecordRestartPolicyAlways(t *testing.T) {
<ide> t.Fatalf("Container restart policy name is %s, expected %s", name, "always")
<ide> }
<ide>
<del> cmd = exec.Command(dockerBinary, "stop", id)
<del> out, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> t.Fatal(err, out)
<del> }
<del>
<ide> logDone("restart - recording restart policy name for --restart=always")
<ide> }
<ide>
<del>func TestRecordRestartPolicyOnFailure(t *testing.T) {
<add>func TestRestartPolicyOnFailure(t *testing.T) {
<ide> defer deleteAllContainers()
<ide>
<ide> cmd := exec.Command(dockerBinary, "run", "-d", "--restart=on-failure:1", "busybox", "false") | 1 |
Javascript | Javascript | propagate weak option for knewlistener | 606f7213c4392e73dbe3aaec2418d6722a86d69a | <ide><path>lib/internal/event_target.js
<ide> class EventTarget {
<ide> initEventTarget(this);
<ide> }
<ide>
<del> [kNewListener](size, type, listener, once, capture, passive) {
<add> [kNewListener](size, type, listener, once, capture, passive, weak) {
<ide> if (this[kMaxEventTargetListeners] > 0 &&
<ide> size > this[kMaxEventTargetListeners] &&
<ide> !this[kMaxEventTargetListenersWarned]) {
<ide> class EventTarget {
<ide> // This is the first handler in our linked list.
<ide> new Listener(root, listener, once, capture, passive,
<ide> isNodeStyleListener, weak);
<del> this[kNewListener](root.size, type, listener, once, capture, passive);
<add> this[kNewListener](
<add> root.size,
<add> type,
<add> listener,
<add> once,
<add> capture,
<add> passive,
<add> weak);
<ide> this[kEvents].set(type, root);
<ide> return;
<ide> }
<ide> class EventTarget {
<ide> new Listener(previous, listener, once, capture, passive,
<ide> isNodeStyleListener, weak);
<ide> root.size++;
<del> this[kNewListener](root.size, type, listener, once, capture, passive);
<add> this[kNewListener](root.size, type, listener, once, capture, passive, weak);
<ide> }
<ide>
<ide> removeEventListener(type, listener, options = {}) {
<ide> function defineEventHandler(emitter, name) {
<ide> if (typeof wrappedHandler.handler === 'function') {
<ide> this[kEvents].get(name).size++;
<ide> const size = this[kEvents].get(name).size;
<del> this[kNewListener](size, name, value, false, false, false);
<add> this[kNewListener](size, name, value, false, false, false, false);
<ide> }
<ide> } else {
<ide> wrappedHandler = makeEventHandler(value); | 1 |
Java | Java | remove factory methods from webreactiveconfigurer | 61cf9fdda5b2219adc76a4a3e024006ed01fcdd6 | <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/config/DelegatingWebReactiveConfiguration.java
<ide> import org.springframework.validation.Validator;
<ide> import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder;
<ide> import org.springframework.web.reactive.result.method.HandlerMethodArgumentResolver;
<del>import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter;
<del>import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping;
<ide>
<ide> /**
<ide> * A subclass of {@code WebReactiveConfigurationSupport} that detects and delegates
<ide> public void setConfigurers(List<WebReactiveConfigurer> configurers) {
<ide> }
<ide> }
<ide>
<del> @Override
<del> protected RequestMappingHandlerMapping createRequestMappingHandlerMapping() {
<del> return this.configurers.createRequestMappingHandlerMapping()
<del> .orElse(super.createRequestMappingHandlerMapping());
<del> }
<del>
<ide> @Override
<ide> protected void configureRequestedContentTypeResolver(RequestedContentTypeResolverBuilder builder) {
<ide> this.configurers.configureRequestedContentTypeResolver(builder);
<ide> protected void addResourceHandlers(ResourceHandlerRegistry registry) {
<ide> this.configurers.addResourceHandlers(registry);
<ide> }
<ide>
<del> @Override
<del> protected RequestMappingHandlerAdapter createRequestMappingHandlerAdapter() {
<del> return this.configurers.createRequestMappingHandlerAdapter()
<del> .orElse(super.createRequestMappingHandlerAdapter());
<del> }
<del>
<ide> @Override
<ide> protected void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
<ide> this.configurers.addArgumentResolvers(resolvers);
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/config/WebReactiveConfigurer.java
<ide> import org.springframework.web.reactive.accept.RequestedContentTypeResolver;
<ide> import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder;
<ide> import org.springframework.web.reactive.result.method.HandlerMethodArgumentResolver;
<del>import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter;
<del>import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping;
<ide>
<ide> /**
<ide> * Defines callback methods to customize the configuration for Web Reactive
<ide> default void extendMessageWriters(List<HttpMessageWriter<?>> writers) {
<ide> default void configureViewResolvers(ViewResolverRegistry registry) {
<ide> }
<ide>
<del> /**
<del> * Factory method for the {@link RequestMappingHandlerMapping} bean creating
<del> * an instance or a custom extension of it. Note that only one configurer
<del> * is allowed to implement this method.
<del> * The default implementation returns {@code Optional.empty()}.
<del> */
<del> default Optional<RequestMappingHandlerMapping> createRequestMappingHandlerMapping() {
<del> return Optional.empty();
<del> }
<del>
<del> /**
<del> * Factory method for the {@link RequestMappingHandlerAdapter} bean creating
<del> * an instance or a custom extension of it. Note that only one configurer
<del> * is allowed to implement this method.
<del> * The default implementation returns {@code Optional.empty()}.
<del> */
<del> default Optional<RequestMappingHandlerAdapter> createRequestMappingHandlerAdapter() {
<del> return Optional.empty();
<del> }
<del>
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/config/WebReactiveConfigurerComposite.java
<ide> import org.springframework.validation.Validator;
<ide> import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder;
<ide> import org.springframework.web.reactive.result.method.HandlerMethodArgumentResolver;
<del>import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter;
<del>import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping;
<ide>
<ide> /**
<ide> * A {@link WebReactiveConfigurer} that delegates to one or more others.
<ide> public void configureViewResolvers(ViewResolverRegistry registry) {
<ide> this.delegates.stream().forEach(delegate -> delegate.configureViewResolvers(registry));
<ide> }
<ide>
<del> @Override
<del> public Optional<RequestMappingHandlerMapping> createRequestMappingHandlerMapping() {
<del> return createSingleBean(WebReactiveConfigurer::createRequestMappingHandlerMapping,
<del> RequestMappingHandlerMapping.class);
<del> }
<del>
<del> @Override
<del> public Optional<RequestMappingHandlerAdapter> createRequestMappingHandlerAdapter() {
<del> return createSingleBean(WebReactiveConfigurer::createRequestMappingHandlerAdapter,
<del> RequestMappingHandlerAdapter.class);
<del> }
<del>
<ide> private <T> Optional<T> createSingleBean(Function<WebReactiveConfigurer, Optional<T>> factory,
<ide> Class<T> beanType) {
<ide>
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/config/DelegatingWebReactiveConfigurationTests.java
<ide>
<ide> package org.springframework.web.reactive.config;
<ide>
<del>import java.util.Arrays;
<ide> import java.util.Collections;
<ide> import java.util.List;
<ide> import java.util.Optional;
<ide>
<ide> import org.junit.Before;
<del>import org.junit.Rule;
<ide> import org.junit.Test;
<del>import org.junit.rules.ExpectedException;
<ide> import org.mockito.ArgumentCaptor;
<ide> import org.mockito.Captor;
<ide> import org.mockito.Mock;
<ide> import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
<ide> import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder;
<ide> import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter;
<del>import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping;
<ide>
<del>import static org.junit.Assert.assertEquals;
<del>import static org.junit.Assert.assertSame;
<del>import static org.junit.Assert.assertTrue;
<del>import static org.mockito.BDDMockito.given;
<add>import static org.junit.Assert.*;
<add>import static org.mockito.BDDMockito.*;
<ide> import static org.mockito.Matchers.any;
<ide> import static org.mockito.Mockito.doAnswer;
<del>import static org.mockito.Mockito.mock;
<ide> import static org.mockito.Mockito.verify;
<del>import static org.mockito.Mockito.when;
<ide>
<ide> /**
<ide> * Test fixture for {@link DelegatingWebReactiveConfiguration} tests.
<ide> public class DelegatingWebReactiveConfigurationTests {
<ide> @Captor
<ide> private ArgumentCaptor<FormatterRegistry> formatterRegistry;
<ide>
<del> @Rule
<del> public ExpectedException thrown = ExpectedException.none();
<del>
<ide>
<ide> @Before
<ide> public void setUp() {
<ide> MockitoAnnotations.initMocks(this);
<ide> delegatingConfig = new DelegatingWebReactiveConfiguration();
<ide> delegatingConfig.setApplicationContext(new StaticApplicationContext());
<del> given(webReactiveConfigurer.createRequestMappingHandlerMapping()).willReturn(Optional.empty());
<del> given(webReactiveConfigurer.createRequestMappingHandlerAdapter()).willReturn(Optional.empty());
<ide> given(webReactiveConfigurer.getValidator()).willReturn(Optional.empty());
<ide> given(webReactiveConfigurer.getMessageCodesResolver()).willReturn(Optional.empty());
<ide> }
<ide> public void requestMappingHandlerMapping() throws Exception {
<ide> delegatingConfig.setConfigurers(Collections.singletonList(webReactiveConfigurer));
<ide> delegatingConfig.requestMappingHandlerMapping();
<ide>
<del> verify(webReactiveConfigurer).createRequestMappingHandlerMapping();
<ide> verify(webReactiveConfigurer).configureRequestedContentTypeResolver(any(RequestedContentTypeResolverBuilder.class));
<ide> verify(webReactiveConfigurer).addCorsMappings(any(CorsRegistry.class));
<ide> verify(webReactiveConfigurer).configurePathMatching(any(PathMatchConfigurer.class));
<ide> }
<ide>
<del> @Test
<del> public void requestMappingHandlerMappingFactoryMethod() throws Exception {
<del> RequestMappingHandlerMapping mapping = new RequestMappingHandlerMapping();
<del>
<del> WebReactiveConfigurer configurer1 = mock(WebReactiveConfigurer.class);
<del> WebReactiveConfigurer configurer2 = mock(WebReactiveConfigurer.class);
<del>
<del> when(configurer1.createRequestMappingHandlerMapping()).thenReturn(Optional.of(mapping));
<del> when(configurer2.createRequestMappingHandlerMapping()).thenReturn(Optional.empty());
<del>
<del> delegatingConfig.setConfigurers(Arrays.asList(configurer1, configurer2));
<del> Object actual = delegatingConfig.createRequestMappingHandlerMapping();
<del>
<del> assertSame(mapping, actual);
<del> }
<del>
<del> @Test
<del> public void multipleRequestMappingHandlerMappingFactoryMethods() throws Exception {
<del> RequestMappingHandlerMapping mapping1 = new RequestMappingHandlerMapping();
<del> RequestMappingHandlerMapping mapping2 = new RequestMappingHandlerMapping();
<del>
<del> WebReactiveConfigurer configurer1 = mock(WebReactiveConfigurer.class);
<del> WebReactiveConfigurer configurer2 = mock(WebReactiveConfigurer.class);
<del>
<del> when(configurer1.createRequestMappingHandlerMapping()).thenReturn(Optional.of(mapping1));
<del> when(configurer2.createRequestMappingHandlerMapping()).thenReturn(Optional.of(mapping2));
<del>
<del> this.thrown.expectMessage("More than one WebReactiveConfigurer implements " +
<del> "RequestMappingHandlerMapping factory method.");
<del>
<del> delegatingConfig.setConfigurers(Arrays.asList(configurer1, configurer2));
<del> delegatingConfig.createRequestMappingHandlerMapping();
<del> }
<del>
<ide> @Test
<ide> public void requestMappingHandlerAdapter() throws Exception {
<ide> delegatingConfig.setConfigurers(Collections.singletonList(webReactiveConfigurer));
<ide> public void requestMappingHandlerAdapter() throws Exception {
<ide> ConversionService initializerConversionService = initializer.getConversionService();
<ide> assertTrue(initializer.getValidator() instanceof LocalValidatorFactoryBean);
<ide>
<del> verify(webReactiveConfigurer).createRequestMappingHandlerAdapter();
<ide> verify(webReactiveConfigurer).configureMessageReaders(readers.capture());
<ide> verify(webReactiveConfigurer).extendMessageReaders(readers.capture());
<ide> verify(webReactiveConfigurer).getValidator(); | 4 |
Python | Python | resolve line-too-long in testing_infra | 37055edc159d9c851262bb657b0f3e1e2254a435 | <ide><path>keras/testing_infra/keras_doctest_lib.py
<ide> class _FloatExtractor(object):
<ide> dot_digits=r"(?:\.[0-9]+)",
<ide> # digits: "12"
<ide> digits=r"(?:[0-9]+)",
<del> # The exponent: An "e" or "E", optional sign, and at least one digit.
<del> # "e-123", "E+12", "e12"
<add> # The exponent: An "e" or "E", optional sign, and at least one
<add> # digit. "e-123", "E+12", "e12"
<ide> exponent=r"(?:[eE][-+]?[0-9]+)",
<ide> ),
<ide> re.VERBOSE,
<ide> def __call__(self, string):
<ide> string: the string to extract floats from.
<ide>
<ide> Returns:
<del> A (string, array) pair, where `string` has each float replaced by "..."
<del> and `array` is a `float32` `numpy.array` containing the extracted floats.
<add> A (string, array) pair, where `string` has each float replaced by
<add> "..." and `array` is a `float32` `numpy.array` containing the
<add> extracted floats.
<ide> """
<ide> texts = []
<ide> floats = []
<ide> def _tf_tensor_numpy_output(self, string):
<ide> )
<ide>
<ide> def check_output(self, want, got, optionflags):
<del> """Compares the docstring output to the output gotten by running the code.
<add> """Compares the docstring output to the output gotten by running the
<add> code.
<ide>
<ide> Python addresses in the output are replaced with wildcards.
<ide>
<ide> Float values in the output compared as using `np.allclose`:
<ide>
<del> * Float values are extracted from the text and replaced with wildcards.
<add> * Float values are extracted from the text and replaced with
<add> wildcards.
<ide> * The wildcard text is compared to the actual output.
<ide> * The float values are compared using `np.allclose`.
<ide>
<ide> def check_output(self, want, got, optionflags):
<ide>
<ide> # If the docstring's output is empty and there is some output generated
<ide> # after running the snippet, return True. This is because if the user
<del> # doesn't want to display output, respect that over what the doctest wants.
<add> # doesn't want to display output, respect that over what the doctest
<add> # wants.
<ide> if got and not want:
<ide> return True
<ide>
<ide> if want is None:
<ide> want = ""
<ide>
<del> # Replace python's addresses with ellipsis (`...`) since it can change on
<del> # each execution.
<add> # Replace python's addresses with ellipsis (`...`) since it can change
<add> # on each execution.
<ide> want = self._ADDRESS_RE.sub("at ...>", want)
<ide>
<ide> # Replace tf.Tensor strings with only their numpy field values.
<ide> def check_output(self, want, got, optionflags):
<ide> return False
<ide>
<ide> if self.want_floats.size == 0:
<del> # If there are no floats in the "want" string, ignore all the floats in
<del> # the result. "np.array([ ... ])" matches "np.array([ 1.0, 2.0 ])"
<add> # If there are no floats in the "want" string, ignore all the floats
<add> # in the result. "np.array([ ... ])" matches "np.array([ 1.0, 2.0
<add> # ])"
<ide> return True
<ide>
<ide> self.float_size_good = self.want_floats.size == self.got_floats.size
<ide> def check_output(self, want, got, optionflags):
<ide> def output_difference(self, example, got, optionflags):
<ide> got = [got]
<ide>
<del> # If the some of the float output is hidden with `...`, `float_size_good`
<del> # will be False. This is because the floats extracted from the string is
<del> # converted into a 1-D numpy array. Hence hidding floats is not allowed
<del> # anymore.
<add> # If the some of the float output is hidden with `...`,
<add> # `float_size_good` will be False. This is because the floats extracted
<add> # from the string is converted into a 1-D numpy array. Hence hidding
<add> # floats is not allowed anymore.
<ide> if self.text_good:
<ide> if not self.float_size_good:
<ide> got.append(
<ide><path>keras/testing_infra/test_combinations.py
<ide> def tearDown(self):
<ide> def run_with_all_saved_model_formats(test_or_class=None, exclude_formats=None):
<ide> """Execute the decorated test with all Keras saved model formats).
<ide>
<del> This decorator is intended to be applied either to individual test methods in
<del> a `test_combinations.TestCase` class, or directly to a test class that
<del> extends it. Doing so will cause the contents of the individual test
<del> method (or all test methods in the class) to be executed multiple times - once
<del> for each Keras saved model format.
<add> This decorator is intended to be applied either to individual test methods
<add> in a `test_combinations.TestCase` class, or directly to a test class that
<add> extends it. Doing so will cause the contents of the individual test method
<add> (or all test methods in the class) to be executed multiple times - once for
<add> each Keras saved model format.
<ide>
<ide> The Keras saved model formats include:
<ide> 1. HDF5: 'h5'
<ide> 2. SavedModel: 'tf'
<ide>
<del> Note: if stacking this decorator with absl.testing's parameterized decorators,
<del> those should be at the bottom of the stack.
<add> Note: if stacking this decorator with absl.testing's parameterized
<add> decorators, those should be at the bottom of the stack.
<ide>
<ide> Various methods in `testing_utils` to get file path for saved models will
<ide> auto-generate a string of the two saved model formats. This allows unittests
<ide> def test_foo(self):
<ide> This test tries to save the model into the formats of 'hdf5', 'h5', 'keras',
<ide> 'tensorflow', and 'tf'.
<ide>
<del> We can also annotate the whole class if we want this to apply to all tests in
<del> the class:
<add> We can also annotate the whole class if we want this to apply to all tests
<add> in the class:
<ide> ```python
<ide> @test_utils.run_with_all_saved_model_formats
<ide> class MyTests(test_utils.KerasTestCase):
<ide> def test_foo(self):
<ide> Defaults to None.
<ide>
<ide> Returns:
<del> Returns a decorator that will run the decorated test method multiple times:
<del> once for each desired Keras saved model format.
<add> Returns a decorator that will run the decorated test method multiple
<add> times: once for each desired Keras saved model format.
<ide>
<ide> Raises:
<ide> ImportError: If abseil parameterized is not installed or not included as
<ide> def test_foo(self):
<ide>
<ide> def single_method_decorator(f):
<ide> """Decorator that constructs the test cases."""
<del> # Use named_parameters so it can be individually run from the command line
<add> # Use named_parameters so it can be individually run from the command
<add> # line
<ide> @parameterized.named_parameters(*params)
<ide> @functools.wraps(f)
<ide> def decorated(self, saved_format, *args, **kwargs):
<ide> def run_with_all_weight_formats(test_or_class=None, exclude_formats=None):
<ide> def run_with_all_model_types(test_or_class=None, exclude_models=None):
<ide> """Execute the decorated test with all Keras model types.
<ide>
<del> This decorator is intended to be applied either to individual test methods in
<del> a `test_combinations.TestCase` class, or directly to a test class that
<del> extends it. Doing so will cause the contents of the individual test
<del> method (or all test methods in the class) to be executed multiple times - once
<del> for each Keras model type.
<add> This decorator is intended to be applied either to individual test methods
<add> in a `test_combinations.TestCase` class, or directly to a test class that
<add> extends it. Doing so will cause the contents of the individual test method
<add> (or all test methods in the class) to be executed multiple times - once for
<add> each Keras model type.
<ide>
<ide> The Keras model types are: ['functional', 'subclass', 'sequential']
<ide>
<del> Note: if stacking this decorator with absl.testing's parameterized decorators,
<del> those should be at the bottom of the stack.
<add> Note: if stacking this decorator with absl.testing's parameterized
<add> decorators, those should be at the bottom of the stack.
<ide>
<ide> Various methods in `testing_utils` to get models will auto-generate a model
<ide> of the currently active Keras model type. This allows unittests to confirm
<ide> def test_foo(self):
<ide> This test tries building a small mlp as both a functional model and as a
<ide> subclass model.
<ide>
<del> We can also annotate the whole class if we want this to apply to all tests in
<del> the class:
<add> We can also annotate the whole class if we want this to apply to all tests
<add> in the class:
<ide> ```python
<ide> @test_utils.run_with_all_model_types(exclude_models = ['sequential'])
<ide> class MyTests(test_utils.KerasTestCase):
<ide> def test_foo(self):
<ide> Defaults to None.
<ide>
<ide> Returns:
<del> Returns a decorator that will run the decorated test method multiple times:
<del> once for each desired Keras model type.
<add> Returns a decorator that will run the decorated test method multiple
<add> times: once for each desired Keras model type.
<ide>
<ide> Raises:
<ide> ImportError: If abseil parameterized is not installed or not included as
<ide> def test_foo(self):
<ide>
<ide> def single_method_decorator(f):
<ide> """Decorator that constructs the test cases."""
<del> # Use named_parameters so it can be individually run from the command line
<add> # Use named_parameters so it can be individually run from the command
<add> # line
<ide> @parameterized.named_parameters(*params)
<ide> @functools.wraps(f)
<ide> def decorated(self, model_type, *args, **kwargs):
<ide> def run_all_keras_modes(
<ide> ):
<ide> """Execute the decorated test with all keras execution modes.
<ide>
<del> This decorator is intended to be applied either to individual test methods in
<del> a `test_combinations.TestCase` class, or directly to a test class that
<del> extends it. Doing so will cause the contents of the individual test
<del> method (or all test methods in the class) to be executed multiple times -
<del> once executing in legacy graph mode, once running eagerly and with
<add> This decorator is intended to be applied either to individual test methods
<add> in a `test_combinations.TestCase` class, or directly to a test class that
<add> extends it. Doing so will cause the contents of the individual test method
<add> (or all test methods in the class) to be executed multiple times - once
<add> executing in legacy graph mode, once running eagerly and with
<ide> `should_run_eagerly` returning True, and once running eagerly with
<ide> `should_run_eagerly` returning False.
<ide>
<ide> If Tensorflow v2 behavior is enabled, legacy graph mode will be skipped, and
<ide> the test will only run twice.
<ide>
<del> Note: if stacking this decorator with absl.testing's parameterized decorators,
<del> those should be at the bottom of the stack.
<add> Note: if stacking this decorator with absl.testing's parameterized
<add> decorators, those should be at the bottom of the stack.
<ide>
<ide> For example, consider the following unittest:
<ide>
<ide> def test_foo(self):
<ide> rolled out yet
<ide>
<ide> Returns:
<del> Returns a decorator that will run the decorated test method multiple times.
<add> Returns a decorator that will run the decorated test method multiple
<add> times.
<ide>
<ide> Raises:
<ide> ImportError: If abseil parameterized is not installed or not included as
<ide> def test_foo(self):
<ide> def single_method_decorator(f):
<ide> """Decorator that constructs the test cases."""
<ide>
<del> # Use named_parameters so it can be individually run from the command line
<add> # Use named_parameters so it can be individually run from the command
<add> # line
<ide> @parameterized.named_parameters(*params)
<ide> @functools.wraps(f)
<ide> def decorated(self, run_mode, *args, **kwargs):
<ide> def _test_or_class_decorator(test_or_class, single_method_decorator):
<ide> parameterized decorators w/ each other, and to apply them to test methods
<ide> that have already been marked with an absl parameterized decorator.
<ide>
<del> Otherwise, treat the obj as a single method and apply the decorator directly.
<add> Otherwise, treat the obj as a single method and apply the decorator
<add> directly.
<ide>
<ide> Args:
<ide> test_or_class: A test method (that may have already been decorated with a
<ide><path>keras/testing_infra/test_utils.py
<ide> def layer_test(
<ide> in the layer class. This is helpful for testing custom layers.
<ide> test_harness: The Tensorflow test, if any, that this function is being
<ide> called in.
<del> supports_masking: Optional boolean to check the `supports_masking` property
<del> of the layer. If None, the check will not be performed.
<add> supports_masking: Optional boolean to check the `supports_masking`
<add> property of the layer. If None, the check will not be performed.
<ide>
<ide> Returns:
<ide> The output data (Numpy array) returned by the layer, for additional
<ide> def layer_test(
<ide> )
<ide>
<ide> def assert_shapes_equal(expected, actual):
<del> """Asserts that the output shape from the layer matches the actual shape."""
<add> """Asserts that the output shape from the layer matches the actual
<add> shape."""
<ide> if len(expected) != len(actual):
<ide> raise AssertionError(
<ide> "When testing layer %s, for input %s, found output_shape="
<ide> def assert_shapes_equal(expected, actual):
<ide> raise AssertionError(
<ide> "When testing layer %s **after deserialization**, "
<ide> "for input %s, found output_shape="
<del> "%s but expected to find inferred shape %s.\nFull kwargs: %s"
<add> "%s but expected to find inferred shape %s.\n"
<add> "Full kwargs: %s"
<ide> % (
<ide> layer_cls.__name__,
<ide> x,
<ide> def run_eagerly_scope(value):
<ide> The boolean gets restored to its original value upon exiting the scope.
<ide>
<ide> Args:
<del> value: Bool specifying if we should run models eagerly in the active test.
<del> Should be True or False.
<add> value: Bool specifying if we should run models eagerly in the active
<add> test. Should be True or False.
<ide>
<ide> Yields:
<ide> The provided value.
<ide> def get_save_format():
<ide> if _thread_local_data.saved_model_format is None:
<ide> raise ValueError(
<ide> "Cannot call `get_save_format()` outside of a "
<del> "`saved_model_format_scope()` or `run_with_all_saved_model_formats` "
<del> "decorator."
<add> "`saved_model_format_scope()` or "
<add> "`run_with_all_saved_model_formats` decorator."
<ide> )
<ide> return _thread_local_data.saved_model_format
<ide>
<ide> def get_save_kwargs():
<ide> if _thread_local_data.save_kwargs is None:
<ide> raise ValueError(
<ide> "Cannot call `get_save_kwargs()` outside of a "
<del> "`saved_model_format_scope()` or `run_with_all_saved_model_formats` "
<del> "decorator."
<add> "`saved_model_format_scope()` or "
<add> "`run_with_all_saved_model_formats` decorator."
<ide> )
<ide> return _thread_local_data.save_kwargs or {}
<ide>
<ide> def __init__(self, model_layers, *args, **kwargs):
<ide> Args:
<ide> model_layers: a list of layers to be added to the model.
<ide> *args: Model's args
<del> **kwargs: Model's keyword args, at most one of input_tensor -> the input
<del> tensor required for ragged/sparse input.
<add> **kwargs: Model's keyword args, at most one of input_tensor -> the
<add> input tensor required for ragged/sparse input.
<ide> """
<ide>
<ide> inputs = kwargs.pop("input_tensor", None)
<ide> super().__init__(*args, **kwargs)
<del> # Note that clone and build doesn't support lists of layers in subclassed
<del> # models. Adding each layer directly here.
<add> # Note that clone and build doesn't support lists of layers in
<add> # subclassed models. Adding each layer directly here.
<ide> for i, layer in enumerate(model_layers):
<ide> setattr(self, self._layer_name_for_i(i), layer)
<ide>
<ide> def get_multi_io_model(
<ide>
<ide> To build a two-input, two-output model:
<ide> Specify a list of layers for branch a and branch b, but do not specify any
<del> shared input branch or shared output branch. The resulting model will apply
<del> each branch to a different input, to produce two outputs.
<add> shared input branch or shared output branch. The resulting model will
<add> apply each branch to a different input, to produce two outputs.
<ide>
<ide> The first value in branch_a must be the Keras 'Input' layer for branch a,
<ide> and the first value in branch_b must be the Keras 'Input' layer for
<ide> def get_multi_io_model(
<ide> branch_a: A sequence of layers for branch a of the model.
<ide> branch_b: A sequence of layers for branch b of the model.
<ide> shared_input_branch: An optional sequence of layers to apply to a single
<del> input, before applying both branches to that intermediate result. If set,
<del> the model will take only one input instead of two. Defaults to None.
<add> input, before applying both branches to that intermediate result. If
<add> set, the model will take only one input instead of two. Defaults to
<add> None.
<ide> shared_output_branch: An optional sequence of layers to merge the
<ide> intermediate results produced by branch a and branch b. If set,
<ide> the model will produce only one output instead of two. Defaults to None.
<ide> def get_v2_optimizer(name, **kwargs):
<ide> return _V2_OPTIMIZER_MAP[name](**kwargs)
<ide> except KeyError:
<ide> raise ValueError(
<del> "Could not find requested v2 optimizer: {}\nValid choices: {}".format(
<del> name, list(_V2_OPTIMIZER_MAP.keys())
<del> )
<add> "Could not find requested v2 optimizer: "
<add> "{}\nValid choices: {}".format(name, list(_V2_OPTIMIZER_MAP.keys()))
<ide> )
<ide>
<ide>
<ide> def run_v2_only(obj=None):
<ide>
<ide> Args:
<ide> obj: function to be annotated. If None, return a
<del> decorator the can be applied to a function or class. If `obj` is not None,
<del> return the decorator applied to `obj`.
<add> decorator the can be applied to a function or class. If `obj` is not
<add> None, return the decorator applied to `obj`.
<ide>
<ide> Returns:
<del> Returns a decorator that will conditionally skip the decorated test method.
<add> Returns a decorator that will conditionally skip the decorated test
<add> method.
<ide> """
<ide> condition = not tf.__internal__.tf2.enabled()
<ide> reason = "Test is only compatible with TF v2." | 3 |
Text | Text | add note about habtm relations with scopes | 2ffeee3d2a211f7bb84c6b209c6d2c576ae6d586 | <ide><path>guides/source/upgrading_ruby_on_rails.md
<ide> CatalogProduct < ActiveRecord::Base
<ide> end
<ide> ```
<ide>
<add>* Note that the the prefix takes scopes into account as well, so relations between `Catalog::Category` and `Catalog::Product` or `Catalog::Category` and `CatalogProduct` need to be updated similarly.
<add>
<ide> ### Active Resource
<ide>
<ide> Rails 4.0 extracted Active Resource to its own gem. If you still need the feature you can add the [Active Resource gem](https://github.com/rails/activeresource) in your Gemfile. | 1 |
Text | Text | add alt to laravel logo image | c233957734b1353d8952e07c1dae462f8cddc3d4 | <ide><path>README.md
<del><p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400"></a></p>
<add><p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
<ide>
<ide> <p align="center">
<ide> <a href="https://travis-ci.org/laravel/framework"><img src="https://travis-ci.org/laravel/framework.svg" alt="Build Status"></a> | 1 |
PHP | PHP | support custom urls for aws storage | dfd494f0515d8bf712ac0e751b2baf7e687fddeb | <ide><path>config/filesystems.php
<ide>
<ide> 's3' => [
<ide> 'driver' => 's3',
<add> 'url' => env('AWS_URL'),
<ide> 'key' => env('AWS_KEY'),
<ide> 'secret' => env('AWS_SECRET'),
<ide> 'region' => env('AWS_REGION'), | 1 |
Python | Python | update quick_sort.py (#830) | a0ab3ce098c95c7edf3f32fedc9d3930d2d641e8 | <ide><path>sorts/quick_sort.py
<ide> def quick_sort(collection):
<ide> return collection
<ide> else:
<ide> pivot = collection[0]
<del> greater = [element for element in collection[1:] if element > pivot]
<del> lesser = [element for element in collection[1:] if element <= pivot]
<add> # Modify the list comprehensions to reduce the number of judgments, the speed has increased by more than 50%.
<add> greater = []
<add> lesser = []
<add> for element in collection[1:]:
<add> if element > pivot:
<add> greater.append(element)
<add> else:
<add> lesser.append(element)
<add> # greater = [element for element in collection[1:] if element > pivot]
<add> # lesser = [element for element in collection[1:] if element <= pivot]
<ide> return quick_sort(lesser) + [pivot] + quick_sort(greater)
<ide>
<ide> | 1 |
Javascript | Javascript | add help option to react-native-cli | 9c667f29688158727f2b02f4a8954e2018423ea0 | <ide><path>react-native-cli/index.js
<ide> var commands = argv._;
<ide> if (cli) {
<ide> cli.run();
<ide> } else {
<add> if (argv._.length === 0 && (argv.h || argv.help)) {
<add> console.log([
<add> '',
<add> ' Usage: react-native [command] [options]',
<add> '',
<add> '',
<add> ' Commands:',
<add> '',
<add> ' init <ProjectName> [options] generates a new project and installs its dependencies',
<add> '',
<add> ' Options:',
<add> '',
<add> ' -h, --help output usage information',
<add> ' -v, --version output the version number',
<add> '',
<add> ].join('\n'));
<add> process.exit(0);
<add> }
<add>
<ide> if (commands.length === 0) {
<ide> console.error(
<del> 'You did not pass any commands, did you mean to run `react-native init`?'
<add> 'You did not pass any commands, run `react-native --help` to see a list of all available commands.'
<ide> );
<ide> process.exit(1);
<ide> } | 1 |
Javascript | Javascript | update webglutils for webgl 2.0 unsigned_int_24_8 | f02117fe857f8bb5517830a14969ade397494e4a | <ide><path>src/renderers/webgl/WebGLUtils.js
<ide> function WebGLUtils( gl, extensions ) {
<ide>
<ide> extension = extensions.get( 'WEBGL_depth_texture' );
<ide>
<del> if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
<add> if ( extension !== null ) return isWebGL2 ? extension.UNSIGNED_INT_24_8 : extension.UNSIGNED_INT_24_8_WEBGL;
<ide>
<ide> }
<ide> | 1 |
Javascript | Javascript | change schema and unpack script | b014b234042c8573660d1cb72ab105d2eeea819c | <ide><path>getChallenges.js
<ide> function superblockInfo(filePath) {
<ide> }
<ide> }
<ide>
<del>module.exports = function getChallenges(challengesDir) {
<add>// unpackFlag is an argument passed by the unpack script in unpack.js
<add>// which allows us to conditionall omit translations when running
<add>// the test suite and prevent schema related errors in the main fCC branch
<add>module.exports = function getChallenges(challengesDir, unpackFlag) {
<ide> if (!challengesDir) {
<ide> challengesDir = 'challenges';
<ide> }
<ide> module.exports = function getChallenges(challengesDir) {
<ide> 'react',
<ide> 'reactRedux',
<ide> 'redux',
<add> 'releasedOn',
<add> unpackFlag ? undefined : 'translations',
<ide> 'type'
<ide> ])
<ide> );
<ide><path>schema/challengeSchema.js
<ide> const schema = Joi.object().keys({
<ide> crossDomain: Joi.bool()
<ide> })
<ide> ),
<del> releasedOn: Joi.string().allow(''),
<ide> solutions: Joi.array().items(Joi.string().optional()),
<ide> superBlock: Joi.string(),
<ide> superOrder: Joi.number(),
<ide> const schema = Joi.object().keys({
<ide> ),
<ide> template: Joi.string(),
<ide> time: Joi.string().allow(''),
<del> title: Joi.string().required(),
<del> translations: Joi.object().pattern(
<del> /\w+(-\w+)*/,
<del> Joi.object().keys({
<del> title: Joi.string(),
<del> description: Joi.array().items(Joi.string().allow(''))
<del> })
<del> )
<add> title: Joi.string().required()
<ide> });
<ide>
<ide> exports.validateChallenge = function validateChallenge(challenge) {
<ide><path>unpack.js
<ide> import fs from 'fs-extra';
<ide> import path from 'path';
<ide> import browserify from 'browserify';
<ide> import getChallenges from './getChallenges';
<del>import {UnpackedChallenge, ChallengeFile} from './unpackedChallenge';
<add>import { UnpackedChallenge, ChallengeFile } from './unpackedChallenge';
<ide>
<ide> // Unpack all challenges
<ide> // from all seed/challenges/00-foo/bar.json files
<ide> // into seed/unpacked/00-foo/bar/000-id.html files
<ide> //
<del>// todo: unpack translations too
<ide> // todo: use common/app/routes/Challenges/utils/index.js:15 maps
<ide> // to determine format/style for non-JS tests
<ide> // todo: figure out embedded images etc. served from elsewhere in the project
<ide> let unpackedDir = path.join(__dirname, 'unpacked');
<ide>
<ide> // bundle up the test-running JS
<ide> function createUnpackedBundle() {
<del> fs.mkdirp(unpackedDir, (err) => {
<add> fs.mkdirp(unpackedDir, err => {
<ide> if (err && err.code !== 'EEXIST') {
<ide> console.log(err);
<ide> throw err;
<ide> function createUnpackedBundle() {
<ide> let unpackedFile = path.join(__dirname, 'unpacked.js');
<ide> let b = browserify(unpackedFile).bundle();
<ide> b.on('error', console.error);
<del> let unpackedBundleFile =
<del> path.join(unpackedDir, 'unpacked-bundle.js');
<add> let unpackedBundleFile = path.join(unpackedDir, 'unpacked-bundle.js');
<ide> const bundleFileStream = fs.createWriteStream(unpackedBundleFile);
<ide> bundleFileStream.on('finish', () => {
<ide> console.log('Wrote bundled JS into ' + unpackedBundleFile);
<ide> async function cleanUnpackedDir(unpackedChallengeBlockDir) {
<ide> filePath = path.join(unpackedChallengeBlockDir, filePath);
<ide> return new Promise(() => fs.unlink(filePath));
<ide> };
<del> let promises = fs.readdirSync(unpackedChallengeBlockDir)
<del> .filter(filePath => (/\.html$/i).test(filePath))
<add> let promises = fs
<add> .readdirSync(unpackedChallengeBlockDir)
<add> .filter(filePath => /\.html$/i.test(filePath))
<ide> .map(promiseToDelete);
<ide> await Promise.all(promises);
<ide> }
<ide> function unpackChallengeBlock(challengeBlock) {
<ide> challengeBlockPath.name
<ide> );
<ide>
<del> fs.mkdirp(unpackedChallengeBlockDir, (err) => {
<add> fs.mkdirp(unpackedChallengeBlockDir, err => {
<ide> if (err && err.code !== 'EEXIST') {
<ide> console.log(err);
<ide> throw err;
<ide> function unpackChallengeBlock(challengeBlock) {
<ide> delete challengeBlock.fileName;
<ide> delete challengeBlock.superBlock;
<ide> delete challengeBlock.superOrder;
<del> let challengeBlockCopy =
<del> new ChallengeFile(
<del> unpackedChallengeBlockDir,
<del> challengeBlockPath.name,
<del> '.json');
<add> let challengeBlockCopy = new ChallengeFile(
<add> unpackedChallengeBlockDir,
<add> challengeBlockPath.name,
<add> '.json'
<add> );
<ide> challengeBlockCopy.write(JSON.stringify(challengeBlock, null, 2));
<ide>
<ide> // unpack each challenge into an HTML file
<ide> function unpackChallengeBlock(challengeBlock) {
<ide> }
<ide>
<ide> createUnpackedBundle();
<del>let challenges = getChallenges();
<add>let challenges = getChallenges(null, true);
<ide> challenges.forEach(challengeBlock => {
<ide> unpackChallengeBlock(challengeBlock);
<ide> });
<ide><path>unpackedChallenge.js
<ide> class UnpackedChallenge {
<ide> text.push('<!--end-->');
<ide> text.push('</div>');
<ide>
<del> text.push('');
<del> text.push('<h2>Released On</h2>');
<del> text.push('<div class="unpacked">');
<del> text.push('<!--releasedOn-->');
<del> text.push(this.challenge.releasedOn);
<del> text.push('<!--end-->');
<del> text.push('</div>');
<del>
<ide> text.push('');
<ide> text.push('<h2>Files</h2>');
<ide> text.push(` | 4 |
Javascript | Javascript | add tests for moment#tonow and fixed prototype | d34425468c8c926ccd1e44d0c1a9288db6c87f67 | <ide><path>src/lib/moment/prototype.js
<ide> proto.format = format;
<ide> proto.from = from;
<ide> proto.fromNow = fromNow;
<ide> proto.to = to;
<del>proto.toNow = fromNow;
<add>proto.toNow = toNow;
<ide> proto.get = getSet;
<ide> proto.invalidAt = invalidAt;
<ide> proto.isAfter = isAfter;
<ide><path>src/test/moment/relative_time.js
<ide> import moment from '../../moment';
<ide>
<ide> module('relative time');
<ide>
<del>test('default thresholds', function (assert) {
<add>test('default thresholds fromNow', function (assert) {
<ide> var a = moment();
<ide>
<ide> // Seconds to minutes threshold
<ide> test('default thresholds', function (assert) {
<ide> assert.equal(a.fromNow(), 'a year ago', 'Above default days to years threshold');
<ide> });
<ide>
<add>test('default thresholds toNow', function (assert) {
<add> var a = moment();
<add>
<add> // Seconds to minutes threshold
<add> a.subtract(44, 'seconds');
<add> assert.equal(a.toNow(), 'in a few seconds', 'Below default seconds to minutes threshold');
<add> a.subtract(1, 'seconds');
<add> assert.equal(a.toNow(), 'in a minute', 'Above default seconds to minutes threshold');
<add>
<add> // Minutes to hours threshold
<add> a = moment();
<add> a.subtract(44, 'minutes');
<add> assert.equal(a.toNow(), 'in 44 minutes', 'Below default minute to hour threshold');
<add> a.subtract(1, 'minutes');
<add> assert.equal(a.toNow(), 'in an hour', 'Above default minute to hour threshold');
<add>
<add> // Hours to days threshold
<add> a = moment();
<add> a.subtract(21, 'hours');
<add> assert.equal(a.toNow(), 'in 21 hours', 'Below default hours to day threshold');
<add> a.subtract(1, 'hours');
<add> assert.equal(a.toNow(), 'in a day', 'Above default hours to day threshold');
<add>
<add> // Days to month threshold
<add> a = moment();
<add> a.subtract(25, 'days');
<add> assert.equal(a.toNow(), 'in 25 days', 'Below default days to month (singular) threshold');
<add> a.subtract(1, 'days');
<add> assert.equal(a.toNow(), 'in a month', 'Above default days to month (singular) threshold');
<add>
<add> // months to year threshold
<add> a = moment();
<add> a.subtract(10, 'months');
<add> assert.equal(a.toNow(), 'in 10 months', 'Below default days to years threshold');
<add> a.subtract(1, 'month');
<add> assert.equal(a.toNow(), 'in a year', 'Above default days to years threshold');
<add>});
<add>
<ide> test('custom thresholds', function (assert) {
<ide> // Seconds to minutes threshold
<ide> moment.relativeTimeThreshold('s', 55); | 2 |
Javascript | Javascript | add use-subscription to rollup bundle config | 8d540387736ac8a3d2d1e932b187cf7fe2c9607e | <ide><path>scripts/rollup/bundles.js
<ide> const bundles = [
<ide> externals: ['react', 'scheduler'],
<ide> },
<ide>
<del> /******* createComponentWithSubscriptions (experimental) *******/
<add> /******* createComponentWithSubscriptions *******/
<ide> {
<ide> bundleTypes: [NODE_DEV, NODE_PROD],
<ide> moduleType: ISOMORPHIC,
<ide> const bundles = [
<ide> }),
<ide> },
<ide>
<add> /******* Hook for managing subscriptions safely *******/
<add> {
<add> bundleTypes: [NODE_DEV, NODE_PROD],
<add> moduleType: ISOMORPHIC,
<add> entry: 'use-subscription',
<add> global: 'useSubscription',
<add> externals: ['react'],
<add> },
<add>
<ide> /******* React Scheduler (experimental) *******/
<ide> {
<ide> bundleTypes: [NODE_DEV, NODE_PROD, FB_WWW_DEV, FB_WWW_PROD], | 1 |
Text | Text | remove unsused link | a17d5d2b0bff535dc1d7dcbd36947648e7a0511f | <ide><path>docs/tutorial/1-serialization.md
<ide> We'll see how we can start to improve things in [part 2 of the tutorial][tut-2].
<ide> [virtualenv]: http://www.virtualenv.org/en/latest/index.html
<ide> [tut-2]: 2-requests-and-responses.md
<ide> [httpie]: https://github.com/jakubroztocil/httpie#installation
<del>[brew]: http://brew.sh | 1 |
Python | Python | move microvertion to connection | 2309be55f5b98e08c557614078195a7ea816ddc4 | <ide><path>libcloud/common/openstack.py
<ide> def __init__(
<ide> ex_force_service_type=None,
<ide> ex_force_service_name=None,
<ide> ex_force_service_region=None,
<add> ex_force_microversion=None,
<ide> ex_auth_cache=None,
<ide> retry_delay=None,
<ide> backoff=None,
<ide> def __init__(
<ide> self._ex_force_service_type = ex_force_service_type
<ide> self._ex_force_service_name = ex_force_service_name
<ide> self._ex_force_service_region = ex_force_service_region
<add> self._ex_force_microversion = ex_force_microversion
<ide> self._ex_auth_cache = ex_auth_cache
<ide> self._osa = None
<ide>
<ide> def get_endpoint(self):
<ide> def add_default_headers(self, headers):
<ide> headers[AUTH_TOKEN_HEADER] = self.auth_token
<ide> headers["Accept"] = self.accept_format
<add> if self._ex_force_microversion:
<add> headers["OpenStack-API-Version"] = (
<add> "compute %s" % self._ex_force_microversion
<add> )
<ide> return headers
<ide>
<ide> def morph_action_hook(self, action):
<ide> def __init__(
<ide> ex_force_service_name=None,
<ide> ex_force_service_region=None,
<ide> ex_auth_cache=None,
<add> ex_force_microversion=None,
<ide> *args,
<ide> **kwargs,
<ide> ):
<ide> def __init__(
<ide> self._ex_force_service_name = ex_force_service_name
<ide> self._ex_force_service_region = ex_force_service_region
<ide> self._ex_auth_cache = ex_auth_cache
<add> self._ex_force_microversion = ex_force_microversion
<ide>
<ide> def openstack_connection_kwargs(self):
<ide> """
<ide> def openstack_connection_kwargs(self):
<ide> rv["ex_force_service_region"] = self._ex_force_service_region
<ide> if self._ex_auth_cache is not None:
<ide> rv["ex_auth_cache"] = self._ex_auth_cache
<add> if self._ex_force_microversion:
<add> rv["ex_force_microversion"] = self._ex_force_microversion
<ide> return rv
<ide><path>libcloud/compute/drivers/openstack.py
<ide> class OpenStack_1_1_NodeDriver(OpenStackNodeDriver):
<ide> _networks_url_prefix = "/os-networks"
<ide>
<ide> def __init__(self, *args, **kwargs):
<del> self.ex_force_microversion = str(kwargs.pop("ex_force_microversion", ''))
<ide> self._ex_force_api_version = str(kwargs.pop("ex_force_api_version", None))
<ide> super(OpenStack_1_1_NodeDriver, self).__init__(*args, **kwargs)
<ide>
<del> def _set_microversion(self, headers=None):
<del> """Add the microversion header to the specified headers"""
<del> res = {}
<del> if self.ex_force_microversion:
<del> if headers:
<del> res.update(headers)
<del> res["OpenStack-API-Version"] = "compute %s" % self.ex_force_microversion
<del> return res
<del>
<ide> def create_node(
<ide> self,
<ide> name,
<ide> def create_node(
<ide> if ex_os_scheduler_hints:
<ide> data["os:scheduler_hints"] = ex_os_scheduler_hints
<ide>
<del> resp = self.connection.request(
<del> "/servers", method="POST", data=data, headers=self._set_microversion()
<del> )
<add> resp = self.connection.request("/servers", method="POST", data=data)
<ide>
<ide> create_response = resp.object["server"]
<ide> server_resp = self.connection.request("/servers/%s" % create_response["id"])
<ide><path>libcloud/test/common/test_openstack.py
<ide> def test_base_connection_timeout(self):
<ide> host="127.0.0.1", secure=1, port=443, timeout=10
<ide> )
<ide>
<add> def test_set_microversion(self):
<add> self.connection._ex_force_microversion = "2.67"
<add> headers = self.connection.add_default_headers({})
<add> self.assertEqual(headers["OpenStack-API-Version"], "compute 2.67")
<add>
<ide>
<ide> if __name__ == "__main__":
<ide> sys.exit(unittest.main()) | 3 |
Javascript | Javascript | show different text for build error skips | d94145e38de0d2a182e872b3eb5ed0cc7119a94b | <ide><path>lib/cache/PackFileCacheStrategy.js
<ide> class PackContentItems {
<ide> } catch (e) {
<ide> rollback(s);
<ide> if (e === NOT_SERIALIZABLE) continue;
<del> const message = `Skipped not serializable cache item: ${e.message}`;
<add> const msg = "Skipped not serializable cache item";
<ide> if (e.message.includes("ModuleBuildError")) {
<del> logger.log(message);
<add> logger.log(`${msg} (in build error): ${e.message}`);
<add> logger.debug(`${msg} '${key}' (in build error): ${e.stack}`);
<ide> } else {
<del> logger.warn(message);
<add> logger.warn(`${msg}: ${e.message}`);
<add> logger.debug(`${msg} '${key}': ${e.stack}`);
<ide> }
<del> logger.debug(
<del> `Skipped not serializable cache item '${key}': ${e.stack}`
<del> );
<ide> }
<ide> }
<ide> write(null); | 1 |
Text | Text | add cask cookbook link to maintainer guidlines | 73ca9a0e05efa24c9e26011271729589d48e481b | <ide><path>docs/Maintainer-Guidelines.md
<ide> access** to Homebrew’s repository and help merge the contributions of
<ide> others. You may find what is written here interesting, but it’s
<ide> definitely not a beginner’s guide.
<ide>
<del>Maybe you were looking for the [Formula Cookbook](Formula-Cookbook.md)?
<add>Maybe you were looking for the [Formula Cookbook](Formula-Cookbook.md) or [Cask Cookbook](Cask-Cookbook.md)?
<ide>
<ide> ## Overview
<ide> | 1 |
Python | Python | fix merge conflicts | 095b6c118cb0b0c3bfda9c012e2dbcd5546f4afb | <ide><path>keras/backend/tensorflow_backend.py
<ide> def mean(x, axis=None, keepdims=False):
<ide> def any(x, axis=None, keepdims=False):
<ide> '''Bitwise reduction (logical OR).
<ide>
<del> Return array of int8 (0s and 1s).
<add> Return array of uint8 (0s and 1s).
<ide> '''
<ide> axis = normalize_axis(axis, ndim(x))
<ide> x = tf.cast(x, tf.bool)
<ide> x = tf.reduce_any(x, reduction_indices=axis, keep_dims=keepdims)
<del> return tf.cast(x, tf.int8)
<add> return tf.cast(x, tf.uint8)
<ide>
<ide>
<ide> def argmax(x, axis=-1):
<ide> def rnn(step_function, inputs, initial_states,
<ide>
<ide> if mask is not None:
<ide> # Transpose not supported by bool tensor types, hence round-trip to uint8.
<del> mask = tf.cast(tf.transpose(tf.cast(mask, tf.uint8), axes), tf.bool)
<add> mask = tf.cast(mask, tf.uint8)
<add> if len(mask.get_shape()) == ndim-1:
<add> mask = expand_dims(mask)
<add> mask = tf.cast(tf.transpose(mask, axes), tf.bool)
<ide> mask_list = tf.unpack(mask)
<ide>
<ide> for input, mask_t in zip(input_list, mask_list):
<ide><path>keras/backend/theano_backend.py
<ide> def rnn(step_function, inputs, initial_states,
<ide> the step function.
<ide> go_backwards: boolean. If True, do the iteration over
<ide> the time dimension in reverse order.
<del> mask: binary tensor with shape (samples, time, 1),
<add> mask: binary tensor with shape (samples, time),
<ide> with a zero for every element that is masked.
<ide>
<ide> Returns
<ide> def rnn(step_function, inputs, initial_states,
<ide> if mask is None:
<ide> mask = expand_dims(ones_like(T.sum(inputs, axis=-1)))
<ide> else:
<add> if mask.ndim == ndim-1:
<add> mask = expand_dims(mask)
<add> assert mask.ndim == ndim
<ide> mask = mask.dimshuffle(axes)
<ide>
<ide> def _step(input, mask, output_tm1, *states):
<ide> def pool2d(x, pool_size, strides=(1, 1), border_mode='valid',
<ide> pool_out = pool_out.dimshuffle((0, 2, 3, 1))
<ide> return pool_out
<ide>
<add>
<ide> # RANDOMNESS
<ide>
<ide>
<ide><path>keras/layers/core.py
<ide> class Masking(MaskedLayer):
<ide> def __init__(self, mask_value=0., **kwargs):
<ide> super(Masking, self).__init__(**kwargs)
<ide> self.mask_value = mask_value
<del> self.input = K.placeholder(ndim=3)
<add> if (not hasattr(self, 'input')):
<add> self.input = K.placeholder(ndim=3)
<ide>
<ide> def get_output_mask(self, train=False):
<ide> X = self.get_input(train)
<del> return K.any(K.ones_like(X) * (1. - K.equal(X, self.mask_value)),
<del> axis=-1)
<add> return K.any(K.not_equal(X, self.mask_value), axis=-1)
<ide>
<ide> def get_output(self, train=False):
<ide> X = self.get_input(train)
<del> return X * K.any((1. - K.equal(X, self.mask_value)),
<del> axis=-1, keepdims=True)
<add> return X * K.cast(K.any(K.not_equal(X, self.mask_value), axis=-1, keepdims=True), K.floatx())
<ide>
<ide> def get_config(self):
<ide> config = {'name': self.__class__.__name__,
<ide><path>keras/layers/embeddings.py
<ide> def get_output_mask(self, train=None):
<ide> if not self.mask_zero:
<ide> return None
<ide> else:
<del> return K.expand_dims(K.not_equal(X, 0))
<add> return K.not_equal(X, 0)
<ide>
<ide> @property
<ide> def output_shape(self):
<ide><path>keras/objectives.py
<ide> def hinge(y_true, y_pred):
<ide> def categorical_crossentropy(y_true, y_pred):
<ide> '''Expects a binary class matrix instead of a vector of scalar classes.
<ide> '''
<del> return K.mean(K.categorical_crossentropy(y_pred, y_true), axis=-1)
<add> return K.categorical_crossentropy(y_pred, y_true)
<ide>
<ide>
<ide> def binary_crossentropy(y_true, y_pred):
<ide> def poisson(y_true, y_pred):
<ide>
<ide>
<ide> def cosine_proximity(y_true, y_pred):
<del> assert K.ndim(y_true) == 2
<del> assert K.ndim(y_pred) == 2
<del> y_true = K.l2_normalize(y_true, axis=1)
<del> y_pred = K.l2_normalize(y_pred, axis=1)
<del> return -K.mean(y_true * y_pred, axis=1)
<add> y_true = K.l2_normalize(y_true, axis=-1)
<add> y_pred = K.l2_normalize(y_pred, axis=-1)
<add> return -K.mean(y_true * y_pred, axis=-1)
<ide>
<ide>
<ide> # aliases
<ide><path>tests/keras/layers/test_core.py
<ide> def test_naming():
<ide> model.train_on_batch(np.random.random((2, 2)), np.random.random((2, 2)))
<ide>
<ide>
<del>@pytest.mark.skipif(K._BACKEND == 'tensorflow',
<del> reason='currently not working with TensorFlow')
<ide> def test_sequences():
<ide> '''Test masking sequences with zeroes as padding'''
<ide> # integer inputs, one per timestep, like embeddings
<ide> layer = core.Masking()
<del> func = K.function([layer.input], [layer.get_output_mask()])
<add> func = K.function([layer.get_input(True)], [layer.get_output_mask()])
<ide> input_data = np.array([[[1], [2], [3], [0]],
<ide> [[0], [4], [5], [0]]], dtype=np.int32)
<ide>
<ide> def test_sequences():
<ide> assert np.all(output == expected), 'Output not as expected'
<ide>
<ide>
<del>@pytest.mark.skipif(K._BACKEND == 'tensorflow',
<del> reason='currently not working with TensorFlow')
<ide> def test_non_zero():
<ide> '''Test masking with non-zero mask value'''
<ide> layer = core.Masking(5)
<ide> def test_non_zero():
<ide> assert np.all(output == expected), 'Output not as expected'
<ide>
<ide>
<del>@pytest.mark.skipif(K._BACKEND == 'tensorflow',
<del> reason='currently not working with TensorFlow')
<ide> def test_non_zero_output():
<ide> '''Test output of masking layer with non-zero mask value'''
<ide> layer = core.Masking(5)
<ide><path>tests/keras/layers/test_recurrent.py
<ide> from numpy.testing import assert_allclose
<ide>
<ide> from keras.layers import recurrent, embeddings
<add>from keras.models import Sequential
<add>from keras.layers.core import Masking
<add>
<ide> from keras import backend as K
<ide> from keras.models import Sequential, model_from_json
<ide>
<ide> def test_batch_input_shape_serialization():
<ide> assert(reconstructed_model.input_shape == (2, 2))
<ide>
<ide>
<add>def test_masking_layer():
<add> ''' This test based on a previously failing issue here:
<add> https://github.com/fchollet/keras/issues/1567
<add>
<add> '''
<add> model = Sequential()
<add> model.add(Masking(input_shape=(3, 4)))
<add> model.add(recurrent.LSTM(output_dim=5, return_sequences=True))
<add> model.compile(loss='categorical_crossentropy', optimizer='adam')
<add> I = np.random.random((6, 3, 4))
<add> V = np.abs(np.random.random((6, 3, 5)))
<add> V /= V.sum(axis=-1, keepdims=True)
<add> model.fit(I, V, nb_epoch=1, batch_size=100, verbose=1)
<add>
<add>
<ide> if __name__ == '__main__':
<ide> pytest.main([__file__])
<ide><path>tests/keras/test_objectives.py
<add>import numpy as np
<add>
<add>from keras import objectives
<add>from keras import backend as K
<add>
<add>
<add>allobj = [objectives.mean_squared_error, objectives.root_mean_squared_error,
<add> objectives.mean_absolute_error, objectives.mean_absolute_percentage_error,
<add> objectives.mean_squared_logarithmic_error, objectives.squared_hinge,
<add> objectives.hinge, objectives.categorical_crossentropy, objectives.binary_crossentropy, objectives.poisson,
<add> objectives.cosine_proximity]
<add>
<add>def test_objective_shapes_3d():
<add> y_a = K.variable(np.random.random((5, 6, 7)))
<add> y_b = K.variable(np.random.random((5, 6, 7)))
<add> for obj in allobj:
<add> objective_output = obj(y_a, y_b)
<add> assert K.eval(objective_output).shape == (5, 6)
<add>
<add>def test_objective_shapes_2d():
<add> y_a = K.variable(np.random.random((6, 7)))
<add> y_b = K.variable(np.random.random((6, 7)))
<add> for obj in allobj:
<add> objective_output = obj(y_a, y_b)
<add> assert K.eval(objective_output).shape == (6,)
<ide><path>tests/test_loss_masking.py
<ide> from keras import backend as K
<ide>
<ide>
<del>@pytest.mark.skipif(K._BACKEND == 'tensorflow',
<del> reason='currently not working with TensorFlow')
<ide> def test_masking():
<ide> np.random.seed(1337)
<ide> X = np.array(
<ide> [[[1, 1], [2, 1], [3, 1], [5, 5]],
<ide> [[1, 5], [5, 0], [0, 0], [0, 0]]], dtype=np.int32)
<ide> model = Sequential()
<del> model.add(Masking(mask_value=0, input_shape=(None, 2)))
<add> model.add(Masking(mask_value=0, input_shape=(4, 2)))
<ide> model.add(TimeDistributedDense(1, init='one'))
<ide> model.compile(loss='mse', optimizer='sgd')
<ide> y = model.predict(X) | 9 |
Go | Go | run auplink before unmounting aufs | 2f67a62b5b48862948b1ce92aeffbb83c3707ee0 | <ide><path>mount.go
<ide> package docker
<ide>
<ide> import (
<ide> "fmt"
<add> "github.com/dotcloud/docker/utils"
<ide> "os"
<add> "os/exec"
<ide> "path/filepath"
<ide> "syscall"
<ide> "time"
<ide> )
<ide>
<ide> func Unmount(target string) error {
<add> if err := exec.Command("auplink", target, "flush").Run(); err != nil {
<add> utils.Debugf("[warning]: couldn't run auplink before unmount: %s", err)
<add> }
<ide> if err := syscall.Unmount(target, 0); err != nil {
<ide> return err
<ide> } | 1 |
Javascript | Javascript | add lazy evaluation tests | 78cea046e4ca01a068ae5701cd835357584327ff | <ide><path>packages/ember-glimmer/tests/utils/shared-conditional-tests.js
<ide> export class TogglingHelperConditionalsTest extends TogglingConditionalsTest {
<ide> this.assertText('T1');
<ide> }
<ide>
<add> ['@glimmer evaluation should be lazy'](assert) {
<add> let truthyEvaluated;
<add> let falsyEvaluated;
<add>
<add> let withoutEvaluatingTruthy = (callback) => {
<add> truthyEvaluated = false;
<add> callback();
<add> assert.ok(!truthyEvaluated, 'x-truthy is not evaluated');
<add> };
<add>
<add> let withoutEvaluatingFalsy = (callback) => {
<add> falsyEvaluated = false;
<add> callback();
<add> assert.ok(!falsyEvaluated, 'x-falsy is not evaluated');
<add> };
<add>
<add> this.registerHelper('x-truthy', {
<add> compute() {
<add> truthyEvaluated = true;
<add> return 'T';
<add> }
<add> });
<add>
<add> this.registerHelper('x-falsy', {
<add> compute() {
<add> falsyEvaluated = true;
<add> return 'F';
<add> }
<add> });
<add>
<add> let template = this.wrappedTemplateFor({ cond: 'cond', truthy: '(x-truthy)', falsy: '(x-falsy)' });
<add>
<add> withoutEvaluatingFalsy(() => this.render(template, { cond: this.truthyValue }));
<add>
<add> this.assertText('T');
<add>
<add> withoutEvaluatingFalsy(() => this.runTask(() => this.rerender()));
<add>
<add> this.assertText('T');
<add>
<add> withoutEvaluatingTruthy(() => this.runTask(() => set(this.context, 'cond', this.falsyValue)));
<add>
<add> this.assertText('F');
<add>
<add> withoutEvaluatingTruthy(() => this.runTask(() => this.rerender()));
<add>
<add> this.assertText('F');
<add>
<add> withoutEvaluatingFalsy(() => this.runTask(() => set(this.context, 'cond', this.truthyValue)));
<add>
<add> this.assertText('T');
<add> }
<add>
<ide> }
<ide>
<ide> export const SyntaxCondtionalTestHelpers = {
<ide> export class TogglingSyntaxConditionalsTest extends TogglingConditionalsTest {
<ide> this.assertText('');
<ide> }
<ide>
<add> ['@test evaluation should be lazy'](assert) {
<add> let truthyEvaluated;
<add> let falsyEvaluated;
<add>
<add> let withoutEvaluatingTruthy = (callback) => {
<add> truthyEvaluated = false;
<add> callback();
<add> assert.ok(!truthyEvaluated, 'x-truthy is not evaluated');
<add> };
<add>
<add> let withoutEvaluatingFalsy = (callback) => {
<add> falsyEvaluated = false;
<add> callback();
<add> assert.ok(!falsyEvaluated, 'x-falsy is not evaluated');
<add> };
<add>
<add> this.registerHelper('x-truthy', {
<add> compute() {
<add> truthyEvaluated = true;
<add> return 'T';
<add> }
<add> });
<add>
<add> this.registerHelper('x-falsy', {
<add> compute() {
<add> falsyEvaluated = true;
<add> return 'F';
<add> }
<add> });
<add>
<add> let template = this.wrappedTemplateFor({ cond: 'cond', truthy: '{{x-truthy}}', falsy: '{{x-falsy}}' });
<add>
<add> withoutEvaluatingFalsy(() => this.render(template, { cond: this.truthyValue }));
<add>
<add> this.assertText('T');
<add>
<add> withoutEvaluatingFalsy(() => this.runTask(() => this.rerender()));
<add>
<add> this.assertText('T');
<add>
<add> withoutEvaluatingTruthy(() => this.runTask(() => set(this.context, 'cond', this.falsyValue)));
<add>
<add> this.assertText('F');
<add>
<add> withoutEvaluatingTruthy(() => this.runTask(() => this.rerender()));
<add>
<add> this.assertText('F');
<add>
<add> withoutEvaluatingFalsy(() => this.runTask(() => set(this.context, 'cond', this.truthyValue)));
<add>
<add> this.assertText('T');
<add> }
<add>
<ide> }
<ide>
<ide> applyMixins(TogglingSyntaxConditionalsTest, SyntaxCondtionalTestHelpers); | 1 |
Ruby | Ruby | fix polymorphic preloads on not null _type columns | de32d972bfde8871f7c1a4621f2223ea9b6715b2 | <ide><path>activerecord/lib/active_record/associations/preloader.rb
<ide> def grouped_records(association, records)
<ide>
<ide> reflection_records.each_with_object({}) do |(reflection, r_records),h|
<ide> h[reflection] = r_records.group_by { |record|
<del> association_klass(reflection, record)
<add> record.association(association).klass
<ide> }
<ide> end
<ide> end
<ide> def raise_config_error(record, association)
<ide> "perhaps you misspelled it?"
<ide> end
<ide>
<del> def association_klass(reflection, record)
<del> if reflection.macro == :belongs_to && reflection.options[:polymorphic]
<del> klass = record.read_attribute(reflection.foreign_type.to_s)
<del> klass && klass.constantize
<del> else
<del> reflection.klass
<del> end
<del> end
<del>
<ide> class AlreadyLoaded
<ide> attr_reader :owners, :reflection
<ide>
<ide><path>activerecord/test/cases/associations/eager_test.rb
<ide> def test_finding_with_includes_on_null_belongs_to_polymorphic_association
<ide> end
<ide> end
<ide>
<add> def test_finding_with_includes_on_empty_polymorphic_type_column
<add> sponsor = sponsors(:moustache_club_sponsor_for_groucho)
<add> sponsor.update!(sponsorable_type: '', sponsorable_id: nil) # sponsorable_type column might be declared NOT NULL
<add> sponsor = assert_queries(1) do
<add> assert_nothing_raised { Sponsor.all.merge!(:includes => :sponsorable).find(sponsor.id) }
<add> end
<add> assert_no_queries do
<add> assert_equal nil, sponsor.sponsorable
<add> end
<add> end
<add>
<ide> def test_loading_from_an_association
<ide> posts = authors(:david).posts.merge(:includes => :comments, :order => "posts.id").to_a
<ide> assert_equal 2, posts.first.comments.size | 2 |
Ruby | Ruby | handle array of licenses | 1ac470fe7a939c628f8e532e313ae06a11aeca4a | <ide><path>Library/Homebrew/dev-cmd/bump-revision.rb
<ide> def bump_revision
<ide> end
<ide>
<ide> old = if formula.license
<add> license_string = if formula.license.length > 1
<add> formula.license
<add> else
<add> "\"#{formula.license.first}\""
<add> end
<ide> # insert replacement revision after license
<ide> <<~EOS
<del> license "#{formula.license}"
<add> license #{license_string}
<ide> EOS
<ide> elsif formula.path.read.include?("stable do\n")
<ide> # insert replacement revision after homepage | 1 |
Javascript | Javascript | allow numbers as answers | 1244e9775f664707bc54d5f977a9b29a34615784 | <ide><path>tools/challenge-md-parser/tests-to-data.js
<ide> function plugin() {
<ide> if (lang === 'yml') {
<ide> const tests = YAML.load(value);
<ide> if (tests.question) {
<add> // mdToHTML can not parse numbers. If an answer is a number
<add> // (i.e. 5, not '5') it has to be converted.
<ide> tests.question.answers = tests.question.answers.map(answer =>
<del> mdToHTML(answer)
<add> mdToHTML(answer.toString())
<ide> );
<ide> tests.question.text = mdToHTML(tests.question.text);
<ide> } | 1 |
Ruby | Ruby | remove dead code | 55b0ee787ae88c4bd1087040984303ba53d33c78 | <ide><path>Library/Homebrew/os/mac/xcode.rb
<ide> def installed?
<ide> !!detect_version
<ide> end
<ide>
<del> def mavericks_dev_tools?
<del> MacOS.dev_tools_path == Pathname("#{MAVERICKS_PKG_PATH}/usr/bin") &&
<del> File.directory?("#{MAVERICKS_PKG_PATH}/usr/include")
<del> end
<del>
<del> def usr_dev_tools?
<del> MacOS.dev_tools_path == Pathname("/usr/bin") && File.directory?("/usr/include")
<del> end
<del>
<ide> def latest_version
<ide> if MacOS.version >= "10.8"
<ide> "503.0.38" | 1 |
Ruby | Ruby | pass the correct formats | 518ae9f055cd31c0f00c221d56bf0d44733cb782 | <ide><path>actionview/lib/action_view/layouts.rb
<ide> def _layout_for_option(name)
<ide> case name
<ide> when String then _normalize_layout(name)
<ide> when Proc then name
<del> when true then Proc.new { _default_layout(formats, true) }
<del> when :default then Proc.new { _default_layout(formats, false) }
<add> when true then Proc.new { |formats| _default_layout(formats, true) }
<add> when :default then Proc.new { |formats| _default_layout(formats, false) }
<ide> when false, nil then nil
<ide> else
<ide> raise ArgumentError, | 1 |
Python | Python | add license to migration file | ddbcd88bb086d1978c9196833d126ded18db97f8 | <ide><path>airflow/migrations/versions/211e584da130_add_ti_state_index.py
<add># -*- coding: utf-8 -*-
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add>
<ide> """add TI state index
<ide>
<ide> Revision ID: 211e584da130 | 1 |
PHP | PHP | method() calls | 9a2d5c67468be927b0e7530b1a5768a03b32c757 | <ide><path>src/Illuminate/Log/Writer.php
<ide> public function write()
<ide> */
<ide> public function __call($method, $parameters)
<ide> {
<add> if (isset($parameters[0]) && in_array(gettype($parameters[0]), ['object', 'array', 'resource'])) {
<add> $parameters[0] = print_r($parameters[0], true);
<add> }
<add>
<ide> if (in_array($method, $this->levels))
<ide> {
<ide> call_user_func_array(array($this, 'fireLogEvent'), array_merge(array($method), $parameters)); | 1 |
Text | Text | add v4.5.0-beta.1 to changelog | 474057360405daf9d1bb3d402f5742e27e76c8af | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v4.5.0-beta.1 (May 2, 2022)
<add>
<add>- [#20052](https://github.com/emberjs/ember.js/pull/20052) / [#20055](https://github.com/emberjs/ember.js/pull/20055) [FEATURE] Add the default helper manager to implement [RFC #0756](https://github.com/emberjs/rfcs/blob/master/text/0756-helper-default-manager.md).
<add>- [#20053](https://github.com/emberjs/ember.js/pull/20053) [FEATURE] Expose `renderSettled` from `@ember/renderer` to enable implementation of [RFC #0785](https://github.com/emberjs/rfcs/blob/master/text/0785-remove-set-get-in-tests.md).
<add>
<ide> ### v4.4.0 (May 2, 2022)
<ide>
<ide> - [#19882](https://github.com/emberjs/ember.js/pull/19882) / [#20005](https://github.com/emberjs/ember.js/pull/20005) [FEATURE] Implement the `unique-id` helper per [RFC #0659](https://github.com/emberjs/rfcs/blob/master/text/0659-unique-id-helper.md). | 1 |
Text | Text | remove duplicate information | 8ca7abd3f67efd4e1bd688986eba7aa156ee93dd | <ide><path>guide/english/css/background-opacity/index.md
<ide> You have to add the following CSS property to achieve the transparency levels.
<ide> .class-name {
<ide> opacity:0.5;
<ide> }
<add>
<ide> /* Opacity value can be anything between 0 and 1; */
<ide> ```
<ide>
<ide> Using the rgba value is most preferable when the background has content like tex
<ide> background: #00ff0080;
<ide> }
<ide> ```
<del> The example above sets the background with a 50% opacity using hex alpha code. The alpha digit is the last two numbers `80`. The formats are sometimes referred to as #RRGGBBAA and #RGBA and the the AA part is a hex representation of 0-100. For example the hex alpha code of 0% is `00` and the hex alpha code of 100% is `FF`.
<add>
<add>The example above sets the background with a 50% opacity using hex alpha code. The alpha digit is the last two numbers `80`. The formats are sometimes referred to as #RRGGBBAA and #RGBA and the the AA part is a hex representation of 0-100. For example the hex alpha code of 0% is `00` and the hex alpha code of 100% is `FF`.
<ide> [A codepen example to show hex alpha values](https://codepen.io/chriscoyier/pen/XjbzAW)
<del>
<ide>
<ide> [A codepen example to show background opacity ranges](https://codepen.io/lvcoulter/full/dVrwmK/)
<ide>
<ide>
<ide> #### More Information:
<del>For more information visit [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/opacity)
<del>[Opacity CSS property at CSS-Tricks](https://css-tricks.com/almanac/properties/o/opacity/)
<add>
<add>+ [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/opacity)
<add>+ [CSS Opacity / Transparency Property at W3Schools](https://www.w3schools.com/css/css_image_transparency.asp)
<add>+ [Opacity CSS property at CSS-Tricks](https://css-tricks.com/almanac/properties/o/opacity/)
<ide>
<ide> Browser support: <a href= 'https://caniuse.com/#search=opacity' target= '_blank' rel= 'nofollow'>caniuse</a> | 1 |
Python | Python | fix critical trace warnings to allow onnx export | d53dffec6ef5f0cf28df3a1e7f70f1c5da5762ce | <ide><path>src/transformers/models/deberta_v2/modeling_deberta_v2.py
<ide> # limitations under the License.
<ide> """ PyTorch DeBERTa-v2 model."""
<ide>
<del>import math
<ide> from collections.abc import Sequence
<ide> from typing import Optional, Tuple, Union
<ide>
<del>import numpy as np
<ide> import torch
<ide> import torch.utils.checkpoint
<ide> from torch import nn
<ide> def custom_forward(*inputs):
<ide>
<ide>
<ide> def make_log_bucket_position(relative_pos, bucket_size, max_position):
<del> sign = np.sign(relative_pos)
<add> sign = torch.sign(relative_pos)
<ide> mid = bucket_size // 2
<del> abs_pos = np.where((relative_pos < mid) & (relative_pos > -mid), mid - 1, np.abs(relative_pos))
<del> log_pos = np.ceil(np.log(abs_pos / mid) / np.log((max_position - 1) / mid) * (mid - 1)) + mid
<del> bucket_pos = np.where(abs_pos <= mid, relative_pos, log_pos * sign).astype(np.int)
<add> abs_pos = torch.where(
<add> (relative_pos < mid) & (relative_pos > -mid),
<add> torch.tensor(mid - 1).type_as(relative_pos),
<add> torch.abs(relative_pos),
<add> )
<add> log_pos = (
<add> torch.ceil(torch.log(abs_pos / mid) / torch.log(torch.tensor((max_position - 1) / mid)) * (mid - 1)) + mid
<add> )
<add> bucket_pos = torch.where(abs_pos <= mid, relative_pos.type_as(log_pos), log_pos * sign)
<ide> return bucket_pos
<ide>
<ide>
<ide> def build_relative_position(query_size, key_size, bucket_size=-1, max_position=-
<ide> `torch.LongTensor`: A tensor with shape [1, query_size, key_size]
<ide>
<ide> """
<del> q_ids = np.arange(0, query_size)
<del> k_ids = np.arange(0, key_size)
<del> rel_pos_ids = q_ids[:, None] - np.tile(k_ids, (q_ids.shape[0], 1))
<add> q_ids = torch.arange(0, query_size)
<add> k_ids = torch.arange(0, key_size)
<add> rel_pos_ids = q_ids[:, None] - k_ids[None, :]
<ide> if bucket_size > 0 and max_position > 0:
<ide> rel_pos_ids = make_log_bucket_position(rel_pos_ids, bucket_size, max_position)
<del> rel_pos_ids = torch.tensor(rel_pos_ids, dtype=torch.long)
<add> rel_pos_ids = rel_pos_ids.to(torch.long)
<ide> rel_pos_ids = rel_pos_ids[:query_size, :]
<ide> rel_pos_ids = rel_pos_ids.unsqueeze(0)
<ide> return rel_pos_ids
<ide> def forward(
<ide> scale_factor += 1
<ide> if "p2c" in self.pos_att_type:
<ide> scale_factor += 1
<del> scale = math.sqrt(query_layer.size(-1) * scale_factor)
<add> scale = torch.sqrt(torch.tensor(query_layer.size(-1), dtype=torch.float) * scale_factor)
<ide> attention_scores = torch.bmm(query_layer, key_layer.transpose(-1, -2)) / scale
<ide> if self.relative_attention:
<ide> rel_embeddings = self.pos_dropout(rel_embeddings)
<ide> def disentangled_attention_bias(self, query_layer, key_layer, relative_pos, rel_
<ide> score = 0
<ide> # content->position
<ide> if "c2p" in self.pos_att_type:
<del> scale = math.sqrt(pos_key_layer.size(-1) * scale_factor)
<add> scale = torch.sqrt(torch.tensor(pos_key_layer.size(-1), dtype=torch.float) * scale_factor)
<ide> c2p_att = torch.bmm(query_layer, pos_key_layer.transpose(-1, -2))
<ide> c2p_pos = torch.clamp(relative_pos + att_span, 0, att_span * 2 - 1)
<ide> c2p_att = torch.gather(
<ide> def disentangled_attention_bias(self, query_layer, key_layer, relative_pos, rel_
<ide>
<ide> # position->content
<ide> if "p2c" in self.pos_att_type:
<del> scale = math.sqrt(pos_query_layer.size(-1) * scale_factor)
<add> scale = torch.sqrt(torch.tensor(pos_query_layer.size(-1), dtype=torch.float) * scale_factor)
<ide> if key_layer.size(-2) != query_layer.size(-2):
<ide> r_pos = build_relative_position(
<ide> key_layer.size(-2),
<ide><path>src/transformers/models/sew_d/modeling_sew_d.py
<ide> def compute_num_masked_span(input_length):
<ide>
<ide> # Copied from transformers.models.deberta_v2.modeling_deberta_v2.make_log_bucket_position
<ide> def make_log_bucket_position(relative_pos, bucket_size, max_position):
<del> sign = np.sign(relative_pos)
<add> sign = torch.sign(relative_pos)
<ide> mid = bucket_size // 2
<del> abs_pos = np.where((relative_pos < mid) & (relative_pos > -mid), mid - 1, np.abs(relative_pos))
<del> log_pos = np.ceil(np.log(abs_pos / mid) / np.log((max_position - 1) / mid) * (mid - 1)) + mid
<del> bucket_pos = np.where(abs_pos <= mid, relative_pos, log_pos * sign).astype(np.int)
<add> abs_pos = torch.where(
<add> (relative_pos < mid) & (relative_pos > -mid),
<add> torch.tensor(mid - 1).type_as(relative_pos),
<add> torch.abs(relative_pos),
<add> )
<add> log_pos = (
<add> torch.ceil(torch.log(abs_pos / mid) / torch.log(torch.tensor((max_position - 1) / mid)) * (mid - 1)) + mid
<add> )
<add> bucket_pos = torch.where(abs_pos <= mid, relative_pos.type_as(log_pos), log_pos * sign)
<ide> return bucket_pos
<ide>
<ide>
<ide> def build_relative_position(query_size, key_size, bucket_size=-1, max_position=-
<ide> `torch.LongTensor`: A tensor with shape [1, query_size, key_size]
<ide>
<ide> """
<del> q_ids = np.arange(0, query_size)
<del> k_ids = np.arange(0, key_size)
<del> rel_pos_ids = q_ids[:, None] - np.tile(k_ids, (q_ids.shape[0], 1))
<add> q_ids = torch.arange(0, query_size)
<add> k_ids = torch.arange(0, key_size)
<add> rel_pos_ids = q_ids[:, None] - k_ids[None, :]
<ide> if bucket_size > 0 and max_position > 0:
<ide> rel_pos_ids = make_log_bucket_position(rel_pos_ids, bucket_size, max_position)
<del> rel_pos_ids = torch.tensor(rel_pos_ids, dtype=torch.long)
<add> rel_pos_ids = rel_pos_ids.to(torch.long)
<ide> rel_pos_ids = rel_pos_ids[:query_size, :]
<ide> rel_pos_ids = rel_pos_ids.unsqueeze(0)
<ide> return rel_pos_ids
<ide> def forward(
<ide> scale_factor += 1
<ide> if "p2c" in self.pos_att_type:
<ide> scale_factor += 1
<del> scale = math.sqrt(query_layer.size(-1) * scale_factor)
<add> scale = torch.sqrt(torch.tensor(query_layer.size(-1), dtype=torch.float) * scale_factor)
<ide> attention_scores = torch.bmm(query_layer, key_layer.transpose(-1, -2)) / scale
<ide> if self.relative_attention:
<ide> rel_embeddings = self.pos_dropout(rel_embeddings)
<ide> def disentangled_attention_bias(self, query_layer, key_layer, relative_pos, rel_
<ide> score = 0
<ide> # content->position
<ide> if "c2p" in self.pos_att_type:
<del> scale = math.sqrt(pos_key_layer.size(-1) * scale_factor)
<add> scale = torch.sqrt(torch.tensor(pos_key_layer.size(-1), dtype=torch.float) * scale_factor)
<ide> c2p_att = torch.bmm(query_layer, pos_key_layer.transpose(-1, -2))
<ide> c2p_pos = torch.clamp(relative_pos + att_span, 0, att_span * 2 - 1)
<ide> c2p_att = torch.gather(
<ide> def disentangled_attention_bias(self, query_layer, key_layer, relative_pos, rel_
<ide>
<ide> # position->content
<ide> if "p2c" in self.pos_att_type:
<del> scale = math.sqrt(pos_query_layer.size(-1) * scale_factor)
<add> scale = torch.sqrt(torch.tensor(pos_query_layer.size(-1), dtype=torch.float) * scale_factor)
<ide> if key_layer.size(-2) != query_layer.size(-2):
<ide> r_pos = build_relative_position(
<ide> key_layer.size(-2), | 2 |
Javascript | Javascript | improve hmac coverage with webcrypto tests | 4811210ca7e49e12512912f3b1bc8fa0ba67ed0f | <ide><path>test/parallel/test-webcrypto-export-import.js
<ide> const { subtle, getRandomValues } = require('crypto').webcrypto;
<ide> code: 'ERR_INVALID_ARG_TYPE'
<ide> });
<ide> });
<add> assert.rejects(
<add> subtle.importKey('raw', keyData, {
<add> name: 'HMAC'
<add> }, false, ['sign', 'verify']), {
<add> code: 'ERR_MISSING_OPTION'
<add> }).then(common.mustCall());
<add> assert.rejects(
<add> subtle.importKey('raw', keyData, {
<add> name: 'HMAC',
<add> hash: 'SHA-256'
<add> }, false, ['deriveBits']), {
<add> name: 'SyntaxError',
<add> message: 'Unsupported key usage for an HMAC key'
<add> }).then(common.mustCall());
<add> assert.rejects(
<add> subtle.importKey('node.keyObject', '', {
<add> name: 'HMAC',
<add> hash: 'SHA-256'
<add> }, false, ['sign', 'verify']), {
<add> code: 'ERR_INVALID_ARG_TYPE'
<add> }).then(common.mustCall());
<add> assert.rejects(
<add> subtle.importKey('raw', keyData, {
<add> name: 'HMAC',
<add> hash: 'SHA-256',
<add> length: 0
<add> }, false, ['sign', 'verify']), {
<add> name: 'DataError',
<add> message: 'Zero-length key is not supported'
<add> }).then(common.mustCall());
<add> assert.rejects(
<add> subtle.importKey('raw', keyData, {
<add> name: 'HMAC',
<add> hash: 'SHA-256',
<add> length: 1
<add> }, false, ['sign', 'verify']), {
<add> name: 'DataError',
<add> message: 'Invalid key length'
<add> }).then(common.mustCall());
<add> assert.rejects(
<add> subtle.importKey('jwk', null, {
<add> name: 'HMAC',
<add> hash: 'SHA-256',
<add> }, false, ['sign', 'verify']), {
<add> name: 'DataError',
<add> message: 'Invalid JWK keyData'
<add> }).then(common.mustCall());
<ide> }
<ide>
<ide> // Import/Export HMAC Secret Key | 1 |
Javascript | Javascript | unify dom helper across htmlbars and ember views | 0c0df5990bf6939c775cd4e82e1a59fde103b710 | <ide><path>packages/ember-application/lib/system/application.js
<ide> import EnumerableUtils from "ember-metal/enumerable_utils";
<ide> import ObjectController from "ember-runtime/controllers/object_controller";
<ide> import ArrayController from "ember-runtime/controllers/array_controller";
<ide> import Renderer from "ember-views/system/renderer";
<add>import { DOMHelper } from "morph";
<ide> import SelectView from "ember-views/views/select";
<ide> import EventDispatcher from "ember-views/system/event_dispatcher";
<ide> import jQuery from "ember-views/system/jquery";
<ide> Application.reopenClass({
<ide> registry.register('controller:object', ObjectController, { instantiate: false });
<ide> registry.register('controller:array', ArrayController, { instantiate: false });
<ide>
<del> registry.register('renderer:-dom', { create: function(opts) { return new Renderer(opts); } });
<add> registry.register('renderer:-dom', { create: function() { return new Renderer(new DOMHelper()); } });
<ide>
<ide> registry.injection('view', 'renderer', 'renderer:-dom');
<ide> registry.register('view:select', SelectView);
<ide><path>packages/ember-htmlbars/lib/env.js
<ide> import set from "ember-htmlbars/hooks/set";
<ide>
<ide> import helpers from "ember-htmlbars/helpers";
<ide>
<del>var domHelper = environment.hasDOM ? new DOMHelper() : null;
<del>
<ide> export default {
<del> dom: domHelper,
<del>
<ide> hooks: {
<ide> get: get,
<ide> set: set,
<ide> export default {
<ide>
<ide> helpers: helpers
<ide> };
<add>
<add>var domHelper = environment.hasDOM ? new DOMHelper() : null;
<add>
<add>export { domHelper };
<ide><path>packages/ember-htmlbars/lib/system/render-view.js
<ide> function renderHTMLBarsTemplate(view, buffer, template) {
<ide> var args = view._blockArguments;
<ide> var env = {
<ide> view: this,
<del> dom: defaultEnv.dom,
<add> dom: view.renderer._dom,
<ide> hooks: defaultEnv.hooks,
<ide> helpers: defaultEnv.helpers,
<ide> data: {
<ide><path>packages/ember-htmlbars/tests/attr_nodes/data_test.js
<ide> import EmberView from "ember-views/views/view";
<ide> import run from "ember-metal/run_loop";
<ide> import EmberObject from "ember-runtime/system/object";
<ide> import compile from "ember-template-compiler/system/compile";
<add>import Renderer from "ember-views/system/renderer";
<ide> import { equalInnerHTML } from "htmlbars-test-helpers";
<del>import defaultEnv from "ember-htmlbars/env";
<add>import { domHelper as dom } from "ember-htmlbars/env";
<ide> import { runAppend, runDestroy } from "ember-runtime/tests/utils";
<ide>
<del>var view, originalSetAttribute, setAttributeCalls;
<del>var dom = defaultEnv.dom;
<add>var view, originalSetAttribute, setAttributeCalls, renderer;
<ide>
<ide> if (Ember.FEATURES.isEnabled('ember-htmlbars-attribute-syntax')) {
<ide>
<ide> if (Ember.FEATURES.isEnabled('ember-htmlbars-attribute-syntax')) {
<ide>
<ide> QUnit.module('ember-htmlbars: {{attribute}} helper -- setAttribute', {
<ide> setup: function() {
<add> renderer = new Renderer(dom);
<add>
<ide> originalSetAttribute = dom.setAttribute;
<ide> dom.setAttribute = function(element, name, value) {
<del> setAttributeCalls.push([name, value]);
<add> if (name.substr(0, 5) === 'data-') {
<add> setAttributeCalls.push([name, value]);
<add> }
<ide>
<ide> originalSetAttribute.call(dom, element, name, value);
<ide> };
<ide> if (Ember.FEATURES.isEnabled('ember-htmlbars-attribute-syntax')) {
<ide> test('calls setAttribute for new values', function() {
<ide> var context = EmberObject.create({ name: 'erik' });
<ide> view = EmberView.create({
<add> renderer: renderer,
<ide> context: context,
<ide> template: compile("<div data-name={{name}}>Hi!</div>")
<ide> });
<ide> if (Ember.FEATURES.isEnabled('ember-htmlbars-attribute-syntax')) {
<ide> test('does not call setAttribute if the same value is set', function() {
<ide> var context = EmberObject.create({ name: 'erik' });
<ide> view = EmberView.create({
<add> renderer: renderer,
<ide> context: context,
<ide> template: compile("<div data-name={{name}}>Hi!</div>")
<ide> });
<ide><path>packages/ember-htmlbars/tests/htmlbars_test.js
<ide> import compile from "ember-template-compiler/system/compile";
<ide> import defaultEnv from "ember-htmlbars/env";
<add>import { domHelper } from "ember-htmlbars/env";
<ide> import { equalHTML } from "htmlbars-test-helpers";
<add>import merge from "ember-metal/merge";
<ide>
<ide> if (Ember.FEATURES.isEnabled('ember-htmlbars')) {
<ide>
<ide> QUnit.module("ember-htmlbars: main");
<ide>
<ide> test("HTMLBars is present and can be executed", function() {
<ide> var template = compile("ohai");
<del> var output = template.render({}, defaultEnv, document.body);
<add>
<add> var env = merge({ dom: domHelper }, defaultEnv);
<add>
<add> var output = template.render({}, env, document.body);
<ide> equalHTML(output, "ohai");
<ide> });
<ide> }
<ide><path>packages/ember-metal-views/lib/renderer.js
<ide> import environment from "ember-metal/environment";
<ide>
<ide> var domHelper = environment.hasDOM ? new DOMHelper() : null;
<ide>
<del>function Renderer() {
<add>function Renderer(_helper) {
<ide> this._uuid = 0;
<ide>
<ide> // These sizes and values are somewhat arbitrary (but sensible)
<ide> function Renderer() {
<ide> this._parents = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
<ide> this._elements = new Array(17);
<ide> this._inserts = {};
<del> this._dom = domHelper;
<add> this._dom = _helper || domHelper;
<ide> }
<ide>
<ide> function Renderer_renderTree(_view, _parentView, _insertAt) {
<ide><path>packages/ember-views/lib/system/render_buffer.js
<ide> */
<ide>
<ide> import jQuery from "ember-views/system/jquery";
<del>import { DOMHelper } from "morph";
<ide> import Ember from "ember-metal/core";
<ide> import { create } from "ember-metal/platform";
<ide> import environment from "ember-metal/environment";
<ide> import environment from "ember-metal/environment";
<ide> var omittedStartTagChildren;
<ide> var omittedStartTagChildTest = /(?:<script)*.*?<([\w:]+)/i;
<ide>
<del>function detectOmittedStartTag(string, contextualElement) {
<add>function detectOmittedStartTag(dom, string, contextualElement) {
<ide> omittedStartTagChildren = omittedStartTagChildren || {
<del> tr: document.createElement('tbody'),
<del> col: document.createElement('colgroup')
<add> tr: dom.createElement('tbody'),
<add> col: dom.createElement('colgroup')
<ide> };
<ide>
<ide> // Omitted start tags are only inside table tags.
<ide> var canSetNameOnInputs = (function() {
<ide> })();
<ide>
<ide> /**
<del> `Ember.renderBuffer` gathers information regarding the view and generates the
<del> final representation. `Ember.renderBuffer` will generate HTML which can be pushed
<add> `Ember.RenderBuffer` gathers information regarding the view and generates the
<add> final representation. `Ember.RenderBuffer` will generate HTML which can be pushed
<ide> to the DOM.
<ide>
<ide> ```javascript
<del> var buffer = Ember.renderBuffer('div', contextualElement);
<add> var buffer = new Ember.RenderBuffer('div', contextualElement);
<ide> ```
<ide>
<ide> @method renderBuffer
<ide> @namespace Ember
<ide> @param {String} tagName tag name (such as 'div' or 'p') used for the buffer
<ide> */
<del>export default function renderBuffer(tagName, contextualElement) {
<del> return new _RenderBuffer(tagName, contextualElement); // jshint ignore:line
<del>}
<ide>
<del>function _RenderBuffer(tagName, contextualElement) {
<del> this.tagName = tagName;
<del> this._outerContextualElement = contextualElement;
<add>var RenderBuffer = function(domHelper) {
<ide> this.buffer = null;
<ide> this.childViews = [];
<del> this.dom = environment.hasDOM ? new DOMHelper() : null;
<del>}
<ide>
<del>_RenderBuffer.prototype = {
<add> Ember.assert("RenderBuffer requires a DOM helper to be passed to its constructor.", !!domHelper);
<add>
<add> this.dom = domHelper;
<add>};
<add>
<add>RenderBuffer.prototype = {
<ide>
<ide> reset: function(tagName, contextualElement) {
<ide> this.tagName = tagName;
<ide> _RenderBuffer.prototype = {
<ide>
<ide> var omittedStartTag;
<ide> if (html) {
<del> omittedStartTag = detectOmittedStartTag(html, innerContextualElement);
<add> omittedStartTag = detectOmittedStartTag(this.dom, html, innerContextualElement);
<ide> }
<ide> return omittedStartTag || innerContextualElement;
<ide> },
<ide> _RenderBuffer.prototype = {
<ide> return this.buffer;
<ide> }
<ide> };
<add>
<add>export default RenderBuffer;
<ide><path>packages/ember-views/lib/system/renderer.js
<ide> import Ember from "ember-metal/core";
<ide> import Renderer from 'ember-metal-views/renderer';
<ide> import { create } from 'ember-metal/platform';
<del>import renderBuffer from "ember-views/system/render_buffer";
<add>import RenderBuffer from "ember-views/system/render_buffer";
<ide> import run from "ember-metal/run_loop";
<ide> import { set } from "ember-metal/property_set";
<ide> import { get } from "ember-metal/property_get";
<ide> import {
<ide> subscribers
<ide> } from "ember-metal/instrumentation";
<ide>
<del>function EmberRenderer() {
<del> this.buffer = renderBuffer();
<del> this._super$constructor();
<add>function EmberRenderer(domHelper) {
<add> this._super$constructor(domHelper);
<add> this.buffer = new RenderBuffer(domHelper);
<ide> }
<ide>
<ide> EmberRenderer.prototype = create(Renderer.prototype);
<ide><path>packages/ember-views/lib/views/core_view.js
<ide> import Renderer from "ember-views/system/renderer";
<add>import { DOMHelper } from "morph";
<ide>
<ide> import {
<ide> cloneStates,
<ide> var CoreView = EmberObject.extend(Evented, ActionHandler, {
<ide> this.currentState = this._states.preRender;
<ide> this._isVisible = get(this, 'isVisible');
<ide>
<add> // Fallback for legacy cases where the view was created directly
<add> // via `create()` instead of going through the container.
<ide> if (!this.renderer) {
<del> renderer = renderer || new Renderer();
<add> renderer = renderer || new Renderer(new DOMHelper());
<ide> this.renderer = renderer;
<ide> }
<ide> },
<ide><path>packages/ember-views/tests/system/render_buffer_test.js
<ide> import jQuery from "ember-views/system/jquery";
<ide> import RenderBuffer from "ember-views/system/render_buffer";
<add>import { DOMHelper } from "morph";
<ide>
<ide> var svgNamespace = "http://www.w3.org/2000/svg";
<ide> var xhtmlNamespace = "http://www.w3.org/1999/xhtml";
<ide> var trim = jQuery.trim;
<ide> //
<ide> QUnit.module("RenderBuffer");
<ide>
<add>var domHelper = new DOMHelper();
<add>
<add>function createRenderBuffer(tagName, contextualElement) {
<add> var buffer = new RenderBuffer(domHelper);
<add> buffer.reset(tagName, contextualElement);
<add>
<add> return buffer;
<add>}
<add>
<ide> test("RenderBuffers raise a deprecation warning without a contextualElement", function() {
<del> var buffer = new RenderBuffer('div');
<add> var buffer = createRenderBuffer('div');
<ide> expectDeprecation(function() {
<ide> buffer.generateElement();
<ide> var el = buffer.element();
<ide> test("RenderBuffers raise a deprecation warning without a contextualElement", fu
<ide> });
<ide>
<ide> test("reset RenderBuffers raise a deprecation warning without a contextualElement", function() {
<del> var buffer = new RenderBuffer('div', document.body);
<add> var buffer = createRenderBuffer('div', document.body);
<ide> buffer.reset('span');
<ide> expectDeprecation(function() {
<ide> buffer.generateElement();
<ide> test("reset RenderBuffers raise a deprecation warning without a contextualElemen
<ide> });
<ide>
<ide> test("RenderBuffers combine strings", function() {
<del> var buffer = new RenderBuffer('div', document.body);
<add> var buffer = createRenderBuffer('div', document.body);
<ide> buffer.generateElement();
<ide>
<ide> buffer.push('a');
<ide> test("RenderBuffers combine strings", function() {
<ide> });
<ide>
<ide> test("RenderBuffers push fragments", function() {
<del> var buffer = new RenderBuffer('div', document.body);
<add> var buffer = createRenderBuffer('div', document.body);
<ide> var fragment = document.createElement('span');
<ide> buffer.generateElement();
<ide>
<ide> test("RenderBuffers push fragments", function() {
<ide> });
<ide>
<ide> test("RenderBuffers cannot push fragments when something else is in the buffer", function() {
<del> var buffer = new RenderBuffer('div', document.body);
<add> var buffer = createRenderBuffer('div', document.body);
<ide> var fragment = document.createElement('span');
<ide> buffer.generateElement();
<ide>
<ide> test("RenderBuffers cannot push fragments when something else is in the buffer",
<ide> });
<ide>
<ide> test("RenderBuffers cannot push strings after fragments", function() {
<del> var buffer = new RenderBuffer('div', document.body);
<add> var buffer = createRenderBuffer('div', document.body);
<ide> var fragment = document.createElement('span');
<ide> buffer.generateElement();
<ide>
<ide> test("RenderBuffers cannot push strings after fragments", function() {
<ide>
<ide> test("value of 0 is included in output", function() {
<ide> var buffer, el;
<del> buffer = new RenderBuffer('input', document.body);
<add> buffer = createRenderBuffer('input', document.body);
<ide> buffer.prop('value', 0);
<ide> buffer.generateElement();
<ide> el = buffer.element();
<ide> strictEqual(el.value, '0', "generated element has value of '0'");
<ide> });
<ide>
<ide> test("sets attributes with camelCase", function() {
<del> var buffer = new RenderBuffer('div', document.body);
<add> var buffer = createRenderBuffer('div', document.body);
<ide> var content = "javascript:someCode()"; //jshint ignore:line
<ide>
<ide> buffer.attr('onClick', content);
<ide> test("sets attributes with camelCase", function() {
<ide> });
<ide>
<ide> test("prevents XSS injection via `id`", function() {
<del> var buffer = new RenderBuffer('div', document.body);
<add> var buffer = createRenderBuffer('div', document.body);
<ide>
<ide> buffer.id('hacked" megahax="yes');
<ide> buffer.generateElement();
<ide> test("prevents XSS injection via `id`", function() {
<ide> });
<ide>
<ide> test("prevents XSS injection via `attr`", function() {
<del> var buffer = new RenderBuffer('div', document.body);
<add> var buffer = createRenderBuffer('div', document.body);
<ide>
<ide> buffer.attr('id', 'trololol" onmouseover="pwn()');
<ide> buffer.attr('class', "hax><img src=\"trollface.png\"");
<ide> test("prevents XSS injection via `attr`", function() {
<ide> });
<ide>
<ide> test("prevents XSS injection via `addClass`", function() {
<del> var buffer = new RenderBuffer('div', document.body);
<add> var buffer = createRenderBuffer('div', document.body);
<ide>
<ide> buffer.addClass('megahax" xss="true');
<ide> buffer.generateElement();
<ide> test("prevents XSS injection via `addClass`", function() {
<ide> });
<ide>
<ide> test("prevents XSS injection via `style`", function() {
<del> var buffer = new RenderBuffer('div', document.body);
<add> var buffer = createRenderBuffer('div', document.body);
<ide>
<ide> buffer.style('color', 'blue;" xss="true" style="color:red');
<ide> buffer.generateElement();
<ide> test("prevents XSS injection via `style`", function() {
<ide> });
<ide>
<ide> test("prevents XSS injection via `tagName`", function() {
<del> var buffer = new RenderBuffer('cool-div><div xss="true"', document.body);
<add> var buffer = createRenderBuffer('cool-div><div xss="true"', document.body);
<ide> try {
<ide> buffer.generateElement();
<ide> equal(buffer.element().childNodes.length, 0, 'no extra nodes created');
<ide> test("prevents XSS injection via `tagName`", function() {
<ide> });
<ide>
<ide> test("handles null props - Issue #2019", function() {
<del> var buffer = new RenderBuffer('div', document.body);
<add> var buffer = createRenderBuffer('div', document.body);
<ide>
<ide> buffer.prop('value', null);
<ide> buffer.generateElement();
<ide> equal(buffer.element().tagName, 'DIV', 'div exists');
<ide> });
<ide>
<ide> test("handles browsers like Firefox < 11 that don't support outerHTML Issue #1952", function() {
<del> var buffer = new RenderBuffer('div', document.body);
<add> var buffer = createRenderBuffer('div', document.body);
<ide> buffer.generateElement();
<ide> // Make sure element.outerHTML is falsy to trigger the fallback.
<ide> var elementStub = '<div></div>';
<ide> test("handles browsers like Firefox < 11 that don't support outerHTML Issue #195
<ide> });
<ide>
<ide> test("lets `setClasses` and `addClass` work together", function() {
<del> var buffer = new RenderBuffer('div', document.body);
<add> var buffer = createRenderBuffer('div', document.body);
<ide> buffer.setClasses(['foo', 'bar']);
<ide> buffer.addClass('baz');
<ide> buffer.generateElement();
<ide> test("lets `setClasses` and `addClass` work together", function() {
<ide>
<ide> test("generates text and a div and text", function() {
<ide> var div = document.createElement('div');
<del> var buffer = new RenderBuffer(undefined, div);
<add> var buffer = createRenderBuffer(undefined, div);
<ide> buffer.buffer = 'Howdy<div>Nick</div>Cage';
<ide>
<ide> var el = buffer.element();
<ide> test("generates text and a div and text", function() {
<ide>
<ide> test("generates a tr from a tr innerString", function() {
<ide> var table = document.createElement('table');
<del> var buffer = new RenderBuffer(undefined, table);
<add> var buffer = createRenderBuffer(undefined, table);
<ide> buffer.buffer = '<tr></tr>';
<ide>
<ide> var el = buffer.element();
<ide> test("generates a tr from a tr innerString", function() {
<ide>
<ide> test("generates a tr from a tr innerString with leading <script", function() {
<ide> var table = document.createElement('table');
<del> var buffer = new RenderBuffer(undefined, table);
<add> var buffer = createRenderBuffer(undefined, table);
<ide> buffer.buffer = '<script></script><tr></tr>';
<ide>
<ide> var el = buffer.element();
<ide> test("generates a tr from a tr innerString with leading <script", function() {
<ide>
<ide> test("generates a tr from a tr innerString with leading comment", function() {
<ide> var table = document.createElement('table');
<del> var buffer = new RenderBuffer(undefined, table);
<add> var buffer = createRenderBuffer(undefined, table);
<ide> buffer.buffer = '<!-- blargh! --><tr></tr>';
<ide>
<ide> var el = buffer.element();
<ide> equal(el.childNodes[1].tagName, 'TR');
<ide> });
<ide>
<ide> test("generates a tr from a tr innerString on rerender", function() {
<del> var buffer = new RenderBuffer('table', document.body);
<add> var buffer = createRenderBuffer('table', document.body);
<ide> buffer.generateElement();
<ide> buffer.buffer = '<tr></tr>';
<ide>
<ide> test("generates a tr from a tr innerString on rerender", function() {
<ide>
<ide> test("generates a tbody from a tbody innerString", function() {
<ide> var table = document.createElement('table');
<del> var buffer = new RenderBuffer(undefined, table);
<add> var buffer = createRenderBuffer(undefined, table);
<ide> buffer.buffer = '<tbody><tr></tr></tbody>';
<ide>
<ide> var el = buffer.element();
<ide> test("generates a tbody from a tbody innerString", function() {
<ide>
<ide> test("generates a col from a col innerString", function() {
<ide> var table = document.createElement('table');
<del> var buffer = new RenderBuffer(undefined, table);
<add> var buffer = createRenderBuffer(undefined, table);
<ide> buffer.buffer = '<col></col>';
<ide>
<ide> var el = buffer.element();
<ide> test("generates a col from a col innerString", function() {
<ide> QUnit.module("RenderBuffer - without tagName");
<ide>
<ide> test("It is possible to create a RenderBuffer without a tagName", function() {
<del> var buffer = new RenderBuffer(undefined, document.body);
<add> var buffer = createRenderBuffer(undefined, document.body);
<ide> buffer.push('a');
<ide> buffer.push('b');
<ide> buffer.push('c');
<ide> test("It is possible to create a RenderBuffer without a tagName", function() {
<ide> QUnit.module("RenderBuffer#element");
<ide>
<ide> test("properly handles old IE's zero-scope bug", function() {
<del> var buffer = new RenderBuffer('div', document.body);
<add> var buffer = createRenderBuffer('div', document.body);
<ide> buffer.generateElement();
<ide> buffer.push('<script></script>foo');
<ide>
<ide> if ('namespaceURI' in document.createElement('div')) {
<ide> QUnit.module("RenderBuffer namespaces");
<ide>
<ide> test("properly makes a content string SVG namespace inside an SVG tag", function() {
<del> var buffer = new RenderBuffer('svg', document.body);
<add> var buffer = createRenderBuffer('svg', document.body);
<ide> buffer.generateElement();
<ide> buffer.push('<path></path>foo');
<ide>
<ide> if ('namespaceURI' in document.createElement('div')) {
<ide> });
<ide>
<ide> test("properly makes a path element svg namespace inside SVG context", function() {
<del> var buffer = new RenderBuffer('path', document.createElementNS(svgNamespace, 'svg'));
<add> var buffer = createRenderBuffer('path', document.createElementNS(svgNamespace, 'svg'));
<ide> buffer.generateElement();
<ide> buffer.push('<g></g>');
<ide>
<ide> if ('namespaceURI' in document.createElement('div')) {
<ide> });
<ide>
<ide> test("properly makes a foreignObject svg namespace inside SVG context", function() {
<del> var buffer = new RenderBuffer('foreignObject', document.createElementNS(svgNamespace, 'svg'));
<add> var buffer = createRenderBuffer('foreignObject', document.createElementNS(svgNamespace, 'svg'));
<ide> buffer.generateElement();
<ide> buffer.push('<div></div>');
<ide>
<ide> if ('namespaceURI' in document.createElement('div')) {
<ide> });
<ide>
<ide> test("properly makes a div xhtml namespace inside foreignObject context", function() {
<del> var buffer = new RenderBuffer('div', document.createElementNS(svgNamespace, 'foreignObject'));
<add> var buffer = createRenderBuffer('div', document.createElementNS(svgNamespace, 'foreignObject'));
<ide> buffer.generateElement();
<ide> buffer.push('<div></div>');
<ide> | 10 |
PHP | PHP | fix failing tests in viewbuilder | 2fa8735ad25ee2678d6fc65ef60cd9af8e619fa9 | <ide><path>src/Error/ExceptionRenderer.php
<ide> public function render()
<ide> if ($unwrapped instanceof CakeException && $isDebug) {
<ide> $this->controller->set($unwrapped->getAttributes());
<ide> }
<del>
<ide> $this->controller->response = $response;
<add>
<ide> return $this->_outputMessage($template);
<ide> }
<ide>
<ide><path>src/Routing/Filter/AssetFilter.php
<ide> protected function _getAssetFile($url)
<ide> protected function _deliverAsset(ServerRequest $request, Response $response, $assetFile, $ext)
<ide> {
<ide> $compressionEnabled = $response->compress();
<del> if ($response->getType($ext) === $ext) {
<add> if ($response->getType() === $ext) {
<ide> $contentType = 'application/octet-stream';
<ide> $agent = $request->getEnv('HTTP_USER_AGENT');
<ide> if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent) || preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) {
<ide><path>tests/TestCase/View/ViewBuilderTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\View;
<ide>
<add>use Cake\Http\Response;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\View\ViewBuilder;
<ide>
<ide> public function testArrayPropertyMerge($property, $value)
<ide> */
<ide> public function testBuildComplete()
<ide> {
<del> $request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
<del> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<add> $request = new ServerRequest();
<add> $response = new Response();
<ide> $events = $this->getMockBuilder('Cake\Event\EventManager')->getMock();
<ide>
<ide> $builder = new ViewBuilder();
<ide> public function testBuildComplete()
<ide> $this->assertEquals('TestPlugin', $view->plugin);
<ide> $this->assertEquals('TestTheme', $view->theme);
<ide> $this->assertSame($request, $view->request);
<del> $this->assertSame($response, $view->response);
<add> $this->assertInstanceOf(Response::class, $view->response);
<ide> $this->assertSame($events, $view->getEventManager());
<ide> $this->assertSame(['one' => 'value'], $view->viewVars);
<ide> $this->assertInstanceOf('Cake\View\Helper\HtmlHelper', $view->Html); | 3 |
Javascript | Javascript | add tests for invalid utf-8 | dc35aef14cdf3d3f382d162967788b9064ca6935 | <ide><path>test/parallel/test-blob.js
<ide> assert.throws(() => new Blob({}), {
<ide> }));
<ide> }
<ide>
<add>{
<add> const b = new Blob(['hello', new Uint8Array([0xed, 0xa0, 0x88])]);
<add> assert.strictEqual(b.size, 8);
<add> b.text().then(common.mustCall((text) => {
<add> assert.strictEqual(text, 'hello\ufffd\ufffd\ufffd');
<add> assert.strictEqual(text.length, 8);
<add> }));
<add>}
<add>
<ide> {
<ide> const b = new Blob(
<ide> [
<ide><path>test/parallel/test-stream-consumers.js
<ide> const {
<ide> } = require('stream/consumers');
<ide>
<ide> const {
<add> Readable,
<ide> PassThrough
<ide> } = require('stream');
<ide>
<ide> const kArrayBuffer =
<ide> setTimeout(() => passthrough.end('there'), 10);
<ide> }
<ide>
<add>{
<add> const readable = new Readable({
<add> read() {}
<add> });
<add>
<add> text(readable).then((data) => {
<add> assert.strictEqual(data, 'foo\ufffd\ufffd\ufffd');
<add> });
<add>
<add> readable.push(new Uint8Array([0x66, 0x6f, 0x6f, 0xed, 0xa0, 0x80]));
<add> readable.push(null);
<add>}
<add>
<ide> {
<ide> const passthrough = new PassThrough();
<ide>
<ide><path>test/parallel/test-whatwg-encoding-custom-textdecoder.js
<ide> if (common.hasIntl) {
<ide> }
<ide> );
<ide> }
<add>
<add>// Test TextDecoder for incomplete UTF-8 byte sequence.
<add>{
<add> const decoder = new TextDecoder();
<add> const chunk = new Uint8Array([0x66, 0x6f, 0x6f, 0xed]);
<add> const str = decoder.decode(chunk);
<add> assert.strictEqual(str, 'foo\ufffd');
<add>} | 3 |
Python | Python | add missing import | a95cb4687b3c6feb8ac8f12f04d6c091c52bbf00 | <ide><path>libcloud/dns/drivers/route53.py
<ide> from libcloud.dns.types import Provider, RecordType
<ide> from libcloud.dns.types import ZoneDoesNotExistError, RecordDoesNotExistError
<ide> from libcloud.dns.base import DNSDriver, Zone, Record
<add>from libcloud.common.types import InvalidCredsError
<ide> from libcloud.common.types import LibcloudError
<ide> from libcloud.common.aws import AWSBaseResponse
<ide> from libcloud.common.base import ConnectionUserAndKey | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.