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 | fix mypy errors for tableau provider | 6174198a3fa3ab7cffa7394afad48e5082210283 | <ide><path>airflow/providers/tableau/operators/tableau.py
<ide> def execute(self, context: dict) -> str:
<ide>
<ide> response = method(resource_id)
<ide>
<del> if self.method == 'refresh':
<del>
<del> job_id = response.id
<add> job_id = response.id
<ide>
<add> if self.method == 'refresh':
<ide> if self.blocking_refresh:
<ide> if not tableau_hook.wait_for_state(
<ide> job_id=job_id,
<ide> def execute(self, context: dict) -> str:
<ide> ):
<ide> raise TableauJobFailedException(f'The Tableau Refresh {self.resource} Job failed!')
<ide>
<del> return job_id
<add> return job_id
<ide>
<ide> def _get_resource_id(self, tableau_hook: TableauHook) -> str:
<ide> | 1 |
Java | Java | remove fixme on retain in reactorserverhttprequest | 65246f8cfdcda92288e96209edbbdad3a4321a80 | <ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/ReactorServerHttpRequest.java
<ide> protected MultiValueMap<String, HttpCookie> initCookies() {
<ide>
<ide> @Override
<ide> public Flux<DataBuffer> getBody() {
<del> return this.channel.receive()
<del> .retain() //FIXME Rogue reference holding
<del> .map(dataBufferFactory::wrap);
<add> return this.channel.receive().retain().map(this.dataBufferFactory::wrap);
<ide> }
<ide>
<ide> } | 1 |
PHP | PHP | reduce duplicate calls | 82913a35db2c80f61b3af713b9493b97235fe89e | <ide><path>src/Illuminate/Queue/Worker.php
<ide> public function __construct(QueueManager $manager,
<ide> */
<ide> public function daemon($connectionName, $queue, WorkerOptions $options)
<ide> {
<del> if ($this->supportsAsyncSignals()) {
<add> if ($supportsAsyncSignals = $this->supportsAsyncSignals()) {
<ide> $this->listenForSignals();
<ide> }
<ide>
<ide> public function daemon($connectionName, $queue, WorkerOptions $options)
<ide> $this->manager->connection($connectionName), $queue
<ide> );
<ide>
<del> if ($this->supportsAsyncSignals()) {
<add> if ($supportsAsyncSignals) {
<ide> $this->registerTimeoutHandler($job, $options);
<ide> }
<ide>
<ide> public function daemon($connectionName, $queue, WorkerOptions $options)
<ide> $this->sleep($options->sleep);
<ide> }
<ide>
<del> if ($this->supportsAsyncSignals()) {
<add> if ($supportsAsyncSignals) {
<ide> $this->resetTimeoutHandler();
<ide> }
<ide> | 1 |
Ruby | Ruby | allow loading formula from contents | ff0f6598ce6057a36c222e2ec374d4ae37e2258a | <ide><path>Library/Homebrew/formulary.rb
<ide> def self.formula_class_get(path)
<ide> FORMULAE.fetch(path)
<ide> end
<ide>
<del> def self.load_formula(name, path)
<add> def self.load_formula(name, path, contents, namespace)
<ide> mod = Module.new
<del> const_set("FormulaNamespace#{Digest::MD5.hexdigest(path.to_s)}", mod)
<del> contents = path.open("r") { |f| set_encoding(f).read }
<add> const_set(namespace, mod)
<ide> mod.module_eval(contents, path)
<ide> class_name = class_s(name)
<ide>
<ide> begin
<del> klass = mod.const_get(class_name)
<add> mod.const_get(class_name)
<ide> rescue NameError => e
<ide> raise FormulaUnavailableError, name, e.backtrace
<del> else
<del> FORMULAE[path] = klass
<ide> end
<ide> end
<ide>
<add> def self.load_formula_from_path(name, path)
<add> contents = path.open("r") { |f| set_encoding(f).read }
<add> namespace = "FormulaNamespace#{Digest::MD5.hexdigest(path.to_s)}"
<add> klass = load_formula(name, path, contents, namespace)
<add> FORMULAE[path] = klass
<add> end
<add>
<ide> if IO.method_defined?(:set_encoding)
<ide> def self.set_encoding(io)
<ide> io.set_encoding(Encoding::UTF_8)
<ide> def klass
<ide> def load_file
<ide> STDERR.puts "#{$0} (#{self.class.name}): loading #{path}" if ARGV.debug?
<ide> raise FormulaUnavailableError.new(name) unless path.file?
<del> Formulary.load_formula(name, path)
<add> Formulary.load_formula_from_path(name, path)
<ide> end
<ide> end
<ide> | 1 |
Text | Text | add resources for learning tableau | e268de9cac4a8ee2fbfdbb1bfc6874890db66376 | <ide><path>guide/english/data-science-tools/tableau/index.md
<ide> If you want to learn Tableau on your own, it's possible to get a free license fo
<ide> ### Links:
<ide> * [Tableau Website](https://www.tableau.com)
<ide> * [Tableau Public Gallery](https://public.tableau.com/en-us/s/gallery)
<add> * [Tableau Learning](https://www.tableau.com/learn/training)
<ide> * [Tableau Blog](https://www.tableau.com/about/blog)
<ide> * [PostgreSQL Server](https://onlinehelp.tableau.com/current/pro/desktop/en-us/examples_postgresql.html)
<ide> * [Using R and Tableau](https://www.tableau.com/learn/whitepapers/using-r-and-tableau)
<ide> * [Tableau Integration with Python](https://community.tableau.com/thread/236479)
<add> * [Tutorialspoint](https://www.tutorialspoint.com/tableau/)
<add> * [Tutorial Gateway](https://www.tutorialgateway.org/tableau/)
<add> | 1 |
Ruby | Ruby | update pat regex | 229e035a3dbc3268683c9f045eb7a58c19f500f7 | <ide><path>Library/Homebrew/utils/github/api.rb
<ide> module GitHub
<ide> #{ALL_SCOPES_URL}
<ide> #{Utils::Shell.set_variable_in_profile("HOMEBREW_GITHUB_API_TOKEN", "your_token_here")}
<ide> EOS
<del> GITHUB_PAT_REGEX = /^(?:[a-f0-9]{40}|gp1_[A-Za-z0-9_]{40,255})$/.freeze
<add> GITHUB_PERSONAL_ACCESS_TOKEN_REGEX = /^(?:[a-f0-9]{40}|ghp_\w{36,251})$/.freeze
<ide>
<ide> # Helper functions to access the GitHub API.
<ide> #
<ide> def keychain_username_password
<ide> # Don't use passwords from the keychain unless they look like
<ide> # GitHub Personal Access Tokens:
<ide> # https://github.com/Homebrew/brew/issues/6862#issuecomment-572610344
<del> return unless GITHUB_PAT_REGEX.match?(github_password)
<add> return unless GITHUB_PERSONAL_ACCESS_TOKEN_REGEX.match?(github_password)
<ide>
<ide> github_password
<ide> rescue Errno::EPIPE | 1 |
PHP | PHP | apply fixes from styleci | 52a6e51d672ed65574733cc8be8652ebd2efad99 | <ide><path>tests/Database/DatabaseEloquentBelongsToManySyncReturnValueTypeTest.php
<ide> protected function seedData()
<ide> BelongsToManySyncTestTestUser::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']);
<ide> BelongsToManySyncTestTestArticle::insert([
<ide> ['id' => '7b7306ae-5a02-46fa-a84c-9538f45c7dd4', 'title' => 'uuid title'],
<del> ['id' => (string)(PHP_INT_MAX+1), 'title' => 'Another title'],
<del> ['id' => '1', 'title' => 'Another title']
<add> ['id' => (string) (PHP_INT_MAX + 1), 'title' => 'Another title'],
<add> ['id' => '1', 'title' => 'Another title'],
<ide> ]);
<ide> }
<ide>
<ide> public function testSyncReturnValueType()
<ide> {
<ide> $this->seedData();
<ide>
<del>
<ide> $user = BelongsToManySyncTestTestUser::query()->first();
<ide> $articleIDs = BelongsToManySyncTestTestArticle::all()->pluck('id')->toArray();
<ide>
<ide> $changes = $user->articles()->sync($articleIDs);
<ide>
<ide> collect($changes['attached'])->map(function ($id) {
<del> $this->assertTrue(gettype($id) === (new BelongsToManySyncTestTestArticle)->getKeyType());
<add> $this->assertTrue(gettype($id) === (new BelongsToManySyncTestTestArticle)->getKeyType());
<ide> });
<ide> }
<ide>
<ide> public function articles()
<ide> }
<ide> }
<ide>
<del>
<ide> class BelongsToManySyncTestTestArticle extends Eloquent
<ide> {
<ide> protected $table = 'articles'; | 1 |
Python | Python | show the full list of leaked objects | d21ec05eb006c072e4fd8c5fe1bd63619378aded | <ide><path>numpy/testing/_private/utils.py
<ide> import contextlib
<ide> from tempfile import mkdtemp, mkstemp
<ide> from unittest.case import SkipTest
<add>import pprint
<ide>
<ide> from numpy.core import(
<ide> float32, empty, arange, array_repr, ndarray, isnat, array)
<ide> def _assert_no_gc_cycles_context(name=None):
<ide>
<ide> assert_(gc.isenabled())
<ide> gc.disable()
<add> gc_debug = gc.get_debug()
<ide> try:
<ide> gc.collect()
<add> gc.set_debug(gc.DEBUG_SAVEALL)
<ide> yield
<ide> # gc.collect returns the number of unreachable objects in cycles that
<ide> # were found -- we are checking that no cycles were created in the context
<ide> n_objects_in_cycles = gc.collect()
<add> objects_in_cycles = gc.garbage[:]
<ide> finally:
<add> del gc.garbage[:]
<add> gc.set_debug(gc_debug)
<ide> gc.enable()
<ide>
<ide> if n_objects_in_cycles:
<ide> name_str = " when calling %s" % name if name is not None else ""
<ide> raise AssertionError(
<del> "Reference cycles were found{}: {} objects were collected"
<del> .format(name_str, n_objects_in_cycles))
<add> "Reference cycles were found{}: {} objects were collected, "
<add> "of which {} are shown below:{}"
<add> .format(
<add> name_str,
<add> n_objects_in_cycles,
<add> len(objects_in_cycles),
<add> ''.join(
<add> "\n {} object with id={}:\n {}".format(
<add> type(o).__name__,
<add> id(o),
<add> pprint.pformat(o).replace('\n', '\n ')
<add> ) for o in objects_in_cycles
<add> )
<add> )
<add> )
<ide>
<ide>
<ide> def assert_no_gc_cycles(*args, **kwargs): | 1 |
Text | Text | fix new version for match_alignments | 40ca23bde007f087c8628811a44c4b8b40c41aba | <ide><path>website/docs/api/matcher.md
<ide> Find all token sequences matching the supplied patterns on the `Doc` or `Span`.
<ide> | _keyword-only_ | |
<ide> | `as_spans` <Tag variant="new">3</Tag> | Instead of tuples, return a list of [`Span`](/api/span) objects of the matches, with the `match_id` assigned as the span label. Defaults to `False`. ~~bool~~ |
<ide> | `allow_missing` <Tag variant="new">3</Tag> | Whether to skip checks for missing annotation for attributes included in patterns. Defaults to `False`. ~~bool~~ |
<del>| `with_alignments` <Tag variant="new">3.1</Tag> | Return match alignment information as part of the match tuple as `List[int]` with the same length as the matched span. Each entry denotes the corresponding index of the token pattern. If `as_spans` is set to `True`, this setting is ignored. Defaults to `False`. ~~bool~~ |
<add>| `with_alignments` <Tag variant="new">3.0.6</Tag> | Return match alignment information as part of the match tuple as `List[int]` with the same length as the matched span. Each entry denotes the corresponding index of the token pattern. If `as_spans` is set to `True`, this setting is ignored. Defaults to `False`. ~~bool~~ |
<ide> | **RETURNS** | A list of `(match_id, start, end)` tuples, describing the matches. A match tuple describes a span `doc[start:end`]. The `match_id` is the ID of the added match pattern. If `as_spans` is set to `True`, a list of `Span` objects is returned instead. ~~Union[List[Tuple[int, int, int]], List[Span]]~~ |
<ide>
<ide> ## Matcher.\_\_len\_\_ {#len tag="method" new="2"} | 1 |
PHP | PHP | pass the locator to the constructor | cb4d38da950d054e4c7785cc5baace8e47310584 | <ide><path>src/ORM/AssociationCollection.php
<ide> use ArrayIterator;
<ide> use Cake\Datasource\EntityInterface;
<ide> use Cake\ORM\Locator\LocatorAwareTrait;
<add>use Cake\ORM\Locator\LocatorInterface;
<ide> use InvalidArgumentException;
<ide> use IteratorAggregate;
<ide>
<ide> class AssociationCollection implements IteratorAggregate
<ide> */
<ide> protected $_items = [];
<ide>
<add> /**
<add> * Constructor.
<add> *
<add> * Sets the default table locator for associations.
<add> * If no locator is provided, the global one will be used.
<add> *
<add> * @param \Cake\ORM\Locator\LocatorInterface|null $tableLocator Table locator instance.
<add> */
<add> public function __construct(LocatorInterface $tableLocator = null)
<add> {
<add> if ($tableLocator !== null) {
<add> $this->_tableLocator = $tableLocator;
<add> }
<add> }
<add>
<ide> /**
<ide> * Add an association to the collection
<ide> *
<ide><path>src/ORM/Locator/TableLocator.php
<ide> public function get($alias, array $options = [])
<ide> $options['connection'] = ConnectionManager::get($connectionName);
<ide> }
<ide> if (empty($options['associations'])) {
<del> $associations = new AssociationCollection();
<del> $associations->setTableLocator($this);
<add> $associations = new AssociationCollection($this);
<ide> $options['associations'] = $associations;
<ide> }
<ide>
<ide><path>tests/TestCase/ORM/AssociationCollectionTest.php
<ide> use Cake\ORM\Association\BelongsToMany;
<ide> use Cake\ORM\Entity;
<ide> use Cake\ORM\Locator\LocatorInterface;
<add>use Cake\ORM\TableRegistry;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> /**
<ide> public function setUp()
<ide> $this->associations = new AssociationCollection();
<ide> }
<ide>
<add> /**
<add> * Test the constructor.
<add> *
<add> * @return void
<add> */
<add> public function testConstructor()
<add> {
<add> $this->assertSame(TableRegistry::getTableLocator(), $this->associations->getTableLocator());
<add>
<add> $tableLocator = $this->createMock(LocatorInterface::class);
<add> $associations = new AssociationCollection($tableLocator);
<add> $this->assertSame($tableLocator, $associations->getTableLocator());
<add> }
<add>
<ide> /**
<ide> * Test the simple add/has and get methods.
<ide> * | 3 |
Text | Text | add flow reminder to pr template | bfd5b1878e6eeebd8899bd221cb62ddc046c875d | <ide><path>.github/PULL_REQUEST_TEMPLATE.md
<del>*Before* submitting a pull request, please make sure the following is done...
<add>**Before submitting a pull request,** please make sure the following is done:
<ide>
<del>1. Fork the repo and create your branch from `master`.
<add>1. Fork [the repository](https://github.com/facebook/react) and create your branch from `master`.
<ide> 2. If you've added code that should be tested, add tests!
<ide> 3. If you've changed APIs, update the documentation.
<ide> 4. Ensure the test suite passes (`npm test`).
<del>5. Make sure your code lints (`npm run lint`) - we've done our best to make sure these rules match our internal linting guidelines.
<del>6. If you haven't already, complete the [CLA](https://code.facebook.com/cla).
<add>5. Make sure your code lints (`npm run lint`).
<add>6. Run the [Flow](https://flowtype.org/) typechecks (`npm run flow`).
<add>7. If you added or removed any tests, run `./scripts/fiber/record-tests` before submitting the pull request, and commit the resulting changes.
<add>8. If you haven't already, complete the [CLA](https://code.facebook.com/cla).
<ide><path>docs/contributing/how-to-contribute.md
<ide> The core team is monitoring for pull requests. We will review your pull request
<ide> 4. Ensure the test suite passes (`npm test`).
<ide> 5. Make sure your code lints (`npm run lint`).
<ide> 6. Run the [Flow](https://flowtype.org/) typechecks (`npm run flow`).
<del>7. If you haven't already, complete the CLA.
<add>7. If you added or removed any tests, run `./scripts/fiber/record-tests` before submitting the pull request, and commit the resulting changes.
<add>8. If you haven't already, complete the CLA.
<ide>
<ide> ### Contributor License Agreement (CLA)
<ide> | 2 |
Ruby | Ruby | add a template per case on asset debugging tests | 0063fb307a8f9cc033e3d6c3de95a0c8dec120e4 | <ide><path>railties/test/application/asset_debugging_test.rb
<ide> class ::PostsController < ActionController::Base ; end
<ide> image_submit_tag: %r{<input type="image" src="/images/#{contents}" />}
<ide> }
<ide>
<add> class ::PostsController < ActionController::Base
<add> def index
<add> render params[:view_method]
<add> end
<add> end
<add>
<ide> cases.each do |(view_method, tag_match)|
<del> app_file "app/views/posts/index.html.erb", "<%= #{view_method} '#{contents}', skip_pipeline: true %>"
<add> app_file "app/views/posts/#{view_method}.html.erb", "<%= #{view_method} '#{contents}', skip_pipeline: true %>"
<ide>
<ide> app "development"
<ide>
<del> class ::PostsController < ActionController::Base ; end
<del>
<del> get "/posts?debug_assets=true"
<add> get "/posts?debug_assets=true&view_method=#{view_method}"
<ide>
<ide> body = last_response.body
<ide> assert_match(tag_match, body, "Expected `#{view_method}` to produce a match to #{tag_match}, but did not: #{body}")
<ide> class ::PostsController < ActionController::Base ; end
<ide> stylesheet_url: %r{http://example.org/stylesheets/#{contents}},
<ide> }
<ide>
<add> class ::PostsController < ActionController::Base
<add> def index
<add> render params[:view_method]
<add> end
<add> end
<add>
<ide> cases.each do |(view_method, tag_match)|
<del> app_file "app/views/posts/index.html.erb", "<%= #{view_method} '#{contents}', skip_pipeline: true %>"
<add> app_file "app/views/posts/#{view_method}.html.erb", "<%= #{view_method} '#{contents}', skip_pipeline: true %> "
<ide>
<ide> app "development"
<ide>
<del> class ::PostsController < ActionController::Base ; end
<del>
<del> get "/posts?debug_assets=true"
<add> get "/posts?debug_assets=true&view_method=#{view_method}"
<ide>
<ide> body = last_response.body
<ide> assert_match(tag_match, body, "Expected `#{view_method}` to produce a match to #{tag_match}, but did not: #{body}")
<ide> class ::PostsController < ActionController::Base ; end
<ide> /\/assets\/application-.*.\.js/ => {},
<ide> /application.js/ => { skip_pipeline: true },
<ide> }
<del> cases.each do |(tag_match, options_hash)|
<del> app_file "app/views/posts/index.html.erb", "<%= asset_path('application.js', #{options_hash}) %>"
<ide>
<del> app "development"
<add> class ::PostsController < ActionController::Base
<add> def index
<add> render params[:version]
<add> end
<add> end
<ide>
<del> class ::PostsController < ActionController::Base ; end
<add> cases.each_with_index do |(tag_match, options_hash), index|
<add> app_file "app/views/posts/version_#{index}.html.erb", "<%= asset_path('application.js', #{options_hash}) %>"
<add>
<add> app "development"
<ide>
<del> get "/posts?debug_assets=true"
<add> get "/posts?debug_assets=true&version=version_#{index}"
<ide>
<ide> body = last_response.body.strip
<ide> assert_match(tag_match, body, "Expected `asset_path` with `#{options_hash}` to produce a match to #{tag_match}, but did not: #{body}")
<ide> class ::PostsController < ActionController::Base ; end
<ide> public_compute_asset_path: /application.js/,
<ide> }
<ide>
<add> class ::PostsController < ActionController::Base
<add> def index
<add> render params[:view_method]
<add> end
<add> end
<add>
<ide> cases.each do |(view_method, tag_match)|
<del> app_file "app/views/posts/index.html.erb", "<%= #{ view_method } 'application.js' %>"
<add> app_file "app/views/posts/#{view_method}.html.erb", "<%= #{ view_method } 'application.js' %>"
<ide>
<ide> app "development"
<ide>
<del> class ::PostsController < ActionController::Base ; end
<del>
<del> get "/posts?debug_assets=true"
<add> get "/posts?debug_assets=true&view_method=#{view_method}"
<ide>
<ide> body = last_response.body.strip
<ide> assert_match(tag_match, body, "Expected `#{view_method}` to produce a match to #{ tag_match }, but did not: #{ body }") | 1 |
PHP | PHP | remove prefix before normalizing the channel name | b204042056458faefee1be04c0e4b2fb59424cbe | <ide><path>src/Illuminate/Broadcasting/Broadcasters/RedisBroadcaster.php
<ide> public function __construct(Redis $redis, $connection = null)
<ide> */
<ide> public function auth($request)
<ide> {
<del> $channelName = $this->normalizeChannelName($request->channel_name);
<add> $channelName = str_replace(config('database.redis.options.prefix', ''), '', $request->channel_name);
<add> $channelName = $this->normalizeChannelName($channelName);
<ide>
<ide> if ($this->isGuardedChannel($request->channel_name) &&
<ide> ! $this->retrieveUser($request, $channelName)) {
<ide> throw new AccessDeniedHttpException;
<ide> }
<ide>
<del> $channelName = str_replace(config('redis.options.prefix', ''), '', $channelName);
<del>
<ide> return parent::verifyUserCanAccessChannel(
<ide> $request, $channelName
<ide> ); | 1 |
PHP | PHP | fix coding style | 50f048dd87d4b28912ccbaa97faf3867cb73f4af | <ide><path>src/ORM/Association/HasMany.php
<ide> protected function _saveTarget(
<ide> if (!empty($options['atomic'])) {
<ide> $original[$k]->setErrors($entity->getErrors());
<ide> $original[$k]->setInvalid($entity->getInvalid());
<add>
<ide> return false;
<ide> }
<ide> }
<ide><path>tests/TestCase/ORM/Association/HasManyTest.php
<ide> public function testSaveAssociatedEmptySetWithReplaceStrategyRemovesAssociatedRe
<ide> *
<ide> * @return void
<ide> */
<del> public function testSaveAssociatedWithFailedRuleOnAssociated() {
<add> public function testSaveAssociatedWithFailedRuleOnAssociated()
<add> {
<ide> $articles = $this->getTableLocator()->get('Articles');
<ide> $articles->hasMany('Comments');
<ide> $comments = $this->getTableLocator()->get('Comments');
<ide> public function testSaveAssociatedWithFailedRuleOnAssociated() {
<ide> 'comment' => 'That is true!',
<ide> ],
<ide> [
<del> 'user_id' => 999,// This rule will fail because the user doesn't exist
<add> 'user_id' => 999, // This rule will fail because the user doesn't exist
<ide> 'comment' => 'Of course',
<ide> ],
<ide> ], | 2 |
Text | Text | update documentation with coding guidelines | 11c41993f1654631a4cc9162404107f76bc5a949 | <ide><path>CONTRIBUTING.md
<ide> to expect from the Spring team when evaluating your submission._
<ide> _Please refer back to this document as a checklist before issuing any pull
<ide> request; this will save time for everyone!_
<ide>
<del>## Understand the basics
<add>## Take your first steps
<add>
<add>### Understand the basics
<ide>
<ide> Not sure what a pull request is, or how to submit one? Take a look at GitHub's
<ide> excellent [help documentation][] first.
<ide>
<ide>
<del>## Search JIRA first; create an issue if necessary
<add>### Search JIRA first; create an issue if necessary
<ide>
<ide> Is there already an issue that addresses your concern? Do a bit of searching
<ide> in our [JIRA issue tracker][] to see if you can find something similar. If not,
<ide> please create a new issue before submitting a pull request unless the change is
<ide> truly trivial, e.g. typo fixes, removing compiler warnings, etc.
<ide>
<del>## Discuss non-trivial contribution ideas with committers
<add>### Discuss non-trivial contribution ideas with committers
<ide>
<ide> If you're considering anything more than correcting a typo or fixing a minor
<ide> bug, please discuss it on the [spring-framework-contrib][] mailing list before
<ide> submitting a pull request. We're happy to provide guidance, but please spend an
<ide> hour or two researching the subject on your own including searching the mailing
<ide> list for prior discussions.
<ide>
<del>## Sign the Contributor License Agreement
<add>### Sign the Contributor License Agreement
<ide>
<ide> If you have not previously done so, please fill out and submit the
<ide> [SpringSource CLA form][]. You'll receive a token when this process is complete.
<ide> You do not need to include your token/id. Please add the statement above to all
<ide> future pull requests as well, simply so that the Spring Framework team knows
<ide> immediately that this process is complete.
<ide>
<add>## Create a branch
<ide>
<del>## Create your branch from `master`
<add>### Branch from `master`
<ide>
<ide> Master currently represents work toward Spring Framework 4.0. Please submit
<ide> all pull requests there, even bug fixes and minor improvements. Backports to
<ide> `3.2.x` will be considered on a case-by-case basis.
<ide>
<ide>
<del>## Use short branch names
<add>### Use short branch names
<ide>
<ide> Branches used when submitting pull requests should preferably be named
<ide> according to JIRA issues, e.g. 'SPR-1234'. Otherwise, use succinct, lower-case,
<ide> dash (-) delimited names, such as 'fix-warnings', 'fix-typo', etc. In
<ide> important, because branch names show up in the merge commits that result from
<ide> accepting pull requests, and should be as expressive and concise as possible.
<ide>
<add>## Use Spring code style
<add>
<add>The complete [Spring Code Style][] reference is available on the wiki.
<add>Here's a quick summary:
<ide>
<del>## Mind the whitespace
<add>### Mind the whitespace
<ide>
<ide> Please carefully follow the whitespace and formatting conventions already
<ide> present in the framework.
<ide> present in the framework.
<ide> if necessary
<ide>
<ide>
<del>## Add Apache license header to all new classes
<add>### Add Apache license header to all new classes
<ide>
<ide> ```java
<ide> /*
<ide> present in the framework.
<ide> package ...;
<ide> ```
<ide>
<del>## Update Apache license header to modified files as necessary
<add>### Update Apache license header to modified files as necessary
<ide>
<ide> Always check the date range in the license header. For example, if you've
<ide> modified a file in 2013 whose header still reads
<ide> then be sure to update it to 2013 appropriately
<ide> * Copyright 2002-2013 the original author or authors.
<ide> ```
<ide>
<del>## Use @since tags for newly-added public API types and methods
<add>### Use @since tags for newly-added public API types and methods
<ide>
<ide> e.g.
<ide>
<ide> e.g.
<ide> */
<ide> ```
<ide>
<del>## Submit JUnit test cases for all behavior changes
<add>## Prepare your commit
<add>
<add>### Submit JUnit test cases for all behavior changes
<ide>
<ide> Search the codebase to find related unit tests and add additional @Test methods
<ide> within. It is also acceptable to submit test cases on a per JIRA issue basis,
<ide> public class Spr8954Tests {
<ide> ```
<ide>
<ide>
<del>## Squash commits
<add>### Squash commits
<ide>
<ide> Use `git rebase --interactive`, `git add --patch` and other tools to "squash"
<ide> multiple commits into atomic changes. In addition to the man pages for git,
<ide> there are many resources online to help you understand how these tools work.
<ide> Here is one: http://book.git-scm.com/4_interactive_rebasing.html.
<ide>
<ide>
<del>## Use real name in git commits
<add>### Use real name in git commits
<ide>
<ide> Please configure git to use your real first and last name for any commits you
<ide> intend to submit as pull requests. For example, this is not acceptable:
<ide> flag:
<ide> git config user.email user@mail.com
<ide>
<ide>
<del>## Format commit messages
<add>### Format commit messages
<ide>
<ide> Please read and follow the [commit guidelines section of Pro Git][].
<ide>
<ide> https://github.com/SpringSource/spring-framework/commit/1d9d3e6ff79ce9f0eca03b02
<ide> https://github.com/SpringSource/spring-framework/commit/8e0b1c3a5f957af3049cfa0438317177e16d6de6
<ide> https://github.com/SpringSource/spring-framework/commit/b787a68f2050df179f7036b209aa741230a02477
<ide>
<del>## Run all tests prior to submission
<add>## Run the final checklist
<add>
<add>### Run all tests prior to submission
<ide>
<ide> See the [building from source][] section of the README for instructions. Make
<ide> sure that all tests pass prior to submitting your pull request.
<ide>
<ide>
<del>## Submit your pull request
<add>### Submit your pull request
<ide>
<ide> Subject line:
<ide>
<ide> the commit message. This is fine, but please also include the items above in the
<ide> body of the request.
<ide>
<ide>
<del>## Mention your pull request on the associated JIRA issue
<add>### Mention your pull request on the associated JIRA issue
<ide>
<ide> Add a comment to the associated JIRA issue(s) linking to your new pull request.
<ide>
<ide>
<del>## Expect discussion and rework
<add>### Expect discussion and rework
<ide>
<ide> The Spring team takes a very conservative approach to accepting contributions to
<ide> the framework. This is to keep code quality and stability as high as possible,
<ide> issue a new pull request when asked to make changes.
<ide> [spring-framework-contrib]: https://groups.google.com/forum/#!forum/spring-framework-contrib
<ide> [SpringSource CLA form]: https://support.springsource.com/spring_committer_signup
<ide> [fork-and-edit]: https://github.com/blog/844-forking-with-the-edit-button
<add>[Spring Code Style]: https://github.com/spring-projects/spring-framework/wiki/Spring-Code-Style
<ide> [commit guidelines section of Pro Git]: http://progit.org/book/ch5-2.html#commit_guidelines
<ide> [building from source]: https://github.com/SpringSource/spring-framework#building-from-source
<ide><path>README.md
<ide> The Spring Framework is released under version 2.0 of the [Apache License][].
<ide> [Pull requests]: http://help.github.com/send-pull-requests
<ide> [contributor guidelines]: https://github.com/SpringSource/spring-framework/blob/master/CONTRIBUTING.md
<ide> [@springframework]: http://twitter.com/springframework
<del>[team members]: http://twitter.com/springframework/team/members
<add>[team members]: http://spring.io/team
<ide> [team blog]: http://blog.springsource.org
<ide> [news feed]: http://www.springsource.org/news-events
<ide> [Apache License]: http://www.apache.org/licenses/LICENSE-2.0
<ide><path>import-into-idea.md
<ide> _Within your locally cloned spring-framework working directory:_
<ide>
<ide> ## Known issues
<ide>
<del>1. `spring-aspects` does not compile out of the box due to references to aspect types unknown to IDEA.
<add>1. Those steps don't work currently for Intellij IDEA 13+
<add>2. `spring-aspects` does not compile out of the box due to references to aspect types unknown to IDEA.
<ide> See http://youtrack.jetbrains.com/issue/IDEA-64446 for details. In the meantime, the 'spring-aspects'
<ide> module has been excluded from the overall project to avoid compilation errors.
<del>2. While all JUnit tests pass from the command line with Gradle, many will fail when run from IDEA.
<add>3. While all JUnit tests pass from the command line with Gradle, many will fail when run from IDEA.
<ide> Resolving this is a work in progress. If attempting to run all JUnit tests from within IDEA, you will
<ide> likely need to set the following VM options to avoid out of memory errors:
<ide> -XX:MaxPermSize=2048m -Xmx2048m -XX:MaxHeapSize=2048m | 3 |
Javascript | Javascript | add forum link in the docs | 760f726e516752d27142346d8552682d3f6f0532 | <ide><path>docs/source/_static/js/custom.js
<ide> function addHfMenu() {
<ide> <div class="menu">
<ide> <a href="/welcome">🔥 Sign in</a>
<ide> <a href="/models">🚀 Models</a>
<add> <a href="http://discuss.huggingface.co">💬 Forum</a>
<ide> </div>
<ide> `;
<ide> document.body.insertAdjacentHTML('afterbegin', div); | 1 |
PHP | PHP | make set() also hook events up | d95c00503897fdc389d19ded11888b979053d894 | <ide><path>src/Utility/ObjectRegistry.php
<ide> public function reset() {
<ide> }
<ide>
<ide> /**
<del> * set an object directly into the registry by name
<add> * Set an object directly into the registry by name.
<ide> *
<del> * This is primarily to aid testing
<add> * If this collection implements events, the passed object will
<add> * be attached into the event manager
<ide> *
<ide> * @param string $objectName The name of the object to set in the registry.
<ide> * @param object $object instance to store in the registry
<ide> * @return void
<ide> */
<ide> public function set($objectName, $object) {
<ide> list($plugin, $name) = pluginSplit($objectName);
<add> $this->unload($objectName);
<add> if (isset($this->_eventManager)) {
<add> $this->_eventManager->attach($object);
<add> }
<ide> $this->_loaded[$name] = $object;
<ide> }
<ide>
<ide><path>tests/TestCase/Controller/ComponentRegistryTest.php
<ide> namespace Cake\Test\TestCase\Controller;
<ide>
<ide> use Cake\Controller\ComponentRegistry;
<add>use Cake\Controller\Component\AuthComponent;
<ide> use Cake\Controller\Component\CookieComponent;
<ide> use Cake\Controller\Controller;
<ide> use Cake\Core\App;
<ide> public function testUnload() {
<ide> $this->assertCount(0, $eventManager->listeners('Controller.startup'));
<ide> }
<ide>
<add>/**
<add> * Test set.
<add> *
<add> * @return void
<add> */
<add> public function testSet() {
<add> $eventManager = $this->Components->getController()->getEventManager();
<add> $this->assertCount(0, $eventManager->listeners('Controller.startup'));
<add>
<add> $auth = new AuthComponent($this->Components);
<add> $this->Components->set('Auth', $auth);
<add>
<add> $this->assertTrue(isset($this->Components->Auth), 'Should be gone');
<add> $this->assertCount(1, $eventManager->listeners('Controller.startup'));
<add> }
<add>
<ide> } | 2 |
Python | Python | assert length first | 0ba5cf51d2735432e367ff384cbb53e10e02bd74 | <ide><path>spacy/tests/tokenizer/test_urls.py
<ide> def test_tokenizer_handles_simple_url(tokenizer, url):
<ide> @pytest.mark.parametrize("url", URLS)
<ide> def test_tokenizer_handles_prefixed_url(tokenizer, prefix, url):
<ide> tokens = tokenizer(prefix + url)
<add> assert len(tokens) == 2
<ide> assert tokens[0].text == prefix
<ide> assert tokens[1].text == url
<del> assert len(tokens) == 2
<ide>
<ide>
<ide> @pytest.mark.parametrize("suffix", SUFFIXES)
<ide> @pytest.mark.parametrize("url", URLS)
<ide> def test_tokenizer_handles_suffixed_url(tokenizer, url, suffix):
<ide> tokens = tokenizer(url + suffix)
<add> assert len(tokens) == 2
<ide> assert tokens[0].text == url
<ide> assert tokens[1].text == suffix
<del> assert len(tokens) == 2
<ide>
<ide>
<ide> @pytest.mark.parametrize("prefix", PREFIXES)
<ide> @pytest.mark.parametrize("suffix", SUFFIXES)
<ide> @pytest.mark.parametrize("url", URLS)
<ide> def test_tokenizer_handles_surround_url(tokenizer, prefix, suffix, url):
<ide> tokens = tokenizer(prefix + url + suffix)
<add> assert len(tokens) == 3
<ide> assert tokens[0].text == prefix
<ide> assert tokens[1].text == url
<ide> assert tokens[2].text == suffix
<ide> def test_tokenizer_handles_surround_url(tokenizer, prefix, suffix, url):
<ide> @pytest.mark.parametrize("url", URLS)
<ide> def test_tokenizer_handles_two_prefix_url(tokenizer, prefix1, prefix2, url):
<ide> tokens = tokenizer(prefix1 + prefix2 + url)
<add> assert len(tokens) == 3
<ide> assert tokens[0].text == prefix1
<ide> assert tokens[1].text == prefix2
<ide> assert tokens[2].text == url
<del> assert len(tokens) == 3
<ide>
<ide>
<ide> @pytest.mark.parametrize("suffix1", SUFFIXES)
<ide> @pytest.mark.parametrize("suffix2", SUFFIXES)
<ide> @pytest.mark.parametrize("url", URLS)
<ide> def test_tokenizer_handles_two_prefix_url(tokenizer, suffix1, suffix2, url):
<ide> tokens = tokenizer(url + suffix1 + suffix2)
<add> assert len(tokens) == 3
<ide> assert tokens[0].text == url
<ide> assert tokens[1].text == suffix1
<ide> assert tokens[2].text == suffix2
<del> assert len(tokens) == 3 | 1 |
Text | Text | update line 28 and 34 | 2e0c720e8aaf08ca1fb8c316cbc616fe0c3590b8 | <ide><path>guide/english/computer-hardware/motherboard/index.md
<ide> To understand how computers work, you don't need to know every single part of th
<ide> - A second chip controls the input and output (I/O) functions. It is not connected directly to the CPU but to the Northbridge. This I/O controller is referred to as the Southbridge. The Northbridge and Southbridge combined are referred to as the chipset.
<ide> - Several connectors, which provide the physical interface between input and output devices and the motherboard. The Southbridge handles these connections.
<ide> - Slots for one or more hard drives to store files. The most common types of connections are Integrated Drive Electronics (IDE) and Serial Advanced Technology Attachment (SATA).
<del>- A read-only memory (ROM) chip, which contains the firmware, or startup instructions for the computer system. This is also called the BIOS.
<add>- A read-only memory (ROM) chip, which contains the firmware, or startup instructions for the computer system. This was previously a system known as BIOS but has been replaced on more modern machines by UEFI
<ide> - A slot for a video or graphics card. There are a number of different types of slots, including the Accelerated Graphics Port (AGP) and Peripheral Component Interconnect Express (PCIe).
<ide> Additional slots to connect hardware in the form of Peripheral Component Interconnect (PCI) slots.
<ide>
<ide> ## Types of Motherboards
<ide>
<del>Motherboards come in different sizes, known as form factors. The most common motherboard form factor is ATX. The different types of ATX are known as micro-ATX (sometimes shown as µATX, mini-ATX, FlexATX, EATX, WATX, nano-ATX, pico-ATX, and mobileATX).
<add>Motherboards come in different sizes, known as form factors. The most common motherboard form factor is ATX. Some of the different types of ATX are micro-ATX (sometimes shown as µATX), mini-ATX, FlexATX, EATX, WATX, nano-ATX, pico-ATX, and mobileATX. There are also a number of other variations.
<ide>
<ide> Additionally there can be even smaller boards like the raspberry pi, which are 65mm by 35mm and have all processing units integrated to the board. There are many others that are even more specific in function, such as an Aurdino board. These are typically limited in I/O, have no expansion slots aside from whatever expansion is offered via USB ports, and some display ports like HDMI or similar variants. These are used for small emulator projects, running small servers, or as an alternative to slim client devices in an office.
<ide> | 1 |
Javascript | Javascript | add batched mode | 862f499facfba9635f21c25b17368cb980b17c7e | <ide><path>packages/react-art/src/ReactART.js
<ide>
<ide> import React from 'react';
<ide> import ReactVersion from 'shared/ReactVersion';
<add>import {LegacyRoot} from 'shared/ReactRootTags';
<ide> import {
<ide> createContainer,
<ide> updateContainer,
<ide> class Surface extends React.Component {
<ide>
<ide> this._surface = Mode.Surface(+width, +height, this._tagRef);
<ide>
<del> this._mountNode = createContainer(this._surface);
<add> this._mountNode = createContainer(this._surface, LegacyRoot, false);
<ide> updateContainer(this.props.children, this._mountNode, this);
<ide> }
<ide>
<ide><path>packages/react-dom/src/client/ReactDOM.js
<ide> */
<ide>
<ide> import type {ReactNodeList} from 'shared/ReactTypes';
<add>import type {RootTag} from 'shared/ReactRootTags';
<ide> // TODO: This type is shared between the reconciler and ReactDOM, but will
<ide> // eventually be lifted out to the renderer.
<ide> import type {
<ide> import {
<ide> accumulateTwoPhaseDispatches,
<ide> accumulateDirectDispatches,
<ide> } from 'events/EventPropagators';
<add>import {LegacyRoot, ConcurrentRoot} from 'shared/ReactRootTags';
<ide> import {has as hasInstance} from 'shared/ReactInstanceMap';
<ide> import ReactVersion from 'shared/ReactVersion';
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide> ReactWork.prototype._onCommit = function(): void {
<ide> }
<ide> };
<ide>
<del>function ReactRoot(
<del> container: DOMContainer,
<del> isConcurrent: boolean,
<del> hydrate: boolean,
<del>) {
<del> const root = createContainer(container, isConcurrent, hydrate);
<add>function ReactRoot(container: DOMContainer, tag: RootTag, hydrate: boolean) {
<add> const root = createContainer(container, tag, hydrate);
<ide> this._internalRoot = root;
<ide> }
<ide> ReactRoot.prototype.render = function(
<ide> function legacyCreateRootFromDOMContainer(
<ide> );
<ide> }
<ide> }
<del> // Legacy roots are not async by default.
<del> const isConcurrent = false;
<del> return new ReactRoot(container, isConcurrent, shouldHydrate);
<add> return new ReactRoot(container, LegacyRoot, shouldHydrate);
<ide> }
<ide>
<ide> function legacyRenderSubtreeIntoContainer(
<ide> function createRoot(container: DOMContainer, options?: RootOptions): ReactRoot {
<ide> container._reactHasBeenPassedToCreateRootDEV = true;
<ide> }
<ide> const hydrate = options != null && options.hydrate === true;
<del> return new ReactRoot(container, true, hydrate);
<add> return new ReactRoot(container, ConcurrentRoot, hydrate);
<ide> }
<ide>
<ide> if (enableStableConcurrentModeAPIs) {
<ide><path>packages/react-dom/src/fire/ReactFire.js
<ide> // console.log('Hello from Fire entry point.');
<ide>
<ide> import type {ReactNodeList} from 'shared/ReactTypes';
<add>import type {RootTag} from 'shared/ReactRootTags';
<ide> // TODO: This type is shared between the reconciler and ReactDOM, but will
<ide> // eventually be lifted out to the renderer.
<ide> import type {
<ide> import {
<ide> accumulateTwoPhaseDispatches,
<ide> accumulateDirectDispatches,
<ide> } from 'events/EventPropagators';
<add>import {LegacyRoot, ConcurrentRoot} from 'shared/ReactRootTags';
<ide> import {has as hasInstance} from 'shared/ReactInstanceMap';
<ide> import ReactVersion from 'shared/ReactVersion';
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide> ReactWork.prototype._onCommit = function(): void {
<ide> }
<ide> };
<ide>
<del>function ReactRoot(
<del> container: DOMContainer,
<del> isConcurrent: boolean,
<del> hydrate: boolean,
<del>) {
<del> const root = createContainer(container, isConcurrent, hydrate);
<add>function ReactRoot(container: DOMContainer, tag: RootTag, hydrate: boolean) {
<add> const root = createContainer(container, tag, hydrate);
<ide> this._internalRoot = root;
<ide> }
<ide> ReactRoot.prototype.render = function(
<ide> function legacyCreateRootFromDOMContainer(
<ide> );
<ide> }
<ide> }
<del> // Legacy roots are not async by default.
<del> const isConcurrent = false;
<del> return new ReactRoot(container, isConcurrent, shouldHydrate);
<add> return new ReactRoot(container, LegacyRoot, shouldHydrate);
<ide> }
<ide>
<ide> function legacyRenderSubtreeIntoContainer(
<ide> function createRoot(container: DOMContainer, options?: RootOptions): ReactRoot {
<ide> container._reactHasBeenPassedToCreateRootDEV = true;
<ide> }
<ide> const hydrate = options != null && options.hydrate === true;
<del> return new ReactRoot(container, true, hydrate);
<add> return new ReactRoot(container, ConcurrentRoot, hydrate);
<ide> }
<ide>
<ide> if (enableStableConcurrentModeAPIs) {
<ide><path>packages/react-native-renderer/src/ReactFabric.js
<ide> import ReactNativeComponent from './ReactNativeComponent';
<ide> import {getClosestInstanceFromNode} from './ReactFabricComponentTree';
<ide> import {getInspectorDataForViewTag} from './ReactNativeFiberInspector';
<ide>
<add>import {LegacyRoot} from 'shared/ReactRootTags';
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide> import getComponentName from 'shared/getComponentName';
<ide> import warningWithoutStack from 'shared/warningWithoutStack';
<ide> const ReactFabric: ReactFabricType = {
<ide> if (!root) {
<ide> // TODO (bvaughn): If we decide to keep the wrapper component,
<ide> // We could create a wrapper for containerTag as well to reduce special casing.
<del> root = createContainer(containerTag, false, false);
<add> root = createContainer(containerTag, LegacyRoot, false);
<ide> roots.set(containerTag, root);
<ide> }
<ide> updateContainer(element, root, null, callback);
<ide><path>packages/react-native-renderer/src/ReactNativeRenderer.js
<ide> import {getClosestInstanceFromNode} from './ReactNativeComponentTree';
<ide> import {getInspectorDataForViewTag} from './ReactNativeFiberInspector';
<ide> import {setNativeProps} from './ReactNativeRendererSharedExports';
<ide>
<add>import {LegacyRoot} from 'shared/ReactRootTags';
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide> import getComponentName from 'shared/getComponentName';
<ide> import warningWithoutStack from 'shared/warningWithoutStack';
<ide> const ReactNativeRenderer: ReactNativeType = {
<ide> if (!root) {
<ide> // TODO (bvaughn): If we decide to keep the wrapper component,
<ide> // We could create a wrapper for containerTag as well to reduce special casing.
<del> root = createContainer(containerTag, false, false);
<add> root = createContainer(containerTag, LegacyRoot, false);
<ide> roots.set(containerTag, root);
<ide> }
<ide> updateContainer(element, root, null, callback);
<ide><path>packages/react-noop-renderer/src/createReactNoop.js
<ide> import type {Thenable} from 'react-reconciler/src/ReactFiberScheduler';
<ide> import type {Fiber} from 'react-reconciler/src/ReactFiber';
<ide> import type {UpdateQueue} from 'react-reconciler/src/ReactUpdateQueue';
<ide> import type {ReactNodeList} from 'shared/ReactTypes';
<add>import type {RootTag} from 'shared/ReactRootTags';
<ide>
<ide> import * as Scheduler from 'scheduler/unstable_mock';
<ide> import {createPortal} from 'shared/ReactPortal';
<ide> import enqueueTask from 'shared/enqueueTask';
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide> import warningWithoutStack from 'shared/warningWithoutStack';
<ide> import {enableEventAPI} from 'shared/ReactFeatureFlags';
<add>import {ConcurrentRoot, BatchedRoot, LegacyRoot} from 'shared/ReactRootTags';
<ide>
<ide> type EventTargetChildElement = {
<ide> type: string,
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide> return textInstance.text;
<ide> }
<ide>
<add> function getChildren(root) {
<add> if (root) {
<add> return root.children;
<add> } else {
<add> return null;
<add> }
<add> }
<add>
<add> function getPendingChildren(root) {
<add> if (root) {
<add> return root.pendingChildren;
<add> } else {
<add> return null;
<add> }
<add> }
<add>
<add> function getChildrenAsJSX(root) {
<add> const children = childToJSX(getChildren(root), null);
<add> if (children === null) {
<add> return null;
<add> }
<add> if (Array.isArray(children)) {
<add> return {
<add> $$typeof: REACT_ELEMENT_TYPE,
<add> type: REACT_FRAGMENT_TYPE,
<add> key: null,
<add> ref: null,
<add> props: {children},
<add> _owner: null,
<add> _store: __DEV__ ? {} : undefined,
<add> };
<add> }
<add> return children;
<add> }
<add>
<add> function getPendingChildrenAsJSX(root) {
<add> const children = childToJSX(getChildren(root), null);
<add> if (children === null) {
<add> return null;
<add> }
<add> if (Array.isArray(children)) {
<add> return {
<add> $$typeof: REACT_ELEMENT_TYPE,
<add> type: REACT_FRAGMENT_TYPE,
<add> key: null,
<add> ref: null,
<add> props: {children},
<add> _owner: null,
<add> _store: __DEV__ ? {} : undefined,
<add> };
<add> }
<add> return children;
<add> }
<add>
<add> let idCounter = 0;
<add>
<ide> const ReactNoop = {
<ide> _Scheduler: Scheduler,
<ide>
<ide> getChildren(rootID: string = DEFAULT_ROOT_ID) {
<ide> const container = rootContainers.get(rootID);
<del> if (container) {
<del> return container.children;
<del> } else {
<del> return null;
<del> }
<add> return getChildren(container);
<ide> },
<ide>
<ide> getPendingChildren(rootID: string = DEFAULT_ROOT_ID) {
<ide> const container = rootContainers.get(rootID);
<del> if (container) {
<del> return container.pendingChildren;
<del> } else {
<del> return null;
<del> }
<add> return getPendingChildren(container);
<ide> },
<ide>
<del> getOrCreateRootContainer(
<del> rootID: string = DEFAULT_ROOT_ID,
<del> isConcurrent: boolean = false,
<del> ) {
<add> getOrCreateRootContainer(rootID: string = DEFAULT_ROOT_ID, tag: RootTag) {
<ide> let root = roots.get(rootID);
<ide> if (!root) {
<ide> const container = {rootID: rootID, pendingChildren: [], children: []};
<ide> rootContainers.set(rootID, container);
<del> root = NoopRenderer.createContainer(container, isConcurrent, false);
<add> root = NoopRenderer.createContainer(container, tag, false);
<ide> roots.set(rootID, root);
<ide> }
<ide> return root.current.stateNode.containerInfo;
<ide> },
<ide>
<add> // TODO: Replace ReactNoop.render with createRoot + root.render
<add> createRoot() {
<add> const container = {
<add> rootID: '' + idCounter++,
<add> pendingChildren: [],
<add> children: [],
<add> };
<add> const fiberRoot = NoopRenderer.createContainer(
<add> container,
<add> ConcurrentRoot,
<add> false,
<add> );
<add> return {
<add> _Scheduler: Scheduler,
<add> render(children: ReactNodeList) {
<add> NoopRenderer.updateContainer(children, fiberRoot, null, null);
<add> },
<add> getChildren() {
<add> return getChildren(fiberRoot);
<add> },
<add> getChildrenAsJSX() {
<add> return getChildrenAsJSX(fiberRoot);
<add> },
<add> };
<add> },
<add>
<add> createSyncRoot() {
<add> const container = {
<add> rootID: '' + idCounter++,
<add> pendingChildren: [],
<add> children: [],
<add> };
<add> const fiberRoot = NoopRenderer.createContainer(
<add> container,
<add> BatchedRoot,
<add> false,
<add> );
<add> return {
<add> _Scheduler: Scheduler,
<add> render(children: ReactNodeList) {
<add> NoopRenderer.updateContainer(children, fiberRoot, null, null);
<add> },
<add> getChildren() {
<add> return getChildren(container);
<add> },
<add> getChildrenAsJSX() {
<add> return getChildrenAsJSX(container);
<add> },
<add> };
<add> },
<add>
<ide> getChildrenAsJSX(rootID: string = DEFAULT_ROOT_ID) {
<del> const children = childToJSX(ReactNoop.getChildren(rootID), null);
<del> if (children === null) {
<del> return null;
<del> }
<del> if (Array.isArray(children)) {
<del> return {
<del> $$typeof: REACT_ELEMENT_TYPE,
<del> type: REACT_FRAGMENT_TYPE,
<del> key: null,
<del> ref: null,
<del> props: {children},
<del> _owner: null,
<del> _store: __DEV__ ? {} : undefined,
<del> };
<del> }
<del> return children;
<add> const container = rootContainers.get(rootID);
<add> return getChildrenAsJSX(container);
<ide> },
<ide>
<ide> getPendingChildrenAsJSX(rootID: string = DEFAULT_ROOT_ID) {
<del> const children = childToJSX(ReactNoop.getPendingChildren(rootID), null);
<del> if (children === null) {
<del> return null;
<del> }
<del> if (Array.isArray(children)) {
<del> return {
<del> $$typeof: REACT_ELEMENT_TYPE,
<del> type: REACT_FRAGMENT_TYPE,
<del> key: null,
<del> ref: null,
<del> props: {children},
<del> _owner: null,
<del> _store: __DEV__ ? {} : undefined,
<del> };
<del> }
<del> return children;
<add> const container = rootContainers.get(rootID);
<add> return getPendingChildrenAsJSX(container);
<ide> },
<ide>
<ide> createPortal(
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide>
<ide> renderLegacySyncRoot(element: React$Element<any>, callback: ?Function) {
<ide> const rootID = DEFAULT_ROOT_ID;
<del> const isConcurrent = false;
<del> const container = ReactNoop.getOrCreateRootContainer(
<del> rootID,
<del> isConcurrent,
<del> );
<add> const container = ReactNoop.getOrCreateRootContainer(rootID, LegacyRoot);
<ide> const root = roots.get(container.rootID);
<ide> NoopRenderer.updateContainer(element, root, null, callback);
<ide> },
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide> rootID: string,
<ide> callback: ?Function,
<ide> ) {
<del> const isConcurrent = true;
<ide> const container = ReactNoop.getOrCreateRootContainer(
<ide> rootID,
<del> isConcurrent,
<add> ConcurrentRoot,
<ide> );
<ide> const root = roots.get(container.rootID);
<ide> NoopRenderer.updateContainer(element, root, null, callback);
<ide><path>packages/react-reconciler/src/ReactFiber.js
<ide> import type {
<ide> ReactEventComponent,
<ide> ReactEventTarget,
<ide> } from 'shared/ReactTypes';
<add>import type {RootTag} from 'shared/ReactRootTags';
<ide> import type {WorkTag} from 'shared/ReactWorkTags';
<ide> import type {TypeOfMode} from './ReactTypeOfMode';
<ide> import type {SideEffectTag} from 'shared/ReactSideEffectTags';
<ide> import invariant from 'shared/invariant';
<ide> import warningWithoutStack from 'shared/warningWithoutStack';
<ide> import {enableProfilerTimer, enableEventAPI} from 'shared/ReactFeatureFlags';
<ide> import {NoEffect} from 'shared/ReactSideEffectTags';
<add>import {ConcurrentRoot, BatchedRoot} from 'shared/ReactRootTags';
<ide> import {
<ide> IndeterminateComponent,
<ide> ClassComponent,
<ide> import getComponentName from 'shared/getComponentName';
<ide> import {isDevToolsPresent} from './ReactFiberDevToolsHook';
<ide> import {NoWork} from './ReactFiberExpirationTime';
<ide> import {
<del> NoContext,
<add> NoMode,
<ide> ConcurrentMode,
<ide> ProfileMode,
<ide> StrictMode,
<add> BatchedMode,
<ide> } from './ReactTypeOfMode';
<ide> import {
<ide> REACT_FORWARD_REF_TYPE,
<ide> export function createWorkInProgress(
<ide> return workInProgress;
<ide> }
<ide>
<del>export function createHostRootFiber(isConcurrent: boolean): Fiber {
<del> let mode = isConcurrent ? ConcurrentMode | StrictMode : NoContext;
<add>export function createHostRootFiber(tag: RootTag): Fiber {
<add> let mode;
<add> if (tag === ConcurrentRoot) {
<add> mode = ConcurrentMode | BatchedMode | StrictMode;
<add> } else if (tag === BatchedRoot) {
<add> mode = BatchedMode | StrictMode;
<add> } else {
<add> mode = NoMode;
<add> }
<ide>
<ide> if (enableProfilerTimer && isDevToolsPresent) {
<ide> // Always collect profile timings when DevTools are present.
<ide> export function createFiberFromTypeAndProps(
<ide> key,
<ide> );
<ide> case REACT_CONCURRENT_MODE_TYPE:
<del> return createFiberFromMode(
<del> pendingProps,
<del> mode | ConcurrentMode | StrictMode,
<del> expirationTime,
<del> key,
<del> );
<add> fiberTag = Mode;
<add> mode |= ConcurrentMode | BatchedMode | StrictMode;
<add> break;
<ide> case REACT_STRICT_MODE_TYPE:
<del> return createFiberFromMode(
<del> pendingProps,
<del> mode | StrictMode,
<del> expirationTime,
<del> key,
<del> );
<add> fiberTag = Mode;
<add> mode |= StrictMode;
<add> break;
<ide> case REACT_PROFILER_TYPE:
<ide> return createFiberFromProfiler(pendingProps, mode, expirationTime, key);
<ide> case REACT_SUSPENSE_TYPE:
<ide> function createFiberFromProfiler(
<ide> return fiber;
<ide> }
<ide>
<del>function createFiberFromMode(
<del> pendingProps: any,
<del> mode: TypeOfMode,
<del> expirationTime: ExpirationTime,
<del> key: null | string,
<del>): Fiber {
<del> const fiber = createFiber(Mode, pendingProps, key, mode);
<del>
<del> // TODO: The Mode fiber shouldn't have a type. It has a tag.
<del> const type =
<del> (mode & ConcurrentMode) === NoContext
<del> ? REACT_STRICT_MODE_TYPE
<del> : REACT_CONCURRENT_MODE_TYPE;
<del> fiber.elementType = type;
<del> fiber.type = type;
<del>
<del> fiber.expirationTime = expirationTime;
<del> return fiber;
<del>}
<del>
<ide> export function createFiberFromSuspense(
<ide> pendingProps: any,
<ide> mode: TypeOfMode,
<ide> export function createFiberFromText(
<ide> }
<ide>
<ide> export function createFiberFromHostInstanceForDeletion(): Fiber {
<del> const fiber = createFiber(HostComponent, null, null, NoContext);
<add> const fiber = createFiber(HostComponent, null, null, NoMode);
<ide> // TODO: These should not need a type.
<ide> fiber.elementType = 'DELETED';
<ide> fiber.type = 'DELETED';
<ide> export function assignFiberPropertiesInDEV(
<ide> if (target === null) {
<ide> // This Fiber's initial properties will always be overwritten.
<ide> // We only use a Fiber to ensure the same hidden class so DEV isn't slow.
<del> target = createFiber(IndeterminateComponent, null, null, NoContext);
<add> target = createFiber(IndeterminateComponent, null, null, NoMode);
<ide> }
<ide>
<ide> // This is intentionally written as a list of all properties.
<ide><path>packages/react-reconciler/src/ReactFiberBeginWork.js
<ide> import {
<ide> } from './ReactFiberExpirationTime';
<ide> import {
<ide> ConcurrentMode,
<del> NoContext,
<add> NoMode,
<ide> ProfileMode,
<ide> StrictMode,
<add> BatchedMode,
<ide> } from './ReactTypeOfMode';
<ide> import {
<ide> shouldSetTextContent,
<ide> function updateSuspenseComponent(
<ide> null,
<ide> );
<ide>
<del> if ((workInProgress.mode & ConcurrentMode) === NoContext) {
<del> // Outside of concurrent mode, we commit the effects from the
<add> if ((workInProgress.mode & BatchedMode) === NoMode) {
<add> // Outside of batched mode, we commit the effects from the
<ide> // partially completed, timed-out tree, too.
<ide> const progressedState: SuspenseState = workInProgress.memoizedState;
<ide> const progressedPrimaryChild: Fiber | null =
<ide> function updateSuspenseComponent(
<ide> NoWork,
<ide> );
<ide>
<del> if ((workInProgress.mode & ConcurrentMode) === NoContext) {
<del> // Outside of concurrent mode, we commit the effects from the
<add> if ((workInProgress.mode & BatchedMode) === NoMode) {
<add> // Outside of batched mode, we commit the effects from the
<ide> // partially completed, timed-out tree, too.
<ide> const progressedState: SuspenseState = workInProgress.memoizedState;
<ide> const progressedPrimaryChild: Fiber | null =
<ide> function updateSuspenseComponent(
<ide> // schedule a placement.
<ide> // primaryChildFragment.effectTag |= Placement;
<ide>
<del> if ((workInProgress.mode & ConcurrentMode) === NoContext) {
<del> // Outside of concurrent mode, we commit the effects from the
<add> if ((workInProgress.mode & BatchedMode) === NoMode) {
<add> // Outside of batched mode, we commit the effects from the
<ide> // partially completed, timed-out tree, too.
<ide> const progressedState: SuspenseState = workInProgress.memoizedState;
<ide> const progressedPrimaryChild: Fiber | null =
<ide><path>packages/react-reconciler/src/ReactFiberCompleteWork.js
<ide> import {
<ide> EventComponent,
<ide> EventTarget,
<ide> } from 'shared/ReactWorkTags';
<del>import {ConcurrentMode, NoContext} from './ReactTypeOfMode';
<add>import {NoMode, BatchedMode} from './ReactTypeOfMode';
<ide> import {
<ide> Placement,
<ide> Ref,
<ide> function completeWork(
<ide> }
<ide>
<ide> if (nextDidTimeout && !prevDidTimeout) {
<del> // If this subtreee is running in concurrent mode we can suspend,
<add> // If this subtreee is running in batched mode we can suspend,
<ide> // otherwise we won't suspend.
<ide> // TODO: This will still suspend a synchronous tree if anything
<ide> // in the concurrent tree already suspended during this render.
<ide> // This is a known bug.
<del> if ((workInProgress.mode & ConcurrentMode) !== NoContext) {
<add> if ((workInProgress.mode & BatchedMode) !== NoMode) {
<ide> renderDidSuspend();
<ide> }
<ide> }
<ide><path>packages/react-reconciler/src/ReactFiberExpirationTime.js
<ide> export type ExpirationTime = number;
<ide> export const NoWork = 0;
<ide> export const Never = 1;
<ide> export const Sync = MAX_SIGNED_31_BIT_INT;
<add>export const Batched = Sync - 1;
<ide>
<ide> const UNIT_SIZE = 10;
<del>const MAGIC_NUMBER_OFFSET = MAX_SIGNED_31_BIT_INT - 1;
<add>const MAGIC_NUMBER_OFFSET = Batched - 1;
<ide>
<ide> // 1 unit of expiration time represents 10ms.
<ide> export function msToExpirationTime(ms: number): ExpirationTime {
<ide><path>packages/react-reconciler/src/ReactFiberReconciler.js
<ide>
<ide> import type {Fiber} from './ReactFiber';
<ide> import type {FiberRoot} from './ReactFiberRoot';
<add>import type {RootTag} from 'shared/ReactRootTags';
<ide> import type {
<ide> Instance,
<ide> TextInstance,
<ide> function findHostInstanceWithWarning(
<ide>
<ide> export function createContainer(
<ide> containerInfo: Container,
<del> isConcurrent: boolean,
<add> tag: RootTag,
<ide> hydrate: boolean,
<ide> ): OpaqueRoot {
<del> return createFiberRoot(containerInfo, isConcurrent, hydrate);
<add> return createFiberRoot(containerInfo, tag, hydrate);
<ide> }
<ide>
<ide> export function updateContainer(
<ide><path>packages/react-reconciler/src/ReactFiberRoot.js
<ide>
<ide> import type {Fiber} from './ReactFiber';
<ide> import type {ExpirationTime} from './ReactFiberExpirationTime';
<add>import type {RootTag} from 'shared/ReactRootTags';
<ide> import type {TimeoutHandle, NoTimeout} from './ReactFiberHostConfig';
<ide> import type {Thenable} from './ReactFiberScheduler';
<ide> import type {Interaction} from 'scheduler/src/Tracing';
<ide> export type Batch = {
<ide> export type PendingInteractionMap = Map<ExpirationTime, Set<Interaction>>;
<ide>
<ide> type BaseFiberRootProperties = {|
<add> // The type of root (legacy, batched, concurrent, etc.)
<add> tag: RootTag,
<add>
<ide> // Any additional information from the host associated with this root.
<ide> containerInfo: any,
<ide> // Used only by persistent updates.
<ide> export type FiberRoot = {
<ide> ...ProfilingOnlyFiberRootProperties,
<ide> };
<ide>
<del>function FiberRootNode(containerInfo, hydrate) {
<add>function FiberRootNode(containerInfo, tag, hydrate) {
<add> this.tag = tag;
<ide> this.current = null;
<ide> this.containerInfo = containerInfo;
<ide> this.pendingChildren = null;
<ide> function FiberRootNode(containerInfo, hydrate) {
<ide>
<ide> export function createFiberRoot(
<ide> containerInfo: any,
<del> isConcurrent: boolean,
<add> tag: RootTag,
<ide> hydrate: boolean,
<ide> ): FiberRoot {
<del> const root: FiberRoot = (new FiberRootNode(containerInfo, hydrate): any);
<add> const root: FiberRoot = (new FiberRootNode(containerInfo, tag, hydrate): any);
<ide>
<ide> // Cyclic construction. This cheats the type system right now because
<ide> // stateNode is any.
<del> const uninitializedFiber = createHostRootFiber(isConcurrent);
<add> const uninitializedFiber = createHostRootFiber(tag);
<ide> root.current = uninitializedFiber;
<ide> uninitializedFiber.stateNode = root;
<ide>
<ide><path>packages/react-reconciler/src/ReactFiberScheduler.js
<ide> import {
<ide> NormalPriority,
<ide> LowPriority,
<ide> IdlePriority,
<del> flushImmediateQueue,
<add> flushSyncCallbackQueue,
<add> scheduleSyncCallback,
<ide> } from './SchedulerWithReactIntegration';
<ide>
<ide> import {__interactionsRef, __subscriberRef} from 'scheduler/tracing';
<ide> import {
<ide> } from './ReactFiberHostConfig';
<ide>
<ide> import {createWorkInProgress, assignFiberPropertiesInDEV} from './ReactFiber';
<del>import {NoContext, ConcurrentMode, ProfileMode} from './ReactTypeOfMode';
<add>import {
<add> NoMode,
<add> ProfileMode,
<add> BatchedMode,
<add> ConcurrentMode,
<add>} from './ReactTypeOfMode';
<ide> import {
<ide> HostRoot,
<ide> ClassComponent,
<ide> import {
<ide> computeAsyncExpiration,
<ide> inferPriorityFromExpirationTime,
<ide> LOW_PRIORITY_EXPIRATION,
<add> Batched,
<ide> } from './ReactFiberExpirationTime';
<ide> import {beginWork as originalBeginWork} from './ReactFiberBeginWork';
<ide> import {completeWork} from './ReactFiberCompleteWork';
<ide> export function computeExpirationForFiber(
<ide> currentTime: ExpirationTime,
<ide> fiber: Fiber,
<ide> ): ExpirationTime {
<del> if ((fiber.mode & ConcurrentMode) === NoContext) {
<add> const mode = fiber.mode;
<add> if ((mode & BatchedMode) === NoMode) {
<ide> return Sync;
<ide> }
<ide>
<add> const priorityLevel = getCurrentPriorityLevel();
<add> if ((mode & ConcurrentMode) === NoMode) {
<add> return priorityLevel === ImmediatePriority ? Sync : Batched;
<add> }
<add>
<ide> if (workPhase === RenderPhase) {
<ide> // Use whatever time we're already rendering
<ide> return renderExpirationTime;
<ide> }
<ide>
<ide> // Compute an expiration time based on the Scheduler priority.
<ide> let expirationTime;
<del> const priorityLevel = getCurrentPriorityLevel();
<ide> switch (priorityLevel) {
<ide> case ImmediatePriority:
<ide> expirationTime = Sync;
<ide> export function scheduleUpdateOnFiber(
<ide> // scheduleCallbackForFiber to preserve the ability to schedule a callback
<ide> // without immediately flushing it. We only do this for user-initated
<ide> // updates, to preserve historical behavior of sync mode.
<del> flushImmediateQueue();
<add> flushSyncCallbackQueue();
<ide> }
<ide> }
<ide> } else {
<ide> function scheduleCallbackForRoot(
<ide> }
<ide> root.callbackExpirationTime = expirationTime;
<ide>
<del> let options = null;
<del> if (expirationTime !== Sync && expirationTime !== Never) {
<del> let timeout = expirationTimeToMs(expirationTime) - now();
<del> if (timeout > 5000) {
<del> // Sanity check. Should never take longer than 5 seconds.
<del> // TODO: Add internal warning?
<del> timeout = 5000;
<add> if (expirationTime === Sync) {
<add> // Sync React callbacks are scheduled on a special internal queue
<add> root.callbackNode = scheduleSyncCallback(
<add> runRootCallback.bind(
<add> null,
<add> root,
<add> renderRoot.bind(null, root, expirationTime),
<add> ),
<add> );
<add> } else {
<add> let options = null;
<add> if (expirationTime !== Sync && expirationTime !== Never) {
<add> let timeout = expirationTimeToMs(expirationTime) - now();
<add> if (timeout > 5000) {
<add> // Sanity check. Should never take longer than 5 seconds.
<add> // TODO: Add internal warning?
<add> timeout = 5000;
<add> }
<add> options = {timeout};
<ide> }
<del> options = {timeout};
<del> }
<ide>
<del> root.callbackNode = scheduleCallback(
<del> priorityLevel,
<del> runRootCallback.bind(
<del> null,
<del> root,
<del> renderRoot.bind(null, root, expirationTime),
<del> ),
<del> options,
<del> );
<del> if (
<del> enableUserTimingAPI &&
<del> expirationTime !== Sync &&
<del> workPhase !== RenderPhase &&
<del> workPhase !== CommitPhase
<del> ) {
<del> // Scheduled an async callback, and we're not already working. Add an
<del> // entry to the flamegraph that shows we're waiting for a callback
<del> // to fire.
<del> startRequestCallbackTimer();
<add> root.callbackNode = scheduleCallback(
<add> priorityLevel,
<add> runRootCallback.bind(
<add> null,
<add> root,
<add> renderRoot.bind(null, root, expirationTime),
<add> ),
<add> options,
<add> );
<add> if (
<add> enableUserTimingAPI &&
<add> expirationTime !== Sync &&
<add> workPhase !== RenderPhase &&
<add> workPhase !== CommitPhase
<add> ) {
<add> // Scheduled an async callback, and we're not already working. Add an
<add> // entry to the flamegraph that shows we're waiting for a callback
<add> // to fire.
<add> startRequestCallbackTimer();
<add> }
<ide> }
<ide> }
<ide>
<ide> export function flushRoot(root: FiberRoot, expirationTime: ExpirationTime) {
<ide> 'means you attempted to commit from inside a lifecycle method.',
<ide> );
<ide> }
<del> scheduleCallback(
<del> ImmediatePriority,
<del> renderRoot.bind(null, root, expirationTime),
<del> );
<del> flushImmediateQueue();
<add> scheduleSyncCallback(renderRoot.bind(null, root, expirationTime));
<add> flushSyncCallbackQueue();
<ide> }
<ide>
<ide> export function flushInteractiveUpdates() {
<ide> function flushPendingDiscreteUpdates() {
<ide> const roots = rootsWithPendingDiscreteUpdates;
<ide> rootsWithPendingDiscreteUpdates = null;
<ide> roots.forEach((expirationTime, root) => {
<del> scheduleCallback(
<del> ImmediatePriority,
<del> renderRoot.bind(null, root, expirationTime),
<del> );
<add> scheduleSyncCallback(renderRoot.bind(null, root, expirationTime));
<ide> });
<ide> // Now flush the immediate queue.
<del> flushImmediateQueue();
<add> flushSyncCallbackQueue();
<ide> }
<ide> }
<ide>
<ide> export function batchedUpdates<A, R>(fn: A => R, a: A): R {
<ide> } finally {
<ide> workPhase = NotWorking;
<ide> // Flush the immediate callbacks that were scheduled during this batch
<del> flushImmediateQueue();
<add> flushSyncCallbackQueue();
<ide> }
<ide> }
<ide>
<ide> export function flushSync<A, R>(fn: A => R, a: A): R {
<ide> // Flush the immediate callbacks that were scheduled during this batch.
<ide> // Note that this will happen even if batchedUpdates is higher up
<ide> // the stack.
<del> flushImmediateQueue();
<add> flushSyncCallbackQueue();
<ide> }
<ide> }
<ide>
<ide> export function flushControlled(fn: () => mixed): void {
<ide> workPhase = prevWorkPhase;
<ide> if (workPhase === NotWorking) {
<ide> // Flush the immediate callbacks that were scheduled during this batch
<del> flushImmediateQueue();
<add> flushSyncCallbackQueue();
<ide> }
<ide> }
<ide> }
<ide> function renderRoot(
<ide> // caused by tearing due to a mutation during an event. Try rendering
<ide> // one more time without yiedling to events.
<ide> prepareFreshStack(root, expirationTime);
<del> scheduleCallback(
<del> ImmediatePriority,
<del> renderRoot.bind(null, root, expirationTime),
<del> );
<add> scheduleSyncCallback(renderRoot.bind(null, root, expirationTime));
<ide> return null;
<ide> }
<ide> // If we're already rendering synchronously, commit the root in its
<ide> function performUnitOfWork(unitOfWork: Fiber): Fiber | null {
<ide> setCurrentDebugFiberInDEV(unitOfWork);
<ide>
<ide> let next;
<del> if (enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoContext) {
<add> if (enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoMode) {
<ide> startProfilerTimer(unitOfWork);
<ide> next = beginWork(current, unitOfWork, renderExpirationTime);
<ide> stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
<ide> function completeUnitOfWork(unitOfWork: Fiber): Fiber | null {
<ide> let next;
<ide> if (
<ide> !enableProfilerTimer ||
<del> (workInProgress.mode & ProfileMode) === NoContext
<add> (workInProgress.mode & ProfileMode) === NoMode
<ide> ) {
<ide> next = completeWork(current, workInProgress, renderExpirationTime);
<ide> } else {
<ide> function completeUnitOfWork(unitOfWork: Fiber): Fiber | null {
<ide>
<ide> if (
<ide> enableProfilerTimer &&
<del> (workInProgress.mode & ProfileMode) !== NoContext
<add> (workInProgress.mode & ProfileMode) !== NoMode
<ide> ) {
<ide> // Record the render duration for the fiber that errored.
<ide> stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
<ide> function resetChildExpirationTime(completedWork: Fiber) {
<ide> let newChildExpirationTime = NoWork;
<ide>
<ide> // Bubble up the earliest expiration time.
<del> if (enableProfilerTimer && (completedWork.mode & ProfileMode) !== NoContext) {
<add> if (enableProfilerTimer && (completedWork.mode & ProfileMode) !== NoMode) {
<ide> // In profiling mode, resetChildExpirationTime is also used to reset
<ide> // profiler durations.
<ide> let actualDuration = completedWork.actualDuration;
<ide> function commitRootImpl(root, expirationTime) {
<ide> }
<ide>
<ide> // If layout work was scheduled, flush it now.
<del> flushImmediateQueue();
<add> flushSyncCallbackQueue();
<ide> return null;
<ide> }
<ide>
<ide> export function flushPassiveEffects() {
<ide> }
<ide>
<ide> workPhase = prevWorkPhase;
<del> flushImmediateQueue();
<add> flushSyncCallbackQueue();
<ide>
<ide> // If additional passive effects were scheduled, increment a counter. If this
<ide> // exceeds the limit, we'll fire a warning.
<ide><path>packages/react-reconciler/src/ReactFiberUnwindWork.js
<ide> import {
<ide> enableSuspenseServerRenderer,
<ide> enableEventAPI,
<ide> } from 'shared/ReactFeatureFlags';
<del>import {ConcurrentMode, NoContext} from './ReactTypeOfMode';
<add>import {NoMode, BatchedMode} from './ReactTypeOfMode';
<ide> import {shouldCaptureSuspense} from './ReactFiberSuspenseComponent';
<ide>
<ide> import {createCapturedValue} from './ReactCapturedValue';
<ide> function throwException(
<ide> thenables.add(thenable);
<ide> }
<ide>
<del> // If the boundary is outside of concurrent mode, we should *not*
<add> // If the boundary is outside of batched mode, we should *not*
<ide> // suspend the commit. Pretend as if the suspended component rendered
<ide> // null and keep rendering. In the commit phase, we'll schedule a
<ide> // subsequent synchronous update to re-render the Suspense.
<ide> //
<ide> // Note: It doesn't matter whether the component that suspended was
<del> // inside a concurrent mode tree. If the Suspense is outside of it, we
<add> // inside a batched mode tree. If the Suspense is outside of it, we
<ide> // should *not* suspend the commit.
<del> if ((workInProgress.mode & ConcurrentMode) === NoContext) {
<add> if ((workInProgress.mode & BatchedMode) === NoMode) {
<ide> workInProgress.effectTag |= DidCapture;
<ide>
<ide> // We're going to commit this fiber even though it didn't complete.
<ide><path>packages/react-reconciler/src/ReactTypeOfMode.js
<ide>
<ide> export type TypeOfMode = number;
<ide>
<del>export const NoContext = 0b000;
<del>export const ConcurrentMode = 0b001;
<del>export const StrictMode = 0b010;
<del>export const ProfileMode = 0b100;
<add>export const NoMode = 0b0000;
<add>export const StrictMode = 0b0001;
<add>// TODO: Remove BatchedMode and ConcurrentMode by reading from the root
<add>// tag instead
<add>export const BatchedMode = 0b0010;
<add>export const ConcurrentMode = 0b0100;
<add>export const ProfileMode = 0b1000;
<ide><path>packages/react-reconciler/src/SchedulerWithReactIntegration.js
<ide> export const shouldYield = disableYielding
<ide> ? () => false // Never yield when `disableYielding` is on
<ide> : Scheduler_shouldYield;
<ide>
<del>let immediateQueue: Array<SchedulerCallback> | null = null;
<add>let syncQueue: Array<SchedulerCallback> | null = null;
<ide> let immediateQueueCallbackNode: mixed | null = null;
<del>let isFlushingImmediate: boolean = false;
<add>let isFlushingSyncQueue: boolean = false;
<ide> let initialTimeMs: number = Scheduler_now();
<ide>
<ide> // If the initial timestamp is reasonably small, use Scheduler's `now` directly.
<ide> export function scheduleCallback(
<ide> callback: SchedulerCallback,
<ide> options: SchedulerCallbackOptions | void | null,
<ide> ) {
<del> if (reactPriorityLevel === ImmediatePriority) {
<del> // Push this callback into an internal queue. We'll flush these either in
<del> // the next tick, or earlier if something calls `flushImmediateQueue`.
<del> if (immediateQueue === null) {
<del> immediateQueue = [callback];
<del> // Flush the queue in the next tick, at the earliest.
<del> immediateQueueCallbackNode = Scheduler_scheduleCallback(
<del> Scheduler_ImmediatePriority,
<del> flushImmediateQueueImpl,
<del> );
<del> } else {
<del> // Push onto existing queue. Don't need to schedule a callback because
<del> // we already scheduled one when we created the queue.
<del> immediateQueue.push(callback);
<del> }
<del> return fakeCallbackNode;
<del> }
<del> // Otherwise pass through to Scheduler.
<ide> const priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
<ide> return Scheduler_scheduleCallback(priorityLevel, callback, options);
<ide> }
<ide>
<add>export function scheduleSyncCallback(callback: SchedulerCallback) {
<add> // Push this callback into an internal queue. We'll flush these either in
<add> // the next tick, or earlier if something calls `flushSyncCallbackQueue`.
<add> if (syncQueue === null) {
<add> syncQueue = [callback];
<add> // Flush the queue in the next tick, at the earliest.
<add> immediateQueueCallbackNode = Scheduler_scheduleCallback(
<add> Scheduler_ImmediatePriority,
<add> flushSyncCallbackQueueImpl,
<add> );
<add> } else {
<add> // Push onto existing queue. Don't need to schedule a callback because
<add> // we already scheduled one when we created the queue.
<add> syncQueue.push(callback);
<add> }
<add> return fakeCallbackNode;
<add>}
<add>
<ide> export function cancelCallback(callbackNode: mixed) {
<ide> if (callbackNode !== fakeCallbackNode) {
<ide> Scheduler_cancelCallback(callbackNode);
<ide> }
<ide> }
<ide>
<del>export function flushImmediateQueue() {
<add>export function flushSyncCallbackQueue() {
<ide> if (immediateQueueCallbackNode !== null) {
<ide> Scheduler_cancelCallback(immediateQueueCallbackNode);
<ide> }
<del> flushImmediateQueueImpl();
<add> flushSyncCallbackQueueImpl();
<ide> }
<ide>
<del>function flushImmediateQueueImpl() {
<del> if (!isFlushingImmediate && immediateQueue !== null) {
<add>function flushSyncCallbackQueueImpl() {
<add> if (!isFlushingSyncQueue && syncQueue !== null) {
<ide> // Prevent re-entrancy.
<del> isFlushingImmediate = true;
<add> isFlushingSyncQueue = true;
<ide> let i = 0;
<ide> try {
<ide> const isSync = true;
<del> for (; i < immediateQueue.length; i++) {
<del> let callback = immediateQueue[i];
<add> for (; i < syncQueue.length; i++) {
<add> let callback = syncQueue[i];
<ide> do {
<ide> callback = callback(isSync);
<ide> } while (callback !== null);
<ide> }
<del> immediateQueue = null;
<add> syncQueue = null;
<ide> } catch (error) {
<ide> // If something throws, leave the remaining callbacks on the queue.
<del> if (immediateQueue !== null) {
<del> immediateQueue = immediateQueue.slice(i + 1);
<add> if (syncQueue !== null) {
<add> syncQueue = syncQueue.slice(i + 1);
<ide> }
<ide> // Resume flushing in the next tick
<ide> Scheduler_scheduleCallback(
<ide> Scheduler_ImmediatePriority,
<del> flushImmediateQueue,
<add> flushSyncCallbackQueue,
<ide> );
<ide> throw error;
<ide> } finally {
<del> isFlushingImmediate = false;
<add> isFlushingSyncQueue = false;
<ide> }
<ide> }
<ide> }
<ide><path>packages/react-reconciler/src/__tests__/ReactBatchedMode-test.internal.js
<add>let React;
<add>let ReactFeatureFlags;
<add>let ReactNoop;
<add>let act;
<add>let Scheduler;
<add>let ReactCache;
<add>let Suspense;
<add>let TextResource;
<add>
<add>describe('ReactBatchedMode', () => {
<add> beforeEach(() => {
<add> jest.resetModules();
<add> ReactFeatureFlags = require('shared/ReactFeatureFlags');
<add> ReactFeatureFlags.debugRenderPhaseSideEffectsForStrictMode = false;
<add> ReactFeatureFlags.replayFailedUnitOfWorkWithInvokeGuardedCallback = false;
<add> React = require('react');
<add> ReactNoop = require('react-noop-renderer');
<add> act = ReactNoop.act;
<add> Scheduler = require('scheduler');
<add> ReactCache = require('react-cache');
<add> Suspense = React.Suspense;
<add>
<add> TextResource = ReactCache.unstable_createResource(([text, ms = 0]) => {
<add> return new Promise((resolve, reject) =>
<add> setTimeout(() => {
<add> Scheduler.yieldValue(`Promise resolved [${text}]`);
<add> resolve(text);
<add> }, ms),
<add> );
<add> }, ([text, ms]) => text);
<add> });
<add>
<add> function Text(props) {
<add> Scheduler.yieldValue(props.text);
<add> return props.text;
<add> }
<add>
<add> function AsyncText(props) {
<add> const text = props.text;
<add> try {
<add> TextResource.read([props.text, props.ms]);
<add> Scheduler.yieldValue(text);
<add> return props.text;
<add> } catch (promise) {
<add> if (typeof promise.then === 'function') {
<add> Scheduler.yieldValue(`Suspend! [${text}]`);
<add> } else {
<add> Scheduler.yieldValue(`Error! [${text}]`);
<add> }
<add> throw promise;
<add> }
<add> }
<add>
<add> it('updates flush without yielding in the next event', () => {
<add> const root = ReactNoop.createSyncRoot();
<add>
<add> root.render(
<add> <React.Fragment>
<add> <Text text="A" />
<add> <Text text="B" />
<add> <Text text="C" />
<add> </React.Fragment>,
<add> );
<add>
<add> // Nothing should have rendered yet
<add> expect(root).toMatchRenderedOutput(null);
<add>
<add> // Everything should render immediately in the next event
<add> expect(Scheduler).toFlushExpired(['A', 'B', 'C']);
<add> expect(root).toMatchRenderedOutput('ABC');
<add> });
<add>
<add> it('layout updates flush synchronously in same event', () => {
<add> const {useLayoutEffect} = React;
<add>
<add> function App() {
<add> useLayoutEffect(() => {
<add> Scheduler.yieldValue('Layout effect');
<add> });
<add> return <Text text="Hi" />;
<add> }
<add>
<add> const root = ReactNoop.createSyncRoot();
<add> root.render(<App />);
<add> expect(root).toMatchRenderedOutput(null);
<add>
<add> expect(Scheduler).toFlushExpired(['Hi', 'Layout effect']);
<add> expect(root).toMatchRenderedOutput('Hi');
<add> });
<add>
<add> it('uses proper Suspense semantics, not legacy ones', async () => {
<add> const root = ReactNoop.createSyncRoot();
<add> root.render(
<add> <Suspense fallback={<Text text="Loading..." />}>
<add> <span>
<add> <Text text="A" />
<add> </span>
<add> <span>
<add> <AsyncText text="B" />
<add> </span>
<add> <span>
<add> <Text text="C" />
<add> </span>
<add> </Suspense>,
<add> );
<add>
<add> expect(Scheduler).toFlushExpired(['A', 'Suspend! [B]', 'C', 'Loading...']);
<add> // In Legacy Mode, A and B would mount in a hidden primary tree. In Batched
<add> // and Concurrent Mode, nothing in the primary tree should mount. But the
<add> // fallback should mount immediately.
<add> expect(root).toMatchRenderedOutput('Loading...');
<add>
<add> await jest.advanceTimersByTime(1000);
<add> expect(Scheduler).toHaveYielded(['Promise resolved [B]']);
<add> expect(Scheduler).toFlushExpired(['A', 'B', 'C']);
<add> expect(root).toMatchRenderedOutput(
<add> <React.Fragment>
<add> <span>A</span>
<add> <span>B</span>
<add> <span>C</span>
<add> </React.Fragment>,
<add> );
<add> });
<add>
<add> it('flushSync does not flush batched work', () => {
<add> const {useState, forwardRef, useImperativeHandle} = React;
<add> const root = ReactNoop.createSyncRoot();
<add>
<add> const Foo = forwardRef(({label}, ref) => {
<add> const [step, setStep] = useState(0);
<add> useImperativeHandle(ref, () => ({setStep}));
<add> return <Text text={label + step} />;
<add> });
<add>
<add> const foo1 = React.createRef(null);
<add> const foo2 = React.createRef(null);
<add> root.render(
<add> <React.Fragment>
<add> <Foo label="A" ref={foo1} />
<add> <Foo label="B" ref={foo2} />
<add> </React.Fragment>,
<add> );
<add>
<add> // Mount
<add> expect(Scheduler).toFlushExpired(['A0', 'B0']);
<add> expect(root).toMatchRenderedOutput('A0B0');
<add>
<add> // Schedule a batched update to the first sibling
<add> act(() => foo1.current.setStep(1));
<add>
<add> // Before it flushes, update the second sibling inside flushSync
<add> act(() =>
<add> ReactNoop.flushSync(() => {
<add> foo2.current.setStep(1);
<add> }),
<add> );
<add>
<add> // Only the second update should have flushed synchronously
<add> expect(Scheduler).toHaveYielded(['B1']);
<add> expect(root).toMatchRenderedOutput('A0B1');
<add>
<add> // Now flush the first update
<add> expect(Scheduler).toFlushExpired(['A1']);
<add> expect(root).toMatchRenderedOutput('A1B1');
<add> });
<add>});
<add><path>packages/react-reconciler/src/__tests__/ReactFiberHostContext-test.internal.js
<del><path>packages/react-reconciler/src/__tests__/ReactFiberHostContext-test.js
<ide>
<ide> let React;
<ide> let ReactFiberReconciler;
<add>let ConcurrentRoot;
<ide>
<ide> describe('ReactFiberHostContext', () => {
<ide> beforeEach(() => {
<ide> jest.resetModules();
<ide> React = require('react');
<ide> ReactFiberReconciler = require('react-reconciler');
<add> ConcurrentRoot = require('shared/ReactRootTags');
<ide> });
<ide>
<ide> it('works with null host context', () => {
<ide> describe('ReactFiberHostContext', () => {
<ide> supportsMutation: true,
<ide> });
<ide>
<del> const container = Renderer.createContainer(/* root: */ null);
<add> const container = Renderer.createContainer(
<add> /* root: */ null,
<add> ConcurrentRoot,
<add> false,
<add> );
<ide> Renderer.updateContainer(
<ide> <a>
<ide> <b />
<ide> describe('ReactFiberHostContext', () => {
<ide> supportsMutation: true,
<ide> });
<ide>
<del> const container = Renderer.createContainer(rootContext);
<add> const container = Renderer.createContainer(
<add> rootContext,
<add> ConcurrentRoot,
<add> false,
<add> );
<ide> Renderer.updateContainer(
<ide> <a>
<ide> <b />
<ide><path>packages/react-reconciler/src/__tests__/ReactHooksWithNoopRenderer-test.internal.js
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> });
<ide>
<ide> it(
<del> 'in sync mode, useEffect is deferred and updates finish synchronously ' +
<add> 'in legacy mode, useEffect is deferred and updates finish synchronously ' +
<ide> '(in a single batch)',
<ide> () => {
<ide> function Counter(props) {
<ide><path>packages/react-reconciler/src/__tests__/ReactSuspenseFuzz-test.internal.js
<ide> describe('ReactSuspenseFuzz', () => {
<ide> resetCache();
<ide> ReactNoop.renderLegacySyncRoot(children);
<ide> resolveAllTasks();
<del> const syncOutput = ReactNoop.getChildrenAsJSX();
<del> expect(syncOutput).toEqual(expectedOutput);
<add> const legacyOutput = ReactNoop.getChildrenAsJSX();
<add> expect(legacyOutput).toEqual(expectedOutput);
<ide> ReactNoop.renderLegacySyncRoot(null);
<ide>
<ide> resetCache();
<ide><path>packages/react-reconciler/src/__tests__/ReactSuspensePlaceholder-test.internal.js
<ide> describe('ReactSuspensePlaceholder', () => {
<ide> });
<ide>
<ide> describe('when suspending during mount', () => {
<del> it('properly accounts for base durations when a suspended times out in a sync tree', () => {
<add> it('properly accounts for base durations when a suspended times out in a legacy tree', () => {
<ide> ReactNoop.renderLegacySyncRoot(<App shouldSuspend={true} />);
<ide> expect(Scheduler).toHaveYielded([
<ide> 'App',
<ide> describe('ReactSuspensePlaceholder', () => {
<ide> });
<ide>
<ide> describe('when suspending during update', () => {
<del> it('properly accounts for base durations when a suspended times out in a sync tree', () => {
<add> it('properly accounts for base durations when a suspended times out in a legacy tree', () => {
<ide> ReactNoop.renderLegacySyncRoot(
<ide> <App shouldSuspend={false} textRenderDuration={5} />,
<ide> );
<ide><path>packages/react-reconciler/src/__tests__/ReactSuspenseWithNoopRenderer-test.internal.js
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> );
<ide> });
<ide>
<del> describe('sync mode', () => {
<add> describe('legacy mode mode', () => {
<ide> it('times out immediately', async () => {
<ide> function App() {
<ide> return (
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> it(
<ide> 'continues rendering asynchronously even if a promise is captured by ' +
<del> 'a sync boundary (default mode)',
<add> 'a sync boundary (legacy mode)',
<ide> async () => {
<ide> class UpdatingText extends React.Component {
<ide> state = {text: this.props.initialText};
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> it(
<ide> 'continues rendering asynchronously even if a promise is captured by ' +
<del> 'a sync boundary (strict, non-concurrent)',
<add> 'a sync boundary (strict, legacy)',
<ide> async () => {
<ide> class UpdatingText extends React.Component {
<ide> state = {text: this.props.initialText};
<ide><path>packages/react-test-renderer/src/ReactTestRenderer.js
<ide> import ReactVersion from 'shared/ReactVersion';
<ide> import act from './ReactTestRendererAct';
<ide>
<ide> import {getPublicInstance} from './ReactTestHostConfig';
<add>import {ConcurrentRoot, LegacyRoot} from 'shared/ReactRootTags';
<ide>
<ide> type TestRendererOptions = {
<ide> createNodeMock: (element: React$Element<any>) => any,
<ide> const ReactTestRendererFiber = {
<ide> };
<ide> let root: FiberRoot | null = createContainer(
<ide> container,
<del> isConcurrent,
<add> isConcurrent ? ConcurrentRoot : LegacyRoot,
<ide> false,
<ide> );
<ide> invariant(root != null, 'something went wrong');
<ide><path>packages/shared/ReactRootTags.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow
<add> */
<add>
<add>export type RootTag = 0 | 1 | 2;
<add>
<add>export const LegacyRoot = 0;
<add>export const BatchedRoot = 1;
<add>export const ConcurrentRoot = 2; | 24 |
Python | Python | fix deprecation warnings for int div | 531336bbfd2a97cf800f610d971d6ec0a1578752 | <ide><path>examples/pytorch/speech-pretraining/run_wav2vec2_pretraining_no_trainer.py
<ide> def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) ->
<ide> batch_size = batch["input_values"].shape[0]
<ide>
<ide> mask_indices_seq_length = self.model._get_feat_extract_output_lengths(batch["input_values"].shape[-1])
<add> # make sure masked sequence length is a Python scalar
<add> mask_indices_seq_length = int(mask_indices_seq_length)
<ide>
<ide> # make sure that no loss is computed on padded inputs
<ide> if batch.get("attention_mask") is not None:
<ide><path>src/transformers/modeling_utils.py
<ide> from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
<ide>
<ide> import torch
<add>from packaging import version
<ide> from torch import Tensor, device, nn
<ide> from torch.nn import CrossEntropyLoss
<ide>
<ide> def forward(self, hidden_states):
<ide> return torch.cat(output_chunks, dim=chunk_dim)
<ide>
<ide> return forward_fn(*input_tensors)
<add>
<add>
<add>def torch_int_div(tensor1, tensor2):
<add> """
<add> A function that performs integer division across different versions of PyTorch.
<add> """
<add> if version.parse(torch.__version__) < version.parse("1.8.0"):
<add> return tensor1 // tensor2
<add> else:
<add> return torch.div(tensor1, tensor2, rounding_mode="floor")
<ide><path>src/transformers/models/hubert/modeling_hubert.py
<ide> replace_return_docstrings,
<ide> )
<ide> from ...modeling_outputs import BaseModelOutput, CausalLMOutput, SequenceClassifierOutput
<del>from ...modeling_utils import PreTrainedModel
<add>from ...modeling_utils import PreTrainedModel, torch_int_div
<ide> from ...utils import logging
<ide> from .configuration_hubert import HubertConfig
<ide>
<ide> def _get_feat_extract_output_lengths(self, input_lengths: Union[torch.LongTensor
<ide> def _conv_out_length(input_length, kernel_size, stride):
<ide> # 1D convolutional layer output length formula taken
<ide> # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
<del> return (input_length - kernel_size) // stride + 1
<add> return torch_int_div(input_length - kernel_size, stride) + 1
<ide>
<ide> for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
<ide> input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
<ide><path>src/transformers/models/sew/modeling_sew.py
<ide> from ...activations import ACT2FN
<ide> from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
<ide> from ...modeling_outputs import BaseModelOutput, CausalLMOutput, SequenceClassifierOutput
<del>from ...modeling_utils import PreTrainedModel
<add>from ...modeling_utils import PreTrainedModel, torch_int_div
<ide> from ...utils import logging
<ide> from .configuration_sew import SEWConfig
<ide>
<ide> def _get_feat_extract_output_lengths(self, input_lengths: Union[torch.LongTensor
<ide> def _conv_out_length(input_length, kernel_size, stride):
<ide> # 1D convolutional layer output length formula taken
<ide> # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
<del> return (input_length - kernel_size) // stride + 1
<add> return torch_int_div(input_length - kernel_size, stride) + 1
<ide>
<ide> for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
<ide> input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
<ide><path>src/transformers/models/sew_d/modeling_sew_d.py
<ide> from ...activations import ACT2FN
<ide> from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
<ide> from ...modeling_outputs import BaseModelOutput, CausalLMOutput, SequenceClassifierOutput
<del>from ...modeling_utils import PreTrainedModel
<add>from ...modeling_utils import PreTrainedModel, torch_int_div
<ide> from ...utils import logging
<ide> from .configuration_sew_d import SEWDConfig
<ide>
<ide> def _get_feat_extract_output_lengths(self, input_lengths: Union[torch.LongTensor
<ide> def _conv_out_length(input_length, kernel_size, stride):
<ide> # 1D convolutional layer output length formula taken
<ide> # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
<del> return (input_length - kernel_size) // stride + 1
<add> return torch_int_div(input_length - kernel_size, stride) + 1
<ide>
<ide> for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
<ide> input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
<ide><path>src/transformers/models/unispeech/modeling_unispeech.py
<ide> replace_return_docstrings,
<ide> )
<ide> from ...modeling_outputs import BaseModelOutput, CausalLMOutput, SequenceClassifierOutput
<del>from ...modeling_utils import PreTrainedModel
<add>from ...modeling_utils import PreTrainedModel, torch_int_div
<ide> from ...utils import logging
<ide> from .configuration_unispeech import UniSpeechConfig
<ide>
<ide> def _get_feat_extract_output_lengths(self, input_lengths: Union[torch.LongTensor
<ide> def _conv_out_length(input_length, kernel_size, stride):
<ide> # 1D convolutional layer output length formula taken
<ide> # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
<del> return (input_length - kernel_size) // stride + 1
<add> return torch_int_div(input_length - kernel_size, stride) + 1
<ide>
<ide> for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
<ide> input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
<ide><path>src/transformers/models/unispeech_sat/modeling_unispeech_sat.py
<ide> replace_return_docstrings,
<ide> )
<ide> from ...modeling_outputs import BaseModelOutput, CausalLMOutput, SequenceClassifierOutput, TokenClassifierOutput
<del>from ...modeling_utils import PreTrainedModel
<add>from ...modeling_utils import PreTrainedModel, torch_int_div
<ide> from ...utils import logging
<ide> from .configuration_unispeech_sat import UniSpeechSatConfig
<ide>
<ide> def _get_feat_extract_output_lengths(self, input_lengths: Union[torch.LongTensor
<ide> def _conv_out_length(input_length, kernel_size, stride):
<ide> # 1D convolutional layer output length formula taken
<ide> # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
<del> return (input_length - kernel_size) // stride + 1
<add> return torch_int_div(input_length - kernel_size, stride) + 1
<ide>
<ide> for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
<ide> input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
<ide><path>src/transformers/models/wav2vec2/modeling_wav2vec2.py
<ide> SequenceClassifierOutput,
<ide> TokenClassifierOutput,
<ide> )
<del>from ...modeling_utils import PreTrainedModel
<add>from ...modeling_utils import PreTrainedModel, torch_int_div
<ide> from ...utils import logging
<ide> from .configuration_wav2vec2 import Wav2Vec2Config
<ide>
<ide> def _get_feat_extract_output_lengths(
<ide> def _conv_out_length(input_length, kernel_size, stride):
<ide> # 1D convolutional layer output length formula taken
<ide> # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
<del> return (input_length - kernel_size) // stride + 1
<add> return torch_int_div(input_length - kernel_size, stride) + 1
<ide>
<ide> for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
<ide> input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
<ide><path>src/transformers/models/wavlm/modeling_wavlm.py
<ide> add_start_docstrings_to_model_forward,
<ide> )
<ide> from ...modeling_outputs import BaseModelOutput, CausalLMOutput, SequenceClassifierOutput, TokenClassifierOutput
<del>from ...modeling_utils import PreTrainedModel
<add>from ...modeling_utils import PreTrainedModel, torch_int_div
<ide> from ...utils import logging
<ide> from .configuration_wavlm import WavLMConfig
<ide>
<ide> def _get_feat_extract_output_lengths(
<ide> def _conv_out_length(input_length, kernel_size, stride):
<ide> # 1D convolutional layer output length formula taken
<ide> # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
<del> return (input_length - kernel_size) // stride + 1
<add> return torch_int_div(input_length - kernel_size, stride) + 1
<ide>
<ide> for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
<ide> input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
<ide><path>tests/test_modeling_wav2vec2.py
<ide> def test_model_for_pretraining(self):
<ide> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<ide> model = Wav2Vec2ForPreTraining(config).to(torch_device)
<ide>
<del> features_shape = (
<del> inputs_dict["input_values"].shape[0],
<del> model._get_feat_extract_output_lengths(inputs_dict["input_values"].shape[1]),
<del> )
<add> batch_size = inputs_dict["input_values"].shape[0]
<add> feature_seq_length = int(model._get_feat_extract_output_lengths(inputs_dict["input_values"].shape[1]))
<add>
<add> features_shape = (batch_size, feature_seq_length)
<ide>
<ide> mask_time_indices = _compute_mask_indices(
<ide> features_shape,
<ide> def test_inference_integration(self):
<ide>
<ide> inputs_dict = feature_extractor(input_speech, return_tensors="pt", padding=True)
<ide>
<del> features_shape = (
<del> inputs_dict["input_values"].shape[0],
<del> model._get_feat_extract_output_lengths(torch.tensor(inputs_dict["input_values"].shape[1])),
<del> )
<add> batch_size = inputs_dict["input_values"].shape[0]
<add> feature_seq_length = int(model._get_feat_extract_output_lengths(inputs_dict["input_values"].shape[1]))
<add>
<add> features_shape = (batch_size, feature_seq_length)
<ide>
<ide> np.random.seed(4)
<ide> mask_time_indices = _compute_mask_indices(
<ide> def test_inference_pretrained(self):
<ide>
<ide> inputs_dict = feature_extractor(input_speech, return_tensors="pt", padding=True)
<ide>
<del> features_shape = (
<del> inputs_dict["input_values"].shape[0],
<del> model._get_feat_extract_output_lengths(torch.tensor(inputs_dict["input_values"].shape[1])),
<del> )
<add> batch_size = inputs_dict["input_values"].shape[0]
<add> feature_seq_length = int(model._get_feat_extract_output_lengths(inputs_dict["input_values"].shape[1]))
<add>
<add> features_shape = (batch_size, feature_seq_length)
<ide>
<ide> torch.manual_seed(0)
<ide> mask_time_indices = _compute_mask_indices(
<ide> def test_loss_pretraining(self):
<ide>
<ide> inputs_dict = feature_extractor(input_speech, return_tensors="pt", padding=True)
<ide>
<del> features_shape = (
<del> inputs_dict["input_values"].shape[0],
<del> model._get_feat_extract_output_lengths(inputs_dict["input_values"].shape[1]),
<del> )
<add> batch_size = inputs_dict["input_values"].shape[0]
<add> feature_seq_length = int(model._get_feat_extract_output_lengths(inputs_dict["input_values"].shape[1]))
<add>
<add> features_shape = (batch_size, feature_seq_length)
<ide>
<ide> torch.manual_seed(0)
<ide> np.random.seed(0) | 10 |
Ruby | Ruby | allow skip_clean? to skip entire directories | 6661f78618a640ac9570f2003df5c359d1027579 | <ide><path>Library/Homebrew/brew.h.rb
<ide> def clean_file path
<ide>
<ide> def clean_dir d
<ide> d.find do |path|
<del> if not path.file?
<add> if path.directory?
<add> Find.prune if @f.skip_clean? path
<add> elsif not path.file?
<ide> next
<ide> elsif path.extname == '.la' and not @f.skip_clean? path
<ide> # *.la files are stupid | 1 |
Javascript | Javascript | add webgl constants for some technique.states | 756df409752902dd860790bcebb25d6f6cdc8c09 | <ide><path>examples/js/loaders/GLTFLoader.js
<ide> THREE.GLTFLoader = ( function () {
<ide> 10497: THREE.RepeatWrapping
<ide> };
<ide>
<add> var WEBGL_SIDES = {
<add> 1028: THREE.BackSide, // Culling front
<add> 1029: THREE.FrontSide // Culling back
<add> //1032: THREE.NoSide // Culling front and back, what to do?
<add> };
<add>
<add> var WEBGL_DEPTH_FUNCS = {
<add> 512: THREE.NeverDepth,
<add> 513: THREE.LessDepth,
<add> 514: THREE.EqualDepth,
<add> 515: THREE.LessEqualDepth,
<add> 516: THREE.GreaterEqualDepth,
<add> 517: THREE.NotEqualDepth,
<add> 518: THREE.GreaterEqualDepth,
<add> 519: THREE.AlwaysDepth
<add> };
<add>
<add> var WEBGL_BLEND_EQUATIONS = {
<add> 32774: THREE.AddEquation,
<add> 32778: THREE.SubtractEquation,
<add> 32779: THREE.ReverseSubtractEquation
<add> };
<add>
<add> var WEBGL_BLEND_FUNCS = {
<add> 0: THREE.ZeroFactor,
<add> 1: THREE.OneFactor,
<add> 768: THREE.SrcColorFactor,
<add> 769: THREE.OneMinusSrcColorFactor,
<add> 770: THREE.SrcAlphaFactor,
<add> 771: THREE.OneMinusSrcAlphaFactor,
<add> 772: THREE.DstAlphaFactor,
<add> 773: THREE.OneMinusDstAlphaFactor,
<add> 774: THREE.DstColorFactor,
<add> 775: THREE.OneMinusDstColorFactor,
<add> 776: THREE.SrcAlphaSaturateFactor
<add> // The followings are not supported by Three.js yet
<add> //32769: CONSTANT_COLOR,
<add> //32770: ONE_MINUS_CONSTANT_COLOR,
<add> //32771: CONSTANT_ALPHA,
<add> //32772: ONE_MINUS_CONSTANT_COLOR
<add> };
<add>
<ide> var WEBGL_TYPE_SIZES = {
<ide> 'SCALAR': 1,
<ide> 'VEC2': 2,
<ide> THREE.GLTFLoader = ( function () {
<ide> STEP: THREE.InterpolateDiscrete
<ide> };
<ide>
<add> var STATES_ENABLES = {
<add> 2884: 'CULL_FACE',
<add> 2929: 'DEPTH_TEST',
<add> 3042: 'BLEND',
<add> 3089: 'SCISSOR_TEST',
<add> 32823: 'POLYGON_OFFSET_FILL',
<add> 32926: 'SAMPLE_ALPHA_TO_COVERAGE'
<add> };
<add>
<ide> /* UTILITY FUNCTIONS */
<ide>
<ide> function _each( object, callback, thisObj ) { | 1 |
Text | Text | update v8 debugger doc to mention --inspect-brk | ec4440aa10383900b023a20582df00df62e74fe7 | <ide><path>doc/api/debugger.md
<ide> V8 Inspector can be enabled by passing the `--inspect` flag when starting a
<ide> Node.js application. It is also possible to supply a custom port with that flag,
<ide> e.g. `--inspect=9222` will accept DevTools connections on port 9222.
<ide>
<del>To break on the first line of the application code, provide the `--debug-brk`
<del>flag in addition to `--inspect`.
<add>To break on the first line of the application code, pass the `--inspect-brk`
<add>flag instead of `--inspect`.
<ide>
<ide> ```txt
<ide> $ node --inspect index.js | 1 |
Javascript | Javascript | add touch support to `d3.svg.mouse` | 5f2e430f25076dd222b1e88bde0ffef857cd80bb | <ide><path>d3.js
<ide> d3.svg.mouse = function(container) {
<ide> d3_mouse_bug44083 = !(ctm.f || ctm.e);
<ide> svg.remove();
<ide> }
<del> if (d3_mouse_bug44083) {
<add> if (d3.event.touches && d3.event.touches.length > 0) {
<add> point.x = d3.event.touches[0].pageX;
<add> point.y = d3.event.touches[0].pageY;
<add> } else if (d3_mouse_bug44083) {
<ide> point.x = d3.event.pageX;
<ide> point.y = d3.event.pageY;
<ide> } else {
<ide><path>d3.min.js
<ide> (function(){function ca(){return"circle"}function b_(){return 64}function bZ(a){return[a.x,a.y]}function bY(a){return a.endAngle}function bX(a){return a.startAngle}function bW(a){return a.radius}function bV(a){return a.target}function bU(a){return a.source}function bT(){return 0}function bS(a){return a.length<3?bz(a):a[0]+bF(a,bR(a))}function bR(a){var b=[],c,d,e,f,g=bQ(a),h=-1,i=a.length-1;while(++h<i)c=bP(a[h],a[h+1]),Math.abs(c)<1e-6?g[h]=g[h+1]=0:(d=g[h]/c,e=g[h+1]/c,f=d*d+e*e,f>9&&(f=c*3/Math.sqrt(f),g[h]=f*d,g[h+1]=f*e));h=-1;while(++h<=i)f=(a[Math.min(i,h+1)][0]-a[Math.max(0,h-1)][0])/(6*(1+g[h]*g[h])),b.push([f||0,g[h]*f||0]);return b}function bQ(a){var b=0,c=a.length-1,d=[],e=a[0],f=a[1],g=d[0]=bP(e,f);while(++b<c)d[b]=g+(g=bP(e=f,f=a[b+1]));d[b]=g;return d}function bP(a,b){return(b[1]-a[1])/(b[0]-a[0])}function bO(a,b,c){a.push("C",bK(bL,b),",",bK(bL,c),",",bK(bM,b),",",bK(bM,c),",",bK(bN,b),",",bK(bN,c))}function bK(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}function bJ(a){var b,c=-1,d=a.length,e=d+4,f,g=[],h=[];while(++c<4)f=a[c%d],g.push(f[0]),h.push(f[1]);b=[bK(bN,g),",",bK(bN,h)],--c;while(++c<e)f=a[c%d],g.shift(),g.push(f[0]),h.shift(),h.push(f[1]),bO(b,g,h);return b.join("")}function bI(a){if(a.length<4)return bz(a);var b=[],c=-1,d=a.length,e,f=[0],g=[0];while(++c<3)e=a[c],f.push(e[0]),g.push(e[1]);b.push(bK(bN,f)+","+bK(bN,g)),--c;while(++c<d)e=a[c],f.shift(),f.push(e[0]),g.shift(),g.push(e[1]),bO(b,f,g);return b.join("")}function bH(a){if(a.length<3)return bz(a);var b=[],c=1,d=a.length,e=a[0],f=e[0],g=e[1],h=[f,f,f,(e=a[1])[0]],i=[g,g,g,e[1]];b.push(f,",",g),bO(b,h,i);while(++c<d)e=a[c],h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),bO(b,h,i);c=-1;while(++c<2)h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),bO(b,h,i);return b.join("")}function bG(a,b){var c=[],d=(1-b)/2,e,f=a[0],g=a[1],h=1,i=a.length;while(++h<i)e=f,f=g,g=a[h],c.push([d*(g[0]-e[0]),d*(g[1]-e[1])]);return c}function bF(a,b){if(b.length<1||a.length!=b.length&&a.length!=b.length+2)return bz(a);var c=a.length!=b.length,d="",e=a[0],f=a[1],g=b[0],h=g,i=1;c&&(d+="Q"+(f[0]-g[0]*2/3)+","+(f[1]-g[1]*2/3)+","+f[0]+","+f[1],e=a[1],i=2);if(b.length>1){h=b[1],f=a[i],i++,d+="C"+(e[0]+g[0])+","+(e[1]+g[1])+","+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1];for(var j=2;j<b.length;j++,i++)f=a[i],h=b[j],d+="S"+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1]}if(c){var k=a[i];d+="Q"+(f[0]+h[0]*2/3)+","+(f[1]+h[1]*2/3)+","+k[0]+","+k[1]}return d}function bE(a,b,c){return a.length<3?bz(a):a[0]+bF(a,bG(a,b))}function bD(a,b){return a.length<3?bz(a):a[0]+bF((a.push(a[0]),a),bG([a[a.length-2]].concat(a,[a[1]]),b))}function bC(a,b){return a.length<4?bz(a):a[1]+bF(a.slice(1,a.length-1),bG(a,b))}function bB(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("H",(e=a[c])[0],"V",e[1]);return b.join("")}function bA(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("V",(e=a[c])[1],"H",e[0]);return b.join("")}function bz(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("L",(e=a[c])[0],",",e[1]);return b.join("")}function bx(a){return a[1]}function bw(a){return a[0]}function bv(a,b,c,d){var e=[],f=-1,g=b.length,h=typeof c=="function",i=typeof d=="function",j;if(h&&i)while(++f<g)e.push([c.call(a,j=b[f],f),d.call(a,j,f)]);else if(h)while(++f<g)e.push([c.call(a,b[f],f),d]);else if(i)while(++f<g)e.push([c,d.call(a,b[f],f)]);else while(++f<g)e.push([c,d]);return e}function bu(a){return a.endAngle}function bt(a){return a.startAngle}function bs(a){return a.outerRadius}function br(a){return a.innerRadius}function bk(a){return function(b){return-Math.pow(-b,a)}}function bj(a){return function(b){return Math.pow(b,a)}}function bi(a){return-Math.log(-a)/Math.LN10}function bh(a){return Math.log(a)/Math.LN10}function bg(a,b,c,d){function i(b){var c=1,d=a.length-2;while(c<=d){var e=c+d>>1,f=a[e];if(f<b)c=e+1;else if(f>b)d=e-1;else return e}return c-1}var e=[],f=[],g=0,h=a.length;while(++g<h)e.push(c(a[g-1],a[g])),f.push(d(b[g-1],b[g]));return function(a){var b=i(a);return f[b](e[b](a))}}function bf(a,b,c,d){var e=c(a[0],a[1]),f=d(b[0],b[1]);return function(a){return f(e(a))}}function bd(){var a=null,b=$,c=Infinity;while(b)b.flush?b=a?a.next=b.next:$=b.next:(c=Math.min(c,b.then+b.delay),b=(a=b).next);return c}function bc(){var a,b=Date.now(),c=$;while(c)a=b-c.then,a>c.delay&&(c.flush=c.callback(a)),c=c.next;var d=bd()-b;d>24?(isFinite(d)&&(clearTimeout(ba),ba=setTimeout(bc,d)),_=0):(_=1,be(bc))}function bb(a,b){var c=Date.now(),d=!1,e,f=$;if(!!isFinite(b)){while(f){if(f.callback===a){f.then=c,f.delay=b,d=!0;break}e=f,f=f.next}d||($={callback:a,then:c,delay:b,next:$}),_||(ba=clearTimeout(ba),_=1,be(bc))}}function Z(a){return typeof a=="function"?function(b,c,d){return d3.interpolate(d,String(a.call(this,b,c)))}:(a=String(a),function(b,c,d){return d3.interpolate(d,a)})}function Y(a){function n(b){var g=!0,l=-1;a.each(function(){if(i[++l]!==2){var a=(b-j[l])/k[l],n=this.__transition__,o,p,q=e[l];if(a<1){g=!1;if(a<0)return}else a=1;if(i[l]){if(!n||n.active!==c){i[l]=2;return}}else{if(!n||n.active>c){i[l]=2;return}i[l]=1,h.start.dispatch.apply(this,arguments),q=e[l]={},n.active=c;for(p in d)if(o=d[p].apply(this,arguments))q[p]=o}o=m(a);for(p in q)q[p].call(this,o);if(a===1){i[l]=2;if(n.active===c){var r=n.owner;r===c&&(delete this.__transition__,f&&this.parentNode.removeChild(this)),X=c,h.end.dispatch.apply(this,arguments),X=0,n.owner=r}}}});return g}var b={},c=X||++W,d={},e=[],f=!1,h=d3.dispatch("start","end"),i=[],j=[],k=[],l,m=d3.ease("cubic-in-out");a.each(function(){(this.__transition__||(this.__transition__={})).owner=c}),b.delay=function(c){var d=Infinity,e=-1;typeof c=="function"?a.each(function(a,b){var f=j[++e]=+c.apply(this,arguments);f<d&&(d=f)}):(d=+c,a.each(function(a,b){j[++e]=d})),bb(n,d);return b},b.duration=function(c){var d=-1;typeof c=="function"?(l=0,a.each(function(a,b){var e=k[++d]=+c.apply(this,arguments);e>l&&(l=e)})):(l=+c,a.each(function(a,b){k[++d]=l}));return b},b.ease=function(a){m=typeof a=="function"?a:d3.ease.apply(d3,arguments);return b},b.attrTween=function(a,c){function f(b,d){var e=c.call(this,b,d,this.getAttributeNS(a.space,a.local));return function(b){this.setAttributeNS(a.space,a.local,e(b))}}function e(b,d){var e=c.call(this,b,d,this.getAttribute(a));return function(b){this.setAttribute(a,e(b))}}d["attr."+a]=a.local?f:e;return b},b.attr=function(a,c){return b.attrTween(a,Z(c))},b.styleTween=function(a,c,e){function f(b,d){var f=c.call(this,b,d,window.getComputedStyle(this,null).getPropertyValue(a));return function(b){this.style.setProperty(a,f(b),e)}}arguments.length<3&&(e=null),d["style."+a]=f;return b},b.style=function(a,c,d){arguments.length<3&&(d=null);return b.styleTween(a,Z(c),d)},b.text=function(a){d.text=function(b,c){this.textContent=typeof a=="function"?a.call(this,b,c):a};return b},b.select=function(b){var c,d=Y(a.select(b)).ease(m);c=-1,d.delay(function(a,b){return j[++c]}),c=-1,d.duration(function(a,b){return k[++c]});return d},b.selectAll=function(b){var c,d=Y(a.selectAll(b)).ease(m);c=-1,d.delay(function(a,b){return j[b?c:++c]}),c=-1,d.duration(function(a,b){return k[b?c:++c]});return d},b.remove=function(){f=!0;return b},b.each=function(a,c){h[a].add(c);return b},b.call=g;return b.delay(0).duration(250)}function V(a){return{__data__:a}}function U(a){arguments.length||(a=d3.ascending);return function(b,c){return a(b&&b.__data__,c&&c.__data__)}}function T(a){function b(b){var c=[],d,e,f,g;for(var h=0,i=a.length;h<i;h++){f=a[h],c.push(d=[]),d.parentNode=f.parentNode;for(var j=0,k=f.length;j<k;j++)(g=f[j])?(d.push(e=b(f.parentNode)),e.__data__=g.__data__):d.push(null)}return S(c)}a.append=function(a){function d(b){return b.appendChild(document.createElementNS(a.space,a.local))}function c(b){return b.appendChild(document.createElement(a))}a=d3.ns.qualify(a);return b(a.local?d:c)},a.insert=function(a,c){function e(b){return b.insertBefore(document.createElementNS(a.space,a.local),P(c,b))}function d(b){return b.insertBefore(document.createElement(a),P(c,b))}a=d3.ns.qualify(a);return b(a.local?e:d)};return a}function S(a){function d(b){for(var c=0,d=a.length;c<d;c++){var e=a[c];for(var f=0,g=e.length;f<g;f++){var h=e[f];if(h)return b.call(h,h.__data__,f)}}return null}function c(b){var c=[],d,e,f;for(var g=0,h=a.length;g<h;g++){e=a[g];for(var i=0,j=e.length;i<j;i++)if(f=e[i])c.push(d=b(f)),d.parentNode=f}return S(c)}function b(b){var c=[],d,e,f,g;for(var h=0,i=a.length;h<i;h++){f=a[h],c.push(d=[]),d.parentNode=f.parentNode;for(var j=0,k=f.length;j<k;j++)(g=f[j])?(d.push(e=b(g)),e&&"__data__"in g&&(e.__data__=g.__data__)):d.push(null)}return S(c)}a.select=function(a){return b(function(b){return P(a,b)})},a.selectAll=function(a){return c(function(b){return Q(a,b)})},a.filter=function(b){var c=[],d,e,f;for(var g=0,h=a.length;g<h;g++){e=a[g],c.push(d=[]),d.parentNode=e.parentNode;for(var i=0,j=e.length;i<j;i++)(f=e[i])&&b.call(f,f.__data__,i)&&d.push(f)}return S(c)},a.map=function(b){var c,d;for(var e=0,f=a.length;e<f;e++){c=a[e];for(var g=0,h=c.length;g<h;g++)if(d=c[g])d.__data__=b.call(d,d.__data__,g)}return a},a.data=function(b,c){function g(a,b){var g=0,h=a.length,i=b.length,j=Math.min(h,i),k=Math.max(h,i),l=[],m=[],n=[],o,p;if(c){var q={},r=[],s,t=b.length;for(g=0;g<h;g++)s=c.call(o=a[g],o.__data__,g),s in q?n[t++]=a[g]:q[s]=o,r.push(s);for(g=0;g<i;g++)o=q[s=c.call(b,p=b[g],g)],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=V(p),l[g]=n[g]=null),delete q[s];for(g=0;g<h;g++)r[g]in q&&(n[g]=a[g])}else{for(;g<j;g++)o=a[g],p=b[g],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=V(p),l[g]=n[g]=null);for(;g<i;g++)m[g]=V(b[g]),l[g]=n[g]=null;for(;g<k;g++)n[g]=a[g],m[g]=l[g]=null}m.parentNode=l.parentNode=n.parentNode=a.parentNode,d.push(m),e.push(l),f.push(n)}var d=[],e=[],f=[],h=-1,i=a.length,j;if(typeof b=="function")while(++h<i)g(j=a[h],b.call(j,j.parentNode.__data__,h));else while(++h<i)g(j=a[h],b);var k=S(e);k.enter=function(){return T(d)},k.exit=function(){return S(f)};return k},a.each=function(b){for(var c=0,d=a.length;c<d;c++){var e=a[c];for(var f=0,g=e.length;f<g;f++){var h=e[f];h&&b.call(h,h.__data__,f)}}return a},a.empty=function(){return!d(function(){return!0})},a.node=function(){return d(function(){return this})},a.attr=function(b,c){function j(){var a=c.apply(this,arguments);a==null?this.removeAttributeNS(b.space,b.local):this.setAttributeNS(b.space,b.local,a)}function i(){var a=c.apply(this,arguments);a==null?this.removeAttribute(b):this.setAttribute(b,a)}function h(){this.setAttributeNS(b.space,b.local,c)}function g(){this.setAttribute(b,c)}function f(){this.removeAttributeNS(b.space,b.local)}function e(){this.removeAttribute(b)}b=d3.ns.qualify(b);if(arguments.length<2)return d(b.local?function(){return this.getAttributeNS(b.space,b.local)}:function(){return this.getAttribute(b)});return a.each(c==null?b.local?f:e:typeof c=="function"?b.local?j:i:b.local?h:g)},a.classed=function(b,c){function i(){(c.apply(this,arguments)?g:h).call(this)}function h(){if(a=this.classList)return a.remove(b);var a=this.className,c=a.baseVal!=null,d=c?a.baseVal:a;d=f(d.replace(e," ")),c?a.baseVal=d:this.className=d}function g(){if(a=this.classList)return a.add(b);var a=this.className,c=a.baseVal!=null,d=c?a.baseVal:a;e.lastIndex=0,e.test(d)||(d=f(d+" "+b),c?a.baseVal=d:this.className=d)}var e=new RegExp("(^|\\s+)"+d3.requote(b)+"(\\s+|$)","g");if(arguments.length<2)return d(function(){if(a=this.classList)return a.contains(b);var a=this.className;e.lastIndex=0;return e.test(a.baseVal!=null?a.baseVal:a)});return a.each(typeof c=="function"?i:c?g:h)},a.style=function(b,c,e){function h(){var a=c.apply(this,arguments);a==null?this.style.removeProperty(b):this.style.setProperty(b,a,e)}function g(){this.style.setProperty(b,c,e)}function f(){this.style.removeProperty(b)}arguments.length<3&&(e="");if(arguments.length<2)return d(function(){return window.getComputedStyle(this,null).getPropertyValue(b)});return a.each(c==null?f:typeof c=="function"?h:g)},a.property=function(b,c){function g(){var a=c.apply(this,arguments);a==null?delete this[b]:this[b]=a}function f(){this[b]=c}function e(){delete this[b]}b=d3.ns.qualify(b);if(arguments.length<2)return d(function(){return this[b]});return a.each(c==null?e:typeof c=="function"?g:f)},a.text=function(b){function e(){this.textContent=b.apply(this,arguments)}function c(){this.textContent=b}if(arguments.length<1)return d(function(){return this.textContent});return a.each(typeof b=="function"?e:c)},a.html=function(b){function e(){this.innerHTML=b.apply(this,arguments)}function c(){this.innerHTML=b}if(arguments.length<1)return d(function(){return this.innerHTML});return a.each(typeof b=="function"?e:c)},a.append=function(a){function d(b){return b.appendChild(document.createElementNS(a.space,a.local))}function c(b){return b.appendChild(document.createElement(a))}a=d3.ns.qualify(a);return b(a.local?d:c)},a.insert=function(a,c){function e(b){return b.insertBefore(document.createElementNS(a.space,a.local),P(c,b))}function d(b){return b.insertBefore(document.createElement(a),P(c,b))}a=d3.ns.qualify(a);return b(a.local?e:d)},a.remove=function(){return a.each(function(){var a=this.parentNode;a&&a.removeChild(this)})},a.sort=function(b){b=U.apply(this,arguments);for(var c=0,d=a.length;c<d;c++){var e=a[c];e.sort(b);for(var f=1,g=e.length,h=e[0];f<g;f++){var i=e[f];i&&(h&&h.parentNode.insertBefore(i,h.nextSibling),h=i)}}return a},a.on=function(b,c,d){arguments.length<3&&(d=!1);var e=b.indexOf("."),f=e===-1?b:b.substring(0,e),g="__on"+b;return a.each(function(a,b){function h(a){var d=d3.event;d3.event=a;try{c.call(this,e.__data__,b)}finally{d3.event=d}}this[g]&&this.removeEventListener(f,this[g],d),c&&this.addEventListener(f,this[g]=h,d);var e=this})},a.transition=function(){return Y(a)},a.call=g;return a}function O(a,b,c){function g(a){return Math.round(f(a)*255)}function f(a){a>360?a-=360:a<0&&(a+=360);if(a<60)return d+(e-d)*a/60;if(a<180)return e;if(a<240)return d+(e-d)*(240-a)/60;return d}var d,e;a=a%360,a<0&&(a+=360),b=b<0?0:b>1?1:b,c=c<0?0:c>1?1:c,e=c<=.5?c*(1+b):c+b-c*b,d=2*c-e;return E(g(a+120),g(a),g(a-120))}function N(a,b,c){this.h=a,this.s=b,this.l=c}function M(a,b,c){return new N(a,b,c)}function J(a){var b=parseFloat(a);return a.charAt(a.length-1)==="%"?Math.round(b*2.55):b}function I(a,b,c){var d=Math.min(a/=255,b/=255,c/=255),e=Math.max(a,b,c),f=e-d,g,h,i=(e+d)/2;f?(h=i<.5?f/(e+d):f/(2-e-d),a==e?g=(b-c)/f+(b<c?6:0):b==e?g=(c-a)/f+2:g=(a-b)/f+4,g*=60):h=g=0;return M(g,h,i)}function H(a,b,c){var d=0,e=0,f=0,g,h,i;g=/([a-z]+)\((.*)\)/i.exec(a);if(g){h=g[2].split(",");switch(g[1]){case"hsl":return c(parseFloat(h[0]),parseFloat(h[1])/100,parseFloat(h[2])/100);case"rgb":return b(J(h[0]),J(h[1]),J(h[2]))}}if(i=K[a])return b(i.r,i.g,i.b);a!=null&&a.charAt(0)==="#"&&(a.length===4?(d=a.charAt(1),d+=d,e=a.charAt(2),e+=e,f=a.charAt(3),f+=f):a.length===7&&(d=a.substring(1,3),e=a.substring(3,5),f=a.substring(5,7)),d=parseInt(d,16),e=parseInt(e,16),f=parseInt(f,16));return b(d,e,f)}function G(a){return a<16?"0"+a.toString(16):a.toString(16)}function F(a,b,c){this.r=a,this.g=b,this.b=c}function E(a,b,c){return new F(a,b,c)}function D(a,b){b=1/(b-(a=+a));return function(c){return Math.max(0,Math.min(1,(c-a)*b))}}function C(a,b){b=1/(b-(a=+a));return function(c){return(c-a)*b}}function B(a){return a in A||/\bcolor\b/.test(a)?d3.interpolateRgb:d3.interpolate}function y(a){return a<1/2.75?7.5625*a*a:a<2/2.75?7.5625*(a-=1.5/2.75)*a+.75:a<2.5/2.75?7.5625*(a-=2.25/2.75)*a+.9375:7.5625*(a-=2.625/2.75)*a+.984375}function x(a){a||(a=1.70158);return function(b){return b*b*((a+1)*b-a)}}function w(a,b){var c;arguments.length<2&&(b=.45),arguments.length<1?(a=1,c=b/4):c=b/(2*Math.PI)*Math.asin(1/a);return function(d){return 1+a*Math.pow(2,10*-d)*Math.sin((d-c)*2*Math.PI/b)}}function v(a){return 1-Math.sqrt(1-a*a)}function u(a){return a?Math.pow(2,10*(a-1))-.001:0}function t(a){return 1-Math.cos(a*Math.PI/2)}function s(a){return function(b){return Math.pow(b,a)}}function r(a){return a}function q(a){return function(b){return.5*(b<.5?a(2*b):2-a(2-2*b))}}function p(a){return function(b){return 1-a(1-b)}}function k(a){var b=a.lastIndexOf("."),c=b>=0?a.substring(b):(b=a.length,""),d=[];while(b>0)d.push(a.substring(b-=3,b+3));return d.reverse().join(",")+c}function i(a){var b={},c=[];b.add=function(a){for(var d=0;d<c.length;d++)if(c[d].listener==a)return b;c.push({listener:a,on:!0});return b},b.remove=function(a){for(var d=0;d<c.length;d++){var e=c[d];if(e.listener==a){e.on=!1,c=c.slice(0,d).concat(c.slice(d+1));break}}return b},b.dispatch=function(){var a=c;for(var b=0,d=a.length;b<d;b++){var e=a[b];e.on&&e.listener.apply(this,arguments)}};return b}function g(a){a.apply(this,(arguments[0]=this,arguments));return this}function f(a){return a.replace(/(^\s+)|(\s+$)/g,"").replace(/\s+/g," ")}function e(a){return a==null}function c(a){return Array.prototype.slice.call(a)}function b(a){var b=-1,c=a.length,d=[];while(++b<c)d.push(a[b]);return d}d3={version:"1.15.1"},Date.now||(Date.now=function(){return+(new Date)}),Object.create||(Object.create=function(a){function b(){}b.prototype=a;return new b});var a=c;try{a(document.documentElement.childNodes)[0].nodeType}catch(d){a=b}d3.functor=function(a){return typeof a=="function"?a:function(){return a}},d3.rebind=function(a,b){return function(){var c=b.apply(a,arguments);return arguments.length?a:c}},d3.ascending=function(a,b){return a<b?-1:a>b?1:0},d3.descending=function(a,b){return b<a?-1:b>a?1:0},d3.min=function(a,b){var c=0,d=a.length,e=a[0],f;if(arguments.length===1)while(++c<d)e>(f=a[c])&&(e=f);else{e=b(a[0]);while(++c<d)e>(f=b(a[c]))&&(e=f)}return e},d3.max=function(a,b){var c=0,d=a.length,e=a[0],f;if(arguments.length===1)while(++c<d)e<(f=a[c])&&(e=f);else{e=b(e);while(++c<d)e<(f=b(a[c]))&&(e=f)}return e},d3.nest=function(){function g(a,d){if(d>=b.length)return a;var e=[],f=c[d++],h;for(h in a)e.push({key:h,values:g(a[h],d)});f&&e.sort(function(a,b){return f(a.key,b.key)});return e}function f(c,g){if(g>=b.length)return e?e.call(a,c):d?c.sort(d):c;var h=-1,i=c.length,j=b[g++],k,l,m={};while(++h<i)(k=j(l=c[h]))in m?m[k].push(l):m[k]=[l];for(k in m)m[k]=f(m[k],g);return m}var a={},b=[],c=[],d,e;a.map=function(a){return f(a,0)},a.entries=function(a){return g(f(a,0),0)},a.key=function(c){b.push(c);return a},a.sortKeys=function(d){c[b.length-1]=d;return a},a.sortValues=function(b){d=b;return a},a.rollup=function(b){e=b;return a};return a},d3.keys=function(a){var b=[];for(var c in a)b.push(c);return b},d3.values=function(a){var b=[];for(var c in a)b.push(a[c]);return b},d3.entries=function(a){var b=[];for(var c in a)b.push({key:c,value:a[c]});return b},d3.merge=function(a){return Array.prototype.concat.apply([],a)},d3.split=function(a,b){var c=[],d=[],f,g=-1,h=a.length;arguments.length<2&&(b=e);while(++g<h)b.call(d,f=a[g],g)?d=[]:(d.length||c.push(d),d.push(f));return c},d3.range=function(a,b,c){arguments.length===1&&(b=a,a=0),c==null&&(c=1);if((b-a)/c==Infinity)throw new Error("infinite range");var d=[],e=-1,f;if(c<0)while((f=a+c*++e)>b)d.push(f);else while((f=a+c*++e)<b)d.push(f);return d},d3.requote=function(a){return a.replace(h,"\\$&")};var h=/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g;d3.xhr=function(a,b,c){var d=new XMLHttpRequest;arguments.length<3?c=b:b&&d.overrideMimeType&&d.overrideMimeType(b),d.open("GET",a,!0),d.onreadystatechange=function(){d.readyState===4&&c(d.status<300?d:null)},d.send(null)},d3.text=function(a,b,c){function d(a){c(a&&a.responseText)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.json=function(a,b){d3.text(a,"application/json",function(a){b(a?JSON.parse(a):null)})},d3.html=function(a,b){d3.text(a,"text/html",function(a){if(a!=null){var c=document.createRange();c.selectNode(document.body),a=c.createContextualFragment(a)}b(a)})},d3.xml=function(a,b,c){function d(a){c(a&&a.responseXML)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.ns={prefix:{svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"},qualify:function(a){var b=a.indexOf(":");return b<0?a:{space:d3.ns.prefix[a.substring(0,b)],local:a.substring(b+1)}}},d3.dispatch=function(a){var b={},c;for(var d=0,e=arguments.length;d<e;d++)c=arguments[d],b[c]=i(c);return b},d3.format=function(a){var b=j.exec(a),c=b[1]||" ",d=b[3]||"",e=b[5],f=+b[6],g=b[7],h=b[8],i=b[9];h&&(h=h.substring(1)),e&&(c="0",g&&(f-=Math.floor((f-1)/4))),i==="d"&&(h="0");return function(a){var b=+a,j=b<0&&(b=-b)?"−":d;if(i==="d"&&b%1)return"";h?a=b.toFixed(h):a=""+b;if(e){var l=a.length+j.length;l<f&&(a=Array(f-l+1).join(c)+a),g&&(a=k(a)),a=j+a}else{g&&(a=k(a)),a=j+a;var l=a.length;l<f&&(a=Array(f-l+1).join(c)+a)}return a}};var j=/(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?([0-9]+)?(,)?(\.[0-9]+)?([a-zA-Z%])?/,l=s(2),m=s(3),n={linear:function(){return r},poly:s,quad:function(){return l},cubic:function(){return m},sin:function(){return t},exp:function(){return u},circle:function(){return v},elastic:w,back:x,bounce:function(){return y}},o={"in":function(a){return a},out:p,"in-out":q,"out-in":function(a){return q(p(a))}};d3.ease=function(a){var b=a.indexOf("-"),c=b>=0?a.substring(0,b):a,d=b>=0?a.substring(b+1):"in";return o[d](n[c].apply(null,Array.prototype.slice.call(arguments,1)))},d3.event=null,d3.interpolate=function(a,b){if(typeof b=="number")return d3.interpolateNumber(+a,b);if(typeof b=="string")return b in K||/^(#|rgb\(|hsl\()/.test(b)?d3.interpolateRgb(String(a),b):d3.interpolateString(String(a),b);if(b instanceof Array)return d3.interpolateArray(a,b);return d3.interpolateObject(a,b)},d3.interpolateNumber=function(a,b){b-=a;return function(c){return a+b*c}},d3.interpolateRound=function(a,b){b-=a;return function(c){return Math.round(a+b*c)}},d3.interpolateString=function(a,b){var c,d,e,f=0,g=0,h=[],i=[],j,k;z.lastIndex=0;for(d=0;c=z.exec(b);++d)c.index&&h.push(b.substring(f,g=c.index)),i.push({i:h.length,x:c[0]}),h.push(null),f=z.lastIndex;f<b.length&&h.push(b.substring(f));for(d=0,j=i.length;(c=z.exec(a))&&d<j;++d){k=i[d];if(k.x==c[0]){if(k.i)if(h[k.i+1]==null){h[k.i-1]+=k.x,h.splice(k.i,1);for(e=d+1;e<j;++e)i[e].i--}else{h[k.i-1]+=k.x+h[k.i+1],h.splice(k.i,2);for(e=d+1;e<j;++e)i[e].i-=2}else if(h[k.i+1]==null)h[k.i]=k.x;else{h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1);for(e=d+1;e<j;++e)i[e].i--}i.splice(d,1),j--,d--}else k.x=d3.interpolateNumber(parseFloat(c[0]),parseFloat(k.x))}while(d<j)k=i.pop(),h[k.i+1]==null?h[k.i]=k.x:(h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1)),j--;if(h.length===1)return h[0]==null?i[0].x:function(){return b};return function(a){for(d=0;d<j;++d)h[(k=i[d]).i]=k.x(a);return h.join("")}},d3.interpolateRgb=function(a,b){a=d3.rgb(a),b=d3.rgb(b);var c=a.r,d=a.g,e=a.b,f=b.r-c,g=b.g-d,h=b.b-e;return function(a){return"rgb("+Math.round(c+f*a)+","+Math.round(d+g*a)+","+Math.round(e+h*a)+")"}},d3.interpolateHsl=function(a,b){a=d3.hsl(a),b=d3.hsl(b);var c=a.h,d=a.s,e=a.l,f=b.h-c,g=b.s-d,h=b.l-e;return function(a){return O(c+f*a,d+g*a,e+h*a).toString()}},d3.interpolateArray=function(a,b){var c=[],d=[],e=a.length,f=b.length,g=Math.min(a.length,b.length),h;for(h=0;h<g;++h)c.push(d3.interpolate(a[h],b[h]));for(;h<e;++h)d[h]=a[h];for(;h<f;++h)d[h]=b[h];return function(a){for(h=0;h<g;++h)d[h]=c[h](a);return d}},d3.interpolateObject=function(a,b){var c={},d={},e;for(e in a)e in b?c[e]=B(e)(a[e],b[e]):d[e]=a[e];for(e in b)e in a||(d[e]=b[e]);return function(a){for(e in c)d[e]=c[e](a);return d}};var z=/[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g,A={background:1,fill:1,stroke:1};d3.rgb=function(a,b,c){return arguments.length===1?H(""+a,E,O):E(~~a,~~b,~~c)},F.prototype.brighter=function(a){a=Math.pow(.7,arguments.length?a:1);var b=this.r,c=this.g,d=this.b,e=30;if(!b&&!c&&!d)return E(e,e,e);b&&b<e&&(b=e),c&&c<e&&(c=e),d&&d<e&&(d=e);return E(Math.min(255,Math.floor(b/a)),Math.min(255,Math.floor(c/a)),Math.min(255,Math.floor(d/a)))},F.prototype.darker=function(a){a=Math.pow(.7,arguments.length?a:1);return E(Math.max(0,Math.floor(a*this.r)),Math.max(0,Math.floor(a*this.g)),Math.max(0,Math.floor(a*this.b)))},F.prototype.hsl=function(){return I(this.r,this.g,this.b)},F.prototype.toString=function(){return"#"+G(this.r)+G(this.g)+G(this.b)};var K={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"};for(var L in K)K[L]=H(K[L],E,O);d3.hsl=function(a,b,c){return arguments.length===1?H(""+a,I,M):M(+a,+b,+c)},N.prototype.brighter=function(a){a=Math.pow(.7,arguments.length?a:1);return M(this.h,this.s,this.l/a)},N.prototype.darker=function(a){a=Math.pow(.7,arguments.length?a:1);return M(this.h,this.s,a*this.l)},N.prototype.rgb=function(){return O(this.h,this.s,this.l)},N.prototype.toString=function(){return"hsl("+this.h+","+this.s*100+"%,"+this.l*100+"%)"};var P=function(a,b){return b.querySelector(a)},Q=function(b,c){return a(c.querySelectorAll(b))};typeof Sizzle=="function"&&(P=function(a,b){return Sizzle(a,b)[0]},Q=function(a,b){return Sizzle.uniqueSort(Sizzle(a,b))});var R=S([[document]]);R[0].parentNode=document.documentElement,d3.select=function(a){return typeof a=="string"?R.select(a):S([[a]])},d3.selectAll=function(b){return typeof b=="string"?R.selectAll(b):S([a(b)])},d3.transition=R.transition;var W=0,X=0,$=null,_,ba;d3.timer=function(a){bb(a,0)},d3.timer.flush=function(){var a,b=Date.now(),c=$;while(c)a=b-c.then,c.delay||(c.flush=c.callback(a)),c=c.next;bd()};var be=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){setTimeout(a,17)};d3.scale={},d3.scale.linear=function(){function i(b){var c=d3.min(a),d=d3.max(a),e=d-c,f=Math.pow(10,Math.floor(Math.log(e/b)/Math.LN10)),g=b/(e/f);g<=.15?f*=10:g<=.35?f*=5:g<=.75&&(f*=2);return{start:Math.ceil(c/f)*f,stop:Math.floor(d/f)*f+f*.5,step:f}}function h(a){return e(a)}function g(){var g=a.length==2?bf:bg,i=d?D:C;e=g(a,b,i,c),f=g(b,a,i,d3.interpolate);return h}var a=[0,1],b=[0,1],c=d3.interpolate,d=!1,e,f;h.invert=function(a){return f(a)},h.domain=function(b){if(!arguments.length)return a;a=b.map(Number);return g()},h.range=function(a){if(!arguments.length)return b;b=a;return g()},h.rangeRound=function(a){return h.range(a).interpolate(d3.interpolateRound)},h.clamp=function(a){if(!arguments.length)return d;d=a;return g()},h.interpolate=function(a){if(!arguments.length)return c;c=a;return g()},h.ticks=function(a){var b=i(a);return d3.range(b.start,b.stop,b.step)},h.tickFormat=function(a){var b=Math.max(0,-Math.floor(Math.log(i(a).step)/Math.LN10+.01));return d3.format(",."+b+"f")};return g()},d3.scale.log=function(){function d(c){return a(b(c))}var a=d3.scale.linear(),b=bh,c=b.pow;d.invert=function(b){return c(a.invert(b))},d.domain=function(e){if(!arguments.length)return a.domain().map(c);b=(e[0]||e[1])<0?bi:bh,c=b.pow,a.domain(e.map(b));return d},d.range=d3.rebind(d,a.range),d.rangeRound=d3.rebind(d,a.rangeRound),d.interpolate=d3.rebind(d,a.interpolate),d.clamp=d3.rebind(d,a.clamp),d.ticks=function(){var d=a.domain(),e=[];if(d.every(isFinite)){var f=Math.floor(d[0]),g=Math.ceil(d[1]),h=c(d[0]),i=c(d[1]);if(b===bi){e.push(c(f));for(;f++<g;)for(var j=9;j>0;j--)e.push(c(f)*j)}else{for(;f<g;f++)for(var j=1;j<10;j++)e.push(c(f)*j);e.push(c(f))}for(f=0;e[f]<h;f++);for(g=e.length;e[g-1]>i;g--);e=e.slice(f,g)}return e},d.tickFormat=function(){return function(a){return a.toPrecision(1)}};return d},bh.pow=function(a){return Math.pow(10,a)},bi.pow=function(a){return-Math.pow(10,-a)},d3.scale.pow=function(){function f(b){return a(d(b))}var a=d3.scale.linear(),b=d3.scale.linear(),c=1,d=Number,e=d;f.invert=function(b){return e(a.invert(b))},f.domain=function(g){if(!arguments.length)return a.domain().map(e);var h=(g[0]||g[1])<0?bk:bj;d=h(c),e=h(1/c),a.domain(g.map(d)),b.domain(g);return f},f.range=d3.rebind(f,a.range),f.rangeRound=d3.rebind(f,a.rangeRound),f.interpolate=d3.rebind(f,a.interpolate),f.clamp=d3.rebind(f,a.clamp),f.ticks=b.ticks,f.tickFormat=b.tickFormat,f.exponent=function(a){if(!arguments.length)return c;var b=f.domain();c=a;return f.domain(b)};return f},d3.scale.sqrt=function(){return d3.scale.pow().exponent(.5)},d3.scale.ordinal=function(){function e(d){var e=d in b?b[d]:b[d]=a.push(d)-1;return c[e%c.length]}var a=[],b={},c=[],d=0;e.domain=function(c){if(!arguments.length)return a;a=c,b={};var d=-1,f=-1,g=a.length;while(++d<g)c=a[d],c in b||(b[c]=++f);return e},e.range=function(a){if(!arguments.length)return c;c=a;return e},e.rangePoints=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=(h-g)/(a.length-1+f);c=a.length==1?[(g+h)/2]:d3.range(g+i*f/2,h+i/2,i),d=0;return e},e.rangeBands=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=(h-g)/(a.length+f);c=d3.range(g+i*f,h,i),d=i*(1-f);return e},e.rangeRoundBands=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=h-g,j=Math.floor(i/(a.length+f)),k=i-(a.length-f)*j;c=d3.range(g+Math.round(k/2),h,j),d=Math.round(j*(1-f));return e},e.rangeBand=function(){return d};return e},d3.scale.category10=function(){return d3.scale.ordinal().range(bl)},d3.scale.category20=function(){return d3.scale.ordinal().range(bm)},d3.scale.category20b=function(){return d3.scale.ordinal().range(bn)},d3.scale.category20c=function(){return d3.scale.ordinal().range(bo)};var bl=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],bm=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],bn=["#393b79","#5254a3","#6b6ecf","#9c9ede","#637939","#8ca252","#b5cf6b","#cedb9c","#8c6d31","#bd9e39","#e7ba52","#e7cb94","#843c39","#ad494a","#d6616b","#e7969c","#7b4173","#a55194","#ce6dbd","#de9ed6"],bo=["#3182bd","#6baed6","#9ecae1","#c6dbef","#e6550d","#fd8d3c","#fdae6b","#fdd0a2","#31a354"
<del>,"#74c476","#a1d99b","#c7e9c0","#756bb1","#9e9ac8","#bcbddc","#dadaeb","#636363","#969696","#bdbdbd","#d9d9d9"];d3.scale.quantile=function(){function f(a){return b[e(a)]}function e(a){if(isNaN(a=+a))return NaN;var b=0,d=c.length-1;while(b<=d){var e=b+d>>1,f=c[e];if(f<a)b=e+1;else if(f>a)d=e-1;else return e}return d<0?0:d}function d(){var d=-1,e=c.length=b.length,f=a.length/e;while(++d<e)c[d]=a[~~(d*f)]}var a=[],b=[],c=[];f.domain=function(b){if(!arguments.length)return a;a=b.filter(function(a){return!isNaN(a)}).sort(d3.ascending),d();return f},f.range=function(a){if(!arguments.length)return b;b=a,d();return f},f.quantiles=function(){return c};return f},d3.scale.quantize=function(){function f(b){return e[Math.max(0,Math.min(d,Math.floor(c*(b-a))))]}var a=0,b=1,c=2,d=1,e=[0,1];f.domain=function(d){if(!arguments.length)return[a,b];a=d[0],b=d[1],c=e.length/(b-a);return f},f.range=function(g){if(!arguments.length)return e;e=g,c=e.length/(b-a),d=e.length-1;return f};return f},d3.svg={},d3.svg.arc=function(){function e(){var e=a.apply(this,arguments),f=b.apply(this,arguments),g=c.apply(this,arguments)+bp,h=d.apply(this,arguments)+bp,i=h-g,j=i<Math.PI?"0":"1",k=Math.cos(g),l=Math.sin(g),m=Math.cos(h),n=Math.sin(h);return i>=bq?e?"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"M0,"+e+"A"+e+","+e+" 0 1,1 0,"+ -e+"A"+e+","+e+" 0 1,1 0,"+e+"Z":"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"Z":e?"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L"+e*m+","+e*n+"A"+e+","+e+" 0 "+j+",0 "+e*k+","+e*l+"Z":"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L0,0"+"Z"}var a=br,b=bs,c=bt,d=bu;e.innerRadius=function(b){if(!arguments.length)return a;a=d3.functor(b);return e},e.outerRadius=function(a){if(!arguments.length)return b;b=d3.functor(a);return e},e.startAngle=function(a){if(!arguments.length)return c;c=d3.functor(a);return e},e.endAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return e},e.centroid=function(){var e=(a.apply(this,arguments)+b.apply(this,arguments))/2,f=(c.apply(this,arguments)+d.apply(this,arguments))/2+bp;return[Math.cos(f)*e,Math.sin(f)*e]};return e};var bp=-Math.PI/2,bq=2*Math.PI-1e-6;d3.svg.line=function(){function f(c){return c.length<1?null:"M"+d(bv(this,c,a,b),e)}var a=bw,b=bx,c="linear",d=by[c],e=.7;f.x=function(b){if(!arguments.length)return a;a=b;return f},f.y=function(a){if(!arguments.length)return b;b=a;return f},f.interpolate=function(a){if(!arguments.length)return c;d=by[c=a];return f},f.tension=function(a){if(!arguments.length)return e;e=a;return f};return f};var by={linear:bz,"step-before":bA,"step-after":bB,basis:bH,"basis-open":bI,"basis-closed":bJ,cardinal:bE,"cardinal-open":bC,"cardinal-closed":bD,monotone:bS},bL=[0,2/3,1/3,0],bM=[0,1/3,2/3,0],bN=[0,1/6,2/3,1/6];d3.svg.area=function(){function g(d){return d.length<1?null:"M"+e(bv(this,d,a,c),f)+"L"+e(bv(this,d,a,b).reverse(),f)+"Z"}var a=bw,b=bT,c=bx,d="linear",e=by[d],f=.7;g.x=function(b){if(!arguments.length)return a;a=b;return g},g.y0=function(a){if(!arguments.length)return b;b=a;return g},g.y1=function(a){if(!arguments.length)return c;c=a;return g},g.interpolate=function(a){if(!arguments.length)return d;e=by[d=a];return g},g.tension=function(a){if(!arguments.length)return f;f=a;return g};return g},d3.svg.chord=function(){function j(a,b,c,d){return"Q 0,0 "+d}function i(a,b){return"A"+a+","+a+" 0 0,1 "+b}function h(a,b){return a.a0==b.a0&&a.a1==b.a1}function g(a,b,f,g){var h=b.call(a,f,g),i=c.call(a,h,g),j=d.call(a,h,g)+bp,k=e.call(a,h,g)+bp;return{r:i,a0:j,a1:k,p0:[i*Math.cos(j),i*Math.sin(j)],p1:[i*Math.cos(k),i*Math.sin(k)]}}function f(c,d){var e=g(this,a,c,d),f=g(this,b,c,d);return"M"+e.p0+i(e.r,e.p1)+(h(e,f)?j(e.r,e.p1,e.r,e.p0):j(e.r,e.p1,f.r,f.p0)+i(f.r,f.p1)+j(f.r,f.p1,e.r,e.p0))+"Z"}var a=bU,b=bV,c=bW,d=bt,e=bu;f.radius=function(a){if(!arguments.length)return c;c=d3.functor(a);return f},f.source=function(b){if(!arguments.length)return a;a=d3.functor(b);return f},f.target=function(a){if(!arguments.length)return b;b=d3.functor(a);return f},f.startAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return f},f.endAngle=function(a){if(!arguments.length)return e;e=d3.functor(a);return f};return f},d3.svg.diagonal=function(){function d(d,e){var f=a.call(this,d,e),g=b.call(this,d,e),h=(f.y+g.y)/2,i=[f,{x:f.x,y:h},{x:g.x,y:h},g];i=i.map(c);return"M"+i[0]+"C"+i[1]+" "+i[2]+" "+i[3]}var a=bU,b=bV,c=bZ;d.source=function(b){if(!arguments.length)return a;a=d3.functor(b);return d},d.target=function(a){if(!arguments.length)return b;b=d3.functor(a);return d},d.projection=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.svg.mouse=function(a){var b=(a.ownerSVGElement||a).createSVGPoint();if(b$<0&&(window.scrollX||window.scrollY)){var c=d3.select(document.body).append("svg:svg").style("position","absolute").style("top",0).style("left",0),d=c[0][0].getScreenCTM();b$=!d.f&&!d.e,c.remove()}b$?(b.x=d3.event.pageX,b.y=d3.event.pageY):(b.x=d3.event.clientX,b.y=d3.event.clientY),b=b.matrixTransform(a.getScreenCTM().inverse());return[b.x,b.y]};var b$=/WebKit/.test(navigator.userAgent)?-1:0;d3.svg.symbol=function(){function c(c,d){return(cb[a.call(this,c,d)]||cb.circle)(b.call(this,c,d))}var a=ca,b=b_;c.type=function(b){if(!arguments.length)return a;a=d3.functor(b);return c},c.size=function(a){if(!arguments.length)return b;b=d3.functor(a);return c};return c},d3.svg.symbolTypes=["circle","cross","diamond","square","triangle-down","triangle-up"];var cb={circle:function(a){var b=Math.sqrt(a/Math.PI);return"M0,"+b+"A"+b+","+b+" 0 1,1 0,"+ -b+"A"+b+","+b+" 0 1,1 0,"+b+"Z"},cross:function(a){var b=Math.sqrt(a/5)/2;return"M"+ -3*b+","+ -b+"H"+ -b+"V"+ -3*b+"H"+b+"V"+ -b+"H"+3*b+"V"+b+"H"+b+"V"+3*b+"H"+ -b+"V"+b+"H"+ -3*b+"Z"},diamond:function(a){var b=Math.sqrt(a/(2*cd)),c=b*cd;return"M0,"+ -b+"L"+c+",0"+" 0,"+b+" "+ -c+",0"+"Z"},square:function(a){var b=Math.sqrt(a)/2;return"M"+ -b+","+ -b+"L"+b+","+ -b+" "+b+","+b+" "+ -b+","+b+"Z"},"triangle-down":function(a){var b=Math.sqrt(a/cc),c=b*cc/2;return"M0,"+c+"L"+b+","+ -c+" "+ -b+","+ -c+"Z"},"triangle-up":function(a){var b=Math.sqrt(a/cc),c=b*cc/2;return"M0,"+ -c+"L"+b+","+c+" "+ -b+","+c+"Z"}},cc=Math.sqrt(3),cd=Math.tan(30*Math.PI/180)})()
<ide>\ No newline at end of file
<add>,"#74c476","#a1d99b","#c7e9c0","#756bb1","#9e9ac8","#bcbddc","#dadaeb","#636363","#969696","#bdbdbd","#d9d9d9"];d3.scale.quantile=function(){function f(a){return b[e(a)]}function e(a){if(isNaN(a=+a))return NaN;var b=0,d=c.length-1;while(b<=d){var e=b+d>>1,f=c[e];if(f<a)b=e+1;else if(f>a)d=e-1;else return e}return d<0?0:d}function d(){var d=-1,e=c.length=b.length,f=a.length/e;while(++d<e)c[d]=a[~~(d*f)]}var a=[],b=[],c=[];f.domain=function(b){if(!arguments.length)return a;a=b.filter(function(a){return!isNaN(a)}).sort(d3.ascending),d();return f},f.range=function(a){if(!arguments.length)return b;b=a,d();return f},f.quantiles=function(){return c};return f},d3.scale.quantize=function(){function f(b){return e[Math.max(0,Math.min(d,Math.floor(c*(b-a))))]}var a=0,b=1,c=2,d=1,e=[0,1];f.domain=function(d){if(!arguments.length)return[a,b];a=d[0],b=d[1],c=e.length/(b-a);return f},f.range=function(g){if(!arguments.length)return e;e=g,c=e.length/(b-a),d=e.length-1;return f};return f},d3.svg={},d3.svg.arc=function(){function e(){var e=a.apply(this,arguments),f=b.apply(this,arguments),g=c.apply(this,arguments)+bp,h=d.apply(this,arguments)+bp,i=h-g,j=i<Math.PI?"0":"1",k=Math.cos(g),l=Math.sin(g),m=Math.cos(h),n=Math.sin(h);return i>=bq?e?"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"M0,"+e+"A"+e+","+e+" 0 1,1 0,"+ -e+"A"+e+","+e+" 0 1,1 0,"+e+"Z":"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"Z":e?"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L"+e*m+","+e*n+"A"+e+","+e+" 0 "+j+",0 "+e*k+","+e*l+"Z":"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L0,0"+"Z"}var a=br,b=bs,c=bt,d=bu;e.innerRadius=function(b){if(!arguments.length)return a;a=d3.functor(b);return e},e.outerRadius=function(a){if(!arguments.length)return b;b=d3.functor(a);return e},e.startAngle=function(a){if(!arguments.length)return c;c=d3.functor(a);return e},e.endAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return e},e.centroid=function(){var e=(a.apply(this,arguments)+b.apply(this,arguments))/2,f=(c.apply(this,arguments)+d.apply(this,arguments))/2+bp;return[Math.cos(f)*e,Math.sin(f)*e]};return e};var bp=-Math.PI/2,bq=2*Math.PI-1e-6;d3.svg.line=function(){function f(c){return c.length<1?null:"M"+d(bv(this,c,a,b),e)}var a=bw,b=bx,c="linear",d=by[c],e=.7;f.x=function(b){if(!arguments.length)return a;a=b;return f},f.y=function(a){if(!arguments.length)return b;b=a;return f},f.interpolate=function(a){if(!arguments.length)return c;d=by[c=a];return f},f.tension=function(a){if(!arguments.length)return e;e=a;return f};return f};var by={linear:bz,"step-before":bA,"step-after":bB,basis:bH,"basis-open":bI,"basis-closed":bJ,cardinal:bE,"cardinal-open":bC,"cardinal-closed":bD,monotone:bS},bL=[0,2/3,1/3,0],bM=[0,1/3,2/3,0],bN=[0,1/6,2/3,1/6];d3.svg.area=function(){function g(d){return d.length<1?null:"M"+e(bv(this,d,a,c),f)+"L"+e(bv(this,d,a,b).reverse(),f)+"Z"}var a=bw,b=bT,c=bx,d="linear",e=by[d],f=.7;g.x=function(b){if(!arguments.length)return a;a=b;return g},g.y0=function(a){if(!arguments.length)return b;b=a;return g},g.y1=function(a){if(!arguments.length)return c;c=a;return g},g.interpolate=function(a){if(!arguments.length)return d;e=by[d=a];return g},g.tension=function(a){if(!arguments.length)return f;f=a;return g};return g},d3.svg.chord=function(){function j(a,b,c,d){return"Q 0,0 "+d}function i(a,b){return"A"+a+","+a+" 0 0,1 "+b}function h(a,b){return a.a0==b.a0&&a.a1==b.a1}function g(a,b,f,g){var h=b.call(a,f,g),i=c.call(a,h,g),j=d.call(a,h,g)+bp,k=e.call(a,h,g)+bp;return{r:i,a0:j,a1:k,p0:[i*Math.cos(j),i*Math.sin(j)],p1:[i*Math.cos(k),i*Math.sin(k)]}}function f(c,d){var e=g(this,a,c,d),f=g(this,b,c,d);return"M"+e.p0+i(e.r,e.p1)+(h(e,f)?j(e.r,e.p1,e.r,e.p0):j(e.r,e.p1,f.r,f.p0)+i(f.r,f.p1)+j(f.r,f.p1,e.r,e.p0))+"Z"}var a=bU,b=bV,c=bW,d=bt,e=bu;f.radius=function(a){if(!arguments.length)return c;c=d3.functor(a);return f},f.source=function(b){if(!arguments.length)return a;a=d3.functor(b);return f},f.target=function(a){if(!arguments.length)return b;b=d3.functor(a);return f},f.startAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return f},f.endAngle=function(a){if(!arguments.length)return e;e=d3.functor(a);return f};return f},d3.svg.diagonal=function(){function d(d,e){var f=a.call(this,d,e),g=b.call(this,d,e),h=(f.y+g.y)/2,i=[f,{x:f.x,y:h},{x:g.x,y:h},g];i=i.map(c);return"M"+i[0]+"C"+i[1]+" "+i[2]+" "+i[3]}var a=bU,b=bV,c=bZ;d.source=function(b){if(!arguments.length)return a;a=d3.functor(b);return d},d.target=function(a){if(!arguments.length)return b;b=d3.functor(a);return d},d.projection=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.svg.mouse=function(a){var b=(a.ownerSVGElement||a).createSVGPoint();if(b$<0&&(window.scrollX||window.scrollY)){var c=d3.select(document.body).append("svg:svg").style("position","absolute").style("top",0).style("left",0),d=c[0][0].getScreenCTM();b$=!d.f&&!d.e,c.remove()}d3.event.touches&&d3.event.touches.length>0?(b.x=d3.event.touches[0].pageX,b.y=d3.event.touches[0].pageY):b$?(b.x=d3.event.pageX,b.y=d3.event.pageY):(b.x=d3.event.clientX,b.y=d3.event.clientY),b=b.matrixTransform(a.getScreenCTM().inverse());return[b.x,b.y]};var b$=/WebKit/.test(navigator.userAgent)?-1:0;d3.svg.symbol=function(){function c(c,d){return(cb[a.call(this,c,d)]||cb.circle)(b.call(this,c,d))}var a=ca,b=b_;c.type=function(b){if(!arguments.length)return a;a=d3.functor(b);return c},c.size=function(a){if(!arguments.length)return b;b=d3.functor(a);return c};return c},d3.svg.symbolTypes=["circle","cross","diamond","square","triangle-down","triangle-up"];var cb={circle:function(a){var b=Math.sqrt(a/Math.PI);return"M0,"+b+"A"+b+","+b+" 0 1,1 0,"+ -b+"A"+b+","+b+" 0 1,1 0,"+b+"Z"},cross:function(a){var b=Math.sqrt(a/5)/2;return"M"+ -3*b+","+ -b+"H"+ -b+"V"+ -3*b+"H"+b+"V"+ -b+"H"+3*b+"V"+b+"H"+b+"V"+3*b+"H"+ -b+"V"+b+"H"+ -3*b+"Z"},diamond:function(a){var b=Math.sqrt(a/(2*cd)),c=b*cd;return"M0,"+ -b+"L"+c+",0"+" 0,"+b+" "+ -c+",0"+"Z"},square:function(a){var b=Math.sqrt(a)/2;return"M"+ -b+","+ -b+"L"+b+","+ -b+" "+b+","+b+" "+ -b+","+b+"Z"},"triangle-down":function(a){var b=Math.sqrt(a/cc),c=b*cc/2;return"M0,"+c+"L"+b+","+ -c+" "+ -b+","+ -c+"Z"},"triangle-up":function(a){var b=Math.sqrt(a/cc),c=b*cc/2;return"M0,"+ -c+"L"+b+","+c+" "+ -b+","+c+"Z"}},cc=Math.sqrt(3),cd=Math.tan(30*Math.PI/180)})()
<ide>\ No newline at end of file
<ide><path>src/svg/mouse.js
<ide> d3.svg.mouse = function(container) {
<ide> d3_mouse_bug44083 = !(ctm.f || ctm.e);
<ide> svg.remove();
<ide> }
<del> if (d3_mouse_bug44083) {
<add> if (d3.event.touches && d3.event.touches.length > 0) {
<add> point.x = d3.event.touches[0].pageX;
<add> point.y = d3.event.touches[0].pageY;
<add> } else if (d3_mouse_bug44083) {
<ide> point.x = d3.event.pageX;
<ide> point.y = d3.event.pageY;
<ide> } else { | 3 |
Go | Go | add compatibility with contrib builder | 756df27e45f2e5d9033058f60afa9547239af1d6 | <ide><path>builder.go
<ide> func (builder *Builder) Build(dockerfile io.Reader, stdout io.Writer) (*Image, e
<ide> }
<ide> return err
<ide> }
<del> line = strings.TrimSpace(line)
<add> line = strings.Replace(strings.TrimSpace(line), " ", " ", 1)
<ide> // Skip comments and empty line
<ide> if len(line) == 0 || line[0] == '#' {
<ide> continue
<ide> func (builder *Builder) Build(dockerfile io.Reader, stdout io.Writer) (*Image, e
<ide> fmt.Fprintf(stdout, "===> %s\n", base.ShortId())
<ide> break
<ide> default:
<del> fmt.Fprintf(stdout, "Skipping unknown op %s\n", tmp[0])
<add> fmt.Fprintf(stdout, "Skipping unknown instruction %s\n", strings.ToUpper(instruction))
<ide> }
<ide> }
<ide> if image != nil { | 1 |
Java | Java | define event category in event class | 8ba4a2f127ee5fd862f2bb573ded50abce70c048 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java
<ide> import com.facebook.react.common.mapbuffer.ReadableMapBuffer;
<ide> import com.facebook.react.config.ReactFeatureFlags;
<ide> import com.facebook.react.fabric.events.EventBeatManager;
<del>import com.facebook.react.fabric.events.EventCategoryDef;
<ide> import com.facebook.react.fabric.events.EventEmitterWrapper;
<ide> import com.facebook.react.fabric.events.FabricEventEmitter;
<ide> import com.facebook.react.fabric.mounting.MountItemDispatcher;
<ide> import com.facebook.react.uimanager.UIManagerHelper;
<ide> import com.facebook.react.uimanager.ViewManagerPropertyUpdater;
<ide> import com.facebook.react.uimanager.ViewManagerRegistry;
<add>import com.facebook.react.uimanager.events.EventCategoryDef;
<ide> import com.facebook.react.uimanager.events.EventDispatcher;
<ide> import com.facebook.react.uimanager.events.EventDispatcherImpl;
<ide> import com.facebook.react.uimanager.events.LockFreeEventDispatcherImpl;
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/events/EventEmitterWrapper.java
<ide> import com.facebook.react.bridge.WritableMap;
<ide> import com.facebook.react.bridge.WritableNativeMap;
<ide> import com.facebook.react.fabric.FabricSoLoader;
<add>import com.facebook.react.uimanager.events.EventCategoryDef;
<ide>
<ide> /**
<ide> * This class holds reference to the C++ EventEmitter object. Instances of this class are created on
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/events/FabricEventEmitter.java
<ide> import com.facebook.react.bridge.WritableNativeArray;
<ide> import com.facebook.react.bridge.WritableNativeMap;
<ide> import com.facebook.react.fabric.FabricUIManager;
<add>import com.facebook.react.uimanager.events.EventCategoryDef;
<ide> import com.facebook.react.uimanager.events.RCTModernEventEmitter;
<ide> import com.facebook.react.uimanager.events.TouchEventType;
<ide> import com.facebook.systrace.Systrace;
<ide> public void receiveEvent(int reactTag, @NonNull String eventName, @Nullable Writ
<ide> @Override
<ide> public void receiveEvent(
<ide> int surfaceId, int reactTag, String eventName, @Nullable WritableMap params) {
<del> receiveEvent(surfaceId, reactTag, eventName, false, 0, params);
<add> receiveEvent(surfaceId, reactTag, eventName, false, 0, params, EventCategoryDef.UNSPECIFIED);
<ide> }
<ide>
<ide> @Override
<ide> public void receiveEvent(
<ide> String eventName,
<ide> boolean canCoalesceEvent,
<ide> int customCoalesceKey,
<del> @Nullable WritableMap params) {
<add> @Nullable WritableMap params,
<add> @EventCategoryDef int category) {
<ide> Systrace.beginSection(
<ide> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE,
<ide> "FabricEventEmitter.receiveEvent('" + eventName + "')");
<ide> mUIManager.receiveEvent(
<del> surfaceId, reactTag, eventName, canCoalesceEvent, customCoalesceKey, params);
<add> surfaceId, reactTag, eventName, canCoalesceEvent, customCoalesceKey, params, category);
<ide> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
<ide> }
<ide>
<add> /**
<add> * Processes touches in a JS compatible way and send it to Fabric core
<add> *
<add> * @param eventName the event name (see {@link TouchEventType})
<add> * @param touches all the touch data extracted from MotionEvent
<add> * @param changedIndices the indices of the pointers that changed (MOVE/CANCEL includes all
<add> * touches, START/END only the one that was added/removed)
<add> */
<ide> @Override
<ide> public void receiveTouches(
<del> @NonNull String eventTopLevelType,
<add> @NonNull String eventName,
<ide> @NonNull WritableArray touches,
<ide> @NonNull WritableArray changedIndices) {
<ide> Systrace.beginSection(
<ide> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE,
<del> "FabricEventEmitter.receiveTouches('" + eventTopLevelType + "')");
<add> "FabricEventEmitter.receiveTouches('" + eventName + "')");
<ide>
<del> boolean isPointerEndEvent =
<del> TouchEventType.END.getJsName().equalsIgnoreCase(eventTopLevelType)
<del> || TouchEventType.CANCEL.getJsName().equalsIgnoreCase(eventTopLevelType);
<add> boolean isFinalEvent =
<add> TouchEventType.END.getJsName().equalsIgnoreCase(eventName)
<add> || TouchEventType.CANCEL.getJsName().equalsIgnoreCase(eventName);
<ide>
<ide> Pair<WritableArray, WritableArray> result =
<del> isPointerEndEvent
<add> isFinalEvent
<ide> ? removeTouchesAtIndices(touches, changedIndices)
<ide> : touchSubsequence(touches, changedIndices);
<ide>
<ide> WritableArray changedTouches = result.first;
<ide> touches = result.second;
<ide>
<del> int eventCategory = getTouchCategory(eventTopLevelType);
<add> int eventCategory = getTouchCategory(eventName);
<ide> for (int jj = 0; jj < changedTouches.size(); jj++) {
<ide> WritableMap touch = getWritableMap(changedTouches.getMap(jj));
<ide> // Touch objects can fulfill the role of `DOM` `Event` objects if we set
<ide> public void receiveTouches(
<ide> rootNodeID = targetReactTag;
<ide> }
<ide>
<del> mUIManager.receiveEvent(
<del> targetSurfaceId, rootNodeID, eventTopLevelType, false, 0, touch, eventCategory);
<add> receiveEvent(targetSurfaceId, rootNodeID, eventName, false, 0, touch, eventCategory);
<ide> }
<ide>
<ide> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/events/Event.java
<ide> protected WritableMap getEventData() {
<ide> return null;
<ide> }
<ide>
<add> @EventCategoryDef
<add> protected int getEventCategory() {
<add> return EventCategoryDef.UNSPECIFIED;
<add> }
<add>
<ide> /**
<ide> * Dispatch this event to JS using a V2 EventEmitter. If surfaceId is not -1 and `getEventData` is
<ide> * non-null, this will use the RCTModernEventEmitter API. Otherwise, it falls back to the
<ide> public void dispatchModernV2(RCTModernEventEmitter rctEventEmitter) {
<ide> getEventName(),
<ide> canCoalesce(),
<ide> getCoalescingKey(),
<del> eventData);
<add> eventData,
<add> getEventCategory());
<ide> return;
<ide> }
<ide> }
<add><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/events/EventCategoryDef.java
<del><path>ReactAndroid/src/main/java/com/facebook/react/fabric/events/EventCategoryDef.java
<ide> * LICENSE file in the root directory of this source tree.
<ide> */
<ide>
<del>package com.facebook.react.fabric.events;
<add>package com.facebook.react.uimanager.events;
<ide>
<del>import static com.facebook.react.fabric.events.EventCategoryDef.CONTINUOUS;
<del>import static com.facebook.react.fabric.events.EventCategoryDef.CONTINUOUS_END;
<del>import static com.facebook.react.fabric.events.EventCategoryDef.CONTINUOUS_START;
<del>import static com.facebook.react.fabric.events.EventCategoryDef.DISCRETE;
<del>import static com.facebook.react.fabric.events.EventCategoryDef.UNSPECIFIED;
<add>import static com.facebook.react.uimanager.events.EventCategoryDef.CONTINUOUS;
<add>import static com.facebook.react.uimanager.events.EventCategoryDef.CONTINUOUS_END;
<add>import static com.facebook.react.uimanager.events.EventCategoryDef.CONTINUOUS_START;
<add>import static com.facebook.react.uimanager.events.EventCategoryDef.DISCRETE;
<add>import static com.facebook.react.uimanager.events.EventCategoryDef.UNSPECIFIED;
<ide>
<ide> import androidx.annotation.IntDef;
<ide>
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/events/RCTModernEventEmitter.java
<ide> void receiveEvent(
<ide> String eventName,
<ide> boolean canCoalesceEvent,
<ide> int customCoalesceKey,
<del> @Nullable WritableMap event);
<add> @Nullable WritableMap event,
<add> @EventCategoryDef int category);
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/events/ReactEventEmitter.java
<ide> public void receiveEvent(
<ide> int surfaceId, int targetTag, String eventName, @Nullable WritableMap event) {
<ide> // The two additional params here, `canCoalesceEvent` and `customCoalesceKey`, have no
<ide> // meaning outside of Fabric.
<del> receiveEvent(surfaceId, targetTag, eventName, false, 0, event);
<add> receiveEvent(surfaceId, targetTag, eventName, false, 0, event, EventCategoryDef.UNSPECIFIED);
<ide> }
<ide>
<ide> @Override
<ide> public void receiveEvent(
<ide> String eventName,
<ide> boolean canCoalesceEvent,
<ide> int customCoalesceKey,
<del> @Nullable WritableMap event) {
<add> @Nullable WritableMap event,
<add> @EventCategoryDef int category) {
<ide> @UIManagerType int uiManagerType = ViewUtil.getUIManagerType(targetReactTag);
<ide> if (uiManagerType == UIManagerType.FABRIC && mFabricEventEmitter != null) {
<ide> mFabricEventEmitter.receiveEvent(
<del> surfaceId, targetReactTag, eventName, canCoalesceEvent, customCoalesceKey, event);
<add> surfaceId,
<add> targetReactTag,
<add> eventName,
<add> canCoalesceEvent,
<add> customCoalesceKey,
<add> event,
<add> category);
<ide> } else if (uiManagerType == UIManagerType.DEFAULT && getEventEmitter(targetReactTag) != null) {
<ide> mRCTEventEmitter.receiveEvent(targetReactTag, eventName, event);
<ide> } else { | 7 |
Text | Text | write changelog entry for . [ci skip] | 9f3b089b7b288cce1cb891537a8ecae7dba015df | <ide><path>activerecord/CHANGELOG.md
<add>* Stop interpreting SQL 'string' columns as :string type because there is no
<add> common STRING datatype in SQL.
<add>
<add> *Ben Woosley*
<add>
<ide> * `ActiveRecord::FinderMethods#exists?` returns `true`/`false` in all cases.
<ide>
<ide> *Xavier Noria* | 1 |
Python | Python | fix intermittent orphan test | 387c43f625e379a0de8e3527a98833eb5f62d3bf | <ide><path>tests/jobs/test_scheduler_job.py
<ide> #
<ide>
<ide> import datetime
<add>import logging
<ide> import os
<ide> import shutil
<ide> from datetime import timedelta
<ide> import airflow.example_dags
<ide> import airflow.smart_sensor_dags
<ide> from airflow import settings
<add>from airflow.configuration import conf
<ide> from airflow.dag_processing.manager import DagFileProcessorAgent
<ide> from airflow.exceptions import AirflowException
<ide> from airflow.executors.base_executor import BaseExecutor
<ide> DEFAULT_DATE = timezone.datetime(2016, 1, 1)
<ide> TRY_NUMBER = 1
<ide>
<add>log = logging.getLogger(__name__)
<add>
<ide>
<ide> @pytest.fixture(scope="class")
<ide> def disable_load_example():
<ide> def run_single_scheduler_loop_with_no_dags(self, dags_folder):
<ide> self.scheduler_job.heartrate = 0
<ide> self.scheduler_job.run()
<ide>
<add> @pytest.mark.skipif(
<add> conf.get('core', 'sql_alchemy_conn').lower().startswith("mssql"),
<add> reason="MSSQL does not like os._exit()",
<add> )
<add> @pytest.mark.skipif(not hasattr(os, 'fork'), reason="Forking not available")
<ide> def test_no_orphan_process_will_be_left(self):
<ide> empty_dir = mkdtemp()
<ide> current_process = psutil.Process()
<del> old_children = current_process.children(recursive=True)
<del> self.scheduler_job = SchedulerJob(
<del> subdir=empty_dir, num_runs=1, executor=MockExecutor(do_update=False)
<del> )
<del> self.scheduler_job.run()
<del> shutil.rmtree(empty_dir)
<del>
<del> # Remove potential noise created by previous tests.
<del> current_children = set(current_process.children(recursive=True)) - set(old_children)
<del> assert not current_children
<add> pid = os.fork()
<add> # Running the test in a fork to avoid side effects from other tests - those side-effects migh
<add> # Cause some processes to be running as children
<add> if pid == 0:
<add> old_children = current_process.children(recursive=True)
<add> self.scheduler_job = SchedulerJob(
<add> subdir=empty_dir, num_runs=1, executor=MockExecutor(do_update=False)
<add> )
<add> self.scheduler_job.run()
<add> shutil.rmtree(empty_dir)
<add>
<add> # Remove potential noise created by previous tests.
<add> current_children = set(current_process.children(recursive=True)) - set(old_children)
<add> if current_children:
<add> log.error(f"Current children: {current_children}")
<add> # Exit immediately from the fork without cleanup (avoid Pytest atexit)
<add> os._exit(1)
<add> # Exit immediately from the fork without cleanup (avoid Pytest atexit)
<add> os._exit(0)
<add> else:
<add> pid, ret_val = os.wait()
<add> assert (
<add> not ret_val
<add> ), "The return value entered from process was non-zero. See error log above for details."
<ide>
<ide> @mock.patch('airflow.jobs.scheduler_job.TaskCallbackRequest')
<ide> @mock.patch('airflow.jobs.scheduler_job.Stats.incr') | 1 |
Go | Go | fix error handling if we didn't receive a response | efe0ab37a1ded98fe879c366ccfa6d6db3d6ed78 | <ide><path>libnetwork/resolver.go
<ide> func (r *resolver) ServeDNS(w dns.ResponseWriter, query *dns.Msg) {
<ide> resp, err = co.ReadMsg()
<ide> // Truncated DNS replies should be sent to the client so that the
<ide> // client can retry over TCP
<del> if err != nil && (resp != nil && !resp.Truncated) {
<add> if err != nil && (resp == nil || !resp.Truncated) {
<ide> r.forwardQueryEnd()
<ide> logrus.Debugf("[resolver] read from DNS server failed, %s", err)
<ide> continue | 1 |
PHP | PHP | convert last long notation array to short notation | 945d4f559448ac6ec125bc44858e6c5815f9afd0 | <ide><path>resources/views/emails/auth/reminder.blade.php
<ide> <h2>Password Reset</h2>
<ide>
<ide> <div>
<del> To reset your password, complete this form: {{ URL::to('password/reset', array($token)) }}.<br/>
<add> To reset your password, complete this form: {{ URL::to('password/reset', [$token]) }}.<br/>
<ide> This link will expire in {{ Config::get('auth.reminder.expire', 60) }} minutes.
<ide> </div>
<ide> </body> | 1 |
Java | Java | update copyright for yoga files | b8cb8d50a5e0bea9ceaade49b97806998c84cdbe | <ide><path>ReactAndroid/src/main/java/com/facebook/yoga/YogaAlign.java
<ide> /*
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<add> * Copyright (c) 2018-present, Facebook, Inc.
<ide> *
<ide> * This source code is licensed under the MIT license found in the LICENSE
<ide> * file in the root directory of this source tree.
<ide><path>ReactAndroid/src/main/java/com/facebook/yoga/YogaConfig.java
<ide> /*
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<add> * Copyright (c) 2018-present, Facebook, Inc.
<ide> *
<ide> * This source code is licensed under the MIT license found in the LICENSE
<ide> * file in the root directory of this source tree.
<ide> package com.facebook.yoga;
<ide>
<ide> import com.facebook.proguard.annotations.DoNotStrip;
<del>import com.facebook.soloader.SoLoader;
<ide>
<ide> @DoNotStrip
<ide> public class YogaConfig {
<ide><path>ReactAndroid/src/main/java/com/facebook/yoga/YogaDimension.java
<ide> /*
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<add> * Copyright (c) 2018-present, Facebook, Inc.
<ide> *
<ide> * This source code is licensed under the MIT license found in the LICENSE
<ide> * file in the root directory of this source tree.
<ide><path>ReactAndroid/src/main/java/com/facebook/yoga/YogaDirection.java
<ide> /*
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<add> * Copyright (c) 2018-present, Facebook, Inc.
<ide> *
<ide> * This source code is licensed under the MIT license found in the LICENSE
<ide> * file in the root directory of this source tree.
<ide><path>ReactAndroid/src/main/java/com/facebook/yoga/YogaDisplay.java
<ide> /*
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<add> * Copyright (c) 2018-present, Facebook, Inc.
<ide> *
<ide> * This source code is licensed under the MIT license found in the LICENSE
<ide> * file in the root directory of this source tree.
<ide><path>ReactAndroid/src/main/java/com/facebook/yoga/YogaEdge.java
<ide> /*
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<add> * Copyright (c) 2018-present, Facebook, Inc.
<ide> *
<ide> * This source code is licensed under the MIT license found in the LICENSE
<ide> * file in the root directory of this source tree.
<ide><path>ReactAndroid/src/main/java/com/facebook/yoga/YogaExperimentalFeature.java
<ide> /*
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<add> * Copyright (c) 2018-present, Facebook, Inc.
<ide> *
<ide> * This source code is licensed under the MIT license found in the LICENSE
<ide> * file in the root directory of this source tree.
<ide><path>ReactAndroid/src/main/java/com/facebook/yoga/YogaFlexDirection.java
<ide> /*
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<add> * Copyright (c) 2018-present, Facebook, Inc.
<ide> *
<ide> * This source code is licensed under the MIT license found in the LICENSE
<ide> * file in the root directory of this source tree.
<ide><path>ReactAndroid/src/main/java/com/facebook/yoga/YogaJustify.java
<ide> /*
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<add> * Copyright (c) 2018-present, Facebook, Inc.
<ide> *
<ide> * This source code is licensed under the MIT license found in the LICENSE
<ide> * file in the root directory of this source tree.
<ide><path>ReactAndroid/src/main/java/com/facebook/yoga/YogaLogLevel.java
<ide> /*
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<add> * Copyright (c) 2018-present, Facebook, Inc.
<ide> *
<ide> * This source code is licensed under the MIT license found in the LICENSE
<ide> * file in the root directory of this source tree.
<ide><path>ReactAndroid/src/main/java/com/facebook/yoga/YogaMeasureMode.java
<ide> /*
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<add> * Copyright (c) 2018-present, Facebook, Inc.
<ide> *
<ide> * This source code is licensed under the MIT license found in the LICENSE
<ide> * file in the root directory of this source tree.
<ide><path>ReactAndroid/src/main/java/com/facebook/yoga/YogaNode.java
<ide> /*
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<add> * Copyright (c) 2018-present, Facebook, Inc.
<ide> *
<ide> * This source code is licensed under the MIT license found in the LICENSE
<ide> * file in the root directory of this source tree.
<ide> *
<ide> */
<del>
<ide> package com.facebook.yoga;
<ide>
<ide> import com.facebook.proguard.annotations.DoNotStrip;
<del>import com.facebook.soloader.SoLoader;
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide> import javax.annotation.Nullable;
<ide><path>ReactAndroid/src/main/java/com/facebook/yoga/YogaNodeType.java
<ide> /*
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<add> * Copyright (c) 2018-present, Facebook, Inc.
<ide> *
<ide> * This source code is licensed under the MIT license found in the LICENSE
<ide> * file in the root directory of this source tree.
<ide><path>ReactAndroid/src/main/java/com/facebook/yoga/YogaOverflow.java
<ide> /*
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<add> * Copyright (c) 2018-present, Facebook, Inc.
<ide> *
<ide> * This source code is licensed under the MIT license found in the LICENSE
<ide> * file in the root directory of this source tree.
<ide><path>ReactAndroid/src/main/java/com/facebook/yoga/YogaPositionType.java
<ide> /*
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<add> * Copyright (c) 2018-present, Facebook, Inc.
<ide> *
<ide> * This source code is licensed under the MIT license found in the LICENSE
<ide> * file in the root directory of this source tree.
<ide><path>ReactAndroid/src/main/java/com/facebook/yoga/YogaPrintOptions.java
<ide> /*
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<add> * Copyright (c) 2018-present, Facebook, Inc.
<ide> *
<ide> * This source code is licensed under the MIT license found in the LICENSE
<ide> * file in the root directory of this source tree.
<ide><path>ReactAndroid/src/main/java/com/facebook/yoga/YogaUnit.java
<ide> /*
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<add> * Copyright (c) 2018-present, Facebook, Inc.
<ide> *
<ide> * This source code is licensed under the MIT license found in the LICENSE
<ide> * file in the root directory of this source tree.
<ide><path>ReactAndroid/src/main/java/com/facebook/yoga/YogaValue.java
<ide> /*
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<add> * Copyright (c) 2018-present, Facebook, Inc.
<ide> *
<ide> * This source code is licensed under the MIT license found in the LICENSE
<ide> * file in the root directory of this source tree.
<ide><path>ReactAndroid/src/main/java/com/facebook/yoga/YogaWrap.java
<ide> /*
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<add> * Copyright (c) 2018-present, Facebook, Inc.
<ide> *
<ide> * This source code is licensed under the MIT license found in the LICENSE
<ide> * file in the root directory of this source tree. | 19 |
Ruby | Ruby | remove array workaround in pg quoting | 228aa4fff8d91a179abc81be7891d5a8772257c3 | <ide><path>activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb
<ide> def quote(value, column = nil) #:nodoc:
<ide> else
<ide> super
<ide> end
<del> when Array
<del> super(value, array_column(column))
<ide> when Hash
<ide> case sql_type
<ide> when 'hstore' then super(PostgreSQLColumn.hstore_to_string(value), column)
<ide> def type_cast(value, column, array_member = false)
<ide> else
<ide> super(value, column)
<ide> end
<del> when Array
<del> super(value, array_column(column))
<ide> when Hash
<ide> case column.sql_type
<ide> when 'hstore' then PostgreSQLColumn.hstore_to_string(value, array_member)
<ide> def _type_cast(value)
<ide> super
<ide> end
<ide> end
<del>
<del> def array_column(column)
<del> if column.array && !column.respond_to?(:cast_type)
<del> Column.new('', nil, OID::Array.new(AdapterProxyType.new(column, self)))
<del> else
<del> column
<del> end
<del> end
<del>
<del> class AdapterProxyType < SimpleDelegator # :nodoc:
<del> def initialize(column, adapter)
<del> @column = column
<del> @adapter = adapter
<del> super(column)
<del> end
<del>
<del> def type_cast_for_database(value)
<del> @adapter.type_cast(value, @column)
<del> end
<del> end
<ide> end
<ide> end
<ide> end | 1 |
Go | Go | monitor the tty after starting the container | 656b66e51b18ff9f5f2720c3ce9ff9ec2937f05f | <ide><path>commands.go
<ide> func (cli *DockerCli) CmdRun(args ...string) error {
<ide> hijacked := make(chan bool)
<ide>
<ide> if config.AttachStdin || config.AttachStdout || config.AttachStderr {
<del> if config.Tty {
<del> if err := cli.monitorTtySize(runResult.ID); err != nil {
<del> utils.Errorf("Error monitoring TTY size: %s\n", err)
<del> }
<del> }
<ide>
<ide> v := url.Values{}
<ide> v.Set("stream", "1")
<ide> func (cli *DockerCli) CmdRun(args ...string) error {
<ide> return err
<ide> }
<ide>
<add> if (config.AttachStdin || config.AttachStdout || config.AttachStderr) && config.Tty {
<add> if err := cli.monitorTtySize(runResult.ID); err != nil {
<add> utils.Errorf("Error monitoring TTY size: %s\n", err)
<add> }
<add> }
<add>
<ide> if errCh != nil {
<ide> if err := <-errCh; err != nil {
<ide> utils.Debugf("Error hijack: %s", err) | 1 |
Python | Python | make main a strict prototype in configure checks | c0bba1ce75197a58a1d9f6ec8b13b5a09f18a558 | <ide><path>numpy/distutils/command/config.py
<ide> def check_decl(self, symbol,
<ide> headers=None, include_dirs=None):
<ide> self._check_compiler()
<ide> body = """
<del>int main()
<add>int main(void)
<ide> {
<ide> #ifndef %s
<ide> (void) %s;
<ide> def check_macro_true(self, symbol,
<ide> headers=None, include_dirs=None):
<ide> self._check_compiler()
<ide> body = """
<del>int main()
<add>int main(void)
<ide> {
<ide> #if %s
<ide> #else
<ide> def check_type(self, type_name, headers=None, include_dirs=None,
<ide>
<ide> # First check the type can be compiled
<ide> body = r"""
<del>int main() {
<add>int main(void) {
<ide> if ((%(name)s *) 0)
<ide> return 0;
<ide> if (sizeof (%(name)s))
<ide> def check_type_size(self, type_name, headers=None, include_dirs=None, library_di
<ide> # First check the type can be compiled
<ide> body = r"""
<ide> typedef %(type)s npy_check_sizeof_type;
<del>int main ()
<add>int main (void)
<ide> {
<ide> static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) >= 0)];
<ide> test_array [0] = 0
<ide> def check_type_size(self, type_name, headers=None, include_dirs=None, library_di
<ide> if expected:
<ide> body = r"""
<ide> typedef %(type)s npy_check_sizeof_type;
<del>int main ()
<add>int main (void)
<ide> {
<ide> static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) == %(size)s)];
<ide> test_array [0] = 0
<ide> def check_type_size(self, type_name, headers=None, include_dirs=None, library_di
<ide> # this fails to *compile* if size > sizeof(type)
<ide> body = r"""
<ide> typedef %(type)s npy_check_sizeof_type;
<del>int main ()
<add>int main (void)
<ide> {
<ide> static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) <= %(size)s)];
<ide> test_array [0] = 0 | 1 |
Javascript | Javascript | stabilize test for windows | f5c8b428ab3975f75461e9d50155bf5344531974 | <ide><path>test/integration/getserversideprops/test/index.test.js
<ide> const runTests = (dev = false) => {
<ide> await waitFor(500)
<ide> await browser.eval('window.beforeClick = "abc"')
<ide> await browser.elementByCss('#broken-post').click()
<del> await waitFor(1000)
<del> expect(await browser.eval('window.beforeClick')).not.toBe('abc')
<add> expect(
<add> await check(() => browser.eval('window.beforeClick'), {
<add> test(v) {
<add> return v !== 'abc'
<add> },
<add> })
<add> ).toBe(true)
<ide> })
<ide>
<ide> it('should always call getServerSideProps without caching', async () => {
<ide><path>test/integration/prerender/test/index.test.js
<ide> const runTests = (dev = false, looseMode = false) => {
<ide> const browser = await webdriver(appPort, '/')
<ide> await browser.eval('window.beforeClick = "abc"')
<ide> await browser.elementByCss('#broken-post').click()
<del> await waitFor(1000)
<del> expect(await browser.eval('window.beforeClick')).not.toBe('abc')
<add> expect(
<add> await check(() => browser.eval('window.beforeClick'), {
<add> test(v) {
<add> return v !== 'abc'
<add> },
<add> })
<add> ).toBe(true)
<ide> })
<ide>
<ide> // TODO: dev currently renders this page as blocking, meaning it shows the
<ide> const runTests = (dev = false, looseMode = false) => {
<ide> const browser = await webdriver(appPort, '/')
<ide> await browser.eval('window.beforeClick = "abc"')
<ide> await browser.elementByCss('#broken-at-first-post').click()
<del> await waitFor(3000)
<del> expect(await browser.eval('window.beforeClick')).not.toBe('abc')
<add> expect(
<add> await check(() => browser.eval('window.beforeClick'), {
<add> test(v) {
<add> return v !== 'abc'
<add> },
<add> })
<add> ).toBe(true)
<ide>
<ide> const text = await browser.elementByCss('#params').text()
<ide> expect(text).toMatch(/post.*?post-999/) | 2 |
Javascript | Javascript | add emoj3 app to showcase | f01addb4a182d973103c931cc9a6b9b34449a76e | <ide><path>website/src/react-native/showcase.js
<ide> var apps = [
<ide> linkPlayStore: 'https://play.google.com/store/apps/details?id=com.eon',
<ide> author: 'Sharath Prabhal',
<ide> },
<add> {
<add> name: 'Emoj3 - The emoji only social network',
<add> icon: 'https://emoj3.com/images/favicon/apple-touch-icon-152x152.png',
<add> linkAppStore: 'https://itunes.apple.com/us/app/emoj3/id1078999427?mt=8',
<add> link: 'https://emoj3.com',
<add> author: 'Waffle and Toast'
<add> },
<ide> {
<ide> name: 'Emoji Poetry',
<ide> icon: 'http://a5.mzstatic.com/us/r30/Purple49/v4/31/b5/09/31b509b2-aaec-760f-ccec-2ce72fe7134e/icon175x175.jpeg', | 1 |
PHP | PHP | fix stupid mistake | fad9daf85238dc788dfb972388c845abbac71399 | <ide><path>tests/TestCase/Database/Type/FloatTypeTest.php
<ide> public function setUp()
<ide> $this->type = Type::build('float');
<ide> $this->driver = $this->getMock('Cake\Database\Driver');
<ide> $this->locale = I18n::locale();
<add> $this->numberClass = FloatType::$numberClass;
<ide>
<ide> I18n::locale($this->locale);
<ide> }
<ide> public function tearDown()
<ide> {
<ide> parent::tearDown();
<ide> I18n::locale($this->locale);
<add> FloatType::$numberClass = $this->numberClass;
<ide> }
<ide>
<ide> /**
<ide> public function testMarshalWithLocaleParsing()
<ide> */
<ide> public function testUseLocaleParsingInvalid()
<ide> {
<del> $this->type->useLocaleParser('stdClass');
<add> FloatType::$numberClass = 'stdClass';
<add> $this->type->useLocaleParser();
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | remove forced optimization from es | ef8cc301fed5f0b4b3107fae5d896eb27f9519f8 | <ide><path>benchmark/es/defaultparams-bench.js
<ide> function defaultParams(x = 1, y = 2) {
<ide>
<ide> function runOldStyleDefaults(n) {
<ide>
<del> common.v8ForceOptimization(oldStyleDefaults);
<del>
<ide> var i = 0;
<ide> bench.start();
<ide> for (; i < n; i++)
<ide> function runOldStyleDefaults(n) {
<ide>
<ide> function runDefaultParams(n) {
<ide>
<del> common.v8ForceOptimization(defaultParams);
<del>
<ide> var i = 0;
<ide> bench.start();
<ide> for (; i < n; i++)
<ide><path>benchmark/es/restparams-bench.js
<ide> function useArguments() {
<ide>
<ide> function runCopyArguments(n) {
<ide>
<del> common.v8ForceOptimization(copyArguments, 1, 2, 'a', 'b');
<del>
<ide> var i = 0;
<ide> bench.start();
<ide> for (; i < n; i++)
<ide> function runCopyArguments(n) {
<ide>
<ide> function runRestArguments(n) {
<ide>
<del> common.v8ForceOptimization(restArguments, 1, 2, 'a', 'b');
<del>
<ide> var i = 0;
<ide> bench.start();
<ide> for (; i < n; i++)
<ide> function runRestArguments(n) {
<ide>
<ide> function runUseArguments(n) {
<ide>
<del> common.v8ForceOptimization(useArguments, 1, 2, 'a', 'b');
<del>
<ide> var i = 0;
<ide> bench.start();
<ide> for (; i < n; i++) | 2 |
Text | Text | remove the need for bootstrap | 9fb0b57c26a7fc754e95d85051aac67841c79240 | <ide><path>docs/how-to-setup-freecodecamp-locally.md
<ide> You need to point your local clone to the `upstream` in addition to the `origin`
<ide> git remote -v
<ide> ```
<ide>
<del> The output should be something like below:
<add> The output should be something like below:
<ide>
<ide> ```shell
<ide> origin https://github.com/YOUR_USER_NAME/freeCodeCamp.git (fetch)
<ide> npm -v
<ide>
<ide> We regularly develop on popular and latest operating systems like macOS 10.12 or later, Ubuntu 16.04 or later and Windows 10. Its recommended to lookup your specific issue on resources like: Google, Stack Overflow or Stack Exchange. Chances are that someone has faced the same issue and there is already an answer to your specific query.
<ide>
<del>If you are on a different OS, and/or are still running into issues, reach out to [contributors community on our public forum](https://www.freecodecamp.org/forum/c/contributors) or the [Contributor's Chat room](https://gitter.im/freeCodeCamp/Contributors). We may be able to troubleshoot some common issues.
<add>If you are on a different OS, and/or are still running into issues, reach out to [contributors community on our public forum](https://www.freeCodeCamp.org/c/contributors) or the [contributor's chat room](https://gitter.im/freeCodeCamp/Contributors).
<ide>
<del>We can't support you on GitHub, because software installation issues are beyond the scope of this project.
<add>Please avoid creating GitHub issues for pre-requisite issues. They are out of the scope of this project.
<ide>
<ide> ### Installing dependencies
<ide>
<ide> The keys are not required to be changed, to run the app locally. You can leave t
<ide>
<ide> You can leave the other keys as they are. Keep in mind if you want to use more services you'll have to get your own API keys for those services and edit those entries accordingly in the `.env` file.
<ide>
<del>Next lets, bootstrap the various services, i.e. the api-server, the client UI application, etc. You can [learn more about these services in this guide](#).
<del>
<del>By bootstrapping you are tying the links between the services. They are semi-independent. Meaning, in production these services are deployed to their own locations, but while running locally you want them all to be available to you.
<del>
<del>```shell
<del># Bootstrap all projects inside this repository
<del>npm run bootstrap
<del>```
<del>
<ide> ### Start MongoDB
<ide>
<ide> You will need to start MongoDB, before you can start the application: | 1 |
Java | Java | provide full request url for "http.url" keyvalue | 681cf0dae7c739125479168b5a7ce7e716eba2f5 | <ide><path>spring-web/src/main/java/org/springframework/http/client/observation/DefaultClientHttpObservationConvention.java
<ide> public class DefaultClientHttpObservationConvention implements ClientHttpObserva
<ide>
<ide> private static final KeyValue EXCEPTION_NONE = KeyValue.of(ClientHttpObservation.LowCardinalityKeyNames.EXCEPTION, "none");
<ide>
<del> private static final KeyValue URI_EXPANDED_NONE = KeyValue.of(ClientHttpObservation.HighCardinalityKeyNames.HTTP_URL, "none");
<add> private static final KeyValue HTTP_URL_NONE = KeyValue.of(ClientHttpObservation.HighCardinalityKeyNames.HTTP_URL, "none");
<ide>
<ide> private static final KeyValue CLIENT_NAME_NONE = KeyValue.of(ClientHttpObservation.HighCardinalityKeyNames.CLIENT_NAME, "none");
<ide>
<ide> protected KeyValue requestUri(ClientHttpObservationContext context) {
<ide> if (context.getCarrier() != null) {
<ide> return KeyValue.of(ClientHttpObservation.HighCardinalityKeyNames.HTTP_URL, context.getCarrier().getURI().toASCIIString());
<ide> }
<del> return URI_EXPANDED_NONE;
<add> return HTTP_URL_NONE;
<ide> }
<ide>
<ide> protected KeyValue clientName(ClientHttpObservationContext context) {
<ide><path>spring-web/src/main/java/org/springframework/web/observation/DefaultHttpRequestsObservationConvention.java
<ide> public class DefaultHttpRequestsObservationConvention implements HttpRequestsObs
<ide>
<ide> private static final KeyValue EXCEPTION_NONE = KeyValue.of(HttpRequestsObservation.LowCardinalityKeyNames.EXCEPTION, "none");
<ide>
<del> private static final KeyValue URI_EXPANDED_UNKNOWN = KeyValue.of(HttpRequestsObservation.HighCardinalityKeyNames.HTTP_URL, "UNKNOWN");
<add> private static final KeyValue HTTP_URL_UNKNOWN = KeyValue.of(HttpRequestsObservation.HighCardinalityKeyNames.HTTP_URL, "UNKNOWN");
<ide>
<ide> private final String name;
<ide>
<ide> protected KeyValue outcome(HttpRequestsObservationContext context) {
<ide>
<ide> protected KeyValue uriExpanded(HttpRequestsObservationContext context) {
<ide> if (context.getCarrier() != null) {
<del> String uriExpanded = (context.getCarrier().getPathInfo() != null) ? context.getCarrier().getPathInfo() : "/";
<del> return KeyValue.of(HttpRequestsObservation.HighCardinalityKeyNames.HTTP_URL, uriExpanded);
<add> return KeyValue.of(HttpRequestsObservation.HighCardinalityKeyNames.HTTP_URL, context.getCarrier().getRequestURI());
<ide> }
<del> return URI_EXPANDED_UNKNOWN;
<add> return HTTP_URL_UNKNOWN;
<ide> }
<ide>
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/web/observation/reactive/DefaultHttpRequestsObservationConvention.java
<ide> public class DefaultHttpRequestsObservationConvention implements HttpRequestsObs
<ide>
<ide> private static final KeyValue EXCEPTION_NONE = KeyValue.of(HttpRequestsObservation.LowCardinalityKeyNames.EXCEPTION, "none");
<ide>
<del> private static final KeyValue URI_EXPANDED_UNKNOWN = KeyValue.of(HttpRequestsObservation.HighCardinalityKeyNames.HTTP_URL, "UNKNOWN");
<add> private static final KeyValue HTTP_URL_UNKNOWN = KeyValue.of(HttpRequestsObservation.HighCardinalityKeyNames.HTTP_URL, "UNKNOWN");
<ide>
<ide> private final String name;
<ide>
<ide> public KeyValues getLowCardinalityKeyValues(HttpRequestsObservationContext conte
<ide>
<ide> @Override
<ide> public KeyValues getHighCardinalityKeyValues(HttpRequestsObservationContext context) {
<del> return KeyValues.of(uriExpanded(context));
<add> return KeyValues.of(httpUrl(context));
<ide> }
<ide>
<ide> protected KeyValue method(HttpRequestsObservationContext context) {
<ide> protected KeyValue outcome(HttpRequestsObservationContext context) {
<ide> return HttpOutcome.UNKNOWN.asKeyValue();
<ide> }
<ide>
<del> protected KeyValue uriExpanded(HttpRequestsObservationContext context) {
<add> protected KeyValue httpUrl(HttpRequestsObservationContext context) {
<ide> if (context.getCarrier() != null) {
<ide> String uriExpanded = context.getCarrier().getPath().toString();
<ide> return KeyValue.of(HttpRequestsObservation.HighCardinalityKeyNames.HTTP_URL, uriExpanded);
<ide> }
<del> return URI_EXPANDED_UNKNOWN;
<add> return HTTP_URL_UNKNOWN;
<ide> }
<ide>
<ide> }
<ide><path>spring-web/src/test/java/org/springframework/web/observation/DefaultHttpRequestsObservationConventionTests.java
<ide> void supportsOnlyHttpRequestsObservationContext() {
<ide> void addsKeyValuesForExchange() {
<ide> this.request.setMethod("POST");
<ide> this.request.setRequestURI("/test/resource");
<del> this.request.setPathInfo("/test/resource");
<ide>
<ide> assertThat(this.convention.getLowCardinalityKeyValues(this.context)).hasSize(5)
<ide> .contains(KeyValue.of("method", "POST"), KeyValue.of("uri", "UNKNOWN"), KeyValue.of("status", "200"),
<ide> void addsKeyValuesForExchange() {
<ide> @Test
<ide> void addsKeyValuesForExchangeWithPathPattern() {
<ide> this.request.setRequestURI("/test/resource");
<del> this.request.setPathInfo("/test/resource");
<ide> this.context.setPathPattern("/test/{name}");
<ide>
<ide> assertThat(this.convention.getLowCardinalityKeyValues(this.context)).hasSize(5)
<ide> void addsKeyValuesForExchangeWithPathPattern() {
<ide> @Test
<ide> void addsKeyValuesForErrorExchange() {
<ide> this.request.setRequestURI("/test/resource");
<del> this.request.setPathInfo("/test/resource");
<ide> this.context.setError(new IllegalArgumentException("custom error"));
<ide> this.response.setStatus(500);
<ide>
<ide> void addsKeyValuesForErrorExchange() {
<ide> @Test
<ide> void addsKeyValuesForRedirectExchange() {
<ide> this.request.setRequestURI("/test/redirect");
<del> this.request.setPathInfo("/test/redirect");
<ide> this.response.setStatus(302);
<ide> this.response.addHeader("Location", "https://example.org/other");
<ide>
<ide> void addsKeyValuesForRedirectExchange() {
<ide> @Test
<ide> void addsKeyValuesForNotFoundExchange() {
<ide> this.request.setRequestURI("/test/notFound");
<del> this.request.setPathInfo("/test/notFound");
<ide> this.response.setStatus(404);
<ide>
<ide> assertThat(this.convention.getLowCardinalityKeyValues(this.context)).hasSize(5)
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultClientObservationConvention.java
<ide> public class DefaultClientObservationConvention implements ClientObservationConv
<ide>
<ide> private static final KeyValue EXCEPTION_NONE = KeyValue.of(ClientObservation.LowCardinalityKeyNames.EXCEPTION, "none");
<ide>
<del> private static final KeyValue URI_EXPANDED_NONE = KeyValue.of(ClientHttpObservation.HighCardinalityKeyNames.HTTP_URL, "none");
<add> private static final KeyValue HTTP_URL_NONE = KeyValue.of(ClientHttpObservation.HighCardinalityKeyNames.HTTP_URL, "none");
<ide>
<ide> private static final KeyValue CLIENT_NAME_NONE = KeyValue.of(ClientHttpObservation.HighCardinalityKeyNames.CLIENT_NAME, "none");
<ide>
<ide> protected KeyValue outcome(ClientObservationContext context) {
<ide>
<ide> @Override
<ide> public KeyValues getHighCardinalityKeyValues(ClientObservationContext context) {
<del> return KeyValues.of(uriExpanded(context), clientName(context));
<add> return KeyValues.of(httpUrl(context), clientName(context));
<ide> }
<ide>
<del> protected KeyValue uriExpanded(ClientObservationContext context) {
<add> protected KeyValue httpUrl(ClientObservationContext context) {
<ide> if (context.getCarrier() != null) {
<ide> return KeyValue.of(ClientObservation.HighCardinalityKeyNames.HTTP_URL, context.getCarrier().url().toASCIIString());
<ide> }
<del> return URI_EXPANDED_NONE;
<add> return HTTP_URL_NONE;
<ide> }
<ide>
<ide> protected KeyValue clientName(ClientObservationContext context) { | 5 |
PHP | PHP | fix coding style | 1ebb2ed0a0d2d710e54fb436c943ceef3ff37fcd | <ide><path>lib/Cake/View/View.php
<ide> public function renderCache($filename, $timeStart) {
<ide> //@codingStandardsIgnoreStart
<ide> @unlink($filename);
<ide> //@codingStandardsIgnoreEnd
<del> unset ($out);
<add> unset($out);
<ide> return false;
<ide> } else {
<ide> if ($this->layout === 'xml') { | 1 |
Go | Go | fix typo in client/errors.go comments | a68ba6be5d5e3341bb1deca52329d1a8aa6c024d | <ide><path>client/errors.go
<ide> type imageNotFoundError struct {
<ide> imageID string
<ide> }
<ide>
<del>// NoFound indicates that this error type is of NotFound
<add>// NotFound indicates that this error type is of NotFound
<ide> func (e imageNotFoundError) NotFound() bool {
<ide> return true
<ide> }
<ide> type containerNotFoundError struct {
<ide> containerID string
<ide> }
<ide>
<del>// NoFound indicates that this error type is of NotFound
<add>// NotFound indicates that this error type is of NotFound
<ide> func (e containerNotFoundError) NotFound() bool {
<ide> return true
<ide> }
<ide> type networkNotFoundError struct {
<ide> networkID string
<ide> }
<ide>
<del>// NoFound indicates that this error type is of NotFound
<add>// NotFound indicates that this error type is of NotFound
<ide> func (e networkNotFoundError) NotFound() bool {
<ide> return true
<ide> }
<ide> type volumeNotFoundError struct {
<ide> volumeID string
<ide> }
<ide>
<del>// NoFound indicates that this error type is of NotFound
<add>// NotFound indicates that this error type is of NotFound
<ide> func (e volumeNotFoundError) NotFound() bool {
<ide> return true
<ide> }
<ide>
<del>// Error returns a string representation of a networkNotFoundError
<add>// Error returns a string representation of a volumeNotFoundError
<ide> func (e volumeNotFoundError) Error() string {
<ide> return fmt.Sprintf("Error: No such volume: %s", e.volumeID)
<ide> }
<ide> func (e nodeNotFoundError) Error() string {
<ide> return fmt.Sprintf("Error: No such node: %s", e.nodeID)
<ide> }
<ide>
<del>// NoFound indicates that this error type is of NotFound
<add>// NotFound indicates that this error type is of NotFound
<ide> func (e nodeNotFoundError) NotFound() bool {
<ide> return true
<ide> }
<ide> func (e serviceNotFoundError) Error() string {
<ide> return fmt.Sprintf("Error: No such service: %s", e.serviceID)
<ide> }
<ide>
<del>// NoFound indicates that this error type is of NotFound
<add>// NotFound indicates that this error type is of NotFound
<ide> func (e serviceNotFoundError) NotFound() bool {
<ide> return true
<ide> }
<ide> func (e taskNotFoundError) Error() string {
<ide> return fmt.Sprintf("Error: No such task: %s", e.taskID)
<ide> }
<ide>
<del>// NoFound indicates that this error type is of NotFound
<add>// NotFound indicates that this error type is of NotFound
<ide> func (e taskNotFoundError) NotFound() bool {
<ide> return true
<ide> } | 1 |
Python | Python | handle unknown tags in koreantokenizer tag map | e908a67829e546d1dc9f93aa409b8bcf8939f758 | <ide><path>spacy/lang/ko/__init__.py
<ide> from ...language import Language, BaseDefaults
<ide> from ...tokens import Doc
<ide> from ...scorer import Scorer
<del>from ...symbols import POS
<add>from ...symbols import POS, X
<ide> from ...training import validate_examples
<ide> from ...util import DummyTokenizer, registry, load_config_from_str
<ide> from ...vocab import Vocab
<ide> def __call__(self, text: str) -> Doc:
<ide> for token, dtoken in zip(doc, dtokens):
<ide> first_tag, sep, eomi_tags = dtoken["tag"].partition("+")
<ide> token.tag_ = first_tag # stem(어간) or pre-final(선어말 어미)
<del> token.pos = TAG_MAP[token.tag_][POS]
<add> if token.tag_ in TAG_MAP:
<add> token.pos = TAG_MAP[token.tag_][POS]
<add> else:
<add> token.pos = X
<ide> token.lemma_ = dtoken["lemma"]
<ide> doc.user_data["full_tags"] = [dt["tag"] for dt in dtokens]
<ide> return doc
<ide><path>spacy/tests/lang/ko/test_tokenizer.py
<ide> def test_ko_empty_doc(ko_tokenizer):
<ide> assert len(tokens) == 0
<ide>
<ide>
<add>@pytest.mark.issue(10535)
<add>def test_ko_tokenizer_unknown_tag(ko_tokenizer):
<add> tokens = ko_tokenizer("미닛 리피터")
<add> assert tokens[1].pos_ == "X"
<add>
<add>
<ide> # fmt: off
<ide> SPACY_TOKENIZER_TESTS = [
<ide> ("있다.", "있다 ."), | 2 |
Javascript | Javascript | add missing semicolon in rollercoaster | 98da28a50e97792e1e9a3746266c88028f65fb41 | <ide><path>examples/js/RollerCoaster.js
<ide> var RollerCoasterLiftersGeometry = function ( curve, size ) {
<ide> var point1 = shape[ j ];
<ide> var point2 = shape[ ( j + 1 ) % jl ];
<ide>
<del> vector1.copy( point1 )
<add> vector1.copy( point1 );
<ide> vector1.applyQuaternion( quaternion );
<ide> vector1.add( fromPoint );
<ide>
<del> vector2.copy( point2 )
<add> vector2.copy( point2 );
<ide> vector2.applyQuaternion( quaternion );
<ide> vector2.add( fromPoint );
<ide>
<del> vector3.copy( point2 )
<add> vector3.copy( point2 );
<ide> vector3.applyQuaternion( quaternion );
<ide> vector3.add( toPoint );
<ide>
<del> vector4.copy( point1 )
<add> vector4.copy( point1 );
<ide> vector4.applyQuaternion( quaternion );
<ide> vector4.add( toPoint );
<ide> | 1 |
Python | Python | remove old example | e44bbb53616e07ffcf855e7dea7bee9e3011d9da | <ide><path>examples/training/load_ner.py
<del># Load NER
<del>from __future__ import unicode_literals
<del>import spacy
<del>import pathlib
<del>from spacy.pipeline import EntityRecognizer
<del>from spacy.vocab import Vocab
<del>
<del>def load_model(model_dir):
<del> model_dir = pathlib.Path(model_dir)
<del> nlp = spacy.load('en', parser=False, entity=False, add_vectors=False)
<del> with (model_dir / 'vocab' / 'strings.json').open('r', encoding='utf8') as file_:
<del> nlp.vocab.strings.load(file_)
<del> nlp.vocab.load_lexemes(model_dir / 'vocab' / 'lexemes.bin')
<del> ner = EntityRecognizer.load(model_dir, nlp.vocab, require=True)
<del> return (nlp, ner)
<del>
<del>(nlp, ner) = load_model('ner')
<del>doc = nlp.make_doc('Who is Shaka Khan?')
<del>nlp.tagger(doc)
<del>ner(doc)
<del>for word in doc:
<del> print(word.text, word.orth, word.lower, word.tag_, word.ent_type_, word.ent_iob) | 1 |
PHP | PHP | fix invalid key in translatorregistry | 703f8a4240a71ec0db9d9bd19a3df2b0af37341d | <ide><path>src/I18n/TranslatorRegistry.php
<ide> public function get($name, $locale = null)
<ide> return $this->registry[$name][$locale] = $this->_getTranslator($name, $locale);
<ide> }
<ide>
<del> $key = "translations.$name.$locale";
<add> // Cache keys cannot contain / if they go to file engine.
<add> $keyName = str_replace('/', '.', $name);
<add> $key = "translations.{$keyName}.{$locale}";
<ide> $translator = $this->_cacher->get($key);
<ide> if (!$translator || !$translator->getPackage()) {
<ide> $translator = $this->_getTranslator($name, $locale); | 1 |
Python | Python | add test_connection method to trino hook | 122d2f69bbf39c445ddcaa5a9c09a9ea86434a55 | <ide><path>airflow/providers/trino/hooks/trino.py
<ide> def insert_rows(
<ide> commit_every = 0
<ide>
<ide> super().insert_rows(table, rows, target_fields, commit_every, replace)
<add>
<add> def test_connection(self):
<add> """Tests the connection from UI using Trino specific query"""
<add> status, message = False, ''
<add> try:
<add> with closing(self.get_conn()) as conn:
<add> with closing(conn.cursor()) as cur:
<add> cur.execute("select 1")
<add> if cur.fetchone():
<add> status = True
<add> message = 'Connection successfully tested'
<add> except Exception as e:
<add> status = False
<add> message = str(e)
<add>
<add> return status, message
<ide><path>tests/providers/trino/hooks/test_trino.py
<ide> def test_run(self, mock_run):
<ide> self.db_hook.run(sql, autocommit, parameters, list)
<ide> mock_run.assert_called_once_with(sql, autocommit, parameters, handler)
<ide>
<add> def test_connection_success(self):
<add> status, msg = self.db_hook.test_connection()
<add> assert status is True
<add> assert msg == 'Connection successfully tested'
<add>
<add> @patch('airflow.providers.trino.hooks.trino.TrinoHook.get_conn')
<add> def test_connection_failure(self, mock_conn):
<add> mock_conn.side_effect = Exception('Test')
<add> self.db_hook.get_conn = mock_conn
<add> status, msg = self.db_hook.test_connection()
<add> assert status is False
<add> assert msg == 'Test'
<add>
<ide>
<ide> class TestTrinoHookIntegration(unittest.TestCase):
<ide> @pytest.mark.integration("trino") | 2 |
PHP | PHP | remove unused use | 7bd077e01692c04329c26148c54f648c3151d5d4 | <ide><path>src/Illuminate/Broadcasting/BroadcastEvent.php
<ide> <?php namespace Illuminate\Broadcasting;
<ide>
<del>use Pusher;
<ide> use ReflectionClass;
<ide> use ReflectionProperty;
<ide> use Illuminate\Contracts\Queue\Job;
<ide><path>src/Illuminate/Console/Command.php
<ide> use Symfony\Component\Console\Input\InputInterface;
<ide> use Symfony\Component\Console\Output\OutputInterface;
<ide> use Symfony\Component\Console\Question\ChoiceQuestion;
<del>use Symfony\Component\Console\Question\ConfirmationQuestion;
<ide> use Illuminate\Contracts\Foundation\Application as LaravelApplication;
<ide>
<ide> class Command extends \Symfony\Component\Console\Command\Command {
<ide><path>src/Illuminate/Foundation/Auth/AuthenticatesAndRegistersUsers.php
<ide>
<ide> use Illuminate\Http\Request;
<ide> use Illuminate\Support\Facades\Auth;
<del>use Illuminate\Contracts\Auth\Guard;
<del>use Illuminate\Contracts\Auth\Registrar;
<ide>
<ide> trait AuthenticatesAndRegistersUsers {
<ide>
<ide><path>src/Illuminate/Session/SessionManager.php
<ide> <?php namespace Illuminate\Session;
<ide>
<del>use InvalidArgumentException;
<ide> use Illuminate\Support\Manager;
<ide> use Symfony\Component\HttpFoundation\Session\Storage\Handler\NullSessionHandler;
<ide>
<ide><path>src/Illuminate/Support/Collection.php
<ide> <?php namespace Illuminate\Support;
<ide>
<del>use Closure;
<ide> use Countable;
<ide> use ArrayAccess;
<ide> use ArrayIterator; | 5 |
Text | Text | fix changelog entry position [ci skip] | ccb009511685adac1d14d3c1e07dde640d0d7042 | <ide><path>activesupport/CHANGELOG.md
<del>## Rails 5.1.0.beta1 (February 23, 2017) ##
<del>
<ide> * `ActiveSupport::Gzip.decompress` now checks checksum and length in footer.
<ide>
<ide> *Dylan Thacker-Smith*
<ide>
<add>
<add>## Rails 5.1.0.beta1 (February 23, 2017) ##
<add>
<ide> * Cache `ActiveSupport::TimeWithZone#to_datetime` before freezing.
<ide>
<ide> *Adam Rice* | 1 |
Javascript | Javascript | fix plugin typos in options validation | 36b7f21b92cd4dbcece4fba3f7bf9dc0b109db56 | <ide><path>lib/WebpackOptionsValidationError.js
<ide> WebpackOptionsValidationError.formatValidationError = function formatValidationE
<ide> "The 'debug' property was removed in webpack 2.\n" +
<ide> "Loaders should be updated to allow passing this option via loader options in module.rules.\n" +
<ide> "Until loaders are updated one can use the LoaderOptionsPlugin to switch loaders into debug mode:\n" +
<del> "plugins: {\n" +
<add> "plugins: [\n" +
<ide> " new webpack.LoaderOptionsPlugin({\n" +
<ide> " debug: true\n" +
<ide> " })\n" +
<del> "}";
<add> "]";
<ide> }
<ide> return baseMessage + "\n" +
<ide> "For typos: please correct them.\n" +
<ide> "For loader options: webpack 2 no longer allows custom properties in configuration.\n" +
<ide> " Loaders should be updated to allow passing options via loader options in module.rules.\n" +
<ide> " Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:\n" +
<del> " plugins: {\n" +
<add> " plugins: [\n" +
<ide> " new webpack.LoaderOptionsPlugin({\n" +
<ide> " // test: /\\.xxx$/, // may apply this only for some modules\n" +
<ide> " options: {\n" +
<ide> " " + err.params.additionalProperty + ": ...\n" +
<ide> " }\n" +
<ide> " })\n" +
<del> " }";
<add> " ]";
<ide> }
<ide> return baseMessage;
<ide> case "oneOf":
<ide><path>test/Validation.test.js
<ide> describe("Validation", function() {
<ide> " For loader options: webpack 2 no longer allows custom properties in configuration.",
<ide> " Loaders should be updated to allow passing options via loader options in module.rules.",
<ide> " Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:",
<del> " plugins: {",
<add> " plugins: [",
<ide> " new webpack.LoaderOptionsPlugin({",
<ide> " // test: /\\.xxx$/, // may apply this only for some modules",
<ide> " options: {",
<ide> " postcss: ...",
<ide> " }",
<ide> " })",
<del> " }"
<add> " ]"
<ide> ]
<ide> }];
<ide> testCases.forEach(function(testCase) { | 2 |
Ruby | Ruby | fix bad const override | 5e6d5f68cacc5e0dbcd130ca62b811edd66bfe96 | <ide><path>Library/Homebrew/test/download_strategies/curl_github_packages_spec.rb
<ide> let(:url) { "https://#{GitHubPackages::URL_DOMAIN}/v2/homebrew/core/spec_test/manifests/1.2.3" }
<ide> let(:version) { "1.2.3" }
<ide> let(:specs) { {} }
<add> let(:authorization) { nil }
<ide>
<ide> describe "#fetch" do
<ide> before do
<add> stub_const("HOMEBREW_GITHUB_PACKAGES_AUTH", authorization) if authorization.present?
<ide> strategy.temporary_path.dirname.mkpath
<ide> FileUtils.touch strategy.temporary_path
<ide> end
<ide> context "with Github Packages authentication defined" do
<ide> let(:authorization) { "Bearer dead-beef-cafe" }
<ide>
<del> before do
<del> HOMEBREW_GITHUB_PACKAGES_AUTH = authorization.freeze
<del> end
<del>
<ide> it "calls curl with the provided header value" do
<ide> expect(strategy).to receive(:system_command).with(
<ide> /curl/, | 1 |
Javascript | Javascript | increase test timeout in examples.test | f3fc2e63c31858119255cece99bca9aeef08bbf3 | <ide><path>test/Examples.test.js
<ide> describe("Examples", () => {
<ide> done();
<ide> });
<ide> },
<del> 30000
<add> 45000
<ide> );
<ide> });
<ide> }); | 1 |
Python | Python | push fix to training | a049c8043b65ffed887e661b3b0506eb7a8c8c50 | <ide><path>examples/run_glue.py
<ide> def train(args, train_dataset, model, tokenizer):
<ide>
<ide> tr_loss += loss.item()
<ide> if (step + 1) % args.gradient_accumulation_steps == 0:
<del> scheduler.step() # Update learning rate schedule
<ide> optimizer.step()
<add> scheduler.step() # Update learning rate schedule
<ide> model.zero_grad()
<ide> global_step += 1
<ide>
<ide><path>examples/run_tf_glue.py
<add>import tensorflow as tf
<add>import tensorflow_datasets
<add>from pytorch_transformers import BertTokenizer, BertForSequenceClassification, TFBertForSequenceClassification, glue_convert_examples_to_features
<add>
<add># Load tokenizer, model, dataset
<add>tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
<add>tf_model = TFBertForSequenceClassification.from_pretrained('bert-base-cased')
<add>dataset = tensorflow_datasets.load("glue/mrpc")
<add>
<add># Prepare dataset for GLUE
<add>train_dataset = glue_convert_examples_to_features(dataset['train'], tokenizer, task='mrpc', max_length=128)
<add>valid_dataset = glue_convert_examples_to_features(dataset['validation'], tokenizer, task='mrpc', max_length=128)
<add>train_dataset = train_dataset.shuffle(100).batch(32).repeat(3)
<add>valid_dataset = valid_dataset.batch(64)
<add>
<add># Compile tf.keras model for training
<add>learning_rate = tf.keras.optimizers.schedules.PolynomialDecay(2e-5, 345, end_learning_rate=0)
<add>loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
<add>tf_model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=learning_rate, epsilon=1e-08, clipnorm=1.0),
<add> loss=loss, metrics=['sparse_categorical_accuracy'])
<add>
<add># Train and evaluate using tf.keras.Model.fit()
<add>tf_model.fit(train_dataset, epochs=3, steps_per_epoch=115, validation_data=valid_dataset, validation_steps=7)
<add>
<add># Save the model and load it in PyTorch
<add>tf_model.save_pretrained('./runs/')
<add>pt_model = BertForSequenceClassification.from_pretrained('./runs/')
<add>
<add># Quickly inspect a few predictions
<add>
<add>
<add># Divers
<add>import torch
<add>
<add>import tensorflow as tf
<add>import tensorflow_datasets
<add>from pytorch_transformers import BertTokenizer, BertForSequenceClassification, TFBertForSequenceClassification, glue_convert_examples_to_features
<add>
<add># Load tokenizer, model, dataset
<add>tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
<add>model = TFBertForSequenceClassification.from_pretrained('bert-base-cased')
<add>
<add>pt_train_dataset = torch.load('../../data/glue_data//MRPC/cached_train_bert-base-cased_128_mrpc')
<add>
<add>def gen():
<add> for el in pt_train_dataset:
<add> yield ((el.input_ids, el.attention_mask, el.token_type_ids), (el.label,))
<add>
<add>dataset = tf.data.Dataset.from_generator(gen,
<add> ((tf.int32, tf.int32, tf.int32), (tf.int64,)),
<add> ((tf.TensorShape([None]), tf.TensorShape([None]), tf.TensorShape([None])),
<add> (tf.TensorShape([]),)))
<add>
<add>dataset = dataset.shuffle(100).batch(32)
<add>next(iter(dataset))
<add>
<add>learning_rate = tf.keras.optimizers.schedules.PolynomialDecay(2e-5, 345, 0)
<add>loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
<add>model.compile(optimizer=tf.keras.optimizers.Adam(
<add> learning_rate=learning_rate,
<add> epsilon=1e-08,
<add> clipnorm=1.0),
<add> loss=loss,
<add> metrics=[['sparse_categorical_accuracy']])
<add>
<add>tensorboard_cbk = tf.keras.callbacks.TensorBoard(log_dir='./runs/', update_freq=10, histogram_freq=1)
<add>
<add># Train model
<add>model.fit(dataset, epochs=3, callbacks=[tensorboard_cbk])
<ide><path>pytorch_transformers/configuration_utils.py
<ide> def save_pretrained(self, save_directory):
<ide> output_config_file = os.path.join(save_directory, CONFIG_NAME)
<ide>
<ide> self.to_json_file(output_config_file)
<add> logger.info("Configuration saved in {}".format(output_config_file))
<ide>
<ide> @classmethod
<ide> def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
<ide><path>pytorch_transformers/data/processors/utils.py
<ide> import csv
<ide> import sys
<ide> import copy
<add>import json
<ide>
<ide> class InputExample(object):
<ide> """A single training/test example for simple sequence classification."""
<ide><path>pytorch_transformers/modeling_tf_utils.py
<ide> def save_pretrained(self, save_directory):
<ide>
<ide> # If we save using the predefined names, we can load using `from_pretrained`
<ide> output_model_file = os.path.join(save_directory, TF2_WEIGHTS_NAME)
<del>
<ide> self.save_weights(output_model_file)
<add> logger.info("Model weights saved in {}".format(output_model_file))
<ide>
<ide> @classmethod
<ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
<ide><path>pytorch_transformers/modeling_utils.py
<ide> def save_pretrained(self, save_directory):
<ide>
<ide> # If we save using the predefined names, we can load using `from_pretrained`
<ide> output_model_file = os.path.join(save_directory, WEIGHTS_NAME)
<del>
<ide> torch.save(model_to_save.state_dict(), output_model_file)
<add> logger.info("Model weights saved in {}".format(output_model_file))
<ide>
<ide> @classmethod
<ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
<ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
<ide> archive_file = os.path.join(pretrained_model_name_or_path, WEIGHTS_NAME)
<ide> else:
<ide> raise EnvironmentError("Error no file named {} found in directory {}".format(
<del> tuple(WEIGHTS_NAME, TF2_WEIGHTS_NAME, TF_WEIGHTS_NAME + ".index"),
<add> [WEIGHTS_NAME, TF2_WEIGHTS_NAME, TF_WEIGHTS_NAME + ".index"],
<ide> pretrained_model_name_or_path))
<ide> elif os.path.isfile(pretrained_model_name_or_path):
<ide> archive_file = pretrained_model_name_or_path | 6 |
Javascript | Javascript | fix typo in example | 2d6c218327c6361fde62efa5c019b49cfeef5c42 | <ide><path>src/ngMock/angular-mocks.js
<ide> angular.mock.$RootElementProvider = function() {
<ide> *
<ide> * myMod.controller('MyDirectiveController', ['$log', function($log) {
<ide> * $log.info(this.name);
<del> * })];
<add> * }]);
<ide> *
<ide> *
<ide> * // In a test ... | 1 |
Python | Python | remove unused train code | ed2aff2db346d7be9d94e73e0e2e2921cf966ccf | <ide><path>spacy/cli/train.py
<ide> from ..training.example import Example
<ide> from ..training.initialize import must_initialize, init_pipeline
<ide> from ..errors import Errors
<del>from ..util import dot_to_object
<add>from ..util import resolve_dot_names
<ide>
<ide>
<ide> @app.command(
<ide> def update_meta(
<ide> nlp.meta["performance"][f"{pipe_name}_loss"] = info["losses"][pipe_name]
<ide>
<ide>
<del>def load_from_paths(
<del> config: Config,
<del>) -> Tuple[List[Dict[str, str]], Dict[str, dict], bytes]:
<del> # TODO: separate checks from loading
<del> raw_text = util.ensure_path(config["training"]["raw_text"])
<del> if raw_text is not None:
<del> if not raw_text.exists():
<del> msg.fail("Can't find raw text", raw_text, exits=1)
<del> raw_text = list(srsly.read_jsonl(config["training"]["raw_text"]))
<del> tag_map = {}
<del> morph_rules = {}
<del> weights_data = None
<del> init_tok2vec = util.ensure_path(config["training"]["init_tok2vec"])
<del> if init_tok2vec is not None:
<del> if not init_tok2vec.exists():
<del> msg.fail("Can't find pretrained tok2vec", init_tok2vec, exits=1)
<del> with init_tok2vec.open("rb") as file_:
<del> weights_data = file_.read()
<del> return raw_text, tag_map, morph_rules, weights_data
<del>
<del>
<ide> def verify_cli_args(config_path: Path, output_path: Optional[Path] = None) -> None:
<ide> # Make sure all files and paths exists if they are needed
<ide> if not config_path or not config_path.exists(): | 1 |
PHP | PHP | fix failing test | 00edc594bf2304d7b36ee36df32760c61a63f004 | <ide><path>lib/Cake/Test/Case/Utility/DebuggerTest.php
<ide> public function testDump() {
<ide> ob_start();
<ide> Debugger::dump($var);
<ide> $result = ob_get_clean();
<add>
<add> $open = php_sapi_name() == 'cli' ? "\n" : '<pre>';
<add> $close = php_sapi_name() == 'cli' ? "\n" : '</pre>';
<ide> $expected = <<<TEXT
<del><pre>array(
<add>{$open}array(
<ide> 'People' => array(
<ide> (int) 0 => array(
<ide> 'name' => 'joeseph',
<ide> public function testDump() {
<ide> 'hair' => 'black'
<ide> )
<ide> )
<del>)</pre>
<add>){$close}
<ide> TEXT;
<ide> $this->assertTextEquals($expected, $result);
<ide> } | 1 |
Python | Python | fix two tests that were setup incorrectly | bd1d6a5d51cda6fdac6986669962e6e79f425656 | <ide><path>numpy/core/tests/test_function_base.py
<ide> def __init__(self, data):
<ide>
<ide> @property
<ide> def __array_interface__(self):
<del> # Ideally should be `'shape': ()` but the current interface
<del> # does not allow that
<del> return {'shape': (1,), 'typestr': '<i4', 'data': self._data,
<add> return {'shape': (), 'typestr': '<i4', 'data': self._data,
<ide> 'version': 3}
<ide>
<ide> def __mul__(self, other):
<ide><path>numpy/lib/tests/test_histograms.py
<ide> def test_unsigned_monotonicity_check(self):
<ide> def test_object_array_of_0d(self):
<ide> # gh-7864
<ide> assert_raises(ValueError,
<del> histogram, [np.array([0.4]) for i in range(10)] + [-np.inf])
<add> histogram, [np.array(0.4) for i in range(10)] + [-np.inf])
<ide> assert_raises(ValueError,
<del> histogram, [np.array([0.4]) for i in range(10)] + [np.inf])
<add> histogram, [np.array(0.4) for i in range(10)] + [np.inf])
<ide>
<ide> # these should not crash
<del> np.histogram([np.array([0.5]) for i in range(10)] + [.500000000000001])
<del> np.histogram([np.array([0.5]) for i in range(10)] + [.5])
<add> np.histogram([np.array(0.5) for i in range(10)] + [.500000000000001])
<add> np.histogram([np.array(0.5) for i in range(10)] + [.5])
<ide>
<ide> def test_some_nan_values(self):
<ide> # gh-7503 | 2 |
Text | Text | replace arraybufferview in crypto | def6072f3a8eeffaa8fd48e9088c50490c647765 | <ide><path>doc/api/crypto.md
<ide> added: v7.10.0
<ide> changes:
<ide> - version: v9.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/15231
<del> description: The `buffer` argument may be any ArrayBufferView
<add> description: The `buffer` argument may be any `TypedArray` or `DataView`.
<ide> -->
<ide>
<del>* `buffer` {Buffer|Uint8Array|ArrayBufferView} Must be supplied.
<add>* `buffer` {Buffer|TypedArray|DataView} Must be supplied.
<ide> * `offset` {number} Defaults to `0`.
<ide> * `size` {number} Defaults to `buffer.length - offset`.
<ide>
<ide> added: v7.10.0
<ide> changes:
<ide> - version: v9.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/15231
<del> description: The `buffer` argument may be any ArrayBufferView
<add> description: The `buffer` argument may be any `TypedArray` or `DataView`.
<ide> -->
<ide>
<del>* `buffer` {Buffer|Uint8Array|ArrayBufferView} Must be supplied.
<add>* `buffer` {Buffer|TypedArray|DataView} Must be supplied.
<ide> * `offset` {number} Defaults to `0`.
<ide> * `size` {number} Defaults to `buffer.length - offset`.
<ide> * `callback` {Function} `function(err, buf) {}`. | 1 |
Text | Text | clarify documentation by removing charged words | b0743dda8c0073df240907caf4e684b27cf13a39 | <ide><path>guides/source/active_record_basics.md
<ide> NOTE: While these column names are optional, they are in fact reserved by Active
<ide> Creating Active Record Models
<ide> -----------------------------
<ide>
<del>It is very easy to create Active Record models. All you have to do is to
<del>subclass the `ApplicationRecord` class and you're good to go:
<add>To create Active Record models, subclass the `ApplicationRecord` class and you're good to go:
<ide>
<ide> ```ruby
<ide> class Product < ApplicationRecord
<ide><path>guides/source/active_record_callbacks.md
<ide> The callback only runs when all the `:if` conditions and none of the `:unless` c
<ide> Callback Classes
<ide> ----------------
<ide>
<del>Sometimes the callback methods that you'll write will be useful enough to be reused by other models. Active Record makes it possible to create classes that encapsulate the callback methods, so it becomes very easy to reuse them.
<add>Sometimes the callback methods that you'll write will be useful enough to be reused by other models. Active Record makes it possible to create classes that encapsulate the callback methods, so they can be reused.
<ide>
<ide> Here's an example where we create a class with an `after_destroy` callback for a `PictureFile` model:
<ide>
<ide><path>guides/source/active_record_migrations.md
<ide> Active Record Migrations
<ide>
<ide> Migrations are a feature of Active Record that allows you to evolve your
<ide> database schema over time. Rather than write schema modifications in pure SQL,
<del>migrations allow you to use an easy Ruby DSL to describe changes to your
<del>tables.
<add>migrations allow you to use a Ruby DSL to describe changes to your tables.
<ide>
<ide> After reading this guide, you will know:
<ide>
<ide> Migration Overview
<ide>
<ide> Migrations are a convenient way to
<ide> [alter your database schema over time](https://en.wikipedia.org/wiki/Schema_migration)
<del>in a consistent and easy way. They use a Ruby DSL so that you don't have to
<add>in a consistent way. They use a Ruby DSL so that you don't have to
<ide> write SQL by hand, allowing your schema and changes to be database independent.
<ide>
<ide> You can think of each migration as being a new 'version' of the database. A
<ide> NOTE: Active Record only supports single column foreign keys. `execute` and
<ide> `structure.sql` are required to use composite foreign keys. See
<ide> [Schema Dumping and You](#schema-dumping-and-you).
<ide>
<del>Removing a foreign key is easy as well:
<add>Foreign keys can also be removed:
<ide>
<ide> ```ruby
<ide> # let Active Record figure out the column name
<ide> $ rails db:migrate:redo STEP=3
<ide> ```
<ide>
<ide> Neither of these rails commands do anything you could not do with `db:migrate`. They
<del>are simply more convenient, since you do not need to explicitly specify the
<add>are there for convenience, since you do not need to explicitly specify the
<ide> version to migrate to.
<ide>
<ide> ### Setup the Database
<ide> end
<ide> ```
<ide>
<ide> To add initial data after a database is created, Rails has a built-in
<del>'seeds' feature that makes the process quick and easy. This is especially
<add>'seeds' feature that speeds up the process. This is especially
<ide> useful when reloading the database frequently in development and test environments.
<del>It's easy to get started with this feature: just fill up `db/seeds.rb` with some
<add>To get started with this feature, fill up `db/seeds.rb` with some
<ide> Ruby code, and run `rails db:seed`:
<ide>
<ide> ```ruby
<ide><path>guides/source/active_record_validations.md
<ide> database. For example, it may be important to your application to ensure that
<ide> every user provides a valid email address and mailing address. Model-level
<ide> validations are the best way to ensure that only valid data is saved into your
<ide> database. They are database agnostic, cannot be bypassed by end users, and are
<del>convenient to test and maintain. Rails makes them easy to use, provides
<del>built-in helpers for common needs, and allows you to create your own validation
<del>methods as well.
<add>convenient to test and maintain. Rails provides built-in helpers for common
<add>needs, and allows you to create your own validation methods as well.
<ide>
<ide> There are several other ways to validate data before it is saved into your
<ide> database, including native database constraints, client-side validations and
<ide> example using the `new` method, that object does not belong to the database
<ide> yet. Once you call `save` upon that object it will be saved into the
<ide> appropriate database table. Active Record uses the `new_record?` instance
<ide> method to determine whether an object is already in the database or not.
<del>Consider the following simple Active Record class:
<add>Consider the following Active Record class:
<ide>
<ide> ```ruby
<ide> class Person < ApplicationRecord
<ide> database only if the object is valid:
<ide>
<ide> The bang versions (e.g. `save!`) raise an exception if the record is invalid.
<ide> The non-bang versions don't: `save` and `update` return `false`, and
<del>`create` just returns the object.
<add>`create` returns the object.
<ide>
<ide> ### Skipping Validations
<ide>
<ide> end
<ide> # => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
<ide> ```
<ide>
<del>`invalid?` is simply the inverse of `valid?`. It triggers your validations,
<add>`invalid?` is the inverse of `valid?`. It triggers your validations,
<ide> returning true if any errors were found in the object, and false otherwise.
<ide>
<ide> ### `errors[]`
<ide> end
<ide>
<ide> This validation is very specific to web applications and this
<ide> 'acceptance' does not need to be recorded anywhere in your database. If you
<del>don't have a field for it, the helper will just create a virtual attribute. If
<add>don't have a field for it, the helper will create a virtual attribute. If
<ide> the field does exist in your database, the `accept` option must be set to
<ide> or include `true` or else the validation will not run.
<ide>
<ide> validator type.
<ide>
<ide> ### `errors[:base]`
<ide>
<del>You can add error messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of its attributes. Since `errors[:base]` is an array, you can simply add a string to it and it will be used as an error message.
<add>You can add error messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of its attributes. Since `errors[:base]` is an array, you can add a string to it and it will be used as an error message.
<ide>
<ide> ```ruby
<ide> class Person < ApplicationRecord
<ide> validations fail.
<ide> Because every application handles this kind of thing differently, Rails does
<ide> not include any view helpers to help you generate these messages directly.
<ide> However, due to the rich number of methods Rails gives you to interact with
<del>validations in general, it's fairly easy to build your own. In addition, when
<add>validations in general, you can build your own. In addition, when
<ide> generating a scaffold, Rails will put some ERB into the `_form.html.erb` that
<ide> it generates that displays the full list of errors on that model.
<ide>
<ide><path>guides/source/association_basics.md
<ide> NOTE: Using `t.bigint :supplier_id` makes the foreign key naming obvious and exp
<ide>
<ide> ### Choosing Between `has_many :through` and `has_and_belongs_to_many`
<ide>
<del>Rails offers two different ways to declare a many-to-many relationship between models. The simpler way is to use `has_and_belongs_to_many`, which allows you to make the association directly:
<add>Rails offers two different ways to declare a many-to-many relationship between models. The first way is to use `has_and_belongs_to_many`, which allows you to make the association directly:
<ide>
<ide> ```ruby
<ide> class Assembly < ApplicationRecord
<ide> Let's say we have Car, Motorcycle, and Bicycle models. We will want to share
<ide> the `color` and `price` fields and some methods for all of them, but having some
<ide> specific behavior for each, and separated controllers too.
<ide>
<del>Rails makes this quite easy. First, let's generate the base Vehicle model:
<add>First, let's generate the base Vehicle model:
<ide>
<ide> ```bash
<ide> $ rails generate model vehicle type:string color:string price:decimal{10.2}
<ide> will generate the following SQL:
<ide> INSERT INTO "vehicles" ("type", "color", "price") VALUES ('Car', 'Red', 10000)
<ide> ```
<ide>
<del>Querying car records will just search for vehicles that are cars:
<add>Querying car records will search only for vehicles that are cars:
<ide>
<ide> ```ruby
<ide> Car.all
<ide><path>guides/source/contributing_to_ruby_on_rails.md
<ide> Having a way to reproduce your issue will be very helpful for others to help con
<ide>
<ide> These templates include the boilerplate code to set up a test case against either a released version of Rails (`*_gem.rb`) or edge Rails (`*_master.rb`).
<ide>
<del>Simply copy the content of the appropriate template into a `.rb` file and make the necessary changes to demonstrate the issue. You can execute it by running `ruby the_file.rb` in your terminal. If all goes well, you should see your test case failing.
<add>Copy the content of the appropriate template into a `.rb` file and make the necessary changes to demonstrate the issue. You can execute it by running `ruby the_file.rb` in your terminal. If all goes well, you should see your test case failing.
<ide>
<del>You can then share your executable test case as a [gist](https://gist.github.com), or simply paste the content into the issue description.
<add>You can then share your executable test case as a [gist](https://gist.github.com), or paste the content into the issue description.
<ide>
<ide> ### Special Treatment for Security Issues
<ide> | 6 |
Text | Text | remove reference to stale citgm job | 48a1f75a90a402fce0664f19e1ddf77e5b281d5c | <ide><path>COLLABORATOR_GUIDE.md
<ide> for changes that only affect comments or documentation.
<ide> * [`citgm-smoker`](https://ci.nodejs.org/job/citgm-smoker/)
<ide> uses [`CitGM`](https://github.com/nodejs/citgm) to allow you to run
<ide> `npm install && npm test` on a large selection of common modules. This is
<del>useful to check whether a change will cause breakage in the ecosystem. To test
<del>Node.js ABI changes you can run [`citgm-abi-smoker`](https://ci.nodejs.org/job/citgm-abi-smoker/).
<add>useful to check whether a change will cause breakage in the ecosystem.
<ide>
<ide> * [`node-stress-single-test`](https://ci.nodejs.org/job/node-stress-single-test/)
<ide> can run a group of tests over and over on a specific platform. Use it to check | 1 |
PHP | PHP | replacearray | 16afbf8465dc54e4998e54e364fe4b0cda4a477f | <ide><path>tests/Support/SupportStrTest.php
<ide> public function testRandom()
<ide> public function testReplaceArray()
<ide> {
<ide> $this->assertEquals('foo/bar/baz', Str::replaceArray('?', ['foo', 'bar', 'baz'], '?/?/?'));
<add> $this->assertEquals('foo/bar/baz/?', Str::replaceArray('?', ['foo', 'bar', 'baz'], '?/?/?/?'));
<add> $this->assertEquals('foo/bar', Str::replaceArray('?', ['foo', 'bar', 'baz'], '?/?'));
<ide> $this->assertEquals('?/?/?', Str::replaceArray('x', ['foo', 'bar', 'baz'], '?/?/?'));
<ide> }
<ide> | 1 |
Javascript | Javascript | add types to nextconfig in default template | 0fd2f3ba98c44bb05df61b51a163081eea1644c8 | <ide><path>packages/create-next-app/templates/default/next.config.js
<del>module.exports = {
<add>/** @type {import('next').NextConfig} */
<add>const nextConfig = {
<ide> reactStrictMode: true,
<ide> }
<add>
<add>module.exports = nextConfig | 1 |
PHP | PHP | fix failing tests | f9928c018345785f47fad078b50e3f1db0f2f97e | <ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testFormControlsBlacklist()
<ide> '*/div',
<ide> '/fieldset',
<ide> ];
<del> $this->assertHtml($expected, $result, 'A falsey value (array) should not remove the input');
<add> $this->assertHtml($expected, $result, true);
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/View/Helper/HtmlHelperTest.php
<ide> public function testTableCells()
<ide> */
<ide> public function testTag()
<ide> {
<del> $result = $this->Html->tag('div');
<del> $this->assertHtml('<div', $result);
<del>
<ide> $result = $this->Html->tag('div', 'text');
<ide> $this->assertHtml(['<div', 'text', '/div'], $result);
<ide>
<ide><path>tests/TestCase/View/Helper/UrlHelperTest.php
<ide> public function testAssetUrlDataUri()
<ide>
<ide> $data = 'data:image/png;base64,<evil>';
<ide> $result = $this->Helper->assetUrl($data);
<del> $this->assertHtml(h($data), $result);
<add> $this->assertSame(h($data), $result);
<ide> }
<ide>
<ide> /** | 3 |
Mixed | Javascript | add edge case to goaway request | 7262d6321b1565bc3388c9e4c7e90b1232c18c71 | <ide><path>doc/api/http2.md
<ide> For HTTP/2 Client `Http2Session` instances only, the `http2session.request()`
<ide> creates and returns an `Http2Stream` instance that can be used to send an
<ide> HTTP/2 request to the connected server.
<ide>
<add>When a `ClientHttp2Session` is first created, the socket may not yet be
<add>connected. if `clienthttp2session.request()` is called during this time, the
<add>actual request will be deferred until the socket is ready to go.
<add>If the `session` is closed before the actual request be executed, an
<add>`ERR_HTTP2_GOAWAY_SESSION` is thrown.
<add>
<ide> This method is only available if `http2session.type` is equal to
<ide> `http2.constants.NGHTTP2_SESSION_CLIENT`.
<ide>
<ide><path>test/parallel/test-http2-goaway-delayed-request.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<add>const http2 = require('http2');
<add>
<add>const server = http2.createServer();
<add>
<add>server.listen(0, () => {
<add> const client = http2.connect(`http://localhost:${server.address().port}`);
<add> client.on('close', common.mustCall(() => {
<add> server.close();
<add> }));
<add>
<add> // The client.close() is executed before the socket is able to make request
<add> const stream = client.request();
<add> stream.on('error', common.expectsError({ code: 'ERR_HTTP2_GOAWAY_SESSION' }));
<add>
<add> setImmediate(() => client.close());
<add>}); | 2 |
Javascript | Javascript | add missing test coverage for setlocaladdress() | e53f23229113edc43e555aae070739b9e88bfc1b | <ide><path>test/parallel/test-dns-setlocaladdress.js
<ide> const promiseResolver = new dns.promises.Resolver();
<ide> }, Error);
<ide> assert.throws(() => {
<ide> resolver.setLocalAddress(123);
<del> }, Error);
<add> }, { code: 'ERR_INVALID_ARG_TYPE' });
<add> assert.throws(() => {
<add> resolver.setLocalAddress('127.0.0.1', 42);
<add> }, { code: 'ERR_INVALID_ARG_TYPE' });
<ide> assert.throws(() => {
<ide> resolver.setLocalAddress();
<ide> }, Error); | 1 |
Text | Text | add changelog for | 951503819e067ee87569137111016e375d7b6a2b | <ide><path>actionmailer/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<add>* Prevent mail from being delievered within the mailer actions by setting `perform_deliveries: false` *Aditya Sanghi*
<add>
<add> mail :to => user.email, :subject => "Campaign", :perform_deliveries => user.sendable?
<add>
<add> Global perform_deliveries flag when set to false is not overridden however. This allows you to stop some emails
<add> from being delivered based on Spam Content/Unsubscribed User criterion from within the mailer action.
<add>
<ide> * Allow to set default Action Mailer options via `config.action_mailer.default_options=` *Robert Pankowecki*
<ide>
<ide> * Raise an `ActionView::MissingTemplate` exception when no implicit template could be found. *Damien Mathieu* | 1 |
Javascript | Javascript | remove needless regexp capturing | b9457717cab131a0f6e58b12f4b65a7aae4ecc30 | <ide><path>benchmark/common.js
<ide> function formatResult(data) {
<ide> }
<ide>
<ide> var rate = data.rate.toString().split('.');
<del> rate[0] = rate[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,');
<add> rate[0] = rate[0].replace(/(\d)(?=(?:\d\d\d)+(?!\d))/g, '$1,');
<ide> rate = (rate[1] ? rate.join('.') : rate[0]);
<ide> return `${data.name}${conf}: ${rate}`;
<ide> }
<ide><path>benchmark/run.js
<ide> if (format === 'csv') {
<ide> console.log(`"${data.name}", "${conf}", ${data.rate}, ${data.time}`);
<ide> } else {
<ide> var rate = data.rate.toString().split('.');
<del> rate[0] = rate[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,');
<add> rate[0] = rate[0].replace(/(\d)(?=(?:\d\d\d)+(?!\d))/g, '$1,');
<ide> rate = (rate[1] ? rate.join('.') : rate[0]);
<ide> console.log(`${data.name} ${conf}: ${rate}`);
<ide> } | 2 |
Python | Python | prepare tools/icu/icutrim.py for python 3 | a91293d4d9ab403046ab5eb022332e4e3d249bd3 | <ide><path>tools/icu/icutrim.py
<ide> # Use "-h" to get help options.
<ide>
<ide> from __future__ import print_function
<del>import sys
<del>import shutil
<del># for utf-8
<del>reload(sys)
<del>sys.setdefaultencoding("utf-8")
<ide>
<add>import json
<ide> import optparse
<ide> import os
<del>import json
<ide> import re
<add>import shutil
<add>import sys
<add>
<add>try:
<add> # for utf-8 on Python 2
<add> reload(sys)
<add> sys.setdefaultencoding("utf-8")
<add>except NameError:
<add> pass # Python 3 already defaults to utf-8
<add>
<add>try:
<add> basestring # Python 2
<add>except NameError:
<add> basestring = str # Python 3
<ide>
<ide> endian=sys.byteorder
<ide>
<ide> def queueForRemoval(tree):
<ide> if(options.verbose>0):
<ide> print("* %s: %d items" % (tree, len(mytree["locs"])))
<ide> # do varible substitution for this tree here
<del> if type(config["trees"][tree]) == str or type(config["trees"][tree]) == unicode:
<add> if isinstance(config["trees"][tree], basestring):
<ide> treeStr = config["trees"][tree]
<ide> if(options.verbose>5):
<ide> print(" Substituting $%s for tree %s" % (treeStr, tree)) | 1 |
Python | Python | set version to v2.1.0a5.dev0 | d8d27f9129f78f34e830c98b002c4cdc5a273639 | <ide><path>spacy/about.py
<ide> # fmt: off
<ide>
<ide> __title__ = "spacy-nightly"
<del>__version__ = "2.1.0a4"
<add>__version__ = "2.1.0a5.dev0"
<ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) with Python and Cython"
<ide> __uri__ = "https://spacy.io"
<ide> __author__ = "Explosion AI"
<ide> __email__ = "contact@explosion.ai"
<ide> __license__ = "MIT"
<del>__release__ = True
<add>__release__ = False
<ide>
<ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download"
<ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json" | 1 |
PHP | PHP | update return description | dd65c3cee78475a9c16465bca5a2883b5530607a | <ide><path>src/Network/Session/CacheSession.php
<ide> public function write($id, $data)
<ide> * Method called on the destruction of a cache session.
<ide> *
<ide> * @param int $id ID that uniquely identifies session in cache
<del> * @return bool True for successful delete, false otherwise.
<add> * @return bool Always true.
<ide> */
<ide> public function destroy($id)
<ide> {
<ide> public function destroy($id)
<ide> * Helper function called on gc for cache sessions.
<ide> *
<ide> * @param string $maxlifetime Sessions that have not updated for the last maxlifetime seconds will be removed.
<del> * @return bool True (irrespective of whether or not the garbage is being successfully collected)
<add> * @return bool Always true.
<ide> */
<ide> public function gc($maxlifetime)
<ide> { | 1 |
Ruby | Ruby | fix path issues in comments | 569bd7c42583040a261372714bbd9abb16467e0c | <ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def check_user_path_2
<ide> <<-EOS.undent
<ide> Homebrew's bin was not found in your PATH.
<ide> Consider setting the PATH for example like so
<del> echo export PATH="#{HOMEBREW_PREFIX}/bin:$PATH" >> ~/.bash_profile
<add> echo export PATH='#{HOMEBREW_PREFIX}/bin:$PATH' >> ~/.bash_profile
<ide> EOS
<ide> end
<ide> end
<ide> def check_user_path_3
<ide> Homebrew's sbin was not found in your PATH but you have installed
<ide> formulae that put executables in #{HOMEBREW_PREFIX}/sbin.
<ide> Consider setting the PATH for example like so
<del> echo export PATH="#{HOMEBREW_PREFIX}/sbin:$PATH" >> ~/.bash_profile
<add> echo export PATH='#{HOMEBREW_PREFIX}/sbin:$PATH' >> ~/.bash_profile
<ide> EOS
<ide> end
<ide> end | 1 |
Python | Python | fix serialization issue with nested sequential | 5156673e1761a3ef8ad0d6d355d15554a8ea10a8 | <ide><path>keras/models.py
<ide> def get_config(self):
<ide> return copy.deepcopy(config)
<ide>
<ide> @classmethod
<del> def from_config(cls, config):
<add> def from_config(cls, config, layer_cache={}):
<ide> '''Supports legacy formats
<ide> '''
<ide> from keras.utils.layer_utils import layer_from_config
<ide> def normalize_legacy_config(conf):
<ide> return new_config
<ide> return conf
<ide>
<add> # the model we will return
<ide> model = cls()
<ide>
<add> def get_or_create_layer(layer_data):
<add> if layer_data['class_name'] == 'Sequential':
<add> return Sequential.from_config(layer_data['config'],
<add> layer_cache=layer_cache)
<add> name = layer_data['config'].get('name')
<add> if name in layer_cache:
<add> return layer_cache[name]
<add> layer = layer_from_config(layer_data)
<add> layer_cache[name] = layer
<add> return layer
<add>
<ide> first_layer = config[0]
<ide> first_layer = normalize_legacy_config(first_layer)
<ide> if first_layer['class_name'] == 'Merge':
<ide> def normalize_legacy_config(conf):
<ide> merge = Merge.from_config(first_layer_config)
<ide> model.add(merge)
<ide> else:
<del> layer = layer_from_config(first_layer)
<add> layer = get_or_create_layer(first_layer)
<ide> model.add(layer)
<ide>
<ide> for conf in config[1:]:
<ide> conf = normalize_legacy_config(conf)
<del> layer = layer_from_config(conf)
<add> layer = get_or_create_layer(conf)
<ide> model.add(layer)
<ide> return model | 1 |
Javascript | Javascript | add test for scale.quantize.invertextent | ea2a48a2481748c5978190061ba45daf9ec23335 | <ide><path>test/scale/quantize-test.js
<ide> suite.addBatch({
<ide> assert.equal(x(.6), b);
<ide> assert.equal(x(.8), c);
<ide> assert.equal(x(1), c);
<add> },
<add> "maps a value in the range to a domain extent": function(quantize) {
<add> var x = quantize().range([0, 1, 2, 3]);
<add> assert.deepEqual(x.invertExtent(0), [0, .25]);
<add> assert.deepEqual(x.invertExtent(1), [.25, .5]);
<add> assert.deepEqual(x.invertExtent(2), [.5, .75]);
<add> assert.deepEqual(x.invertExtent(3), [.75, 1]);
<ide> }
<ide> }
<ide> }); | 1 |
Javascript | Javascript | improve test coverage of readline/promises | bb3ff8139b60f5d8fe48035cc5f4082f61155867 | <ide><path>test/parallel/test-readline-promises-interface.js
<ide> for (let i = 0; i < 12; i++) {
<ide> rli.close();
<ide> }
<ide>
<add> // Throw an error when question is executed with an aborted signal
<add> {
<add> const ac = new AbortController();
<add> const signal = ac.signal;
<add> ac.abort();
<add> const [rli] = getInterface({ terminal });
<add> assert.rejects(
<add> rli.question('hello?', { signal }),
<add> {
<add> name: 'AbortError'
<add> }
<add> ).then(common.mustCall());
<add> rli.close();
<add> }
<add>
<ide> // Can create a new readline Interface with a null output argument
<ide> {
<ide> const [rli, fi] = getInterface({ output: null, terminal }); | 1 |
Text | Text | remove article from repo root | c1eaa4899f53b857b67c5d9b59ca56025088a499 | <ide><path>freeCodeCamp/guide/english/book-recommendations/javascript/index.md
<del>---
<del>title: Books on JavaScript
<del>---
<del> ### List of Books
<del>
<del>*Eloquent JavaScript*
<del>
<del>One of the best books on JavaScript. A must for both, beginners and intermediate programmers, who code in JavaScript. The best part is that the e-book is available for free.
<del>
<del>- [E-book](https://eloquentjavascript.net/)(free)
<del>- [Amazon](https://www.amazon.com/gp/product/1593275846/ref=as_li_qf_sp_asin_il_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1593275846&linkCode=as2&tag=marijhaver-20&linkId=VPXXXSRYC5COG5R5)
<del>
<del>*You Don't Know JS*
<del>
<del>Six book series by Kyle Simpson. In-depth series on every aspect of JavaScript.
<del>
<del>- [Github](https://github.com/getify/You-Dont-Know-JS)(free)
<del>- [Kindle Version, Amazon](https://www.amazon.com/You-Dont-Know-Js-Book/dp/B01AY9P0P6)
<del>
<del>*JavaScript: The Good Parts*
<del>Book by the "grandfather" of JavaScript, Douglas Crockford. He discusses both the "good" and "bad" parts of JavaScript.
<del>
<del>- [Amazon](https://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742)
<del>
<del>*JavaScript: Info*
<del>A collection of articles covering the basics (core language and working with a browser) as well as advanced topics with concise explanations. Available as an e-book with pay and also as an online tutorial.
<del>
<del>- [Online](https://javascript.info/)
<del>- [E-book](https://javascript.info/ebook)
<del>
<del>*JavaScript and JQuery: Interactive Front-End Web Development*
<del>
<del>A very fun and easy book for beginners.
<del>
<del>- [Amazon](https://www.amazon.com/JavaScript-JQuery-Interactive-Front-End-Development/dp/1118531647) | 1 |
Javascript | Javascript | fix ngdocspec tests | bb7228e2d906602608a878092158c8004a190809 | <ide><path>docs/spec/ngdocSpec.js
<ide> describe('ngdoc', function(){
<ide> doc.parse();
<ide>
<ide> expect(doc.description).
<del> toContain('foo <a href="#!api/angular.foo"><code>angular.foo</code></a>');
<add> toContain('foo <a href="#!/api/angular.foo"><code>angular.foo</code></a>');
<ide> expect(doc.description).
<del> toContain('da <a href="#!api/angular.foo"><code>bar foo bar</code></a>');
<add> toContain('da <a href="#!/api/angular.foo"><code>bar foo bar</code></a>');
<ide> expect(doc.description).
<del> toContain('dad<a href="#!api/angular.foo"><code>angular.foo</code></a>');
<add> toContain('dad<a href="#!/api/angular.foo"><code>angular.foo</code></a>');
<ide> expect(doc.description).
<del> toContain('<a href="#!api/angular.directive.ng:foo"><code>ng:foo</code></a>');
<add> toContain('<a href="#!/api/angular.directive.ng:foo"><code>ng:foo</code></a>');
<ide> expect(doc.description).
<ide> toContain('<a href="http://angularjs.org">http://angularjs.org</a>');
<ide> expect(doc.description).
<ide> toContain('<a href="./static.html">./static.html</a>');
<ide> });
<ide>
<del> it('shoul support line breaks in @link', function(){
<add> it('should support line breaks in @link', function(){
<ide> var doc = new Doc("@description " +
<ide> '{@link\napi/angular.foo\na\nb}');
<ide> doc.parse();
<ide> expect(doc.description).
<del> toContain('<a href="#!api/angular.foo">a b</a>');
<add> toContain('<a href="#!/api/angular.foo"><code>a b</code></a>');
<ide> });
<ide>
<ide> }); | 1 |
Javascript | Javascript | remove unused parameter | 88f2bf871d4c0dd751cf2295773e55b59dbb2d14 | <ide><path>test/sequential/test-async-wrap-getasyncid.js
<ide> if (common.hasCrypto) { // eslint-disable-line crypto-check
<ide> const tcp_wrap = process.binding('tcp_wrap');
<ide> const server = net.createServer(common.mustCall((socket) => {
<ide> server.close();
<del> socket.on('data', (x) => {
<add> socket.on('data', () => {
<ide> socket.end();
<ide> socket.destroy();
<ide> }); | 1 |
Ruby | Ruby | use default + merge! instead of reverse_merge | fef781cac4cb6ff6482307f3c253bdc01d4bed82 | <ide><path>activemodel/lib/active_model/validations/acceptance.rb
<ide> module ActiveModel
<ide> module Validations
<ide> class AcceptanceValidator < EachValidator #:nodoc:
<ide> def initialize(options)
<del> super(options.reverse_merge(:allow_nil => true, :accept => "1"))
<add> super({ :allow_nil => true, :accept => "1" }.merge!(options))
<ide> end
<ide>
<ide> def validate_each(record, attribute, value) | 1 |
Text | Text | fix incorrect path in entrypoint example | 2819d9b4062914daa5b6bd4d08676807859eae3f | <ide><path>docs/sources/reference/builder.md
<ide> optional but default, you could use a `CMD` instruction:
<ide>
<ide> FROM ubuntu
<ide> CMD ["-l"]
<del> ENTRYPOINT ["/usr/bin/ls"]
<add> ENTRYPOINT ["ls"]
<ide>
<ide> > **Note**:
<ide> > It is preferable to use the JSON array format for specifying | 1 |
Text | Text | remove ^m chars from profiling-node-js blog post | f70be41d80b389cb0d1ce12fa93669b0b44e4005 | <ide><path>doc/blog/Uncategorized/profiling-node-js.md
<ide> status: publish
<ide> category: Uncategorized
<ide> slug: profiling-node-js
<ide>
<del>It's incredibly easy to visualize where your Node program spends its time using DTrace and <a href="http://github.com/davepacheco/node-stackvis">node-stackvis</a> (a Node port of Brendan Gregg's <a href="http://github.com/brendangregg/FlameGraph/">FlameGraph</a> tool):
<del>
<del><ol>
<del> <li>Run your Node.js program as usual.</li>
<del> <li>In another terminal, run:
<del> <pre>
<del>$ dtrace -o stacks.out -n 'profile-97/execname == "node" && arg1/{
<del> @[jstack(100, 8000)] = count(); } tick-60s { exit(0); }'</pre>
<del> This will sample about 100 times per second for 60 seconds and emit results to stacks.out. <strong>Note that this will sample all running programs called "node". If you want a specific process, replace <code>execname == "node"</code> with <code>pid == 12345</code> (the process id).</strong>
<del> </li>
<del> <li>Use the "stackvis" tool to transform this directly into a flame graph. First, install it:
<del> <pre>$ npm install -g stackvis</pre>
<del> then use <code>stackvis</code> to convert the DTrace output to a flamegraph:
<del> <pre>$ stackvis dtrace flamegraph-svg < stacks.out > stacks.svg</pre>
<del> </li>
<del> <li>Open stacks.svg in your favorite browser.</li>
<del></ol>
<del>
<del>You'll be looking at something like this:
<del>
<del><a href="http://www.cs.brown.edu/~dap/helloworld.svg"><img src="http://dtrace.org/blogs/dap/files/2012/04/helloworld-flamegraph-550x366.png" alt="" title="helloworld-flamegraph" width="550" height="366" class="aligncenter size-large wp-image-1047" /></a>
<del>
<del>This is a visualization of all of the profiled call stacks. This example is from the "hello world" HTTP server on the <a href="http://nodejs.org">Node.js</a> home page under load. Start at the bottom, where you have "main", which is present in most Node stacks because Node spends most on-CPU time in the main thread. Above each row, you have the functions called by the frame beneath it. As you move up, you'll see actual JavaScript function names. The boxes in each row are not in chronological order, but their width indicates how much time was spent there. When you hover over each box, you can see exactly what percentage of time is spent in each function. This lets you see at a glance where your program spends its time.
<del>
<del>That's the summary. There are a few prerequisites:
<del>
<del><ul>
<del> <li>You must gather data on a system that supports DTrace with the Node.js ustack helper. For now, this pretty much means <a href="http://illumos.org/">illumos</a>-based systems like <a href="http://smartos.org/">SmartOS</a>, including the Joyent Cloud. <strong>MacOS users:</strong> OS X supports DTrace, but not ustack helpers. The way to get this changed is to contact your Apple developer liason (if you're lucky enough to have one) or <strong>file a bug report at bugreport.apple.com</strong>. I'd suggest referencing existing bugs 5273057 and 11206497. More bugs filed (even if closed as dups) show more interest and make it more likely Apple will choose to fix this.</li>
<del> <li>You must be on 32-bit Node.js 0.6.7 or later, built <code>--with-dtrace</code>. The helper doesn't work with 64-bit Node yet. On illumos (including SmartOS), development releases (the 0.7.x train) include DTrace support by default.</li>
<del></ul>
<del>
<del>There are a few other notes:
<del>
<del><ul>
<del> <li>You can absolutely profile apps <strong>in production</strong>, not just development, since compiling with DTrace support has very minimal overhead. You can start and stop profiling without restarting your program.</li>
<del> <li>You may want to run the stacks.out output through <code>c++filt</code> to demangle C++ symbols. Be sure to use the <code>c++filt</code> that came with the compiler you used to build Node. For example:
<del> <pre>c++filt < stacks.out > demangled.out</pre>
<del> then you can use demangled.out to create the flamegraph.
<del> </li>
<del> <li>If you want, you can filter stacks containing a particular function. The best way to do this is to first collapse the original DTrace output, then grep out what you want:
<del> <pre>
<del>$ stackvis dtrace collapsed < stacks.out | grep SomeFunction > collapsed.out
<del>$ stackvis collapsed flamegraph-svg < collapsed.out > stacks.svg</pre>
<del> </li>
<del> <li>If you've used Brendan's FlameGraph tools, you'll notice the coloring is a little different in the above flamegraph. I ported his tools to Node first so I could incorporate it more easily into other Node programs, but I've also been playing with different coloring options. The current default uses hue to denote stack depth and saturation to indicate time spent. (These are also indicated by position and size.) Other ideas include coloring by module (so V8, JavaScript, libc, etc. show up as different colors.)
<del> </li>
<del></ul>
<del>
<del>For more on the underlying pieces, see my <a href="http://dtrace.org/blogs/dap/2012/01/05/where-does-your-node-program-spend-its-time/">previous post on Node.js profiling</a> and <a href="http://dtrace.org/blogs/brendan/2011/12/16/flame-graphs/">Brendan's post on Flame Graphs</a>.
<del>
<del><hr />
<del>
<add>It's incredibly easy to visualize where your Node program spends its time using DTrace and <a href="http://github.com/davepacheco/node-stackvis">node-stackvis</a> (a Node port of Brendan Gregg's <a href="http://github.com/brendangregg/FlameGraph/">FlameGraph</a> tool):
<add>
<add><ol>
<add> <li>Run your Node.js program as usual.</li>
<add> <li>In another terminal, run:
<add> <pre>
<add>$ dtrace -o stacks.out -n 'profile-97/execname == "node" && arg1/{
<add> @[jstack(100, 8000)] = count(); } tick-60s { exit(0); }'</pre>
<add> This will sample about 100 times per second for 60 seconds and emit results to stacks.out. <strong>Note that this will sample all running programs called "node". If you want a specific process, replace <code>execname == "node"</code> with <code>pid == 12345</code> (the process id).</strong>
<add> </li>
<add> <li>Use the "stackvis" tool to transform this directly into a flame graph. First, install it:
<add> <pre>$ npm install -g stackvis</pre>
<add> then use <code>stackvis</code> to convert the DTrace output to a flamegraph:
<add> <pre>$ stackvis dtrace flamegraph-svg < stacks.out > stacks.svg</pre>
<add> </li>
<add> <li>Open stacks.svg in your favorite browser.</li>
<add></ol>
<add>
<add>You'll be looking at something like this:
<add>
<add><a href="http://www.cs.brown.edu/~dap/helloworld.svg"><img src="http://dtrace.org/blogs/dap/files/2012/04/helloworld-flamegraph-550x366.png" alt="" title="helloworld-flamegraph" width="550" height="366" class="aligncenter size-large wp-image-1047" /></a>
<add>
<add>This is a visualization of all of the profiled call stacks. This example is from the "hello world" HTTP server on the <a href="http://nodejs.org">Node.js</a> home page under load. Start at the bottom, where you have "main", which is present in most Node stacks because Node spends most on-CPU time in the main thread. Above each row, you have the functions called by the frame beneath it. As you move up, you'll see actual JavaScript function names. The boxes in each row are not in chronological order, but their width indicates how much time was spent there. When you hover over each box, you can see exactly what percentage of time is spent in each function. This lets you see at a glance where your program spends its time.
<add>
<add>That's the summary. There are a few prerequisites:
<add>
<add><ul>
<add> <li>You must gather data on a system that supports DTrace with the Node.js ustack helper. For now, this pretty much means <a href="http://illumos.org/">illumos</a>-based systems like <a href="http://smartos.org/">SmartOS</a>, including the Joyent Cloud. <strong>MacOS users:</strong> OS X supports DTrace, but not ustack helpers. The way to get this changed is to contact your Apple developer liason (if you're lucky enough to have one) or <strong>file a bug report at bugreport.apple.com</strong>. I'd suggest referencing existing bugs 5273057 and 11206497. More bugs filed (even if closed as dups) show more interest and make it more likely Apple will choose to fix this.</li>
<add> <li>You must be on 32-bit Node.js 0.6.7 or later, built <code>--with-dtrace</code>. The helper doesn't work with 64-bit Node yet. On illumos (including SmartOS), development releases (the 0.7.x train) include DTrace support by default.</li>
<add></ul>
<add>
<add>There are a few other notes:
<add>
<add><ul>
<add> <li>You can absolutely profile apps <strong>in production</strong>, not just development, since compiling with DTrace support has very minimal overhead. You can start and stop profiling without restarting your program.</li>
<add> <li>You may want to run the stacks.out output through <code>c++filt</code> to demangle C++ symbols. Be sure to use the <code>c++filt</code> that came with the compiler you used to build Node. For example:
<add> <pre>c++filt < stacks.out > demangled.out</pre>
<add> then you can use demangled.out to create the flamegraph.
<add> </li>
<add> <li>If you want, you can filter stacks containing a particular function. The best way to do this is to first collapse the original DTrace output, then grep out what you want:
<add> <pre>
<add>$ stackvis dtrace collapsed < stacks.out | grep SomeFunction > collapsed.out
<add>$ stackvis collapsed flamegraph-svg < collapsed.out > stacks.svg</pre>
<add> </li>
<add> <li>If you've used Brendan's FlameGraph tools, you'll notice the coloring is a little different in the above flamegraph. I ported his tools to Node first so I could incorporate it more easily into other Node programs, but I've also been playing with different coloring options. The current default uses hue to denote stack depth and saturation to indicate time spent. (These are also indicated by position and size.) Other ideas include coloring by module (so V8, JavaScript, libc, etc. show up as different colors.)
<add> </li>
<add></ul>
<add>
<add>For more on the underlying pieces, see my <a href="http://dtrace.org/blogs/dap/2012/01/05/where-does-your-node-program-spend-its-time/">previous post on Node.js profiling</a> and <a href="http://dtrace.org/blogs/brendan/2011/12/16/flame-graphs/">Brendan's post on Flame Graphs</a>.
<add>
<add><hr />
<add>
<ide> Dave Pacheco blogs at <a href="http://dtrace.org/blogs/dap">dtrace.org</a> | 1 |
Javascript | Javascript | fix treemap overlap problem | 1708e5e7a57dcc856ad0352f3a76ff62c2366a1d | <ide><path>d3.layout.js
<ide> d3.layout.treemap = function() {
<ide> v = u ? round(row.area / u) : 0,
<ide> o;
<ide> if (u == rect.dx) { // horizontal subdivision
<del> if (flush || v > rect.dy) v = v ? rect.dy : 0; // over+underflow
<add> if (flush || v > rect.dy) v = rect.dy; // over+underflow
<ide> while (++i < n) {
<ide> o = row[i];
<ide> o.x = x;
<ide> o.y = y;
<ide> o.dy = v;
<del> x += o.dx = v ? round(o.area / v) : 0;
<add> x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0);
<ide> }
<ide> o.z = true;
<ide> o.dx += rect.x + rect.dx - x; // rounding error
<ide> rect.y += v;
<ide> rect.dy -= v;
<ide> } else { // vertical subdivision
<del> if (flush || v > rect.dx) v = v ? rect.dx : 0; // over+underflow
<add> if (flush || v > rect.dx) v = rect.dx; // over+underflow
<ide> while (++i < n) {
<ide> o = row[i];
<ide> o.x = x;
<ide> o.y = y;
<ide> o.dx = v;
<del> y += o.dy = v ? round(o.area / v) : 0;
<add> y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0);
<ide> }
<ide> o.z = false;
<ide> o.dy += rect.y + rect.dy - y; // rounding error
<ide><path>d3.layout.min.js
<del>(function(){function a(a){var b=a.source,d=a.target,e=c(b,d),f=[b];while(b!==e)b=b.parent,f.push(b);var g=f.length;while(d!==e)f.splice(g,0,d),d=d.parent;return f}function b(a){var b=[],c=a.parent;while(c!=null)b.push(a),a=c,c=c.parent;return b.push(a),b}function c(a,c){if(a===c)return a;var d=b(a),e=b(c),f=d.pop(),g=e.pop(),h=null;while(f===g)h=f,f=d.pop(),g=e.pop();return h}function g(a){a.fixed|=2}function h(a){a!==f&&(a.fixed&=1)}function i(){j(),f.fixed&=1,e=f=null}function j(){f.px=d3.event.x,f.py=d3.event.y,e.resume()}function k(a,b,c){var d=0,e=0;a.charge=0;if(!a.leaf){var f=a.nodes,g=f.length,h=-1,i;while(++h<g){i=f[h];if(i==null)continue;k(i,b,c),a.charge+=i.charge,d+=i.charge*i.cx,e+=i.charge*i.cy}}if(a.point){a.leaf||(a.point.x+=Math.random()-.5,a.point.y+=Math.random()-.5);var j=b*c[a.point.index];a.charge+=a.pointCharge=j,d+=j*a.point.x,e+=j*a.point.y}a.cx=d/a.charge,a.cy=e/a.charge}function l(a){return 20}function m(a){return 1}function o(a){return a.x}function p(a){return a.y}function q(a,b,c){a.y0=b,a.y=c}function t(a){var b=1,c=0,d=a[0][1],e,f=a.length;for(;b<f;++b)(e=a[b][1])>d&&(c=b,d=e);return c}function u(a){return a.reduce(v,0)}function v(a,b){return a+b[1]}function w(a,b){return x(a,Math.ceil(Math.log(b.length)/Math.LN2+1))}function x(a,b){var c=-1,d=+a[0],e=(a[1]-d)/b,f=[];while(++c<=b)f[c]=e*c+d;return f}function y(a){return[d3.min(a),d3.max(a)]}function z(a,b){return d3.rebind(a,b,"sort","children","value"),a.links=D,a.nodes=function(b){return E=!0,(a.nodes=a)(b)},a}function A(a){return a.children}function B(a){return a.value}function C(a,b){return b.value-a.value}function D(a){return d3.merge(a.map(function(a){return(a.children||[]).map(function(b){return{source:a,target:b}})}))}function F(a,b){return a.value-b.value}function G(a,b){var c=a._pack_next;a._pack_next=b,b._pack_prev=a,b._pack_next=c,c._pack_prev=b}function H(a,b){a._pack_next=b,b._pack_prev=a}function I(a,b){var c=b.x-a.x,d=b.y-a.y,e=a.r+b.r;return e*e-c*c-d*d>.001}function J(a){function l(a){b=Math.min(a.x-a.r,b),c=Math.max(a.x+a.r,c),d=Math.min(a.y-a.r,d),e=Math.max(a.y+a.r,e)}var b=Infinity,c=-Infinity,d=Infinity,e=-Infinity,f=a.length,g,h,i,j,k;a.forEach(K),g=a[0],g.x=-g.r,g.y=0,l(g);if(f>1){h=a[1],h.x=h.r,h.y=0,l(h);if(f>2){i=a[2],O(g,h,i),l(i),G(g,i),g._pack_prev=i,G(i,h),h=g._pack_next;for(var m=3;m<f;m++){O(g,h,i=a[m]);var n=0,o=1,p=1;for(j=h._pack_next;j!==h;j=j._pack_next,o++)if(I(j,i)){n=1;break}if(n==1)for(k=g._pack_prev;k!==j._pack_prev;k=k._pack_prev,p++)if(I(k,i))break;n?(o<p||o==p&&h.r<g.r?H(g,h=j):H(g=k,h),m--):(G(g,i),h=i,l(i))}}}var q=(b+c)/2,r=(d+e)/2,s=0;for(var m=0;m<f;m++){var t=a[m];t.x-=q,t.y-=r,s=Math.max(s,t.r+Math.sqrt(t.x*t.x+t.y*t.y))}return a.forEach(L),s}function K(a){a._pack_next=a._pack_prev=a}function L(a){delete a._pack_next,delete a._pack_prev}function M(a){var b=a.children;b&&b.length?(b.forEach(M),a.r=J(b)):a.r=Math.sqrt(a.value)}function N(a,b,c,d){var e=a.children;a.x=b+=d*a.x,a.y=c+=d*a.y,a.r*=d;if(e){var f=-1,g=e.length;while(++f<g)N(e[f],b,c,d)}}function O(a,b,c){var d=a.r+c.r,e=b.x-a.x,f=b.y-a.y;if(d&&(e||f)){var g=b.r+c.r,h=Math.sqrt(e*e+f*f),i=Math.max(-1,Math.min(1,(d*d+h*h-g*g)/(2*d*h))),j=Math.acos(i),k=i*(d/=h),l=Math.sin(j)*d;c.x=a.x+k*e+l*f,c.y=a.y+k*f-l*e}else c.x=a.x+d,c.y=a.y}function P(a){return 1+d3.max(a,function(a){return a.y})}function Q(a){return a.reduce(function(a,b){return a+b.x},0)/a.length}function R(a){var b=a.children;return b&&b.length?R(b[0]):a}function S(a){var b=a.children,c;return b&&(c=b.length)?S(b[c-1]):a}function T(a,b){return a.parent==b.parent?1:2}function U(a){var b=a.children;return b&&b.length?b[0]:a._tree.thread}function V(a){var b=a.children,c;return b&&(c=b.length)?b[c-1]:a._tree.thread}function W(a,b){var c=a.children;if(c&&(e=c.length)){var d,e,f=-1;while(++f<e)b(d=W(c[f],b),a)>0&&(a=d)}return a}function X(a,b){return a.x-b.x}function Y(a,b){return b.x-a.x}function Z(a,b){return a.depth-b.depth}function $(a,b){function c(a,d){var e=a.children;if(e&&(i=e.length)){var f,g=null,h=-1,i;while(++h<i)f=e[h],c(f,g),g=f}b(a,d)}c(a,null)}function _(a){var b=0,c=0,d=a.children,e=d.length,f;while(--e>=0)f=d[e]._tree,f.prelim+=b,f.mod+=b,b+=f.shift+(c+=f.change)}function ba(a,b,c){a=a._tree,b=b._tree;var d=c/(b.number-a.number);a.change+=d,b.change-=d,b.shift+=c,b.prelim+=c,b.mod+=c}function bb(a,b,c){return a._tree.ancestor.parent==b.parent?a._tree.ancestor:c}function bc(a){return{x:a.x,y:a.y,dx:a.dx,dy:a.dy}}function bd(a,b){var c=a.x+b[3],d=a.y+b[0],e=a.dx-b[1]-b[3],f=a.dy-b[0]-b[2];return e<0&&(c+=e/2,e=0),f<0&&(d+=f/2,f=0),{x:c,y:d,dx:e,dy:f}}d3.layout={},d3.layout.bundle=function(){return function(b){var c=[],d=-1,e=b.length;while(++d<e)c.push(a(b[d]));return c}},d3.layout.chord=function(){function j(){var a={},j=[],l=d3.range(e),m=[],n,o,p,q,r;b=[],c=[],n=0,q=-1;while(++q<e){o=0,r=-1;while(++r<e)o+=d[q][r];j.push(o),m.push(d3.range(e)),n+=o}g&&l.sort(function(a,b){return g(j[a],j[b])}),h&&m.forEach(function(a,b){a.sort(function(a,c){return h(d[b][a],d[b][c])})}),n=(2*Math.PI-f*e)/n,o=0,q=-1;while(++q<e){p=o,r=-1;while(++r<e){var s=l[q],t=m[s][r],u=d[s][t],v=o,w=o+=u*n;a[s+"-"+t]={index:s,subindex:t,startAngle:v,endAngle:w,value:u}}c.push({index:s,startAngle:p,endAngle:o,value:(o-p)/n}),o+=f}q=-1;while(++q<e){r=q-1;while(++r<e){var x=a[q+"-"+r],y=a[r+"-"+q];(x.value||y.value)&&b.push(x.value<y.value?{source:y,target:x}:{source:x,target:y})}}i&&k()}function k(){b.sort(function(a,b){return i((a.source.value+a.target.value)/2,(b.source.value+b.target.value)/2)})}var a={},b,c,d,e,f=0,g,h,i;return a.matrix=function(f){return arguments.length?(e=(d=f)&&d.length,b=c=null,a):d},a.padding=function(d){return arguments.length?(f=d,b=c=null,a):f},a.sortGroups=function(d){return arguments.length?(g=d,b=c=null,a):g},a.sortSubgroups=function(c){return arguments.length?(h=c,b=null,a):h},a.sortChords=function(c){return arguments.length?(i=c,b&&k(),a):i},a.chords=function(){return b||j(),b},a.groups=function(){return c||j(),c},a},d3.layout.force=function(){function A(a){return function(b,c,d,e,f){if(b.point!==a){var g=b.cx-a.x,h=b.cy-a.y,i=1/Math.sqrt(g*g+h*h);if((e-c)*i<t){var j=b.charge*i*i;return a.px-=g*j,a.py-=h*j,!0}if(b.point&&isFinite(i)){var j=b.pointCharge*i*i;a.px-=g*j,a.py-=h*j}}return!b.charge}}function B(){var a=v.length,d=w.length,e,f,g,h,i,j,l,m,p;for(f=0;f<d;++f){g=w[f],h=g.source,i=g.target,m=i.x-h.x,p=i.y-h.y;if(j=m*m+p*p)j=n*y[f]*((j=Math.sqrt(j))-x[f])/j,m*=j,p*=j,i.x-=m*(l=h.weight/(i.weight+h.weight)),i.y-=p*l,h.x+=m*(l=1-l),h.y+=p*l}if(l=n*s){m=c[0]/2,p=c[1]/2,f=-1;if(l)while(++f<a)g=v[f],g.x+=(m-g.x)*l,g.y+=(p-g.y)*l}if(r){k(e=d3.geom.quadtree(v),n,z),f=-1;while(++f<a)(g=v[f]).fixed||e.visit(A(g))}f=-1;while(++f<a)g=v[f],g.fixed?(g.x=g.px,g.y=g.py):(g.x-=(g.px-(g.px=g.x))*o,g.y-=(g.py-(g.py=g.y))*o);return b.tick({type:"tick",alpha:n}),(n*=.99)<.005}function C(b){g(f=b),e=a}var a={},b=d3.dispatch("tick"),c=[1,1],d,n,o=.9,p=l,q=m,r=-30,s=.1,t=.8,u,v=[],w=[],x,y,z;return a.nodes=function(b){return arguments.length?(v=b,a):v},a.links=function(b){return arguments.length?(w=b,a):w},a.size=function(b){return arguments.length?(c=b,a):c},a.linkDistance=function(b){return arguments.length?(p=d3.functor(b),a):p},a.distance=a.linkDistance,a.linkStrength=function(b){return arguments.length?(q=d3.functor(b),a):q},a.friction=function(b){return arguments.length?(o=b,a):o},a.charge=function(b){return arguments.length?(r=typeof b=="function"?b:+b,a):r},a.gravity=function(b){return arguments.length?(s=b,a):s},a.theta=function(b){return arguments.length?(t=b,a):t},a.start=function(){function k(a,c){var d=l(b),e=-1,f=d.length,g;while(++e<f)if(!isNaN(g=d[e][a]))return g;return Math.random()*c}function l(){if(!i){i=[];for(d=0;d<e;++d)i[d]=[];for(d=0;d<f;++d){var a=w[d];i[a.source.index].push(a.target),i[a.target.index].push(a.source)}}return i[b]}var b,d,e=v.length,f=w.length,g=c[0],h=c[1],i,j;for(b=0;b<e;++b)(j=v[b]).index=b,j.weight=0;x=[],y=[];for(b=0;b<f;++b)j=w[b],typeof j.source=="number"&&(j.source=v[j.source]),typeof j.target=="number"&&(j.target=v[j.target]),x[b]=p.call(this,j,b),y[b]=q.call(this,j,b),++j.source.weight,++j.target.weight;for(b=0;b<e;++b)j=v[b],isNaN(j.x)&&(j.x=k("x",g)),isNaN(j.y)&&(j.y=k("y",h)),isNaN(j.px)&&(j.px=j.x),isNaN(j.py)&&(j.py=j.y);z=[];if(typeof r=="function")for(b=0;b<e;++b)z[b]=+r.call(this,v[b],b);else for(b=0;b<e;++b)z[b]=r;return a.resume()},a.resume=function(){return n=.1,d3.timer(B),a},a.stop=function(){return n=0,a},a.drag=function(){d||(d=d3.behavior.drag().origin(Object).on("dragstart",C).on("drag",j).on("dragend",i)),this.on("mouseover.force",g).on("mouseout.force",h).call(d)},d3.rebind(a,b,"on")};var e,f;d3.layout.partition=function(){function c(a,b,d,e){var f=a.children;a.x=b,a.y=a.depth*e,a.dx=d,a.dy=e;if(f&&(h=f.length)){var g=-1,h,i,j;d=a.value?d/a.value:0;while(++g<h)c(i=f[g],b,j=i.value*d,e),b+=j}}function d(a){var b=a.children,c=0;if(b&&(f=b.length)){var e=-1,f;while(++e<f)c=Math.max(c,d(b[e]))}return 1+c}function e(e,f){var g=a.call(this,e,f);return c(g[0],0,b[0],b[1]/d(g[0])),g}var a=d3.layout.hierarchy(),b=[1,1];return e.size=function(a){return arguments.length?(b=a,e):b},z(e,a)},d3.layout.pie=function(){function f(g,h){var i=g.map(function(b,c){return+a.call(f,b,c)}),j=+(typeof c=="function"?c.apply(this,arguments):c),k=((typeof e=="function"?e.apply(this,arguments):e)-c)/d3.sum(i),l=d3.range(g.length);b!=null&&l.sort(b===n?function(a,b){return i[b]-i[a]}:function(a,c){return b(g[a],g[c])});var m=[];return l.forEach(function(a){m[a]={data:g[a],value:d=i[a],startAngle:j,endAngle:j+=d*k}}),m}var a=Number,b=n,c=0,e=2*Math.PI;return f.value=function(b){return arguments.length?(a=b,f):a},f.sort=function(a){return arguments.length?(b=a,f):b},f.startAngle=function(a){return arguments.length?(c=a,f):c},f.endAngle=function(a){return arguments.length?(e=a,f):e},f};var n={};d3.layout.stack=function(){function g(h,i){var j=h.map(function(b,c){return a.call(g,b,c)}),k=j.map(function(a,b){return a.map(function(a,b){return[e.call(g,a,b),f.call(g,a,b)]})}),l=b.call(g,k,i);j=d3.permute(j,l),k=d3.permute(k,l);var m=c.call(g,k,i),n=j.length,o=j[0].length,p,q,r;for(q=0;q<o;++q){d.call(g,j[0][q],r=m[q],k[0][q][1]);for(p=1;p<n;++p)d.call(g,j[p][q],r+=k[p-1][q][1],k[p][q][1])}return h}var a=Object,b=r["default"],c=s.zero,d=q,e=o,f=p;return g.values=function(b){return arguments.length?(a=b,g):a},g.order=function(a){return arguments.length?(b=typeof a=="function"?a:r[a],g):b},g.offset=function(a){return arguments.length?(c=typeof a=="function"?a:s[a],g):c},g.x=function(a){return arguments.length?(e=a,g):e},g.y=function(a){return arguments.length?(f=a,g):f},g.out=function(a){return arguments.length?(d=a,g):d},g};var r={"inside-out":function(a){var b=a.length,c,d,e=a.map(t),f=a.map(u),g=d3.range(b).sort(function(a,b){return e[a]-e[b]}),h=0,i=0,j=[],k=[];for(c=0;c<b;++c)d=g[c],h<i?(h+=f[d],j.push(d)):(i+=f[d],k.push(d));return k.reverse().concat(j)},reverse:function(a){return d3.range(a.length).reverse()},"default":function(a){return d3.range(a.length)}},s={silhouette:function(a){var b=a.length,c=a[0].length,d=[],e=0,f,g,h,i=[];for(g=0;g<c;++g){for(f=0,h=0;f<b;f++)h+=a[f][g][1];h>e&&(e=h),d.push(h)}for(g=0;g<c;++g)i[g]=(e-d[g])/2;return i},wiggle:function(a){var b=a.length,c=a[0],d=c.length,e=0,f,g,h,i,j,k,l,m,n,o=[];o[0]=m=n=0;for(g=1;g<d;++g){for(f=0,i=0;f<b;++f)i+=a[f][g][1];for(f=0,j=0,l=c[g][0]-c[g-1][0];f<b;++f){for(h=0,k=(a[f][g][1]-a[f][g-1][1])/(2*l);h<f;++h)k+=(a[h][g][1]-a[h][g-1][1])/l;j+=k*a[f][g][1]}o[g]=m-=i?j/i*l:0,m<n&&(n=m)}for(g=0;g<d;++g)o[g]-=n;return o},expand:function(a){var b=a.length,c=a[0].length,d=1/b,e,f,g,h=[];for(f=0;f<c;++f){for(e=0,g=0;e<b;e++)g+=a[e][f][1];if(g)for(e=0;e<b;e++)a[e][f][1]/=g;else for(e=0;e<b;e++)a[e][f][1]=d}for(f=0;f<c;++f)h[f]=0;return h},zero:function(a){var b=-1,c=a[0].length,d=[];while(++b<c)d[b]=0;return d}};d3.layout.histogram=function(){function e(e,f){var g=[],h=e.map(b,this),i=c.call(this,h,f),j=d.call(this,i,h,f),k,f=-1,l=h.length,m=j.length-1,n=a?1:1/l,o;while(++f<m)k=g[f]=[],k.dx=j[f+1]-(k.x=j[f]),k.y=0;f=-1;while(++f<l)o=h[f],o>=i[0]&&o<=i[1]&&(k=g[d3.bisect(j,o,1,m)-1],k.y+=n,k.push(e[f]));return g}var a=!0,b=Number,c=y,d=w;return e.value=function(a){return arguments.length?(b=a,e):b},e.range=function(a){return arguments.length?(c=d3.functor(a),e):c},e.bins=function(a){return arguments.length?(d=typeof a=="number"?function(b){return x(b,a)}:d3.functor(a),e):d},e.frequency=function(b){return arguments.length?(a=!!b,e):a},e},d3.layout.hierarchy=function(){function e(f,h,i){var j=b.call(g,f,h),k=E?f:{data:f};k.depth=h,i.push(k);if(j&&(m=j.length)){var l=-1,m,n=k.children=[],o=0,p=h+1;while(++l<m)d=e(j[l],p,i),d.parent=k,n.push(d),o+=d.value;a&&n.sort(a),c&&(k.value=o)}else c&&(k.value=+c.call(g,f,h)||0);return k}function f(a,b){var d=a.children,e=0;if(d&&(i=d.length)){var h=-1,i,j=b+1;while(++h<i)e+=f(d[h],j)}else c&&(e=+c.call(g,E?a:a.data,b)||0);return c&&(a.value=e),e}function g(a){var b=[];return e(a,0,b),b}var a=C,b=A,c=B;return g.sort=function(b){return arguments.length?(a=b,g):a},g.children=function(a){return arguments.length?(b=a,g):b},g.value=function(a){return arguments.length?(c=a,g):c},g.revalue=function(a){return f(a,0),a},g};var E=!1;d3.layout.pack=function(){function c(c,d){var e=a.call(this,c,d),f=e[0];f.x=0,f.y=0,M(f);var g=b[0],h=b[1],i=1/Math.max(2*f.r/g,2*f.r/h);return N(f,g/2,h/2,i),e}var a=d3.layout.hierarchy().sort(F),b=[1,1];return c.size=function(a){return arguments.length?(b=a,c):b},z(c,a)},d3.layout.cluster=function(){function d(d,e){var f=a.call(this,d,e),g=f[0],h,i=0,j,k;$(g,function(a){var c=a.children;c&&c.length?(a.x=Q(c),a.y=P(c)):(a.x=h?i+=b(a,h):0,a.y=0,h=a)});var l=R(g),m=S(g),n=l.x-b(l,m)/2,o=m.x+b(m,l)/2;return $(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=(1-(g.y?a.y/g.y:1))*c[1]}),f}var a=d3.layout.hierarchy().sort(null).value(null),b=T,c=[1,1];return d.separation=function(a){return arguments.length?(b=a,d):b},d.size=function(a){return arguments.length?(c=a,d):c},z(d,a)},d3.layout.tree=function(){function d(d,e){function h(a,c){var d=a.children,e=a._tree;if(d&&(f=d.length)){var f,g=d[0],i,k=g,l,m=-1;while(++m<f)l=d[m],h(l,i),k=j(l,i,k),i=l;_(a);var n=.5*(g._tree.prelim+l._tree.prelim);c?(e.prelim=c._tree.prelim+b(a,c),e.mod=e.prelim-n):e.prelim=n}else c&&(e.prelim=c._tree.prelim+b(a,c))}function i(a,b){a.x=a._tree.prelim+b;var c=a.children;if(c&&(e=c.length)){var d=-1,e;b+=a._tree.mod;while(++d<e)i(c[d],b)}}function j(a,c,d){if(c){var e=a,f=a,g=c,h=a.parent.children[0],i=e._tree.mod,j=f._tree.mod,k=g._tree.mod,l=h._tree.mod,m;while(g=V(g),e=U(e),g&&e)h=U(h),f=V(f),f._tree.ancestor=a,m=g._tree.prelim+k-e._tree.prelim-i+b(g,e),m>0&&(ba(bb(g,a,d),a,m),i+=m,j+=m),k+=g._tree.mod,i+=e._tree.mod,l+=h._tree.mod,j+=f._tree.mod;g&&!V(f)&&(f._tree.thread=g,f._tree.mod+=k-j),e&&!U(h)&&(h._tree.thread=e,h._tree.mod+=i-l,d=a)}return d}var f=a.call(this,d,e),g=f[0];$(g,function(a,b){a._tree={ancestor:a,prelim:0,mod:0,change:0,shift:0,number:b?b._tree.number+1:0}}),h(g),i(g,-g._tree.prelim);var k=W(g,Y),l=W(g,X),m=W(g,Z),n=k.x-b(k,l)/2,o=l.x+b(l,k)/2,p=m.depth||1;return $(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=a.depth/p*c[1],delete a._tree}),f}var a=d3.layout.hierarchy().sort(null).value(null),b=T,c=[1,1];return d.separation=function(a){return arguments.length?(b=a,d):b},d.size=function(a){return arguments.length?(c=a,d):c},z(d,a)},d3.layout.treemap=function(){function i(a,b){var c=-1,d=a.length,e,f;while(++c<d)f=(e=a[c]).value*(b<0?0:b),e.area=isNaN(f)||f<=0?0:f}function j(a){var b=a.children;if(b&&b.length){var c=e(a),d=[],f=b.slice(),g,h=Infinity,k,n=Math.min(c.dx,c.dy),o;i(f,c.dx*c.dy/a.value),d.area=0;while((o=f.length)>0)d.push(g=f[o-1]),d.area+=g.area,(k=l(d,n))<=h?(f.pop(),h=k):(d.area-=d.pop().area,m(d,n,c,!1),n=Math.min(c.dx,c.dy),d.length=d.area=0,h=Infinity);d.length&&(m(d,n,c,!0),d.length=d.area=0),b.forEach(j)}}function k(a){var b=a.children;if(b&&b.length){var c=e(a),d=b.slice(),f,g=[];i(d,c.dx*c.dy/a.value),g.area=0;while(f=d.pop())g.push(f),g.area+=f.area,f.z!=null&&(m(g,f.z?c.dx:c.dy,c,!d.length),g.length=g.area=0);b.forEach(k)}}function l(a,b){var c=a.area,d,e=0,f=Infinity,g=-1,i=a.length;while(++g<i){if(!(d=a[g].area))continue;d<f&&(f=d),d>e&&(e=d)}return c*=c,b*=b,c?Math.max(b*e*h/c,c/(b*f*h)):Infinity}function m(a,c,d,e){var f=-1,g=a.length,h=d.x,i=d.y,j=c?b(a.area/c):0,k;if(c==d.dx){if(e||j>d.dy)j=j?d.dy:0;while(++f<g)k=a[f],k.x=h,k.y=i,k.dy=j,h+=k.dx=j?b(k.area/j):0;k.z=!0,k.dx+=d.x+d.dx-h,d.y+=j,d.dy-=j}else{if(e||j>d.dx)j=j?d.dx:0;while(++f<g)k=a[f],k.x=h,k.y=i,k.dx=j,i+=k.dy=j?b(k.area/j):0;k.z=!1,k.dy+=d.y+d.dy-i,d.x+=j,d.dx-=j}}function n(b){var d=g||a(b),e=d[0];return e.x=0,e.y=0,e.dx=c[0],e.dy=c[1],g&&a.revalue(e),i([e],e.dx*e.dy/e.value),(g?k:j)(e),f&&(g=d),d}var a=d3.layout.hierarchy(),b=Math.round,c=[1,1],d=null,e=bc,f=!1,g,h=.5*(1+Math.sqrt(5));return n.size=function(a){return arguments.length?(c=a,n):c},n.padding=function(a){function b(b){var c=a.call(n,b,b.depth);return c==null?bc(b):bd(b,typeof c=="number"?[c,c,c,c]:c)}function c(b){return bd(b,a)}if(!arguments.length)return d;var f;return e=(d=a)==null?bc:(f=typeof a)==="function"?b:f==="number"?(a=[a,a,a,a],c):c,n},n.round=function(a){return arguments.length?(b=a?Math.round:Number,n):b!=Number},n.sticky=function(a){return arguments.length?(f=a,g=null,n):f},n.ratio=function(a){return arguments.length?(h=a,n):h},z(n,a)}})();
<ide>\ No newline at end of file
<add>(function(){function a(a){var b=a.source,d=a.target,e=c(b,d),f=[b];while(b!==e)b=b.parent,f.push(b);var g=f.length;while(d!==e)f.splice(g,0,d),d=d.parent;return f}function b(a){var b=[],c=a.parent;while(c!=null)b.push(a),a=c,c=c.parent;return b.push(a),b}function c(a,c){if(a===c)return a;var d=b(a),e=b(c),f=d.pop(),g=e.pop(),h=null;while(f===g)h=f,f=d.pop(),g=e.pop();return h}function g(a){a.fixed|=2}function h(a){a!==f&&(a.fixed&=1)}function i(){j(),f.fixed&=1,e=f=null}function j(){f.px=d3.event.x,f.py=d3.event.y,e.resume()}function k(a,b,c){var d=0,e=0;a.charge=0;if(!a.leaf){var f=a.nodes,g=f.length,h=-1,i;while(++h<g){i=f[h];if(i==null)continue;k(i,b,c),a.charge+=i.charge,d+=i.charge*i.cx,e+=i.charge*i.cy}}if(a.point){a.leaf||(a.point.x+=Math.random()-.5,a.point.y+=Math.random()-.5);var j=b*c[a.point.index];a.charge+=a.pointCharge=j,d+=j*a.point.x,e+=j*a.point.y}a.cx=d/a.charge,a.cy=e/a.charge}function l(a){return 20}function m(a){return 1}function o(a){return a.x}function p(a){return a.y}function q(a,b,c){a.y0=b,a.y=c}function t(a){var b=1,c=0,d=a[0][1],e,f=a.length;for(;b<f;++b)(e=a[b][1])>d&&(c=b,d=e);return c}function u(a){return a.reduce(v,0)}function v(a,b){return a+b[1]}function w(a,b){return x(a,Math.ceil(Math.log(b.length)/Math.LN2+1))}function x(a,b){var c=-1,d=+a[0],e=(a[1]-d)/b,f=[];while(++c<=b)f[c]=e*c+d;return f}function y(a){return[d3.min(a),d3.max(a)]}function z(a,b){return d3.rebind(a,b,"sort","children","value"),a.links=D,a.nodes=function(b){return E=!0,(a.nodes=a)(b)},a}function A(a){return a.children}function B(a){return a.value}function C(a,b){return b.value-a.value}function D(a){return d3.merge(a.map(function(a){return(a.children||[]).map(function(b){return{source:a,target:b}})}))}function F(a,b){return a.value-b.value}function G(a,b){var c=a._pack_next;a._pack_next=b,b._pack_prev=a,b._pack_next=c,c._pack_prev=b}function H(a,b){a._pack_next=b,b._pack_prev=a}function I(a,b){var c=b.x-a.x,d=b.y-a.y,e=a.r+b.r;return e*e-c*c-d*d>.001}function J(a){function l(a){b=Math.min(a.x-a.r,b),c=Math.max(a.x+a.r,c),d=Math.min(a.y-a.r,d),e=Math.max(a.y+a.r,e)}var b=Infinity,c=-Infinity,d=Infinity,e=-Infinity,f=a.length,g,h,i,j,k;a.forEach(K),g=a[0],g.x=-g.r,g.y=0,l(g);if(f>1){h=a[1],h.x=h.r,h.y=0,l(h);if(f>2){i=a[2],O(g,h,i),l(i),G(g,i),g._pack_prev=i,G(i,h),h=g._pack_next;for(var m=3;m<f;m++){O(g,h,i=a[m]);var n=0,o=1,p=1;for(j=h._pack_next;j!==h;j=j._pack_next,o++)if(I(j,i)){n=1;break}if(n==1)for(k=g._pack_prev;k!==j._pack_prev;k=k._pack_prev,p++)if(I(k,i))break;n?(o<p||o==p&&h.r<g.r?H(g,h=j):H(g=k,h),m--):(G(g,i),h=i,l(i))}}}var q=(b+c)/2,r=(d+e)/2,s=0;for(var m=0;m<f;m++){var t=a[m];t.x-=q,t.y-=r,s=Math.max(s,t.r+Math.sqrt(t.x*t.x+t.y*t.y))}return a.forEach(L),s}function K(a){a._pack_next=a._pack_prev=a}function L(a){delete a._pack_next,delete a._pack_prev}function M(a){var b=a.children;b&&b.length?(b.forEach(M),a.r=J(b)):a.r=Math.sqrt(a.value)}function N(a,b,c,d){var e=a.children;a.x=b+=d*a.x,a.y=c+=d*a.y,a.r*=d;if(e){var f=-1,g=e.length;while(++f<g)N(e[f],b,c,d)}}function O(a,b,c){var d=a.r+c.r,e=b.x-a.x,f=b.y-a.y;if(d&&(e||f)){var g=b.r+c.r,h=Math.sqrt(e*e+f*f),i=Math.max(-1,Math.min(1,(d*d+h*h-g*g)/(2*d*h))),j=Math.acos(i),k=i*(d/=h),l=Math.sin(j)*d;c.x=a.x+k*e+l*f,c.y=a.y+k*f-l*e}else c.x=a.x+d,c.y=a.y}function P(a){return 1+d3.max(a,function(a){return a.y})}function Q(a){return a.reduce(function(a,b){return a+b.x},0)/a.length}function R(a){var b=a.children;return b&&b.length?R(b[0]):a}function S(a){var b=a.children,c;return b&&(c=b.length)?S(b[c-1]):a}function T(a,b){return a.parent==b.parent?1:2}function U(a){var b=a.children;return b&&b.length?b[0]:a._tree.thread}function V(a){var b=a.children,c;return b&&(c=b.length)?b[c-1]:a._tree.thread}function W(a,b){var c=a.children;if(c&&(e=c.length)){var d,e,f=-1;while(++f<e)b(d=W(c[f],b),a)>0&&(a=d)}return a}function X(a,b){return a.x-b.x}function Y(a,b){return b.x-a.x}function Z(a,b){return a.depth-b.depth}function $(a,b){function c(a,d){var e=a.children;if(e&&(i=e.length)){var f,g=null,h=-1,i;while(++h<i)f=e[h],c(f,g),g=f}b(a,d)}c(a,null)}function _(a){var b=0,c=0,d=a.children,e=d.length,f;while(--e>=0)f=d[e]._tree,f.prelim+=b,f.mod+=b,b+=f.shift+(c+=f.change)}function ba(a,b,c){a=a._tree,b=b._tree;var d=c/(b.number-a.number);a.change+=d,b.change-=d,b.shift+=c,b.prelim+=c,b.mod+=c}function bb(a,b,c){return a._tree.ancestor.parent==b.parent?a._tree.ancestor:c}function bc(a){return{x:a.x,y:a.y,dx:a.dx,dy:a.dy}}function bd(a,b){var c=a.x+b[3],d=a.y+b[0],e=a.dx-b[1]-b[3],f=a.dy-b[0]-b[2];return e<0&&(c+=e/2,e=0),f<0&&(d+=f/2,f=0),{x:c,y:d,dx:e,dy:f}}d3.layout={},d3.layout.bundle=function(){return function(b){var c=[],d=-1,e=b.length;while(++d<e)c.push(a(b[d]));return c}},d3.layout.chord=function(){function j(){var a={},j=[],l=d3.range(e),m=[],n,o,p,q,r;b=[],c=[],n=0,q=-1;while(++q<e){o=0,r=-1;while(++r<e)o+=d[q][r];j.push(o),m.push(d3.range(e)),n+=o}g&&l.sort(function(a,b){return g(j[a],j[b])}),h&&m.forEach(function(a,b){a.sort(function(a,c){return h(d[b][a],d[b][c])})}),n=(2*Math.PI-f*e)/n,o=0,q=-1;while(++q<e){p=o,r=-1;while(++r<e){var s=l[q],t=m[s][r],u=d[s][t],v=o,w=o+=u*n;a[s+"-"+t]={index:s,subindex:t,startAngle:v,endAngle:w,value:u}}c.push({index:s,startAngle:p,endAngle:o,value:(o-p)/n}),o+=f}q=-1;while(++q<e){r=q-1;while(++r<e){var x=a[q+"-"+r],y=a[r+"-"+q];(x.value||y.value)&&b.push(x.value<y.value?{source:y,target:x}:{source:x,target:y})}}i&&k()}function k(){b.sort(function(a,b){return i((a.source.value+a.target.value)/2,(b.source.value+b.target.value)/2)})}var a={},b,c,d,e,f=0,g,h,i;return a.matrix=function(f){return arguments.length?(e=(d=f)&&d.length,b=c=null,a):d},a.padding=function(d){return arguments.length?(f=d,b=c=null,a):f},a.sortGroups=function(d){return arguments.length?(g=d,b=c=null,a):g},a.sortSubgroups=function(c){return arguments.length?(h=c,b=null,a):h},a.sortChords=function(c){return arguments.length?(i=c,b&&k(),a):i},a.chords=function(){return b||j(),b},a.groups=function(){return c||j(),c},a},d3.layout.force=function(){function A(a){return function(b,c,d,e,f){if(b.point!==a){var g=b.cx-a.x,h=b.cy-a.y,i=1/Math.sqrt(g*g+h*h);if((e-c)*i<t){var j=b.charge*i*i;return a.px-=g*j,a.py-=h*j,!0}if(b.point&&isFinite(i)){var j=b.pointCharge*i*i;a.px-=g*j,a.py-=h*j}}return!b.charge}}function B(){var a=v.length,d=w.length,e,f,g,h,i,j,l,m,p;for(f=0;f<d;++f){g=w[f],h=g.source,i=g.target,m=i.x-h.x,p=i.y-h.y;if(j=m*m+p*p)j=n*y[f]*((j=Math.sqrt(j))-x[f])/j,m*=j,p*=j,i.x-=m*(l=h.weight/(i.weight+h.weight)),i.y-=p*l,h.x+=m*(l=1-l),h.y+=p*l}if(l=n*s){m=c[0]/2,p=c[1]/2,f=-1;if(l)while(++f<a)g=v[f],g.x+=(m-g.x)*l,g.y+=(p-g.y)*l}if(r){k(e=d3.geom.quadtree(v),n,z),f=-1;while(++f<a)(g=v[f]).fixed||e.visit(A(g))}f=-1;while(++f<a)g=v[f],g.fixed?(g.x=g.px,g.y=g.py):(g.x-=(g.px-(g.px=g.x))*o,g.y-=(g.py-(g.py=g.y))*o);return b.tick({type:"tick",alpha:n}),(n*=.99)<.005}function C(b){g(f=b),e=a}var a={},b=d3.dispatch("tick"),c=[1,1],d,n,o=.9,p=l,q=m,r=-30,s=.1,t=.8,u,v=[],w=[],x,y,z;return a.nodes=function(b){return arguments.length?(v=b,a):v},a.links=function(b){return arguments.length?(w=b,a):w},a.size=function(b){return arguments.length?(c=b,a):c},a.linkDistance=function(b){return arguments.length?(p=d3.functor(b),a):p},a.distance=a.linkDistance,a.linkStrength=function(b){return arguments.length?(q=d3.functor(b),a):q},a.friction=function(b){return arguments.length?(o=b,a):o},a.charge=function(b){return arguments.length?(r=typeof b=="function"?b:+b,a):r},a.gravity=function(b){return arguments.length?(s=b,a):s},a.theta=function(b){return arguments.length?(t=b,a):t},a.start=function(){function k(a,c){var d=l(b),e=-1,f=d.length,g;while(++e<f)if(!isNaN(g=d[e][a]))return g;return Math.random()*c}function l(){if(!i){i=[];for(d=0;d<e;++d)i[d]=[];for(d=0;d<f;++d){var a=w[d];i[a.source.index].push(a.target),i[a.target.index].push(a.source)}}return i[b]}var b,d,e=v.length,f=w.length,g=c[0],h=c[1],i,j;for(b=0;b<e;++b)(j=v[b]).index=b,j.weight=0;x=[],y=[];for(b=0;b<f;++b)j=w[b],typeof j.source=="number"&&(j.source=v[j.source]),typeof j.target=="number"&&(j.target=v[j.target]),x[b]=p.call(this,j,b),y[b]=q.call(this,j,b),++j.source.weight,++j.target.weight;for(b=0;b<e;++b)j=v[b],isNaN(j.x)&&(j.x=k("x",g)),isNaN(j.y)&&(j.y=k("y",h)),isNaN(j.px)&&(j.px=j.x),isNaN(j.py)&&(j.py=j.y);z=[];if(typeof r=="function")for(b=0;b<e;++b)z[b]=+r.call(this,v[b],b);else for(b=0;b<e;++b)z[b]=r;return a.resume()},a.resume=function(){return n=.1,d3.timer(B),a},a.stop=function(){return n=0,a},a.drag=function(){d||(d=d3.behavior.drag().origin(Object).on("dragstart",C).on("drag",j).on("dragend",i)),this.on("mouseover.force",g).on("mouseout.force",h).call(d)},d3.rebind(a,b,"on")};var e,f;d3.layout.partition=function(){function c(a,b,d,e){var f=a.children;a.x=b,a.y=a.depth*e,a.dx=d,a.dy=e;if(f&&(h=f.length)){var g=-1,h,i,j;d=a.value?d/a.value:0;while(++g<h)c(i=f[g],b,j=i.value*d,e),b+=j}}function d(a){var b=a.children,c=0;if(b&&(f=b.length)){var e=-1,f;while(++e<f)c=Math.max(c,d(b[e]))}return 1+c}function e(e,f){var g=a.call(this,e,f);return c(g[0],0,b[0],b[1]/d(g[0])),g}var a=d3.layout.hierarchy(),b=[1,1];return e.size=function(a){return arguments.length?(b=a,e):b},z(e,a)},d3.layout.pie=function(){function f(g,h){var i=g.map(function(b,c){return+a.call(f,b,c)}),j=+(typeof c=="function"?c.apply(this,arguments):c),k=((typeof e=="function"?e.apply(this,arguments):e)-c)/d3.sum(i),l=d3.range(g.length);b!=null&&l.sort(b===n?function(a,b){return i[b]-i[a]}:function(a,c){return b(g[a],g[c])});var m=[];return l.forEach(function(a){m[a]={data:g[a],value:d=i[a],startAngle:j,endAngle:j+=d*k}}),m}var a=Number,b=n,c=0,e=2*Math.PI;return f.value=function(b){return arguments.length?(a=b,f):a},f.sort=function(a){return arguments.length?(b=a,f):b},f.startAngle=function(a){return arguments.length?(c=a,f):c},f.endAngle=function(a){return arguments.length?(e=a,f):e},f};var n={};d3.layout.stack=function(){function g(h,i){var j=h.map(function(b,c){return a.call(g,b,c)}),k=j.map(function(a,b){return a.map(function(a,b){return[e.call(g,a,b),f.call(g,a,b)]})}),l=b.call(g,k,i);j=d3.permute(j,l),k=d3.permute(k,l);var m=c.call(g,k,i),n=j.length,o=j[0].length,p,q,r;for(q=0;q<o;++q){d.call(g,j[0][q],r=m[q],k[0][q][1]);for(p=1;p<n;++p)d.call(g,j[p][q],r+=k[p-1][q][1],k[p][q][1])}return h}var a=Object,b=r["default"],c=s.zero,d=q,e=o,f=p;return g.values=function(b){return arguments.length?(a=b,g):a},g.order=function(a){return arguments.length?(b=typeof a=="function"?a:r[a],g):b},g.offset=function(a){return arguments.length?(c=typeof a=="function"?a:s[a],g):c},g.x=function(a){return arguments.length?(e=a,g):e},g.y=function(a){return arguments.length?(f=a,g):f},g.out=function(a){return arguments.length?(d=a,g):d},g};var r={"inside-out":function(a){var b=a.length,c,d,e=a.map(t),f=a.map(u),g=d3.range(b).sort(function(a,b){return e[a]-e[b]}),h=0,i=0,j=[],k=[];for(c=0;c<b;++c)d=g[c],h<i?(h+=f[d],j.push(d)):(i+=f[d],k.push(d));return k.reverse().concat(j)},reverse:function(a){return d3.range(a.length).reverse()},"default":function(a){return d3.range(a.length)}},s={silhouette:function(a){var b=a.length,c=a[0].length,d=[],e=0,f,g,h,i=[];for(g=0;g<c;++g){for(f=0,h=0;f<b;f++)h+=a[f][g][1];h>e&&(e=h),d.push(h)}for(g=0;g<c;++g)i[g]=(e-d[g])/2;return i},wiggle:function(a){var b=a.length,c=a[0],d=c.length,e=0,f,g,h,i,j,k,l,m,n,o=[];o[0]=m=n=0;for(g=1;g<d;++g){for(f=0,i=0;f<b;++f)i+=a[f][g][1];for(f=0,j=0,l=c[g][0]-c[g-1][0];f<b;++f){for(h=0,k=(a[f][g][1]-a[f][g-1][1])/(2*l);h<f;++h)k+=(a[h][g][1]-a[h][g-1][1])/l;j+=k*a[f][g][1]}o[g]=m-=i?j/i*l:0,m<n&&(n=m)}for(g=0;g<d;++g)o[g]-=n;return o},expand:function(a){var b=a.length,c=a[0].length,d=1/b,e,f,g,h=[];for(f=0;f<c;++f){for(e=0,g=0;e<b;e++)g+=a[e][f][1];if(g)for(e=0;e<b;e++)a[e][f][1]/=g;else for(e=0;e<b;e++)a[e][f][1]=d}for(f=0;f<c;++f)h[f]=0;return h},zero:function(a){var b=-1,c=a[0].length,d=[];while(++b<c)d[b]=0;return d}};d3.layout.histogram=function(){function e(e,f){var g=[],h=e.map(b,this),i=c.call(this,h,f),j=d.call(this,i,h,f),k,f=-1,l=h.length,m=j.length-1,n=a?1:1/l,o;while(++f<m)k=g[f]=[],k.dx=j[f+1]-(k.x=j[f]),k.y=0;f=-1;while(++f<l)o=h[f],o>=i[0]&&o<=i[1]&&(k=g[d3.bisect(j,o,1,m)-1],k.y+=n,k.push(e[f]));return g}var a=!0,b=Number,c=y,d=w;return e.value=function(a){return arguments.length?(b=a,e):b},e.range=function(a){return arguments.length?(c=d3.functor(a),e):c},e.bins=function(a){return arguments.length?(d=typeof a=="number"?function(b){return x(b,a)}:d3.functor(a),e):d},e.frequency=function(b){return arguments.length?(a=!!b,e):a},e},d3.layout.hierarchy=function(){function e(f,h,i){var j=b.call(g,f,h),k=E?f:{data:f};k.depth=h,i.push(k);if(j&&(m=j.length)){var l=-1,m,n=k.children=[],o=0,p=h+1;while(++l<m)d=e(j[l],p,i),d.parent=k,n.push(d),o+=d.value;a&&n.sort(a),c&&(k.value=o)}else c&&(k.value=+c.call(g,f,h)||0);return k}function f(a,b){var d=a.children,e=0;if(d&&(i=d.length)){var h=-1,i,j=b+1;while(++h<i)e+=f(d[h],j)}else c&&(e=+c.call(g,E?a:a.data,b)||0);return c&&(a.value=e),e}function g(a){var b=[];return e(a,0,b),b}var a=C,b=A,c=B;return g.sort=function(b){return arguments.length?(a=b,g):a},g.children=function(a){return arguments.length?(b=a,g):b},g.value=function(a){return arguments.length?(c=a,g):c},g.revalue=function(a){return f(a,0),a},g};var E=!1;d3.layout.pack=function(){function c(c,d){var e=a.call(this,c,d),f=e[0];f.x=0,f.y=0,M(f);var g=b[0],h=b[1],i=1/Math.max(2*f.r/g,2*f.r/h);return N(f,g/2,h/2,i),e}var a=d3.layout.hierarchy().sort(F),b=[1,1];return c.size=function(a){return arguments.length?(b=a,c):b},z(c,a)},d3.layout.cluster=function(){function d(d,e){var f=a.call(this,d,e),g=f[0],h,i=0,j,k;$(g,function(a){var c=a.children;c&&c.length?(a.x=Q(c),a.y=P(c)):(a.x=h?i+=b(a,h):0,a.y=0,h=a)});var l=R(g),m=S(g),n=l.x-b(l,m)/2,o=m.x+b(m,l)/2;return $(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=(1-(g.y?a.y/g.y:1))*c[1]}),f}var a=d3.layout.hierarchy().sort(null).value(null),b=T,c=[1,1];return d.separation=function(a){return arguments.length?(b=a,d):b},d.size=function(a){return arguments.length?(c=a,d):c},z(d,a)},d3.layout.tree=function(){function d(d,e){function h(a,c){var d=a.children,e=a._tree;if(d&&(f=d.length)){var f,g=d[0],i,k=g,l,m=-1;while(++m<f)l=d[m],h(l,i),k=j(l,i,k),i=l;_(a);var n=.5*(g._tree.prelim+l._tree.prelim);c?(e.prelim=c._tree.prelim+b(a,c),e.mod=e.prelim-n):e.prelim=n}else c&&(e.prelim=c._tree.prelim+b(a,c))}function i(a,b){a.x=a._tree.prelim+b;var c=a.children;if(c&&(e=c.length)){var d=-1,e;b+=a._tree.mod;while(++d<e)i(c[d],b)}}function j(a,c,d){if(c){var e=a,f=a,g=c,h=a.parent.children[0],i=e._tree.mod,j=f._tree.mod,k=g._tree.mod,l=h._tree.mod,m;while(g=V(g),e=U(e),g&&e)h=U(h),f=V(f),f._tree.ancestor=a,m=g._tree.prelim+k-e._tree.prelim-i+b(g,e),m>0&&(ba(bb(g,a,d),a,m),i+=m,j+=m),k+=g._tree.mod,i+=e._tree.mod,l+=h._tree.mod,j+=f._tree.mod;g&&!V(f)&&(f._tree.thread=g,f._tree.mod+=k-j),e&&!U(h)&&(h._tree.thread=e,h._tree.mod+=i-l,d=a)}return d}var f=a.call(this,d,e),g=f[0];$(g,function(a,b){a._tree={ancestor:a,prelim:0,mod:0,change:0,shift:0,number:b?b._tree.number+1:0}}),h(g),i(g,-g._tree.prelim);var k=W(g,Y),l=W(g,X),m=W(g,Z),n=k.x-b(k,l)/2,o=l.x+b(l,k)/2,p=m.depth||1;return $(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=a.depth/p*c[1],delete a._tree}),f}var a=d3.layout.hierarchy().sort(null).value(null),b=T,c=[1,1];return d.separation=function(a){return arguments.length?(b=a,d):b},d.size=function(a){return arguments.length?(c=a,d):c},z(d,a)},d3.layout.treemap=function(){function i(a,b){var c=-1,d=a.length,e,f;while(++c<d)f=(e=a[c]).value*(b<0?0:b),e.area=isNaN(f)||f<=0?0:f}function j(a){var b=a.children;if(b&&b.length){var c=e(a),d=[],f=b.slice(),g,h=Infinity,k,n=Math.min(c.dx,c.dy),o;i(f,c.dx*c.dy/a.value),d.area=0;while((o=f.length)>0)d.push(g=f[o-1]),d.area+=g.area,(k=l(d,n))<=h?(f.pop(),h=k):(d.area-=d.pop().area,m(d,n,c,!1),n=Math.min(c.dx,c.dy),d.length=d.area=0,h=Infinity);d.length&&(m(d,n,c,!0),d.length=d.area=0),b.forEach(j)}}function k(a){var b=a.children;if(b&&b.length){var c=e(a),d=b.slice(),f,g=[];i(d,c.dx*c.dy/a.value),g.area=0;while(f=d.pop())g.push(f),g.area+=f.area,f.z!=null&&(m(g,f.z?c.dx:c.dy,c,!d.length),g.length=g.area=0);b.forEach(k)}}function l(a,b){var c=a.area,d,e=0,f=Infinity,g=-1,i=a.length;while(++g<i){if(!(d=a[g].area))continue;d<f&&(f=d),d>e&&(e=d)}return c*=c,b*=b,c?Math.max(b*e*h/c,c/(b*f*h)):Infinity}function m(a,c,d,e){var f=-1,g=a.length,h=d.x,i=d.y,j=c?b(a.area/c):0,k;if(c==d.dx){if(e||j>d.dy)j=d.dy;while(++f<g)k=a[f],k.x=h,k.y=i,k.dy=j,h+=k.dx=Math.min(d.x+d.dx-h,j?b(k.area/j):0);k.z=!0,k.dx+=d.x+d.dx-h,d.y+=j,d.dy-=j}else{if(e||j>d.dx)j=d.dx;while(++f<g)k=a[f],k.x=h,k.y=i,k.dx=j,i+=k.dy=Math.min(d.y+d.dy-i,j?b(k.area/j):0);k.z=!1,k.dy+=d.y+d.dy-i,d.x+=j,d.dx-=j}}function n(b){var d=g||a(b),e=d[0];return e.x=0,e.y=0,e.dx=c[0],e.dy=c[1],g&&a.revalue(e),i([e],e.dx*e.dy/e.value),(g?k:j)(e),f&&(g=d),d}var a=d3.layout.hierarchy(),b=Math.round,c=[1,1],d=null,e=bc,f=!1,g,h=.5*(1+Math.sqrt(5));return n.size=function(a){return arguments.length?(c=a,n):c},n.padding=function(a){function b(b){var c=a.call(n,b,b.depth);return c==null?bc(b):bd(b,typeof c=="number"?[c,c,c,c]:c)}function c(b){return bd(b,a)}if(!arguments.length)return d;var f;return e=(d=a)==null?bc:(f=typeof a)==="function"?b:f==="number"?(a=[a,a,a,a],c):c,n},n.round=function(a){return arguments.length?(b=a?Math.round:Number,n):b!=Number},n.sticky=function(a){return arguments.length?(f=a,g=null,n):f},n.ratio=function(a){return arguments.length?(h=a,n):h},z(n,a)}})();
<ide>\ No newline at end of file
<ide><path>src/layout/treemap.js
<ide> d3.layout.treemap = function() {
<ide> v = u ? round(row.area / u) : 0,
<ide> o;
<ide> if (u == rect.dx) { // horizontal subdivision
<del> if (flush || v > rect.dy) v = v ? rect.dy : 0; // over+underflow
<add> if (flush || v > rect.dy) v = rect.dy; // over+underflow
<ide> while (++i < n) {
<ide> o = row[i];
<ide> o.x = x;
<ide> o.y = y;
<ide> o.dy = v;
<del> x += o.dx = v ? round(o.area / v) : 0;
<add> x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0);
<ide> }
<ide> o.z = true;
<ide> o.dx += rect.x + rect.dx - x; // rounding error
<ide> rect.y += v;
<ide> rect.dy -= v;
<ide> } else { // vertical subdivision
<del> if (flush || v > rect.dx) v = v ? rect.dx : 0; // over+underflow
<add> if (flush || v > rect.dx) v = rect.dx; // over+underflow
<ide> while (++i < n) {
<ide> o = row[i];
<ide> o.x = x;
<ide> o.y = y;
<ide> o.dx = v;
<del> y += o.dy = v ? round(o.area / v) : 0;
<add> y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0);
<ide> }
<ide> o.z = false;
<ide> o.dy += rect.y + rect.dy - y; // rounding error
<ide><path>test/layout/treemap-test.js
<ide> suite.addBatch({
<ide> },
<ide> "no negatively sized rectangles": function(treemap) {
<ide> var t = treemap().size([615, 500]).sort(function(a, b) { return a.value - b.value; }).padding(29),
<del> nodes = t.nodes({"children": [
<del> {"value": 1},
<del> {"value": 9},
<del> {"value": 3},
<del> {"value": 15},
<del> {"value": 44},
<del> {"value": 28},
<del> {"value": 32},
<del> {"value": 41},
<del> {"value": 50},
<del> {"value": 60},
<del> {"value": 64},
<del> {"value": 75},
<del> {"value": 76},
<del> {"value": 84},
<del> {"value": 88},
<del> {"value": 100},
<del> {"value": 140},
<del> {"value": 142},
<del> {"value": 363},
<del> {"value": 657},
<del> {"value": 670},
<del> {"value": 822},
<del> {"value": 1173},
<del> {"value": 1189}
<del> ]}).map(layout);
<add> data = [1, 9, 3, 15, 44, 28, 32, 41, 50, 60, 64, 75, 76, 84, 88, 100, 140, 142, 363, 657, 670, 822, 1173, 1189],
<add> nodes = t.nodes({children: data.map(function(d) { return {value: d}; })}).map(layout);
<ide> assert.equal(nodes.filter(function(n) { return n.dx < 0 || n.dy < 0; }).length, 0);
<ide> },
<add> "no overhanging rectangles": function(treemap) {
<add> var t = treemap().size([100, 100]).sort(function(a, b) { return a.value - b.value; }),
<add> data = [0, 0, 81681.85, 370881.9, 0, 0, 0, 255381.59, 0, 0, 0, 0, 0, 0, 0, 125323.95, 0, 0, 0, 186975.07, 185707.05, 267370.93, 0]
<add> nodes = t.nodes({children: data.map(function(d) { return {value: d}; })}).map(layout);
<add> assert.equal(nodes.filter(function(n) { return n.dx < 0 || n.dy < 0 || n.x + n.dx > 100 || n.y + n.dy > 100; }).length, 0);
<add> },
<ide> "can handle an empty children array": function(treemap) {
<ide> assert.deepEqual(treemap().nodes({children: []}).map(layout), [
<ide> {x: 0, y: 0, dx: 1, dy: 1} | 4 |
Javascript | Javascript | add userdata to buffergeometry | 0e489d543b20f4406bbc95a2dae45bcfe67f4c2b | <ide><path>src/core/BufferGeometry.js
<ide> function BufferGeometry() {
<ide>
<ide> this.drawRange = { start: 0, count: Infinity };
<ide>
<add> this.userData = {};
<add>
<ide> }
<ide>
<ide> BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
<ide> BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy
<ide> data.uuid = this.uuid;
<ide> data.type = this.type;
<ide> if ( this.name !== '' ) data.name = this.name;
<add> if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
<ide>
<ide> if ( this.parameters !== undefined ) {
<ide>
<ide> BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy
<ide> this.drawRange.start = source.drawRange.start;
<ide> this.drawRange.count = source.drawRange.count;
<ide>
<add> // user data
<add>
<add> this.userData = source.userData;
<add>
<ide> return this;
<ide>
<ide> }, | 1 |
Python | Python | use more meaningfull message for dagbag timeouts | 0382f7728e3a53049c1e826221fb99efed594ca5 | <ide><path>airflow/models/dagbag.py
<ide> def _load_modules_from_file(self, filepath, safe_mode):
<ide> if mod_name in sys.modules:
<ide> del sys.modules[mod_name]
<ide>
<del> with timeout(self.DAGBAG_IMPORT_TIMEOUT):
<add> timeout_msg = f"DagBag import timeout for {filepath} after {self.DAGBAG_IMPORT_TIMEOUT}s"
<add> with timeout(self.DAGBAG_IMPORT_TIMEOUT, error_message=timeout_msg):
<ide> try:
<ide> loader = importlib.machinery.SourceFileLoader(mod_name, filepath)
<ide> spec = importlib.util.spec_from_loader(mod_name, loader) | 1 |
Python | Python | fix typo in polyint | dde6a64fc78bd2159ae610e59bdc99ee5211ab08 | <ide><path>numpy/lib/polynomial.py
<ide> def polyint(p, m=1, k=None):
<ide> Parameters
<ide> ----------
<ide> p : array_like or poly1d
<del> Polynomial to differentiate.
<add> Polynomial to integrate.
<ide> A sequence is interpreted as polynomial coefficients, see `poly1d`.
<ide> m : int, optional
<ide> Order of the antiderivative. (Default: 1) | 1 |
Java | Java | verify types when setting header | 98d70733704fd96b999e1664a6609e5191affc2d | <ide><path>spring-context/src/main/java/org/springframework/messaging/support/MessageHeaderAccessor.java
<ide> else if (this.originalHeaders != null) {
<ide> */
<ide> public void setHeader(String name, Object value) {
<ide> Assert.isTrue(!isReadOnly(name), "The '" + name + "' header is read-only.");
<add> verifyType(name, value);
<ide> if (!ObjectUtils.nullSafeEquals(value, getHeader(name))) {
<ide> this.headers.put(name, value);
<ide> }
<ide> public void setErrorChannelName(String errorChannelName) {
<ide> setHeader(MessageHeaders.ERROR_CHANNEL, errorChannelName);
<ide> }
<ide>
<del>
<ide> @Override
<ide> public String toString() {
<ide> return getClass().getSimpleName() + " [originalHeaders=" + this.originalHeaders
<ide> + ", updated headers=" + this.headers + "]";
<ide> }
<ide>
<add> protected void verifyType(String headerName, Object headerValue) {
<add> if (headerName != null && headerValue != null) {
<add> if (MessageHeaders.ERROR_CHANNEL.equals(headerName)
<add> || MessageHeaders.REPLY_CHANNEL.endsWith(headerName)) {
<add> Assert.isTrue(headerValue instanceof MessageChannel || headerValue instanceof String, "The '"
<add> + headerName + "' header value must be a MessageChannel or String.");
<add> }
<add> }
<add> }
<ide> } | 1 |
Javascript | Javascript | replace annonymous functions with arrow | 73900983f0180f563b9a6959fee378789db6854c | <ide><path>test/parallel/test-net-reconnect.js
<ide> const server = net.createServer(function(socket) {
<ide> console.error('SERVER connect, writing');
<ide> socket.write('hello\r\n');
<ide>
<del> socket.on('end', function() {
<add> socket.on('end', () => {
<ide> console.error('SERVER socket end, calling end()');
<ide> socket.end();
<ide> });
<ide>
<del> socket.on('close', function(had_error) {
<add> socket.on('close', (had_error) => {
<ide> console.log(`SERVER had_error: ${JSON.stringify(had_error)}`);
<ide> assert.strictEqual(had_error, false);
<ide> });
<ide> server.listen(0, function() {
<ide>
<ide> client.setEncoding('UTF8');
<ide>
<del> client.on('connect', function() {
<add> client.on('connect', () => {
<ide> console.error('CLIENT connected', client._writableState);
<ide> });
<ide>
<ide> server.listen(0, function() {
<ide> client.end();
<ide> });
<ide>
<del> client.on('end', function() {
<add> client.on('end', () => {
<ide> console.error('CLIENT end');
<ide> client_end_count++;
<ide> });
<ide>
<del> client.on('close', function(had_error) {
<add> client.on('close', (had_error) => {
<ide> console.log('CLIENT disconnect');
<ide> assert.strictEqual(had_error, false);
<ide> if (disconnect_count++ < N)
<ide> server.listen(0, function() {
<ide> });
<ide> });
<ide>
<del>process.on('exit', function() {
<add>process.on('exit', () => {
<ide> assert.strictEqual(disconnect_count, N + 1);
<ide> assert.strictEqual(client_recv_count, N + 1);
<ide> assert.strictEqual(client_end_count, N + 1); | 1 |
Java | Java | support variable resolution of wildcard types | 7c84695333228fb2960d69aa312e41e4ead3b5aa | <ide><path>spring-core/src/main/java/org/springframework/core/ResolvableType.java
<ide> private ResolvableType resolveVariable(TypeVariable<?> variable) {
<ide> return forType(ownerType, this.variableResolver).resolveVariable(variable);
<ide> }
<ide> }
<add> if (this.type instanceof WildcardType) {
<add> ResolvableType resolved = resolveType().resolveVariable(variable);
<add> if (resolved != null) {
<add> return resolved;
<add> }
<add> }
<ide> if (this.variableResolver != null) {
<ide> return this.variableResolver.resolveVariable(variable);
<ide> }
<ide><path>spring-core/src/test/java/org/springframework/core/ResolvableTypeTests.java
<ide> void resolveBoundedTypeVariableResult() throws Exception {
<ide> assertThat(type.resolve()).isEqualTo(CharSequence.class);
<ide> }
<ide>
<add>
<add> @Test
<add> void resolveBoundedTypeVariableWildcardResult() throws Exception {
<add> ResolvableType type = ResolvableType.forMethodReturnType(Methods.class.getMethod("boundedTypeVaraibleWildcardResult"));
<add> assertThat(type.getGeneric(1).asCollection().resolveGeneric()).isEqualTo(CharSequence.class);
<add> }
<add>
<ide> @Test
<ide> void resolveVariableNotFound() throws Exception {
<ide> ResolvableType type = ResolvableType.forMethodReturnType(Methods.class.getMethod("typedReturn"));
<ide> static class TypedFields extends Fields<String> {
<ide>
<ide> <R extends CharSequence & Serializable> R boundedTypeVaraibleResult();
<ide>
<add> Map<String, ? extends List<? extends CharSequence>> boundedTypeVaraibleWildcardResult();
<add>
<ide> void nested(Map<Map<String, Integer>, Map<Byte, Long>> p);
<ide>
<ide> void typedParameter(T p); | 2 |
Python | Python | add docs for detection generator | 1b42579112143632993db667491e3e8593ff1f25 | <ide><path>official/vision/beta/projects/yolo/modeling/layers/detection_generator.py
<ide> def __init__(self,
<ide> """
<ide> parameters for the loss functions used at each detection head output
<ide>
<del>scale_anchors: `int` for how much to scale this level to get the orginal
<del> input shape
<del>
<ide> Args:
<ide> masks: `List[int]` for the output level that this specific model output
<ide> level.
<ide> def __init__(self,
<ide> max_delta: gradient clipping to apply to the box loss.
<ide> loss_type: `str` for the typeof iou loss to use with in {ciou, diou,
<ide> giou, iou}.
<del>
<add> use_tie_breaker: TODO unused?
<ide> iou_normalizer: `float` for how much to scale the loss on the IOU or the
<ide> boxes.
<ide> cls_normalizer: `float` for how much to scale the loss on the classes.
<ide> obj_normalizer: `float` for how much to scale loss on the detection map.
<del> objectness_smooth: `float` for how much to smooth the loss on the
<del> detection map.
<ide> use_scaled_loss: `bool` for whether to use the scaled loss
<ide> or the traditional loss.
<del>
<add> darknet: `bool` for whether to use the DarkNet or PyTorch loss function
<add> implementation.
<add> pre_nms_points: `int` number of top candidate detections per class before
<add> NMS.
<ide> label_smoothing: `float` for how much to smooth the loss on the classes.
<del> new_cords: `bool` for which scaling type to use.
<add> max_boxes: `int` for the maximum number of boxes retained over all
<add> classes.
<add> new_cords: `bool` for using the ScaledYOLOv4 coordinates.
<add> path_scale: `dict` for the size of the input tensors. Defaults to
<add> precalulated values from the `mask`.
<ide> scale_xy: dictionary `float` values inidcating how far each pixel can see
<ide> outside of its containment of 1.0. a value of 1.2 indicates there is a
<ide> 20% extended radius around each pixel that this specific pixel can
<ide> predict values for a center at. the center can range from 0 - value/2
<ide> to 1 + value/2, this value is set in the yolo filter, and resused here.
<ide> there should be one value for scale_xy for each level from min_level to
<ide> max_level.
<del> nms_type: "greedy",
<del> nms_thresh: 0.6,
<del> iou_thresh: 0.213,
<del> name=None,
<del>
<add> nms_type: `str` for which non max suppression to use.
<add> objectness_smooth: `float` for how much to smooth the loss on the
<add> detection map.
<ide>
<ide> Return:
<ide> loss: `float` for the actual loss.
<ide><path>official/vision/beta/projects/yolo/modeling/layers/detection_generator_test.py
<add># Lint as: python3
<add># Copyright 2020 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>"""Tests for yolo."""
<add>
<add># Import libraries
<add>from absl.testing import parameterized
<add>import numpy as np
<add>import tensorflow as tf
<add>
<add>from tensorflow.python.distribute import combinations
<add>from tensorflow.python.distribute import strategy_combinations
<add># from official.vision.beta.projects.yolo.modeling.backbones import darknet
<add>from official.vision.beta.projects.yolo.modeling.layers import detection_generator as dg
<add>
<add>
<add>class YoloDecoderTest(parameterized.TestCase, tf.test.TestCase):
<add>
<add> @parameterized.parameters(
<add> (True),
<add> (False),
<add> )
<add> def test_network_creation(self, nms):
<add> """Test creation of ResNet family models."""
<add> tf.keras.backend.set_image_data_format('channels_last')
<add> input_shape = {
<add> '3': [1, 52, 52, 255],
<add> '4': [1, 26, 26, 255],
<add> '5': [1, 13, 13, 255]
<add> }
<add> classes = 80
<add> masks = {'3': [0, 1, 2], '4': [3, 4, 5], '5': [6, 7, 8]}
<add> anchors = [[12.0, 19.0], [31.0, 46.0], [96.0, 54.0], [46.0, 114.0],
<add> [133.0, 127.0], [79.0, 225.0], [301.0, 150.0], [172.0, 286.0],
<add> [348.0, 340.0]]
<add> layer = dg.YoloLayer(masks, anchors, classes, max_boxes=10)
<add>
<add> inputs = {}
<add> for key in input_shape.keys():
<add> inputs[key] = tf.ones(input_shape[key], dtype=tf.float32)
<add>
<add> endpoints = layer(inputs)
<add>
<add> boxes = endpoints['bbox']
<add> classes = endpoints['classes']
<add>
<add> self.assertAllEqual(boxes.shape.as_list(), [1, 10, 4])
<add> self.assertAllEqual(classes.shape.as_list(), [1, 10])
<add>
<add>
<add>if __name__ == '__main__':
<add> from yolo.utils.run_utils import prep_gpu
<add> prep_gpu()
<add> tf.test.main() | 2 |
Python | Python | move matrix_power to linalg | e3eeec78a902cb2fcbf67d8c4e1ffc6141ed68f3 | <ide><path>numpy/linalg/linalg.py
<ide> add, multiply, sqrt, maximum, fastCopyAndTranspose, sum, isfinite, size,
<ide> finfo, errstate, geterrobj, longdouble, moveaxis, amin, amax, product, abs,
<ide> broadcast, atleast_2d, intp, asanyarray, object_, ones, matmul,
<del> swapaxes, divide, count_nonzero, ndarray, isnan
<add> swapaxes, divide, count_nonzero, ndarray, isnan, identity, issubdtype,
<add> binary_repr, integer
<ide> )
<ide> from numpy.core.multiarray import normalize_axis_index
<del>from numpy.lib import triu, asfarray
<add>from numpy.lib.twodim_base import triu
<ide> from numpy.linalg import lapack_lite, _umath_linalg
<del>from numpy.matrixlib.defmatrix import matrix_power
<ide>
<ide> # For Python2/3 compatibility
<ide> _N = b'N'
<ide> def inv(a):
<ide> return wrap(ainv.astype(result_t, copy=False))
<ide>
<ide>
<add>def matrix_power(M, n):
<add> """
<add> Raise a square matrix to the (integer) power `n`.
<add>
<add> For positive integers `n`, the power is computed by repeated matrix
<add> squarings and matrix multiplications. If ``n == 0``, the identity matrix
<add> of the same shape as M is returned. If ``n < 0``, the inverse
<add> is computed and then raised to the ``abs(n)``.
<add>
<add> Parameters
<add> ----------
<add> M : ndarray or matrix object
<add> Matrix to be "powered." Must be square, i.e. ``M.shape == (m, m)``,
<add> with `m` a positive integer.
<add> n : int
<add> The exponent can be any integer or long integer, positive,
<add> negative, or zero.
<add>
<add> Returns
<add> -------
<add> M**n : ndarray or matrix object
<add> The return value is the same shape and type as `M`;
<add> if the exponent is positive or zero then the type of the
<add> elements is the same as those of `M`. If the exponent is
<add> negative the elements are floating-point.
<add>
<add> Raises
<add> ------
<add> LinAlgError
<add> If the matrix is not numerically invertible.
<add>
<add> See Also
<add> --------
<add> matrix
<add> Provides an equivalent function as the exponentiation operator
<add> (``**``, not ``^``).
<add>
<add> Examples
<add> --------
<add> >>> from numpy import linalg as LA
<add> >>> i = np.array([[0, 1], [-1, 0]]) # matrix equiv. of the imaginary unit
<add> >>> LA.matrix_power(i, 3) # should = -i
<add> array([[ 0, -1],
<add> [ 1, 0]])
<add> >>> LA.matrix_power(np.matrix(i), 3) # matrix arg returns matrix
<add> matrix([[ 0, -1],
<add> [ 1, 0]])
<add> >>> LA.matrix_power(i, 0)
<add> array([[1, 0],
<add> [0, 1]])
<add> >>> LA.matrix_power(i, -3) # should = 1/(-i) = i, but w/ f.p. elements
<add> array([[ 0., 1.],
<add> [-1., 0.]])
<add>
<add> Somewhat more sophisticated example
<add>
<add> >>> q = np.zeros((4, 4))
<add> >>> q[0:2, 0:2] = -i
<add> >>> q[2:4, 2:4] = i
<add> >>> q # one of the three quaternion units not equal to 1
<add> array([[ 0., -1., 0., 0.],
<add> [ 1., 0., 0., 0.],
<add> [ 0., 0., 0., 1.],
<add> [ 0., 0., -1., 0.]])
<add> >>> LA.matrix_power(q, 2) # = -np.eye(4)
<add> array([[-1., 0., 0., 0.],
<add> [ 0., -1., 0., 0.],
<add> [ 0., 0., -1., 0.],
<add> [ 0., 0., 0., -1.]])
<add>
<add> """
<add> M = asanyarray(M)
<add> if M.ndim != 2 or M.shape[0] != M.shape[1]:
<add> raise ValueError("input must be a square array")
<add> if not issubdtype(type(n), integer):
<add> raise TypeError("exponent must be an integer")
<add>
<add> from numpy.linalg import inv
<add>
<add> if n==0:
<add> M = M.copy()
<add> M[:] = identity(M.shape[0])
<add> return M
<add> elif n<0:
<add> M = inv(M)
<add> n *= -1
<add>
<add> result = M
<add> if n <= 3:
<add> for _ in range(n-1):
<add> result=dot(result, M)
<add> return result
<add>
<add> # binary decomposition to reduce the number of Matrix
<add> # multiplications for n > 3.
<add> beta = binary_repr(n)
<add> Z, q, t = M, 0, len(beta)
<add> while beta[t-q-1] == '0':
<add> Z = dot(Z, Z)
<add> q += 1
<add> result = Z
<add> for k in range(q+1, t):
<add> Z = dot(Z, Z)
<add> if beta[t-k-1] == '1':
<add> result = dot(result, Z)
<add> return result
<add>
<add>
<ide> # Cholesky decomposition
<ide>
<ide> def cholesky(a):
<ide><path>numpy/matrixlib/defmatrix.py
<ide> import sys
<ide> import ast
<ide> import numpy.core.numeric as N
<del>from numpy.core.numeric import concatenate, isscalar, binary_repr, identity, asanyarray
<del>from numpy.core.numerictypes import issubdtype
<add>from numpy.core.numeric import concatenate, isscalar
<add># While not in __all__, matrix_power used to be defined here, so we import
<add># it for backward compatibility.
<add>from numpy.linalg import matrix_power
<add>
<ide>
<ide> def _convert_from_string(data):
<ide> for char in '[]':
<ide> def asmatrix(data, dtype=None):
<ide> """
<ide> return matrix(data, dtype=dtype, copy=False)
<ide>
<del>def matrix_power(M, n):
<del> """
<del> Raise a square matrix to the (integer) power `n`.
<del>
<del> For positive integers `n`, the power is computed by repeated matrix
<del> squarings and matrix multiplications. If ``n == 0``, the identity matrix
<del> of the same shape as M is returned. If ``n < 0``, the inverse
<del> is computed and then raised to the ``abs(n)``.
<del>
<del> Parameters
<del> ----------
<del> M : ndarray or matrix object
<del> Matrix to be "powered." Must be square, i.e. ``M.shape == (m, m)``,
<del> with `m` a positive integer.
<del> n : int
<del> The exponent can be any integer or long integer, positive,
<del> negative, or zero.
<del>
<del> Returns
<del> -------
<del> M**n : ndarray or matrix object
<del> The return value is the same shape and type as `M`;
<del> if the exponent is positive or zero then the type of the
<del> elements is the same as those of `M`. If the exponent is
<del> negative the elements are floating-point.
<del>
<del> Raises
<del> ------
<del> LinAlgError
<del> If the matrix is not numerically invertible.
<del>
<del> See Also
<del> --------
<del> matrix
<del> Provides an equivalent function as the exponentiation operator
<del> (``**``, not ``^``).
<del>
<del> Examples
<del> --------
<del> >>> from numpy import linalg as LA
<del> >>> i = np.array([[0, 1], [-1, 0]]) # matrix equiv. of the imaginary unit
<del> >>> LA.matrix_power(i, 3) # should = -i
<del> array([[ 0, -1],
<del> [ 1, 0]])
<del> >>> LA.matrix_power(np.matrix(i), 3) # matrix arg returns matrix
<del> matrix([[ 0, -1],
<del> [ 1, 0]])
<del> >>> LA.matrix_power(i, 0)
<del> array([[1, 0],
<del> [0, 1]])
<del> >>> LA.matrix_power(i, -3) # should = 1/(-i) = i, but w/ f.p. elements
<del> array([[ 0., 1.],
<del> [-1., 0.]])
<del>
<del> Somewhat more sophisticated example
<del>
<del> >>> q = np.zeros((4, 4))
<del> >>> q[0:2, 0:2] = -i
<del> >>> q[2:4, 2:4] = i
<del> >>> q # one of the three quaternion units not equal to 1
<del> array([[ 0., -1., 0., 0.],
<del> [ 1., 0., 0., 0.],
<del> [ 0., 0., 0., 1.],
<del> [ 0., 0., -1., 0.]])
<del> >>> LA.matrix_power(q, 2) # = -np.eye(4)
<del> array([[-1., 0., 0., 0.],
<del> [ 0., -1., 0., 0.],
<del> [ 0., 0., -1., 0.],
<del> [ 0., 0., 0., -1.]])
<del>
<del> """
<del> M = asanyarray(M)
<del> if M.ndim != 2 or M.shape[0] != M.shape[1]:
<del> raise ValueError("input must be a square array")
<del> if not issubdtype(type(n), N.integer):
<del> raise TypeError("exponent must be an integer")
<del>
<del> from numpy.linalg import inv
<del>
<del> if n==0:
<del> M = M.copy()
<del> M[:] = identity(M.shape[0])
<del> return M
<del> elif n<0:
<del> M = inv(M)
<del> n *= -1
<del>
<del> result = M
<del> if n <= 3:
<del> for _ in range(n-1):
<del> result=N.dot(result, M)
<del> return result
<del>
<del> # binary decomposition to reduce the number of Matrix
<del> # multiplications for n > 3.
<del> beta = binary_repr(n)
<del> Z, q, t = M, 0, len(beta)
<del> while beta[t-q-1] == '0':
<del> Z = N.dot(Z, Z)
<del> q += 1
<del> result = Z
<del> for k in range(q+1, t):
<del> Z = N.dot(Z, Z)
<del> if beta[t-k-1] == '1':
<del> result = N.dot(result, Z)
<del> return result
<del>
<del>
<ide> class matrix(N.ndarray):
<ide> """
<ide> matrix(data, dtype=None, copy=True)
<ide><path>numpy/matrixlib/tests/test_defmatrix.py
<ide> assert_, assert_equal, assert_almost_equal, assert_array_equal,
<ide> assert_array_almost_equal, assert_raises
<ide> )
<del>from numpy.matrixlib.defmatrix import matrix_power
<add>from numpy.linalg import matrix_power
<ide> from numpy.matrixlib import mat
<ide>
<ide> class TestCtor(object): | 3 |
Python | Python | add test for prediction with structured output | 19c1fddda6b2f8f95745d5d288767dcfac3a74e7 | <ide><path>keras/engine/training_test.py
<ide> def test_predict_error_with_empty_x(self):
<ide> 'Unexpected result of `predict_function`.*'):
<ide> model.predict(np.array([]))
<ide>
<add> @test_combinations.run_all_keras_modes(always_skip_v1=True)
<add> @parameterized.named_parameters(
<add> ('dynamic', 0, False),
<add> ('dynamic_multistep', 10, False),
<add> ('static', 0, True),
<add> ('static_multistep', 10, True),
<add> )
<add> def test_predict_structured(self, spe, static_batch):
<add> inputs = layers_module.Input(shape=(2,))
<add> outputs = layers_module.Dense(2)(inputs)
<add> model = training_module.Model(
<add> inputs=inputs,
<add> outputs={'out': outputs},
<add> )
<add> model.compile(
<add> loss='mse',
<add> steps_per_execution=spe,
<add> run_eagerly=test_utils.should_run_eagerly(),
<add> )
<add> xdata = np.random.uniform(size=(8, 2)).astype(np.float32)
<add> dataset = tf.data.Dataset.from_tensor_slices((xdata, xdata))
<add> dataset = dataset.batch(8, drop_remainder=static_batch)
<add> ret = model.predict(dataset, steps=1)
<add> tf.nest.assert_same_structure(ret, {'out': ''})
<add>
<ide> @test_combinations.run_all_keras_modes(always_skip_v1=True)
<ide> def test_on_batch_error_inconsistent_batch_size(self):
<ide> input_node1 = layers_module.Input(shape=(5,)) | 1 |
Javascript | Javascript | make redirection from http to https work | 00cd48027bdfe1998da7100a56b5d68cc57277c2 | <ide><path>lib/adapters/http.js
<ide> module.exports = function httpAdapter(config) {
<ide> method: config.method.toUpperCase(),
<ide> headers: headers,
<ide> agent: agent,
<add> agents: {
<add> httpsAgent: config.httpsAgent,
<add> httpAgent: config.httpAgent
<add> },
<ide> auth: auth
<ide> };
<ide> | 1 |
Javascript | Javascript | fix several issues with glyph id mappings | ac33358e1fd34fbb30a9f73bba7a729ebf97f2dc | <ide><path>src/core/fonts.js
<ide> var ProblematicCharRanges = new Int32Array([
<ide> */
<ide> var Font = (function FontClosure() {
<ide> function Font(name, file, properties) {
<del> var charCode, glyphName, unicode;
<add> var charCode;
<ide>
<ide> this.name = name;
<ide> this.loadedName = properties.loadedName;
<ide> var Font = (function FontClosure() {
<ide> var type = properties.type;
<ide> var subtype = properties.subtype;
<ide> this.type = type;
<add> this.subtype = subtype;
<ide>
<ide> this.fallbackName = (this.isMonospace ? 'monospace' :
<ide> (this.isSerifFont ? 'serif' : 'sans-serif'));
<ide> var Font = (function FontClosure() {
<ide> this.descent = properties.descent / PDF_GLYPH_SPACE_UNITS;
<ide> this.fontMatrix = properties.fontMatrix;
<ide> this.bbox = properties.bbox;
<add> this.defaultEncoding = properties.defaultEncoding;
<ide>
<ide> this.toUnicode = properties.toUnicode;
<ide>
<ide> var Font = (function FontClosure() {
<ide> this.vmetrics = properties.vmetrics;
<ide> this.defaultVMetrics = properties.defaultVMetrics;
<ide> }
<del> var glyphsUnicodeMap;
<add>
<ide> if (!file || file.isEmpty) {
<ide> if (file) {
<ide> // Some bad PDF generators will include empty font files,
<ide> // attempting to recover by assuming that no file exists.
<ide> warn('Font file is empty in "' + name + '" (' + this.loadedName + ')');
<ide> }
<del>
<del> this.missingFile = true;
<del> // The file data is not specified. Trying to fix the font name
<del> // to be used with the canvas.font.
<del> var fontName = name.replace(/[,_]/g, '-');
<del> var stdFontMap = getStdFontMap(), nonStdFontMap = getNonStdFontMap();
<del> var isStandardFont = !!stdFontMap[fontName] ||
<del> !!(nonStdFontMap[fontName] && stdFontMap[nonStdFontMap[fontName]]);
<del> fontName = stdFontMap[fontName] || nonStdFontMap[fontName] || fontName;
<del>
<del> this.bold = (fontName.search(/bold/gi) !== -1);
<del> this.italic = ((fontName.search(/oblique/gi) !== -1) ||
<del> (fontName.search(/italic/gi) !== -1));
<del>
<del> // Use 'name' instead of 'fontName' here because the original
<del> // name ArialBlack for example will be replaced by Helvetica.
<del> this.black = (name.search(/Black/g) !== -1);
<del>
<del> // if at least one width is present, remeasure all chars when exists
<del> this.remeasure = Object.keys(this.widths).length > 0;
<del> if (isStandardFont && type === 'CIDFontType2' &&
<del> properties.cidEncoding.indexOf('Identity-') === 0) {
<del> var GlyphMapForStandardFonts = getGlyphMapForStandardFonts();
<del> // Standard fonts might be embedded as CID font without glyph mapping.
<del> // Building one based on GlyphMapForStandardFonts.
<del> var map = [];
<del> for (charCode in GlyphMapForStandardFonts) {
<del> map[+charCode] = GlyphMapForStandardFonts[charCode];
<del> }
<del> if (/Arial-?Black/i.test(name)) {
<del> var SupplementalGlyphMapForArialBlack =
<del> getSupplementalGlyphMapForArialBlack();
<del> for (charCode in SupplementalGlyphMapForArialBlack) {
<del> map[+charCode] = SupplementalGlyphMapForArialBlack[charCode];
<del> }
<del> }
<del> var isIdentityUnicode = this.toUnicode instanceof IdentityToUnicodeMap;
<del> if (!isIdentityUnicode) {
<del> this.toUnicode.forEach(function(charCode, unicodeCharCode) {
<del> map[+charCode] = unicodeCharCode;
<del> });
<del> }
<del> this.toFontChar = map;
<del> this.toUnicode = new ToUnicodeMap(map);
<del> } else if (/Symbol/i.test(fontName)) {
<del> this.toFontChar = buildToFontChar(SymbolSetEncoding, getGlyphsUnicode(),
<del> properties.differences);
<del> } else if (/Dingbats/i.test(fontName)) {
<del> if (/Wingdings/i.test(name)) {
<del> warn('Non-embedded Wingdings font, falling back to ZapfDingbats.');
<del> }
<del> this.toFontChar = buildToFontChar(ZapfDingbatsEncoding,
<del> getDingbatsGlyphsUnicode(),
<del> properties.differences);
<del> } else if (isStandardFont) {
<del> this.toFontChar = buildToFontChar(properties.defaultEncoding,
<del> getGlyphsUnicode(),
<del> properties.differences);
<del> } else {
<del> glyphsUnicodeMap = getGlyphsUnicode();
<del> this.toUnicode.forEach((charCode, unicodeCharCode) => {
<del> if (!this.composite) {
<del> glyphName = (properties.differences[charCode] ||
<del> properties.defaultEncoding[charCode]);
<del> unicode = getUnicodeForGlyph(glyphName, glyphsUnicodeMap);
<del> if (unicode !== -1) {
<del> unicodeCharCode = unicode;
<del> }
<del> }
<del> this.toFontChar[charCode] = unicodeCharCode;
<del> });
<del> }
<del> this.loadedName = fontName.split('-')[0];
<del> this.loading = false;
<del> this.fontType = getFontType(type, subtype);
<add> this.fallbackToSystemFont();
<ide> return;
<ide> }
<ide>
<ide> var Font = (function FontClosure() {
<ide> type = 'OpenType';
<ide> }
<ide>
<del> var data;
<del> switch (type) {
<del> case 'MMType1':
<del> info('MMType1 font (' + name + '), falling back to Type1.');
<del> /* falls through */
<del> case 'Type1':
<del> case 'CIDFontType0':
<del> this.mimetype = 'font/opentype';
<del>
<del> var cff = (subtype === 'Type1C' || subtype === 'CIDFontType0C') ?
<del> new CFFFont(file, properties) : new Type1Font(name, file, properties);
<add> try {
<add> var data;
<add> switch (type) {
<add> case 'MMType1':
<add> info('MMType1 font (' + name + '), falling back to Type1.');
<add> /* falls through */
<add> case 'Type1':
<add> case 'CIDFontType0':
<add> this.mimetype = 'font/opentype';
<add>
<add> var cff = (subtype === 'Type1C' || subtype === 'CIDFontType0C') ?
<add> new CFFFont(file, properties) :
<add> new Type1Font(name, file, properties);
<ide>
<del> adjustWidths(properties);
<add> adjustWidths(properties);
<ide>
<del> // Wrap the CFF data inside an OTF font file
<del> data = this.convert(name, cff, properties);
<del> break;
<add> // Wrap the CFF data inside an OTF font file
<add> data = this.convert(name, cff, properties);
<add> break;
<ide>
<del> case 'OpenType':
<del> case 'TrueType':
<del> case 'CIDFontType2':
<del> this.mimetype = 'font/opentype';
<add> case 'OpenType':
<add> case 'TrueType':
<add> case 'CIDFontType2':
<add> this.mimetype = 'font/opentype';
<ide>
<del> // Repair the TrueType file. It is can be damaged in the point of
<del> // view of the sanitizer
<del> data = this.checkAndRepair(name, file, properties);
<del> if (this.isOpenType) {
<del> adjustWidths(properties);
<add> // Repair the TrueType file. It is can be damaged in the point of
<add> // view of the sanitizer
<add> data = this.checkAndRepair(name, file, properties);
<add> if (this.isOpenType) {
<add> adjustWidths(properties);
<ide>
<del> type = 'OpenType';
<del> }
<del> break;
<add> type = 'OpenType';
<add> }
<add> break;
<ide>
<del> default:
<del> throw new FormatError(`Font ${type} is not supported`);
<add> default:
<add> throw new FormatError(`Font ${type} is not supported`);
<add> }
<add> } catch (e) {
<add> if (!(e instanceof FormatError)) {
<add> throw e;
<add> }
<add> warn(e);
<add> this.fallbackToSystemFont();
<add> return;
<ide> }
<ide>
<ide> this.data = data;
<ide> var Font = (function FontClosure() {
<ide> for (var originalCharCode in charCodeToGlyphId) {
<ide> originalCharCode |= 0;
<ide> var glyphId = charCodeToGlyphId[originalCharCode];
<add> // For missing glyphs don't create the mappings so the glyph isn't
<add> // drawn.
<add> if (missingGlyphs[glyphId]) {
<add> continue;
<add> }
<ide> var fontCharCode = originalCharCode;
<ide> // First try to map the value to a unicode position if a non identity map
<ide> // was created.
<ide> var Font = (function FontClosure() {
<ide> // font was symbolic and there is only an identity unicode map since the
<ide> // characters probably aren't in the correct position (fixes an issue
<ide> // with firefox and thuluthfont).
<del> if (!missingGlyphs[glyphId] &&
<del> (usedFontCharCodes[fontCharCode] !== undefined ||
<add> if ((usedFontCharCodes[fontCharCode] !== undefined ||
<ide> isProblematicUnicodeLocation(fontCharCode) ||
<del> (isSymbolic && !hasUnicodeValue)) &&
<del> nextAvailableFontCharCode <= PRIVATE_USE_OFFSET_END) { // Room left.
<add> (isSymbolic && !hasUnicodeValue))) {
<ide> // Loop to try and find a free spot in the private use area.
<ide> do {
<add> if (nextAvailableFontCharCode > PRIVATE_USE_OFFSET_END) {
<add> warn('Ran out of space in font private use area.');
<add> break;
<add> }
<ide> fontCharCode = nextAvailableFontCharCode++;
<ide>
<ide> if (SKIP_PRIVATE_USE_RANGE_F000_TO_F01F && fontCharCode === 0xF000) {
<ide> fontCharCode = 0xF020;
<ide> nextAvailableFontCharCode = fontCharCode + 1;
<ide> }
<ide>
<del> } while (usedFontCharCodes[fontCharCode] !== undefined &&
<del> nextAvailableFontCharCode <= PRIVATE_USE_OFFSET_END);
<add> } while (usedFontCharCodes[fontCharCode] !== undefined);
<ide> }
<ide>
<ide> newMap[fontCharCode] = glyphId;
<ide> var Font = (function FontClosure() {
<ide> }
<ide> codes.push({ fontCharCode: charCode | 0, glyphId: glyphs[charCode], });
<ide> }
<add> // Some fonts have zero glyphs and are used only for text selection, but
<add> // there needs to be at least one to build a valid cmap table.
<add> if (codes.length === 0) {
<add> codes.push({ fontCharCode: 0, glyphId: 0, });
<add> }
<ide> codes.sort(function fontGetRangesSort(a, b) {
<ide> return a.fontCharCode - b.fontCharCode;
<ide> });
<ide> var Font = (function FontClosure() {
<ide> return data;
<ide> },
<ide>
<add> fallbackToSystemFont: function Font_fallbackToSystemFont() {
<add> this.missingFile = true;
<add> var charCode, unicode;
<add> // The file data is not specified. Trying to fix the font name
<add> // to be used with the canvas.font.
<add> var name = this.name;
<add> var type = this.type;
<add> var subtype = this.subtype;
<add> var fontName = name.replace(/[,_]/g, '-');
<add> var stdFontMap = getStdFontMap(), nonStdFontMap = getNonStdFontMap();
<add> var isStandardFont = !!stdFontMap[fontName] ||
<add> !!(nonStdFontMap[fontName] && stdFontMap[nonStdFontMap[fontName]]);
<add> fontName = stdFontMap[fontName] || nonStdFontMap[fontName] || fontName;
<add>
<add> this.bold = (fontName.search(/bold/gi) !== -1);
<add> this.italic = ((fontName.search(/oblique/gi) !== -1) ||
<add> (fontName.search(/italic/gi) !== -1));
<add>
<add> // Use 'name' instead of 'fontName' here because the original
<add> // name ArialBlack for example will be replaced by Helvetica.
<add> this.black = (name.search(/Black/g) !== -1);
<add>
<add> // if at least one width is present, remeasure all chars when exists
<add> this.remeasure = Object.keys(this.widths).length > 0;
<add> if (isStandardFont && type === 'CIDFontType2' &&
<add> this.cidEncoding.indexOf('Identity-') === 0) {
<add> var GlyphMapForStandardFonts = getGlyphMapForStandardFonts();
<add> // Standard fonts might be embedded as CID font without glyph mapping.
<add> // Building one based on GlyphMapForStandardFonts.
<add> var map = [];
<add> for (charCode in GlyphMapForStandardFonts) {
<add> map[+charCode] = GlyphMapForStandardFonts[charCode];
<add> }
<add> if (/Arial-?Black/i.test(name)) {
<add> var SupplementalGlyphMapForArialBlack =
<add> getSupplementalGlyphMapForArialBlack();
<add> for (charCode in SupplementalGlyphMapForArialBlack) {
<add> map[+charCode] = SupplementalGlyphMapForArialBlack[charCode];
<add> }
<add> }
<add> var isIdentityUnicode = this.toUnicode instanceof IdentityToUnicodeMap;
<add> if (!isIdentityUnicode) {
<add> this.toUnicode.forEach(function(charCode, unicodeCharCode) {
<add> map[+charCode] = unicodeCharCode;
<add> });
<add> }
<add> this.toFontChar = map;
<add> this.toUnicode = new ToUnicodeMap(map);
<add> } else if (/Symbol/i.test(fontName)) {
<add> this.toFontChar = buildToFontChar(SymbolSetEncoding, getGlyphsUnicode(),
<add> this.differences);
<add> } else if (/Dingbats/i.test(fontName)) {
<add> if (/Wingdings/i.test(name)) {
<add> warn('Non-embedded Wingdings font, falling back to ZapfDingbats.');
<add> }
<add> this.toFontChar = buildToFontChar(ZapfDingbatsEncoding,
<add> getDingbatsGlyphsUnicode(),
<add> this.differences);
<add> } else if (isStandardFont) {
<add> this.toFontChar = buildToFontChar(this.defaultEncoding,
<add> getGlyphsUnicode(),
<add> this.differences);
<add> } else {
<add> var glyphsUnicodeMap = getGlyphsUnicode();
<add> this.toUnicode.forEach((charCode, unicodeCharCode) => {
<add> if (!this.composite) {
<add> var glyphName = (this.differences[charCode] ||
<add> this.defaultEncoding[charCode]);
<add> unicode = getUnicodeForGlyph(glyphName, glyphsUnicodeMap);
<add> if (unicode !== -1) {
<add> unicodeCharCode = unicode;
<add> }
<add> }
<add> this.toFontChar[charCode] = unicodeCharCode;
<add> });
<add> }
<add> this.loadedName = fontName.split('-')[0];
<add> this.loading = false;
<add> this.fontType = getFontType(type, subtype);
<add> },
<add>
<ide> checkAndRepair: function Font_checkAndRepair(name, font, properties) {
<ide> function readTableEntry(file) {
<ide> var tag = bytesToString(file.getBytes(4));
<ide> var Font = (function FontClosure() {
<ide> data[50] = 0;
<ide> data[51] = 1;
<ide> } else {
<del> warn('Could not fix indexToLocFormat: ' + indexToLocFormat);
<add> throw new FormatError('Could not fix indexToLocFormat: ' +
<add> indexToLocFormat);
<ide> }
<ide> }
<ide> }
<ide> var Font = (function FontClosure() {
<ide> var startOffset = itemDecode(locaData, 0);
<ide> var writeOffset = 0;
<ide> var missingGlyphData = Object.create(null);
<del> // Glyph zero should be notdef which isn't drawn. Sometimes this is a
<del> // valid glyph but, then it is duplicated.
<del> missingGlyphData[0] = true;
<ide> itemEncode(locaData, 0, writeOffset);
<ide> var i, j;
<ide> // When called with dupFirstEntry the number of glyphs has already been
<ide> var Font = (function FontClosure() {
<ide> found = true;
<ide> }
<ide> }
<del> if (!found) {
<del> charCodeToGlyphId[charCode] = 0; // notdef
<del> }
<ide> }
<ide> } else if (cmapPlatformId === 0 && cmapEncodingId === 0) {
<ide> // Default Unicode semantics, use the charcodes as is. | 1 |
Javascript | Javascript | remove repeated test | 69d4a48ff67188214bc28ec1a4d138c5997ce171 | <ide><path>test/unit/core.js
<ide> test( "isNumeric", function() {
<ide> equal( t( [ 42 ] ), false, "Array with one number" );
<ide> equal( t(function(){} ), false, "Instance of a function");
<ide> equal( t( new Date() ), false, "Instance of a Date");
<del> equal( t(function(){} ), false, "Instance of a function");
<ide> });
<ide>
<ide> test("isXMLDoc - HTML", function() { | 1 |
Text | Text | move thefourtheye to tsc emeritus | c3c64a1034a52e58c9684a0135a2e4ce536e41ef | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> **Sam Roberts** <vieuxtech@gmail.com>
<ide> * [targos](https://github.com/targos) -
<ide> **Michaël Zasso** <targos@protonmail.com> (he/him)
<del>* [thefourtheye](https://github.com/thefourtheye) -
<del>**Sakthipriyan Vairamani** <thechargingvolcano@gmail.com> (he/him)
<ide> * [tniessen](https://github.com/tniessen) -
<ide> **Tobias Nießen** <tniessen@tnie.de>
<ide> * [Trott](https://github.com/Trott) -
<ide> For information about the governance of the Node.js project, see
<ide> **Rod Vagg** <r@va.gg>
<ide> * [shigeki](https://github.com/shigeki) -
<ide> **Shigeki Ohtsu** <ohtsu@ohtsu.org> (he/him)
<add>* [thefourtheye](https://github.com/thefourtheye) -
<add>**Sakthipriyan Vairamani** <thechargingvolcano@gmail.com> (he/him)
<ide> * [TimothyGu](https://github.com/TimothyGu) -
<ide> **Tiancheng "Timothy" Gu** <timothygu99@gmail.com> (he/him)
<ide> * [trevnorris](https://github.com/trevnorris) - | 1 |
Javascript | Javascript | add coverage for string array dgram send() | df14956ca05aa26573474af17e00abf0e02edb6a | <ide><path>test/parallel/test-dgram-send-multi-string-array.js
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const dgram = require('dgram');
<add>const socket = dgram.createSocket('udp4');
<add>const data = ['foo', 'bar', 'baz'];
<add>
<add>socket.on('message', common.mustCall((msg, rinfo) => {
<add> socket.close();
<add> assert.deepStrictEqual(msg.toString(), data.join(''));
<add>}));
<add>
<add>socket.bind(() => socket.send(data, socket.address().port, 'localhost')); | 1 |
PHP | PHP | fix a typo in artisan command description | 72546bb59b55cf8edb0ddbdf49ac8537ae3e9f3c | <ide><path>src/Illuminate/Foundation/Console/UpCommand.php
<ide> class UpCommand extends Command {
<ide> *
<ide> * @var string
<ide> */
<del> protected $description = "Bring the application out of maintenace mode";
<add> protected $description = "Bring the application out of maintenance mode";
<ide>
<ide> /**
<ide> * Execute the console command. | 1 |
Python | Python | fix image ids in libvirt driver | 78527a5e8e41244820b03a007ba8f495f331c36e | <ide><path>libcloud/compute/drivers/libvirt_driver.py
<ide> def list_images(self, location=IMAGES_LOCATION):
<ide> name, size = image.split(' ')
<ide> name = name.replace(IMAGES_LOCATION + '/', '')
<ide> size = int(size)
<del> nodeimage = NodeImage(id=image, name=name, driver=self, extra={'host': self.host, 'size': size})
<add> nodeimage = NodeImage(id=name, name=name, driver=self, extra={'host': self.host, 'size': size})
<ide> images.append(nodeimage)
<ide>
<ide> return images | 1 |
Text | Text | add global node_modules to require.resolve() | 6fd8022641da3e58fa44f339457110b15813c9be | <ide><path>doc/api/modules.md
<ide> LOAD_AS_DIRECTORY(X)
<ide> 2. LOAD_INDEX(X)
<ide>
<ide> LOAD_NODE_MODULES(X, START)
<del>1. let DIRS=NODE_MODULES_PATHS(START)
<add>1. let DIRS = NODE_MODULES_PATHS(START)
<ide> 2. for each DIR in DIRS:
<ide> a. LOAD_AS_FILE(DIR/X)
<ide> b. LOAD_AS_DIRECTORY(DIR/X)
<ide>
<ide> NODE_MODULES_PATHS(START)
<ide> 1. let PARTS = path split(START)
<ide> 2. let I = count of PARTS - 1
<del>3. let DIRS = []
<add>3. let DIRS = [GLOBAL_FOLDERS]
<ide> 4. while I >= 0,
<ide> a. if PARTS[I] = "node_modules" CONTINUE
<ide> b. DIR = path join(PARTS[0 .. I] + "node_modules")
<ide> when people are unaware that `NODE_PATH` must be set. Sometimes a
<ide> module's dependencies change, causing a different version (or even a
<ide> different module) to be loaded as the `NODE_PATH` is searched.
<ide>
<del>Additionally, Node.js will search in the following locations:
<add>Additionally, Node.js will search in the following list of GLOBAL_FOLDERS:
<ide>
<ide> * 1: `$HOME/.node_modules`
<ide> * 2: `$HOME/.node_libraries`
<ide> changes:
<ide> * `request` {string} The module path to resolve.
<ide> * `options` {Object}
<ide> * `paths` {string[]} Paths to resolve module location from. If present, these
<del> paths are used instead of the default resolution paths. Note that each of
<del> these paths is used as a starting point for the module resolution algorithm,
<del> meaning that the `node_modules` hierarchy is checked from this location.
<add> paths are used instead of the default resolution paths, with the exception
<add> of [GLOBAL_FOLDERS][] like `$HOME/.node_modules`, which are always
<add> included. Note that each of these paths is used as a starting point for
<add> the module resolution algorithm, meaning that the `node_modules` hierarchy
<add> is checked from this location.
<ide> * Returns: {string}
<ide>
<ide> Use the internal `require()` machinery to look up the location of a module,
<ide> const builtin = require('module').builtinModules;
<ide> [`Error`]: errors.html#errors_class_error
<ide> [`module` object]: #modules_the_module_object
<ide> [`path.dirname()`]: path.html#path_path_dirname_path
<add>[GLOBAL_FOLDERS]: #modules_loading_from_the_global_folders
<ide> [exports shortcut]: #modules_exports_shortcut
<ide> [module resolution]: #modules_all_together
<ide> [module wrapper]: #modules_the_module_wrapper | 1 |
Javascript | Javascript | add `js_file_prod` rule | 0b2d5317c419a78f2068437c18a0bf54c0ef325d | <ide><path>packager/react-packager/src/JSTransformer/worker/__tests__/inline-test.js
<ide> describe('inline constants', () => {
<ide> const {ast} = inline('arbitrary.hs', {ast: toAst(code)}, {dev: false});
<ide> expect(toString(ast)).toEqual(code.replace(/__DEV__/, 'false'));
<ide> });
<del>});
<ide>
<add> it('can work with wrapped modules', () => {
<add> const code = `__arbitrary(function() {
<add> var Platform = require('react-native').Platform;
<add> var a = Platform.OS, b = Platform.select({android: 1, ios: 2});
<add> });`;
<add> const {ast} = inline(
<add> 'arbitrary', {code}, {dev: true, platform: 'android', isWrapped: true});
<add> expect(toString(ast)).toEqual(
<add> normalize(
<add> code
<add> .replace(/Platform\.OS/, '"android"')
<add> .replace(/Platform\.select[^)]+\)/, 1)
<add> )
<add> );
<add> });
<add>
<add> it('can work with transformed require calls', () => {
<add> const code = `__arbitrary(function() {
<add> var a = require(123, 'react-native').Platform.OS;
<add> });`;
<add> const {ast} = inline(
<add> 'arbitrary', {code}, {dev: true, platform: 'android', isWrapped: true});
<add> expect(toString(ast)).toEqual(
<add> normalize(code.replace(/require\([^)]+\)\.Platform\.OS/, '"android"')));
<add> });
<add>});
<ide><path>packager/react-packager/src/JSTransformer/worker/collect-dependencies.js
<ide>
<ide> const {traverse, types} = require('babel-core');
<ide>
<del>const isRequireCall = (callee, firstArg) =>
<del> callee.type !== 'Identifier' ||
<del> callee.name !== 'require' ||
<del> !firstArg ||
<del> firstArg.type !== 'StringLiteral';
<del>
<del>function collectDependencies(ast, code) {
<del> let nextIndex = 0;
<del> const dependencyIndexes = new Map();
<del>
<del> function getIndex(depencyId) {
<del> let index = dependencyIndexes.get(depencyId);
<add>class Replacement {
<add> constructor() {
<add> this.nameToIndex = new Map();
<add> this.nextIndex = 0;
<add> }
<add>
<add> isRequireCall(callee, firstArg) {
<add> return (
<add> callee.type === 'Identifier' && callee.name === 'require' &&
<add> firstArg && firstArg.type === 'StringLiteral'
<add> );
<add> }
<add>
<add> getIndex(name) {
<add> let index = this.nameToIndex.get(name);
<ide> if (index !== undefined) {
<ide> return index;
<ide> }
<del>
<del> index = nextIndex++;
<del> dependencyIndexes.set(depencyId, index);
<add> index = this.nextIndex++;
<add> this.nameToIndex.set(name, index);
<ide> return index;
<ide> }
<ide>
<add> getNames() {
<add> return Array.from(this.nameToIndex.keys());
<add> }
<add>
<add> makeArgs(newId, oldId) {
<add> return [newId, oldId];
<add> }
<add>}
<add>
<add>class ProdReplacement {
<add> constructor(names) {
<add> this.replacement = new Replacement();
<add> this.names = names;
<add> }
<add>
<add> isRequireCall(callee, firstArg) {
<add> return (
<add> callee.type === 'Identifier' && callee.name === 'require' &&
<add> firstArg && firstArg.type === 'NumericLiteral'
<add> );
<add> }
<add>
<add> getIndex(id) {
<add> if (id in this.names) {
<add> return this.replacement.getIndex(this.names[id]);
<add> }
<add>
<add> throw new Error(
<add> `${id} is not a known module ID. Existing mappings: ${
<add> this.names.map((n, i) => `${i} => ${n}`).join(', ')}`
<add> );
<add> }
<add>
<add> getNames() {
<add> return this.replacement.getNames();
<add> }
<add>
<add> makeArgs(newId) {
<add> return [newId];
<add> }
<add>}
<add>
<add>function collectDependencies(ast, replacement) {
<ide> traverse(ast, {
<ide> CallExpression(path) {
<ide> const node = path.node;
<ide> const arg = node.arguments[0];
<del> if (isRequireCall(node.callee, arg)) {
<del> return;
<add> if (replacement.isRequireCall(node.callee, arg)) {
<add> const index = replacement.getIndex(arg.value);
<add> node.arguments = replacement.makeArgs(types.numericLiteral(index), arg);
<ide> }
<del>
<del> node.arguments[0] = types.numericLiteral(getIndex(arg.value));
<ide> }
<ide> });
<ide>
<del> return Array.from(dependencyIndexes.keys());
<add> return replacement.getNames();
<ide> }
<ide>
<del>module.exports = collectDependencies;
<add>exports = module.exports =
<add> ast => collectDependencies(ast, new Replacement());
<add>exports.forOptimization =
<add> (ast, names) => collectDependencies(ast, new ProdReplacement(names));
<ide><path>packager/react-packager/src/JSTransformer/worker/constant-folding.js
<ide> const babel = require('babel-core');
<ide> const t = babel.types;
<ide>
<del>const isLiteral = binaryExpression =>
<del> t.isLiteral(binaryExpression.left) && t.isLiteral(binaryExpression.right);
<del>
<ide> const Conditional = {
<ide> exit(path) {
<ide> const node = path.node;
<ide> function constantFolding(filename, transformResult) {
<ide> });
<ide> }
<ide>
<add>constantFolding.plugin = plugin;
<ide> module.exports = constantFolding;
<del>
<ide><path>packager/react-packager/src/JSTransformer/worker/inline.js
<ide> const importMap = new Map([['ReactNative', 'react-native']]);
<ide>
<ide> const isGlobal = (binding) => !binding;
<ide>
<del>const isToplevelBinding = (binding) => isGlobal(binding) || !binding.scope.parent;
<add>const isToplevelBinding = (binding, isWrappedModule) =>
<add> isGlobal(binding) ||
<add> !binding.scope.parent ||
<add> isWrappedModule && !binding.scope.parent.parent;
<ide>
<ide> const isRequireCall = (node, dependencyId, scope) =>
<ide> t.isCallExpression(node) &&
<ide> t.isIdentifier(node.callee, requirePattern) &&
<del> t.isStringLiteral(node.arguments[0], t.stringLiteral(dependencyId));
<add> checkRequireArgs(node.arguments, dependencyId);
<ide>
<ide> const isImport = (node, scope, patterns) =>
<ide> patterns.some(pattern => {
<ide> const importName = importMap.get(pattern.name) || pattern.name;
<ide> return isRequireCall(node, importName, scope);
<ide> });
<ide>
<del>function isImportOrGlobal(node, scope, patterns) {
<add>function isImportOrGlobal(node, scope, patterns, isWrappedModule) {
<ide> const identifier = patterns.find(pattern => t.isIdentifier(node, pattern));
<del> return identifier && isToplevelBinding(scope.getBinding(identifier.name)) ||
<del> isImport(node, scope, patterns);
<add> return (
<add> identifier &&
<add> isToplevelBinding(scope.getBinding(identifier.name), isWrappedModule) ||
<add> isImport(node, scope, patterns)
<add> );
<ide> }
<ide>
<del>const isPlatformOS = (node, scope) =>
<add>const isPlatformOS = (node, scope, isWrappedModule) =>
<ide> t.isIdentifier(node.property, os) &&
<del> isImportOrGlobal(node.object, scope, [platform]);
<add> isImportOrGlobal(node.object, scope, [platform], isWrappedModule);
<ide>
<del>const isReactPlatformOS = (node, scope) =>
<add>const isReactPlatformOS = (node, scope, isWrappedModule) =>
<ide> t.isIdentifier(node.property, os) &&
<ide> t.isMemberExpression(node.object) &&
<ide> t.isIdentifier(node.object.property, platform) &&
<del> isImportOrGlobal(node.object.object, scope, [React, ReactNative]);
<add> isImportOrGlobal(
<add> node.object.object, scope, [React, ReactNative], isWrappedModule);
<ide>
<ide> const isProcessEnvNodeEnv = (node, scope) =>
<ide> t.isIdentifier(node.property, nodeEnv) &&
<ide> const isProcessEnvNodeEnv = (node, scope) =>
<ide> t.isIdentifier(node.object.object, processId) &&
<ide> isGlobal(scope.getBinding(processId.name));
<ide>
<del>const isPlatformSelect = (node, scope) =>
<add>const isPlatformSelect = (node, scope, isWrappedModule) =>
<ide> t.isMemberExpression(node.callee) &&
<ide> t.isIdentifier(node.callee.object, platform) &&
<ide> t.isIdentifier(node.callee.property, select) &&
<del> isImportOrGlobal(node.callee.object, scope, [platform]);
<add> isImportOrGlobal(node.callee.object, scope, [platform], isWrappedModule);
<ide>
<del>const isReactPlatformSelect = (node, scope) =>
<add>const isReactPlatformSelect = (node, scope, isWrappedModule) =>
<ide> t.isMemberExpression(node.callee) &&
<ide> t.isIdentifier(node.callee.property, select) &&
<ide> t.isMemberExpression(node.callee.object) &&
<ide> t.isIdentifier(node.callee.object.property, platform) &&
<del> isImportOrGlobal(node.callee.object.object, scope, [React, ReactNative]);
<add> isImportOrGlobal(
<add> node.callee.object.object, scope, [React, ReactNative], isWrappedModule);
<ide>
<ide> const isDev = (node, parent, scope) =>
<ide> t.isIdentifier(node, dev) &&
<ide> const inlinePlugin = {
<ide> MemberExpression(path, state) {
<ide> const node = path.node;
<ide> const scope = path.scope;
<add> const opts = state.opts;
<ide>
<del> if (isPlatformOS(node, scope) || isReactPlatformOS(node, scope)) {
<del> path.replaceWith(t.stringLiteral(state.opts.platform));
<add> if (
<add> isPlatformOS(node, scope, opts.isWrapped) ||
<add> isReactPlatformOS(node, scope, opts.isWrapped)
<add> ) {
<add> path.replaceWith(t.stringLiteral(opts.platform));
<ide> } else if (isProcessEnvNodeEnv(node, scope)) {
<ide> path.replaceWith(
<del> t.stringLiteral(state.opts.dev ? 'development' : 'production'));
<add> t.stringLiteral(opts.dev ? 'development' : 'production'));
<ide> }
<ide> },
<ide> CallExpression(path, state) {
<ide> const node = path.node;
<ide> const scope = path.scope;
<ide> const arg = node.arguments[0];
<add> const opts = state.opts;
<ide>
<del> if (isPlatformSelect(node, scope) || isReactPlatformSelect(node, scope)) {
<add> if (
<add> isPlatformSelect(node, scope, opts.isWrapped) ||
<add> isReactPlatformSelect(node, scope, opts.isWrapped)
<add> ) {
<ide> const replacement = t.isObjectExpression(arg)
<del> ? findProperty(arg, state.opts.platform)
<add> ? findProperty(arg, opts.platform)
<ide> : node;
<ide>
<ide> path.replaceWith(replacement);
<ide> const inlinePlugin = {
<ide>
<ide> const plugin = () => inlinePlugin;
<ide>
<add>function checkRequireArgs(args, dependencyId) {
<add> const pattern = t.stringLiteral(dependencyId);
<add> return t.isStringLiteral(args[0], pattern) ||
<add> t.isNumericLiteral(args[0]) && t.isStringLiteral(args[1], pattern);
<add>}
<add>
<ide> function inline(filename, transformResult, options) {
<ide> const code = transformResult.code;
<ide> const babelOptions = {
<ide> function inline(filename, transformResult, options) {
<ide> : babel.transform(code, babelOptions);
<ide> }
<ide>
<add>inline.plugin = inlinePlugin;
<ide> module.exports = inline;
<ide><path>packager/react-packager/src/ModuleGraph/worker.js
<ide> const dirname = require('path').dirname;
<ide>
<ide> const babel = require('babel-core');
<ide> const generate = require('babel-generator').default;
<del>const series = require('async/series');
<add>
<ide> const mkdirp = require('mkdirp');
<add>const series = require('async/series');
<add>const sourceMap = require('source-map');
<ide>
<ide> const collectDependencies = require('../JSTransformer/worker/collect-dependencies');
<add>const constantFolding = require('../JSTransformer/worker/constant-folding').plugin;
<add>const inline = require('../JSTransformer/worker/inline').plugin;
<add>const minify = require('../JSTransformer/worker/minify');
<add>
<ide> const docblock = require('../node-haste/DependencyGraph/docblock');
<ide>
<ide> function transformModule(infile, options, outfile, callback) {
<ide> function transformModule(infile, options, outfile, callback) {
<ide> };
<ide>
<ide> try {
<del> mkdirp.sync(dirname(outfile));
<del> fs.writeFileSync(outfile, JSON.stringify(result), 'utf8');
<add> writeResult(outfile, result);
<ide> } catch (writeError) {
<ide> callback(writeError);
<ide> return;
<ide> function transformModule(infile, options, outfile, callback) {
<ide> });
<ide> }
<ide>
<add>function optimizeModule(infile, outfile, options, callback) {
<add> let data;
<add> try {
<add> data = JSON.parse(fs.readFileSync(infile, 'utf8'));
<add> } catch (readError) {
<add> callback(readError);
<add> return;
<add> }
<add>
<add> const transformed = data.transformed;
<add> const result = Object.assign({}, data);
<add> result.transformed = {};
<add>
<add> const file = data.file;
<add> const code = data.code;
<add> try {
<add> Object.keys(transformed).forEach(key => {
<add> result.transformed[key] = optimize(transformed[key], file, code, options);
<add> });
<add>
<add> writeResult(outfile, result);
<add> } catch (error) {
<add> callback(error);
<add> return;
<add> }
<add>
<add> callback(null);
<add>}
<add>
<ide> function makeResult(ast, filename, sourceCode) {
<ide> const dependencies = collectDependencies(ast);
<ide> const file = wrapModule(ast);
<ide> function wrapModule(file) {
<ide> return t.file(t.program([t.expressionStatement(def)]));
<ide> }
<ide>
<add>function optimize(transformed, file, originalCode, options) {
<add> const optimized =
<add> optimizeCode(transformed.code, transformed.map, file, options);
<add>
<add> const dependencies = collectDependencies.forOptimization(
<add> optimized.ast, transformed.dependencies);
<add>
<add> const gen = generate(optimized.ast, {
<add> comments: false,
<add> compact: true,
<add> filename: file,
<add> sourceMaps: true,
<add> sourceMapTarget: file,
<add> sourceFileName: file,
<add> }, originalCode);
<add>
<add> const merged = new sourceMap.SourceMapGenerator();
<add> const inputMap = new sourceMap.SourceMapConsumer(transformed.map);
<add> new sourceMap.SourceMapConsumer(gen.map)
<add> .eachMapping(mapping => {
<add> const original = inputMap.originalPositionFor({
<add> line: mapping.originalLine,
<add> column: mapping.originalColumn,
<add> });
<add> if (original.line == null) {
<add> return;
<add> }
<add>
<add> merged.addMapping({
<add> generated: {line: mapping.generatedLine, column: mapping.generatedColumn},
<add> original: {line: original.line, column: original.column || 0},
<add> source: file,
<add> name: original.name || mapping.name,
<add> });
<add> });
<add>
<add> const min = minify(file, gen.code, merged.toJSON());
<add> return {code: min.code, map: min.map, dependencies};
<add>}
<add>
<add>function optimizeCode(code, map, filename, options) {
<add> const inlineOptions = Object.assign({isWrapped: true}, options);
<add> return babel.transform(code, {
<add> plugins: [[constantFolding], [inline, inlineOptions]],
<add> babelrc: false,
<add> code: false,
<add> filename,
<add> });
<add>}
<add>
<add>function writeResult(outfile, result) {
<add> mkdirp.sync(dirname(outfile));
<add> fs.writeFileSync(outfile, JSON.stringify(result), 'utf8');
<add>}
<add>
<ide> exports.transformModule = transformModule;
<add>exports.optimizeModule = optimizeModule; | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.