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
|
---|---|---|---|---|---|
Mixed | PHP | remove stupid test | a4c781ac40695051b2559d127e3d7595dcc5f904 | <ide><path>CHANGELOG-5.4.md
<ide> # Release Notes for 5.4.x
<ide>
<add>## [Unreleased]
<add>
<add>### Changed
<add>- Moved `tap()` method from `Builder` to `BuildsQueries` ([#20384](https://github.com/laravel/framework/pull/20384))
<add>- Made Blade `or` operator case-insensitive ([#20425](https://github.com/laravel/framework/pull/20425))
<add>- Support `$amount = 0` in `Arr::random()` ([#20439](https://github.com/laravel/framework/pull/20439))
<add>
<add>### Fixed
<add>- Fixed bug when using empty values in `SQLiteGrammar::compileInsert()` ([#20424](https://github.com/laravel/framework/pull/20424))
<add>
<add>
<add>## v5.4.32 (2017-08-03)
<add>
<add>### Added
<add>- Added `FilesystemAdapter::path()` method ([#20395](https://github.com/laravel/framework/pull/20395))
<add>
<add>### Changed
<add>- Allow `Collection::random()` to return `0` items ([#20396](https://github.com/laravel/framework/pull/20396), [#20402](https://github.com/laravel/framework/pull/20402))
<add>- Accept options on `FilesystemAdapter::temporaryUrl()` ([#20394](https://github.com/laravel/framework/pull/20394))
<add>- Sync `withoutOverlapping` method on `Event` and `CallbackEvent` ([#20389](https://github.com/laravel/framework/pull/20389))
<add>- Prevent PHP file uploads by default unless explicitly allowed ([#20392](https://github.com/laravel/framework/pull/20392), [#20400](https://github.com/laravel/framework/pull/20400))
<add>- Allow other filesystem adapter to implement `temporaryUrl()` ([#20398](https://github.com/laravel/framework/pull/20398))
<add>
<add>### Fixed
<add>- Reverted breaking change on `BelongsToMany::create()` ([#20407](https://github.com/laravel/framework/pull/20407))
<add>
<add>
<ide> ## v5.4.31 (2017-08-02)
<ide>
<ide> ### Added
<ide><path>src/Illuminate/Database/Concerns/BuildsQueries.php
<ide> public function when($value, $callback, $default = null)
<ide> return $this;
<ide> }
<ide>
<add> /**
<add> * Pass the query to a given callback.
<add> *
<add> * @param \Closure $callback
<add> * @return \Illuminate\Database\Query\Builder
<add> */
<add> public function tap($callback)
<add> {
<add> return $this->when(true, $callback);
<add> }
<add>
<ide> /**
<ide> * Apply the callback's query changes if the given "value" is false.
<ide> *
<ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> public function where($column, $operator = null, $value = null, $boolean = 'and'
<ide> /**
<ide> * Add an "or where" clause to the query.
<ide> *
<del> * @param \Closure|string $column
<add> * @param \Closure|array|string $column
<ide> * @param string $operator
<ide> * @param mixed $value
<ide> * @return \Illuminate\Database\Eloquent\Builder|static
<ide><path>src/Illuminate/Database/Migrations/Migrator.php
<ide> protected function rollbackMigrations(array $migrations, $paths, array $options)
<ide> $migration = (object) $migration;
<ide>
<ide> if (! $file = Arr::get($files, $migration->migration)) {
<add> $this->note("<fg=red>Migration not found:</> {$migration->migration}");
<add>
<ide> continue;
<ide> }
<ide>
<ide><path>src/Illuminate/Database/Query/Builder.php
<ide> public function crossJoin($table, $first = null, $operator = null, $second = nul
<ide> return $this;
<ide> }
<ide>
<del> /**
<del> * Pass the query to a given callback.
<del> *
<del> * @param \Closure $callback
<del> * @return \Illuminate\Database\Query\Builder
<del> */
<del> public function tap($callback)
<del> {
<del> return $this->when(true, $callback);
<del> }
<del>
<ide> /**
<ide> * Merge an array of where clauses and bindings.
<ide> *
<ide><path>src/Illuminate/Database/Query/Grammars/SQLiteGrammar.php
<ide> public function compileInsert(Builder $query, array $values)
<ide> // grammar insert builder because no special syntax is needed for the single
<ide> // row inserts in SQLite. However, if there are multiples, we'll continue.
<ide> if (count($values) == 1) {
<del> return parent::compileInsert($query, reset($values));
<add> return empty(reset($values))
<add> ? "insert into $table default values"
<add> : parent::compileInsert($query, reset($values));
<ide> }
<ide>
<ide> $names = $this->columnize(array_keys(reset($values)));
<ide><path>src/Illuminate/Foundation/helpers.php
<ide> function storage_path($path = '')
<ide> /**
<ide> * Translate the given message.
<ide> *
<del> * @param string $id
<add> * @param string $key
<ide> * @param array $replace
<ide> * @param string $locale
<ide> * @return \Illuminate\Contracts\Translation\Translator|string|array|null
<ide> */
<del> function trans($id = null, $replace = [], $locale = null)
<add> function trans($key = null, $replace = [], $locale = null)
<ide> {
<del> if (is_null($id)) {
<add> if (is_null($key)) {
<ide> return app('translator');
<ide> }
<ide>
<del> return app('translator')->trans($id, $replace, $locale);
<add> return app('translator')->trans($key, $replace, $locale);
<ide> }
<ide> }
<ide>
<ide> if (! function_exists('trans_choice')) {
<ide> /**
<ide> * Translates the given message based on a count.
<ide> *
<del> * @param string $id
<add> * @param string $key
<ide> * @param int|array|\Countable $number
<ide> * @param array $replace
<ide> * @param string $locale
<ide> * @return string
<ide> */
<del> function trans_choice($id, $number, array $replace = [], $locale = null)
<add> function trans_choice($key, $number, array $replace = [], $locale = null)
<ide> {
<del> return app('translator')->transChoice($id, $number, $replace, $locale);
<add> return app('translator')->transChoice($key, $number, $replace, $locale);
<ide> }
<ide> }
<ide>
<ide><path>src/Illuminate/Support/Arr.php
<ide> public static function pull(&$array, $key, $default = null)
<ide> }
<ide>
<ide> /**
<del> * Get a random value from an array.
<add> * Get one or a specified number of random values from an array.
<ide> *
<ide> * @param array $array
<del> * @param int|null $amount
<add> * @param int|null $number
<ide> * @return mixed
<ide> *
<ide> * @throws \InvalidArgumentException
<ide> */
<del> public static function random($array, $amount = null)
<add> public static function random($array, $number = null)
<ide> {
<del> if (($requested = $amount ?: 1) > ($count = count($array))) {
<add> $requested = is_null($number) ? 1 : $number;
<add>
<add> $count = count($array);
<add>
<add> if ($requested > $count) {
<ide> throw new InvalidArgumentException(
<del> "You requested {$requested} items, but there are only {$count} items in the array."
<add> "You requested {$requested} items, but there are only {$count} items available."
<ide> );
<ide> }
<ide>
<del> if (is_null($amount)) {
<add> if (is_null($number)) {
<ide> return $array[array_rand($array)];
<ide> }
<ide>
<del> $keys = array_rand($array, $amount);
<add> if ((int) $number === 0) {
<add> return [];
<add> }
<add>
<add> $keys = array_rand($array, $number);
<ide>
<ide> $results = [];
<ide>
<ide><path>src/Illuminate/Support/Collection.php
<ide> public static function unwrap($value)
<ide> /**
<ide> * Create a new collection by invoking the callback a given amount of times.
<ide> *
<del> * @param int $amount
<del> * @param callable|null $callback
<add> * @param int $number
<add> * @param callable $callback
<ide> * @return static
<ide> */
<del> public static function times($amount, callable $callback = null)
<add> public static function times($number, callable $callback = null)
<ide> {
<del> if ($amount < 1) {
<add> if ($number < 1) {
<ide> return new static;
<ide> }
<ide>
<ide> if (is_null($callback)) {
<del> return new static(range(1, $amount));
<add> return new static(range(1, $number));
<ide> }
<ide>
<del> return (new static(range(1, $amount)))->map($callback);
<add> return (new static(range(1, $number)))->map($callback);
<ide> }
<ide>
<ide> /**
<ide> public function put($key, $value)
<ide> }
<ide>
<ide> /**
<del> * Get zero or more items randomly from the collection.
<add> * Get one or a specified number of items randomly from the collection.
<ide> *
<del> * @param int|null $amount
<add> * @param int|null $number
<ide> * @return mixed
<ide> *
<ide> * @throws \InvalidArgumentException
<ide> */
<del> public function random($amount = null)
<add> public function random($number = null)
<ide> {
<del> if ($amount === 0) {
<del> return new static;
<del> }
<del>
<del> if (($requested = $amount ?: 1) > ($count = $this->count())) {
<del> throw new InvalidArgumentException(
<del> "You requested {$requested} items, but there are only {$count} items in the collection."
<del> );
<del> }
<del>
<del> if (is_null($amount)) {
<add> if (is_null($number)) {
<ide> return Arr::random($this->items);
<ide> }
<ide>
<del> return new static(Arr::random($this->items, $amount));
<add> return new static(Arr::random($this->items, $number));
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/View/Compilers/Concerns/CompilesEchos.php
<ide> protected function compileEscapedEchos($value)
<ide> */
<ide> public function compileEchoDefaults($value)
<ide> {
<del> return preg_replace('/^(?=\$)(.+?)(?:\s+or\s+)(.+?)$/s', 'isset($1) ? $1 : $2', $value);
<add> return preg_replace('/^(?=\$)(.+?)(?:\s+or\s+)(.+?)$/si', 'isset($1) ? $1 : $2', $value);
<ide> }
<ide> }
<ide><path>src/Illuminate/View/Engines/EngineResolver.php
<ide> public function register($engine, Closure $resolver)
<ide> }
<ide>
<ide> /**
<del> * Resolver an engine instance by name.
<add> * Resolve an engine instance by name.
<ide> *
<ide> * @param string $engine
<ide> * @return \Illuminate\Contracts\View\Engine
<ide><path>tests/Database/DatabaseConcernsBuildsQueriesTraitTest.php
<add><?php
<add>
<add>namespace Illuminate\Tests\Database;
<add>
<add>use PHPUnit\Framework\TestCase;
<add>use Illuminate\Database\Concerns\BuildsQueries;
<add>
<add>class DatabaseConcernsBuildsQueriesTraitTest extends TestCase
<add>{
<add> public function testTapCallbackInstance()
<add> {
<add> $mock = $this->getMockForTrait(BuildsQueries::class);
<add> $mock->tap(function ($builder) use ($mock) {
<add> $this->assertEquals($mock, $builder);
<add> });
<add> }
<add>}
<ide><path>tests/Support/SupportArrTest.php
<ide> public function testPull()
<ide>
<ide> public function testRandom()
<ide> {
<del> $randomValue = Arr::random(['foo', 'bar', 'baz']);
<del>
<del> $this->assertContains($randomValue, ['foo', 'bar', 'baz']);
<del>
<del> $randomValues = Arr::random(['foo', 'bar', 'baz'], 1);
<add> $random = Arr::random(['foo', 'bar', 'baz']);
<add> $this->assertContains($random, ['foo', 'bar', 'baz']);
<add>
<add> $random = Arr::random(['foo', 'bar', 'baz'], 0);
<add> $this->assertInternalType('array', $random);
<add> $this->assertCount(0, $random);
<add>
<add> $random = Arr::random(['foo', 'bar', 'baz'], 1);
<add> $this->assertInternalType('array', $random);
<add> $this->assertCount(1, $random);
<add> $this->assertContains($random[0], ['foo', 'bar', 'baz']);
<add>
<add> $random = Arr::random(['foo', 'bar', 'baz'], 2);
<add> $this->assertInternalType('array', $random);
<add> $this->assertCount(2, $random);
<add> $this->assertContains($random[0], ['foo', 'bar', 'baz']);
<add> $this->assertContains($random[1], ['foo', 'bar', 'baz']);
<add>
<add> $random = Arr::random(['foo', 'bar', 'baz'], '0');
<add> $this->assertInternalType('array', $random);
<add> $this->assertCount(0, $random);
<add>
<add> $random = Arr::random(['foo', 'bar', 'baz'], '1');
<add> $this->assertInternalType('array', $random);
<add> $this->assertCount(1, $random);
<add> $this->assertContains($random[0], ['foo', 'bar', 'baz']);
<add>
<add> $random = Arr::random(['foo', 'bar', 'baz'], '2');
<add> $this->assertInternalType('array', $random);
<add> $this->assertCount(2, $random);
<add> $this->assertContains($random[0], ['foo', 'bar', 'baz']);
<add> $this->assertContains($random[1], ['foo', 'bar', 'baz']);
<add> }
<ide>
<del> $this->assertInternalType('array', $randomValues);
<del> $this->assertCount(1, $randomValues);
<del> $this->assertContains($randomValues[0], ['foo', 'bar', 'baz']);
<add> public function testRandomOnEmptyArray()
<add> {
<add> $random = Arr::random([], 0);
<add> $this->assertInternalType('array', $random);
<add> $this->assertCount(0, $random);
<ide>
<del> $randomValues = Arr::random(['foo', 'bar', 'baz'], 2);
<add> $random = Arr::random([], '0');
<add> $this->assertInternalType('array', $random);
<add> $this->assertCount(0, $random);
<add> }
<ide>
<del> $this->assertInternalType('array', $randomValues);
<del> $this->assertCount(2, $randomValues);
<del> $this->assertContains($randomValues[0], ['foo', 'bar', 'baz']);
<del> $this->assertContains($randomValues[1], ['foo', 'bar', 'baz']);
<add> public function testRandomThrowsAnErrorWhenRequestingMoreItemsThanAreAvailable()
<add> {
<add> $exceptions = 0;
<add>
<add> try {
<add> Arr::random([]);
<add> } catch (\InvalidArgumentException $e) {
<add> ++$exceptions;
<add> }
<add>
<add> try {
<add> Arr::random([], 1);
<add> } catch (\InvalidArgumentException $e) {
<add> ++$exceptions;
<add> }
<add>
<add> try {
<add> Arr::random([], 2);
<add> } catch (\InvalidArgumentException $e) {
<add> ++$exceptions;
<add> }
<add>
<add> $this->assertSame(3, $exceptions);
<ide> }
<ide>
<ide> public function testSet()
<ide><path>tests/Support/SupportCollectionTest.php
<ide> public function testRandom()
<ide> {
<ide> $data = new Collection([1, 2, 3, 4, 5, 6]);
<ide>
<add> $random = $data->random();
<add> $this->assertInternalType('integer', $random);
<add> $this->assertContains($random, $data->all());
<add>
<ide> $random = $data->random(0);
<ide> $this->assertInstanceOf(Collection::class, $random);
<ide> $this->assertCount(0, $random);
<ide> public function testRandom()
<ide> $this->assertInstanceOf(Collection::class, $random);
<ide> $this->assertCount(1, $random);
<ide>
<del> $random = $data->random(3);
<add> $random = $data->random(2);
<add> $this->assertInstanceOf(Collection::class, $random);
<add> $this->assertCount(2, $random);
<add>
<add> $random = $data->random('0');
<add> $this->assertInstanceOf(Collection::class, $random);
<add> $this->assertCount(0, $random);
<add>
<add> $random = $data->random('1');
<add> $this->assertInstanceOf(Collection::class, $random);
<add> $this->assertCount(1, $random);
<add>
<add> $random = $data->random('2');
<ide> $this->assertInstanceOf(Collection::class, $random);
<del> $this->assertCount(3, $random);
<add> $this->assertCount(2, $random);
<ide> }
<ide>
<ide> public function testRandomOnEmptyCollection()
<ide> public function testRandomOnEmptyCollection()
<ide> $random = $data->random(0);
<ide> $this->assertInstanceOf(Collection::class, $random);
<ide> $this->assertCount(0, $random);
<del> }
<ide>
<del> public function testRandomWithoutArgument()
<del> {
<del> $data = new Collection([1, 2, 3, 4, 5, 6]);
<del>
<del> $random = $data->random();
<del> $this->assertInternalType('integer', $random);
<del> $this->assertContains($random, $data->all());
<del> }
<del>
<del> /**
<del> * @expectedException \InvalidArgumentException
<del> */
<del> public function testRandomThrowsAnErrorWhenRequestingMoreItemsThanAreAvailable()
<del> {
<del> (new Collection)->random();
<add> $random = $data->random('0');
<add> $this->assertInstanceOf(Collection::class, $random);
<add> $this->assertCount(0, $random);
<ide> }
<ide>
<ide> public function testTakeLast() | 14 |
Javascript | Javascript | add an example of overriding the handler | 666705c0a4d128fdaa0a53929c194232a4e34087 | <ide><path>src/ng/exceptionHandler.js
<ide> * Any uncaught exception in angular expressions is delegated to this service.
<ide> * The default implementation simply delegates to `$log.error` which logs it into
<ide> * the browser console.
<del> *
<add> *
<ide> * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
<ide> * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
<ide> *
<add> * ## Example:
<add> *
<add> * <pre>
<add> * angular.module('exceptionOverride', []).factory('$exceptionHandler', function () {
<add> * return function (exception, cause) {
<add> * exception.message += ' (caused by "' + cause + '")';
<add> * throw exception;
<add> * };
<add> * });
<add> * </pre>
<add> *
<add> * This example will override the normal action of `$exceptionHandler`, to make angular
<add> * exceptions fail hard when they happen, instead of just logging to the console.
<add> *
<ide> * @param {Error} exception Exception associated with the error.
<ide> * @param {string=} cause optional information about the context in which
<ide> * the error was thrown. | 1 |
Python | Python | prepare new pypi release | d4b618bf23d83b1a7306bc6816bd509c23bba15d | <ide><path>keras/__init__.py
<ide> # Importable from root because it's technically not a layer
<ide> from .layers import Input
<ide>
<del>__version__ = '2.0.4'
<add>__version__ = '2.0.5'
<ide><path>setup.py
<ide>
<ide>
<ide> setup(name='Keras',
<del> version='2.0.4',
<add> version='2.0.5',
<ide> description='Deep Learning for Python',
<ide> author='Francois Chollet',
<ide> author_email='[email protected]',
<ide> url='https://github.com/fchollet/keras',
<del> download_url='https://github.com/fchollet/keras/tarball/2.0.4',
<add> download_url='https://github.com/fchollet/keras/tarball/2.0.5',
<ide> license='MIT',
<ide> install_requires=['theano', 'pyyaml', 'six'],
<ide> extras_require={ | 2 |
Text | Text | fix broken link in readme.md | e4e44c10fee2479ab789738664090628837d8313 | <ide><path>README.md
<ide> Airflow is the work of the [community](https://github.com/apache/airflow/graphs/
<ide> but the [core committers/maintainers](https://people.apache.org/committers-by-project.html#airflow)
<ide> are responsible for reviewing and merging PRs as well as steering conversation around new feature requests.
<ide> If you would like to become a maintainer, please review the Apache Airflow
<del>[committer requirements](https://cwiki.apache.org/confluence/display/AIRFLOW/Committers).
<add>[committer requirements](https://airflow.apache.org/docs/stable/project.html#committers).
<ide>
<ide> ## Can I use the Apache Airflow logo in my presentation?
<ide> | 1 |
Ruby | Ruby | inform users of macos upgrade | 1373441e53d838264c70690e9612009f0e9735d8 | <ide><path>Library/Homebrew/requirements/xcode_requirement.rb
<ide> def message
<ide> A full installation of Xcode.app#{version} is required to compile this software.
<ide> Installing just the Command Line Tools is not sufficient.
<ide> EOS
<del> if MacOS.version >= :lion
<add> if Version.new(MacOS::Xcode.latest_version) < Version.new(@version)
<add> message + <<~EOS
<add> Xcode#{version} cannot be installed on macOS #{MacOS.version}.
<add> You must upgrade your version of macOS.
<add> EOS
<add> elsif MacOS.version >= :lion
<ide> message + <<~EOS
<ide> Xcode can be installed from the App Store.
<ide> EOS | 1 |
Text | Text | add chinese version of the chapter fog | e5c645f8643ff3358309393f8e4852710a2ac97d | <ide><path>threejs/lessons/zh_cn/threejs-fog.md
<add>Title: Three.js 雾
<add>Description: Three.js中的雾
<add>TOC: 雾
<add>
<add>本文是three.js系列文章的一部分。第一篇文章是[three.js 基础](threejs-fundamentals.html)。如果你是个新手,还没读过,请从那里开始。如果你还没读过有关摄像机的章节,请从[这篇文章](threejs-cameras.html)开始。
<add>
<add>在3D引擎里,雾通常是基于离摄像机的距离褪色至某种特定颜色的方式。在three.js中添加雾是通过创建 `Fog` 或者 `FogExp2` 实例并设定scene的[`fog`](Scene.fog) 属性。
<add>
<add>`Fog` 让你设定 `near` 和 `far` 属性,代表距离摄像机的距离。任何物体比 `near` 近不会受到影响,任何物体比 `far` 远则完全是雾的颜色。在 `near` 和 `far` 中间的物体,会从它们自身材料的颜色褪色到雾的颜色。
<add>
<add>`FogExp2` 会根据离摄像机的距离呈指数增长。
<add>
<add>选择其中一个类型,创建雾并设定到场景中如下:
<add>
<add>```js
<add>const scene = new THREE.Scene();
<add>{
<add> const color = 0xFFFFFF; // white
<add> const near = 10;
<add> const far = 100;
<add> scene.fog = new THREE.Fog(color, near, far);
<add>}
<add>```
<add>
<add>或者对于 `FogExp2` 会是:
<add>
<add>```js
<add>const scene = new THREE.Scene();
<add>{
<add> const color = 0xFFFFFF;
<add> const density = 0.1;
<add> scene.fog = new THREE.FogExp2(color, density);
<add>}
<add>```
<add>
<add>`FogExp2` 比较接近现实效果,但是 `Fog` 使用的更加普遍,因为它支持设定影响区域,所以你可以设定一定距离内显示清晰的场景,过了这段距离再褪色到某种颜色。
<add>
<add><div class="spread">
<add> <div>
<add> <div data-diagram="fog" style="height: 300px;"></div>
<add> <div class="code">THREE.Fog</div>
<add> </div>
<add> <div>
<add> <div data-diagram="fogExp2" style="height: 300px;"></div>
<add> <div class="code">THREE.FogExp2</div>
<add> </div>
<add></div>
<add>
<add>需要注意的是雾是作用在 *渲染的物体* 上的,是物体颜色中每个像素计算的一部分。这意味着如果你想让你的场景褪色到某种颜色,你需要设定雾 **和** 场景的背景颜色为同一种颜色。背景颜色通过[`scene.background`](Scene.background)属性设置。你可以通过 `THREE.Color` 选择背景颜色设置。例如:
<add>
<add>```js
<add>scene.background = new THREE.Color('#F00'); // red
<add>```
<add>
<add><div class="spread">
<add> <div>
<add> <div data-diagram="fogBlueBackgroundRed" style="height: 300px;" class="border"></div>
<add> <div class="code">fog blue, background red</div>
<add> </div>
<add> <div>
<add> <div data-diagram="fogBlueBackgroundBlue" style="height: 300px;" class="border"></div>
<add> <div class="code">fog blue, background blue</div>
<add> </div>
<add></div>
<add>
<add>这是我们之前添加雾的例子。唯一的改动是在添加雾之后,我们设置了场景的背景颜色。
<add>
<add>```js
<add>const scene = new THREE.Scene();
<add>
<add>+{
<add>+ const near = 1;
<add>+ const far = 2;
<add>+ const color = 'lightblue';
<add>+ scene.fog = new THREE.Fog(color, near, far);
<add>+ scene.background = new THREE.Color(color);
<add>+}
<add>```
<add>
<add>在下面的例子,摄像机的 `near` 是0.1, `far` 是5,位于 `z = 2`的位置。方块为单位大小,位于Z=0的位置。这意味着将雾设置为 `near = 1` 和 `far = 2` ,方块会在它的中间位置淡出。
<add>
<add>{{{example url="../threejs-fog.html" }}}
<add>
<add>让我们添加界面来调整雾。我们将再次使用[dat.GUI](https://github.com/dataarts/dat.gui)。dat.GUI接收对象和属性参数,并自动为其创建界面。我们能够简单地操纵雾的 `near` 和 `far` 属性,但是 `near` 数值大于 `far` 是无效的,所以我们创建助手(helper)来确保 `near` 和 `far` 属性,让 `near` 小于或等于 `far` , `far` 大于或等于 `near`。
<add>
<add>```js
<add>// We use this class to pass to dat.gui
<add>// so when it manipulates near or far
<add>// near is never > far and far is never < near
<add>class FogGUIHelper {
<add> constructor(fog) {
<add> this.fog = fog;
<add> }
<add> get near() {
<add> return this.fog.near;
<add> }
<add> set near(v) {
<add> this.fog.near = v;
<add> this.fog.far = Math.max(this.fog.far, v);
<add> }
<add> get far() {
<add> return this.fog.far;
<add> }
<add> set far(v) {
<add> this.fog.far = v;
<add> this.fog.near = Math.min(this.fog.near, v);
<add> }
<add>}
<add>```
<add>
<add>之后我们可以像这样添加
<add>
<add>```js
<add>{
<add> const near = 1;
<add> const far = 2;
<add> const color = 'lightblue';
<add> scene.fog = new THREE.Fog(color, near, far);
<add> scene.background = new THREE.Color(color);
<add>+
<add>+ const fogGUIHelper = new FogGUIHelper(scene.fog);
<add>+ gui.add(fogGUIHelper, 'near', near, far).listen();
<add>+ gui.add(fogGUIHelper, 'far', near, far).listen();
<add>}
<add>```
<add>
<add>当我们设置摄像机的时候,设置(助手的 `near` 和 `far` 以调节雾的最小值和最大值。
<add>
<add>最后两行调用 `.listen()` 告诉dat.GUI *监听* 变化。当我们编辑 `far` 改变了 `near` 或者编辑 `near` 改变了 `far` ,dat.GUI将会为我们更新其他属性的UI。
<add>
<add>或许能够改变雾的颜色是个不错的主意,但是如上面提到的,我们需要保持雾的颜色和背景颜色一致。所以,让我们在助手上添加另一个 *虚拟* 属性,当dat.GUI改变它时会设置这两个颜色。
<add>
<add>dat.GUI能够通过4种方式设置颜色。分别是6位hex字符串 (如: `#112233`),色相、饱和度、明度的对象 (如: `{h: 60, s: 1, v: }`),RGB数组 (如: `[255, 128, 64]`),或者RGBA数组 (如: `[127, 200, 75, 0.3]`)。
<add>
<add>对于我们的目的而言,最简单的是用hex字符串的方式,因为dat.GUI只修改单个数值。幸运的是通过 `THREE.Color` 的 [`getHexString`](Color.getHexString) 方法我们能轻松地获得这个字符串,只需要在其前面添加 '#' 。
<add>
<add>```js
<add>// We use this class to pass to dat.gui
<add>// so when it manipulates near or far
<add>// near is never > far and far is never < near
<add>+// Also when dat.gui manipulates color we'll
<add>+// update both the fog and background colors.
<add>class FogGUIHelper {
<add>* constructor(fog, backgroundColor) {
<add> this.fog = fog;
<add>+ this.backgroundColor = backgroundColor;
<add> }
<add> get near() {
<add> return this.fog.near;
<add> }
<add> set near(v) {
<add> this.fog.near = v;
<add> this.fog.far = Math.max(this.fog.far, v);
<add> }
<add> get far() {
<add> return this.fog.far;
<add> }
<add> set far(v) {
<add> this.fog.far = v;
<add> this.fog.near = Math.min(this.fog.near, v);
<add> }
<add>+ get color() {
<add>+ return `#${this.fog.color.getHexString()}`;
<add>+ }
<add>+ set color(hexString) {
<add>+ this.fog.color.set(hexString);
<add>+ this.backgroundColor.set(hexString);
<add>+ }
<add>}
<add>```
<add>
<add>然后我们调用 `gui.addColor` 来为我们的助手虚拟属性添加颜色界面。
<add>
<add>```js
<add>{
<add> const near = 1;
<add> const far = 2;
<add> const color = 'lightblue';
<add> scene.fog = new THREE.Fog(color, near, far);
<add> scene.background = new THREE.Color(color);
<add>
<add>* const fogGUIHelper = new FogGUIHelper(scene.fog, scene.background);
<add> gui.add(fogGUIHelper, 'near', near, far).listen();
<add> gui.add(fogGUIHelper, 'far', near, far).listen();
<add>+ gui.addColor(fogGUIHelper, 'color');
<add>}
<add>```
<add>
<add>{{{example url="../threejs-fog-gui.html" }}}
<add>
<add>你可以观察到,设置 `near` 如1.9, `far` 为2.0能在未雾化和完全雾化之间获得锐利的变化效果,而设置 `near` = 1.1, `far` = 2.9 会让我们旋转的方块在距离摄像机2个单位距离的位置获得最平滑的变化效果。
<add>
<add>最后, [`fog`](Material.fog) 在材料上有个布尔属性,用来设置渲染物体的材料是否会受到雾的影响。对于大多数材料而言默认设置为 `true` ,作为你可能想关掉雾生效的例子,设想下你正在制作一个3D车辆模拟器并处于驾驶员座位或座舱的视角,你很可能为了看清车内的物体将它们的是否受雾影响属性关闭。
<add>
<add>一个更好的例子会是一个外面弥漫浓雾的房子。让我们假设将雾设置在2米外 (near = 2) 并且在4米的地方完全进入雾中 (far = 4)。房间大于2米并且很可能大于4米,那么你需要将房子内的材质设置为不受雾的影响,否则当站在房子内尽头往墙壁外看会觉得房子是在雾里。
<add>
<add><div class="spread">
<add> <div>
<add> <div data-diagram="fogHouseAll" style="height: 300px;" class="border"></div>
<add> <div class="code">fog: true, all</div>
<add> </div>
<add></div>
<add>
<add>注意房间尽头的墙壁和天花板正受到雾的影响,当我们把房子材料上的是否受雾影响属性关闭可以解决这个问题。
<add>
<add><div class="spread">
<add> <div>
<add> <div data-diagram="fogHouseInsideNoFog" style="height: 300px;" class="border"></div>
<add> <div class="code">fog: true, only outside materials</div>
<add> </div>
<add></div>
<add>
<add><canvas id="c"></canvas>
<add><script type="module" src="resources/threejs-fog.js"></script> | 1 |
Javascript | Javascript | add tests for duration.add and .remove | c823fbcbce189894792792e35c1bc7f42d783a37 | <ide><path>test/moment/duration.js
<ide> exports.duration = {
<ide> test.ok(moment.isDuration(moment.duration(12345678)), "correctly says true");
<ide> test.ok(!moment.isDuration(moment()), "moment object is not a duration");
<ide> test.ok(!moment.isDuration({milliseconds: 1}), "plain object is not a duration");
<add> test.done();
<add> },
<add>
<add> "add" : function(test) {
<add> test.expect(4);
<add>
<add> var d = moment.duration({months: 4, weeks: 3, days: 2});
<add> // for some reason, d._data._months does not get updated; use d._months instead.
<add> test.equal(d.add(1, 'month')._months, 5, 'Add months');
<add> test.equal(d.add(5, 'days')._days, 28, 'Add days');
<add> test.equal(d.add(10000)._milliseconds, 10000, 'Add milliseconds');
<add> test.equal(d.add({h: 23, m: 59})._milliseconds, 23*60*60*1000 + 59*60*1000 + 10000, 'Add hour:minute');
<add>
<add> test.done();
<add> },
<add>
<add> "subtract" : function(test) {
<add> test.expect(4);
<add>
<add> var d = moment.duration({months: 2, weeks: 2, days: 0, hours: 5});
<add> // for some reason, d._data._months does not get updated; use d._months instead.
<add> test.equal(d.subtract(1, 'months')._months, 1, 'Subtract months');
<add> test.equal(d.subtract(14, 'days')._days, 0, 'Subtract days');
<add> test.equal(d.subtract(10000)._milliseconds, 5*60*60*1000 - 10000, 'Subtract milliseconds');
<add> test.equal(d.subtract({h: 1, m: 59})._milliseconds, 3*60*60*1000 + 1*60*1000 - 10000, 'Subtract hour:minute');
<add>
<ide> test.done();
<ide> }
<add>
<ide> }; | 1 |
Python | Python | add tests for matrix return types | 8d915a55c5ecbca15ebaf13584b0c255d22768a1 | <ide><path>numpy/linalg/linalg.py
<ide> isfinite, size
<ide> from numpy.lib import triu
<ide> from numpy.linalg import lapack_lite
<del>from numpy.core.defmatrix import matrix_power
<add>from numpy.core.defmatrix import matrix_power, matrix
<ide>
<ide> fortran_int = intc
<ide>
<ide> def svd(a, full_matrices=1, compute_uv=1):
<ide> else:
<ide> return wrap(s)
<ide>
<del>def cond(x,p=None):
<add>def cond(x, p=None):
<ide> """Compute the condition number of a matrix.
<ide>
<ide> The condition number of x is the norm of x times the norm
<ide> def cond(x,p=None):
<ide> c : float
<ide> The condition number of the matrix. May be infinite.
<ide> """
<add> x = asarray(x) # in case we have a matrix
<ide> if p is None:
<ide> s = svd(x,compute_uv=False)
<ide> return s[0]/s[-1]
<ide> def lstsq(a, b, rcond=-1):
<ide>
<ide> """
<ide> import math
<del> a = asarray(a)
<add> a = _makearray(a)
<ide> b, wrap = _makearray(b)
<ide> one_eq = len(b.shape) == 1
<ide> if one_eq:
<ide><path>numpy/linalg/tests/test_linalg.py
<ide>
<ide> from numpy.testing import *
<ide> set_package_path()
<del>from numpy import array, single, double, csingle, cdouble, dot, identity, \
<del> multiply, atleast_2d, inf, asarray
<add>from numpy import array, single, double, csingle, cdouble, dot, identity
<add>from numpy import multiply, atleast_2d, inf, asarray, matrix
<ide> from numpy import linalg
<ide> from linalg import matrix_power
<ide> restore_path()
<ide>
<add>def ifthen(a, b):
<add> return not a or b
<add>
<ide> old_assert_almost_equal = assert_almost_equal
<add>def imply(a, b):
<add> return not a or b
<add>
<ide> def assert_almost_equal(a, b, **kw):
<ide> if asarray(a).dtype.type in (single, csingle):
<ide> decimal = 6
<ide> def check_nonarray(self):
<ide> b = [2, 1]
<ide> self.do(a,b)
<ide>
<add> def check_matrix_b_only(self):
<add> """Check that matrix type is preserved."""
<add> a = array([[1.,2.], [3.,4.]])
<add> b = matrix([2., 1.]).T
<add> self.do(a, b)
<add>
<add> def check_matrix_a_and_b(self):
<add> """Check that matrix type is preserved."""
<add> a = matrix([[1.,2.], [3.,4.]])
<add> b = matrix([2., 1.]).T
<add> self.do(a, b)
<add>
<ide>
<ide> class TestSolve(LinalgTestCase):
<ide> def do(self, a, b):
<ide> x = linalg.solve(a, b)
<ide> assert_almost_equal(b, dot(a, x))
<add> assert imply(isinstance(b, matrix), isinstance(x, matrix))
<ide>
<ide> class TestInv(LinalgTestCase):
<ide> def do(self, a, b):
<ide> a_inv = linalg.inv(a)
<ide> assert_almost_equal(dot(a, a_inv), identity(asarray(a).shape[0]))
<add> assert imply(isinstance(a, matrix), isinstance(a_inv, matrix))
<ide>
<ide> class TestEigvals(LinalgTestCase):
<ide> def do(self, a, b):
<ide> ev = linalg.eigvals(a)
<ide> evalues, evectors = linalg.eig(a)
<ide> assert_almost_equal(ev, evalues)
<add> assert imply(isinstance(a, matrix), isinstance(ev, matrix))
<ide>
<ide> class TestEig(LinalgTestCase):
<ide> def do(self, a, b):
<ide> evalues, evectors = linalg.eig(a)
<del> assert_almost_equal(dot(a, evectors), evectors*evalues)
<add> assert_almost_equal(dot(a, evectors), multiply(evectors, evalues))
<add> assert imply(isinstance(a, matrix), isinstance(evalues, matrix))
<add> assert imply(isinstance(a, matrix), isinstance(evectors, matrix))
<ide>
<ide> class TestSVD(LinalgTestCase):
<ide> def do(self, a, b):
<ide> u, s, vt = linalg.svd(a, 0)
<del> assert_almost_equal(a, dot(u*s, vt))
<add> assert_almost_equal(a, dot(multiply(u, s), vt))
<add> assert imply(isinstance(a, matrix), isinstance(u, matrix))
<add> assert imply(isinstance(a, matrix), isinstance(s, matrix))
<add> assert imply(isinstance(a, matrix), isinstance(vt, matrix))
<ide>
<ide> class TestCondSVD(LinalgTestCase):
<ide> def do(self, a, b):
<del> s = linalg.svd(a, compute_uv=False)
<add> c = asarray(a) # a might be a matrix
<add> s = linalg.svd(c, compute_uv=False)
<ide> old_assert_almost_equal(s[0]/s[-1], linalg.cond(a), decimal=5)
<ide>
<ide> class TestCond2(LinalgTestCase):
<ide> def do(self, a, b):
<del> s = linalg.svd(a, compute_uv=False)
<add> c = asarray(a) # a might be a matrix
<add> s = linalg.svd(c, compute_uv=False)
<ide> old_assert_almost_equal(s[0]/s[-1], linalg.cond(a,2), decimal=5)
<ide>
<ide> class TestCondInf(NumpyTestCase):
<ide> class TestPinv(LinalgTestCase):
<ide> def do(self, a, b):
<ide> a_ginv = linalg.pinv(a)
<ide> assert_almost_equal(dot(a, a_ginv), identity(asarray(a).shape[0]))
<add> assert imply(isinstance(a, matrix), isinstance(a_ginv, matrix))
<ide>
<ide> class TestDet(LinalgTestCase):
<ide> def do(self, a, b):
<ide> def do(self, a, b):
<ide> assert_almost_equal(b, dot(a, x))
<ide> assert_equal(rank, asarray(a).shape[0])
<ide> assert_almost_equal(sv, s)
<add> assert imply(isinstance(b, matrix), isinstance(x, matrix))
<add> assert imply(isinstance(b, matrix), isinstance(residuals, matrix))
<add> assert imply(isinstance(b, matrix), isinstance(sv, matrix))
<ide>
<ide> class TestMatrixPower(ParametricTestCase):
<ide> R90 = array([[0,1],[-1,0]]) | 2 |
Javascript | Javascript | remove unactionable warning when on 'paper' | 494b73cb33197fa865e9ead8fdca11bce6822917 | <ide><path>Libraries/Utilities/codegenNativeComponent.js
<ide> function codegenNativeComponent<Props>(
<ide> componentName: string,
<ide> options?: Options,
<ide> ): NativeComponentType<Props> {
<del> const errorMessage =
<del> "Native Component '" +
<del> componentName +
<del> "' that calls codegenNativeComponent was not code generated at build time. Please check its definition.";
<ide> if (global.RN$Bridgeless === true) {
<add> const errorMessage =
<add> "Native Component '" +
<add> componentName +
<add> "' that calls codegenNativeComponent was not code generated at build time. Please check its definition.";
<ide> console.error(errorMessage);
<del> } else {
<del> console.warn(errorMessage);
<ide> }
<add>
<ide> let componentNameInUse =
<ide> options && options.paperComponentName != null
<ide> ? options.paperComponentName | 1 |
Text | Text | fix a typo in electron url | 16faef2b79802441b9c101b169a04a57928ae93d | <ide><path>CONTRIBUTING.md
<ide> Please open an issue on `atom/atom` if you have suggestions for new labels, and
<ide> | `installer` | [search][search-atom-repo-label-installer] | [search][search-atom-org-label-installer] | Related to the Atom installers for different OSes. |
<ide> | `auto-updater` | [search][search-atom-repo-label-auto-updater] | [search][search-atom-org-label-auto-updater] | Related to the auto-updater for different OSes. |
<ide> | `deprecation-help` | [search][search-atom-repo-label-deprecation-help] | [search][search-atom-org-label-deprecation-help] | Issues for helping package authors remove usage of deprecated APIs in packages. |
<del>| `electron` | [search][search-atom-repo-label-electron] | [search][search-atom-org-label-electron] | Issues that require changes to [Electron](https://electron.aton.io) to fix or implement. |
<add>| `electron` | [search][search-atom-repo-label-electron] | [search][search-atom-org-label-electron] | Issues that require changes to [Electron](https://electron.atom.io) to fix or implement. |
<ide>
<ide> #### Core Team Project Management
<ide> | 1 |
Ruby | Ruby | remove warning of shadowing variable | dc3d3fb0b97d3be0501d66ba71a71611cf942b2b | <ide><path>actionpack/lib/action_controller/caching/fragments.rb
<ide> def fragment_cache_key(value = nil, &key)
<ide> # with the specified +key+ value. The key is expanded using
<ide> # ActiveSupport::Cache.expand_cache_key.
<ide> def fragment_cache_key(key)
<del> head = self.class.fragment_cache_keys.map { |key| instance_exec(&key) }
<add> head = self.class.fragment_cache_keys.map { |k| instance_exec(&k) }
<ide> tail = key.is_a?(Hash) ? url_for(key).split("://").last : key
<ide> ActiveSupport::Cache.expand_cache_key([*head, *tail], :views)
<ide> end | 1 |
Javascript | Javascript | remove wasteful checks from `shouldyield` | 9abc2785cb070148d64fae81e523246b90b92016 | <ide><path>packages/react/src/__tests__/ReactProfiler-test.internal.js
<ide> describe('Profiler', () => {
<ide> // Errors that happen inside of a subscriber should throw,
<ide> throwInOnWorkStarted = true;
<ide> expect(Scheduler).toFlushAndThrow('Expected error onWorkStarted');
<del> // Rendering was interrupted by the error that was thrown
<del> expect(Scheduler).toHaveYielded([]);
<del> // Rendering continues in the next task
<del> expect(Scheduler).toFlushAndYield(['Component:text']);
<ide> throwInOnWorkStarted = false;
<add> // Rendering was interrupted by the error that was thrown, then
<add> // continued and finished in the next task.
<add> expect(Scheduler).toHaveYielded(['Component:text']);
<ide> expect(onWorkStarted).toHaveBeenCalled();
<del>
<del> // But the React work should have still been processed.
<del> expect(Scheduler).toFlushAndYield([]);
<ide> const tree = renderer.toTree();
<ide> expect(tree.type).toBe(Component);
<ide> expect(tree.props.children).toBe('text');
<ide><path>packages/scheduler/src/Scheduler.js
<ide> function unstable_getCurrentPriorityLevel() {
<ide> return currentPriorityLevel;
<ide> }
<ide>
<del>function unstable_shouldYield() {
<del> const currentTime = getCurrentTime();
<del> advanceTimers(currentTime);
<del> const firstTask = peek(taskQueue);
<del> return (
<del> (firstTask !== currentTask &&
<del> currentTask !== null &&
<del> firstTask !== null &&
<del> firstTask.callback !== null &&
<del> firstTask.startTime <= currentTime &&
<del> firstTask.expirationTime < currentTask.expirationTime) ||
<del> shouldYieldToHost()
<del> );
<del>}
<del>
<ide> const unstable_requestPaint = requestPaint;
<ide>
<ide> export {
<ide> export {
<ide> unstable_cancelCallback,
<ide> unstable_wrapCallback,
<ide> unstable_getCurrentPriorityLevel,
<del> unstable_shouldYield,
<add> shouldYieldToHost as unstable_shouldYield,
<ide> unstable_requestPaint,
<ide> unstable_continueExecution,
<ide> unstable_pauseExecution,
<ide><path>packages/scheduler/src/__tests__/Scheduler-test.js
<ide> describe('Scheduler', () => {
<ide> });
<ide>
<ide> it(
<del> 'continuations are interrupted by higher priority work scheduled ' +
<add> 'continuations do not block higher priority work scheduled ' +
<ide> 'inside an executing callback',
<ide> () => {
<ide> const tasks = [
<ide> describe('Scheduler', () => {
<ide> Scheduler.unstable_yieldValue('High pri');
<ide> });
<ide> }
<del> if (tasks.length > 0 && shouldYield()) {
<del> Scheduler.unstable_yieldValue('Yield!');
<add> if (tasks.length > 0) {
<add> // Return a continuation
<ide> return work;
<ide> }
<ide> }
<ide> describe('Scheduler', () => {
<ide> 'A',
<ide> 'B',
<ide> 'Schedule high pri',
<del> // Even though there's time left in the frame, the low pri callback
<del> // should yield to the high pri callback
<del> 'Yield!',
<add> // The high pri callback should fire before the continuation of the
<add> // lower pri work
<ide> 'High pri',
<ide> // Continue low pri work
<ide> 'C',
<ide> describe('Scheduler', () => {
<ide> const [label, ms] = task;
<ide> Scheduler.unstable_advanceTime(ms);
<ide> Scheduler.unstable_yieldValue(label);
<del> if (tasks.length > 0 && shouldYield()) {
<add> if (tasks.length > 0) {
<ide> return work;
<ide> }
<ide> } | 3 |
Text | Text | add theanarkh to collaborators | be5face1571136e8f9af3fe6c5f0006ea6ed1ea9 | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> **Stewart X Addison** <<[email protected]>> (he/him)
<ide> * [targos](https://github.com/targos) -
<ide> **Michaël Zasso** <<[email protected]>> (he/him)
<add>* [theanarkh](https://github.com/theanarkh) -
<add> **theanarkh** <<[email protected]>> (he/him)
<ide> * [TimothyGu](https://github.com/TimothyGu) -
<ide> **Tiancheng "Timothy" Gu** <<[email protected]>> (he/him)
<ide> * [tniessen](https://github.com/tniessen) - | 1 |
Javascript | Javascript | remove fix for | 6215840995ae77f8d309ccaf58c6966b23925602 | <ide><path>src/manipulation.js
<ide> var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>
<ide>
<ide> // Support: IE 9
<ide> option: [ 1, "<select multiple='multiple'>" ],
<del> param: [ 1, "<object>" ],
<ide> thead: [ 1, "<table>" ],
<ide> tr: [ 2, "<table><tbody>" ],
<ide> col: [ 2, "<table><tbody></tbody><colgroup>" ], | 1 |
Text | Text | update changelog for 3.0.0-beta.4 | 28753cf193ed8fccacc535dc9af09a9d1cb91f09 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### 3.0.0-beta.4 (January 25, 2018)
<add>
<add>- [#16160](https://github.com/emberjs/ember.js/pull/16160) [BUGFIX] Remove humanize() call from generated test descriptions
<add>- [#16101](https://github.com/emberjs/ember.js/pull/16101) [CLEANUP] Remove legacy ArrayProxy features
<add>- [#16116](https://github.com/emberjs/ember.js/pull/16116) [CLEANUP] Remove private enumerable observers
<add>- [#16117](https://github.com/emberjs/ember.js/pull/16117) [BUGFIX] link-to active class applied when params change
<add>- [#16132](https://github.com/emberjs/ember.js/pull/16132) [BUGFIX] Bring back `sync` queue with deprecation (until: 3.5.0).
<add>- [#16156](https://github.com/emberjs/ember.js/pull/16156) [BUGFIX] Update to [email protected].
<add>- [#16157](https://github.com/emberjs/ember.js/pull/16157) [BUGFIX] Mutating an arranged ArrayProxy is not allowed
<add>- [#16162](https://github.com/emberjs/ember.js/pull/16162) [CLEANUP] Remove unused private listener methods
<add>- [#16163](https://github.com/emberjs/ember.js/pull/16163) [CLEANUP] Remove unused path caches
<add>- [#16169](https://github.com/emberjs/ember.js/pull/16169) [BUGFIX] Fix various issues with descriptor trap.
<add>- [#16174](https://github.com/emberjs/ember.js/pull/16174) [BUGFIX] Enable _some_ recovery of errors thrown during render.
<add>
<add>
<ide> ### 3.0.0-beta.3 (January 15, 2018)
<ide>
<ide> - [#16095](https://github.com/emberjs/ember.js/pull/16095) [CLEANUP] Fix ember-2-legacy support for Ember.Binding. | 1 |
PHP | PHP | fix bug in session class | b9e91835ec9d8d66e94452c676a632ac9887a6c7 | <ide><path>laravel/session.php
<ide> public static function start(Driver $driver)
<ide> static::$session = $driver->load($id);
<ide> }
<ide>
<del> if (static::invalid())
<add> if (is_null(static::$session) or static::invalid())
<ide> {
<ide> static::$exists = false;
<ide>
<ide> protected static function invalid()
<ide> {
<ide> $lifetime = Config::$items['session']['lifetime'];
<ide>
<del> $idle = time() - static::$session['last_activity'];
<del>
<del> return is_null(static::$session) or ($idle > ($lifetime * 60));
<add> return (time() - static::$session['last_activity']) > ($lifetime * 60);
<ide> }
<ide>
<ide> /** | 1 |
Ruby | Ruby | move integration test runner into actiondispatch | 4a55d1de8d42694bd060d834c549c53c079dd747 | <ide><path>actionpack/lib/action_controller.rb
<ide> module ActionController
<ide> # require 'action_controller/routing'
<ide> autoload :Caching, 'action_controller/caching'
<ide> autoload :Dispatcher, 'action_controller/dispatch/dispatcher'
<del> autoload :Integration, 'action_controller/testing/integration'
<add> autoload :Integration, 'action_controller/deprecated/integration_test'
<add> autoload :IntegrationTest, 'action_controller/deprecated/integration_test'
<ide> autoload :MimeResponds, 'action_controller/metal/mime_responds'
<add> autoload :PerformanceTest, 'action_controller/deprecated/performance_test'
<ide> autoload :PolymorphicRoutes, 'action_controller/routing/generation/polymorphic_routes'
<ide> autoload :RecordIdentifier, 'action_controller/record_identifier'
<ide> autoload :Resources, 'action_controller/routing/resources'
<ide><path>actionpack/lib/action_controller/deprecated/integration_test.rb
<add>ActionController::Integration = ActionDispatch::Integration
<add>ActionController::IntegrationTest = ActionDispatch::IntegrationTest
<ide><path>actionpack/lib/action_controller/deprecated/performance_test.rb
<add>ActionController::PerformanceTest = ActionDispatch::PerformanceTest
<ide><path>actionpack/lib/action_dispatch.rb
<ide> module ActionDispatch
<ide> autoload :ShowExceptions, 'action_dispatch/middleware/show_exceptions'
<ide> autoload :MiddlewareStack, 'action_dispatch/middleware/stack'
<ide>
<del> autoload :HTML, 'action_controller/vendor/html-scanner'
<ide> autoload :Assertions, 'action_dispatch/testing/assertions'
<add> autoload :Integration, 'action_dispatch/testing/integration'
<add> autoload :IntegrationTest, 'action_dispatch/testing/integration'
<add> autoload :PerformanceTest, 'action_dispatch/testing/performance_test'
<ide> autoload :TestRequest, 'action_dispatch/testing/test_request'
<ide> autoload :TestResponse, 'action_dispatch/testing/test_response'
<ide>
<add> autoload :HTML, 'action_controller/vendor/html-scanner'
<add>
<ide> module Http
<ide> autoload :Headers, 'action_dispatch/http/headers'
<ide> end
<add><path>actionpack/lib/action_dispatch/testing/integration.rb
<del><path>actionpack/lib/action_controller/testing/integration.rb
<ide> require 'uri'
<ide> require 'active_support/test_case'
<ide> require 'active_support/core_ext/object/metaclass'
<del>require 'rack/test'
<ide>
<del>module ActionController
<add># TODO: Remove circular dependency on ActionController
<add>require 'action_controller/testing/process'
<add>
<add>module ActionDispatch
<ide> module Integration #:nodoc:
<ide> module RequestHelpers
<ide> # Performs a GET request with the given parameters.
<ide> module RequestHelpers
<ide> #
<ide> # This method returns an Response object, which one can use to
<ide> # inspect the details of the response. Furthermore, if this method was
<del> # called from an ActionController::IntegrationTest object, then that
<add> # called from an ActionDispatch::IntegrationTest object, then that
<ide> # object's <tt>@response</tt> instance variable will point to the same
<ide> # response object.
<ide> #
<ide> def reset!
<ide> unless defined? @named_routes_configured
<ide> # install the named routes in this session instance.
<ide> klass = metaclass
<del> Routing::Routes.install_helpers(klass)
<add> ActionController::Routing::Routes.install_helpers(klass)
<ide>
<ide> # the helpers are made protected by default--we make them public for
<ide> # easier access during testing and troubleshooting.
<del> klass.module_eval { public *Routing::Routes.named_routes.helpers }
<add> klass.module_eval { public *ActionController::Routing::Routes.named_routes.helpers }
<ide> @named_routes_configured = true
<ide> end
<ide> end
<add><path>actionpack/lib/action_dispatch/testing/performance_test.rb
<del><path>actionpack/lib/action_controller/testing/performance_test.rb
<ide> require 'active_support/testing/performance'
<ide> require 'active_support/testing/default'
<ide>
<del>module ActionController
<add>module ActionDispatch
<ide> # An integration test that runs a code profiler on your test methods.
<ide> # Profiling output for combinations of each test method, measurement, and
<ide> # output format are written to your tmp/performance directory.
<ide> #
<ide> # By default, process_time is measured and both flat and graph_html output
<ide> # formats are written, so you'll have two output files per test method.
<del> class PerformanceTest < ActionController::IntegrationTest
<add> class PerformanceTest < ActionDispatch::IntegrationTest
<ide> include ActiveSupport::Testing::Performance
<ide> include ActiveSupport::Testing::Default
<ide> end
<ide><path>actionpack/test/abstract_unit.rb
<ide> require 'action_dispatch'
<ide> require 'active_model'
<ide> require 'fixture_template'
<del>require 'action_controller/testing/process'
<del>require 'action_controller/testing/integration'
<ide> require 'action_view/test_case'
<ide> require 'active_support/dependencies'
<ide> | 7 |
Ruby | Ruby | combine aliased_table_for and aliased_name_for | 9e7037f19865021030893880b16be7b1ecbd3470 | <ide><path>activerecord/lib/active_record/associations/alias_tracker.rb
<ide> def initialize(connection, aliases)
<ide> end
<ide>
<ide> def aliased_table_for(table_name, aliased_name)
<del> table_alias = aliased_name_for(table_name, aliased_name)
<del>
<del> if table_alias == table_name
<del> Arel::Table.new(table_name)
<del> else
<del> Arel::Table.new(table_name).alias(table_alias)
<del> end
<del> end
<del>
<del> def aliased_name_for(table_name, aliased_name)
<ide> if aliases[table_name].zero?
<ide> # If it's zero, we can have our table_name
<ide> aliases[table_name] = 1
<del> table_name
<add> Arel::Table.new(table_name)
<ide> else
<ide> # Otherwise, we need to use an alias
<ide> aliased_name = connection.table_alias_for(aliased_name)
<ide>
<ide> # Update the count
<ide> aliases[aliased_name] += 1
<ide>
<del> if aliases[aliased_name] > 1
<add> table_alias = if aliases[aliased_name] > 1
<ide> "#{truncate(aliased_name)}_#{aliases[aliased_name]}"
<ide> else
<ide> aliased_name
<ide> end
<add> Arel::Table.new(table_name).alias(table_alias)
<ide> end
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/associations/join_dependency.rb
<ide> def self.walk_tree(associations, hash)
<ide> #
<ide> def initialize(base, associations, joins)
<ide> @alias_tracker = AliasTracker.create(base.connection, joins)
<del> @alias_tracker.aliased_name_for(base.table_name, base.table_name) # Updates the count for base.table_name to 1
<add> @alias_tracker.aliased_table_for(base.table_name, base.table_name) # Updates the count for base.table_name to 1
<ide> tree = self.class.make_tree associations
<ide> @join_root = JoinBase.new base, build(tree, base)
<ide> @join_root.children.each { |child| construct_tables! @join_root, child } | 2 |
Python | Python | fix triggerdagrunoperator docstring | b65c4f277254ad3811123edda2574e0e458368e3 | <ide><path>airflow/operators/trigger_dagrun.py
<ide> class TriggerDagRunOperator(BaseOperator):
<ide> :param trigger_dag_id: The dag_id to trigger (templated).
<ide> :param trigger_run_id: The run ID to use for the triggered DAG run (templated).
<ide> If not provided, a run ID will be automatically generated.
<del> :param conf: Configuration for the DAG run.
<add> :param conf: Configuration for the DAG run (templated).
<ide> :param execution_date: Execution date for the dag (templated).
<ide> :param reset_dag_run: Whether or not clear existing dag run if already exists.
<ide> This is useful when backfill or rerun an existing dag run. | 1 |
Ruby | Ruby | freeze all the strings in visitors | 685825cdfc3c5595b504ae5dd0fc45638c47aeec | <ide><path>lib/arel/visitors/bind_visitor.rb
<add># frozen_string_literal: true
<ide> module Arel
<ide> module Visitors
<ide> module BindVisitor
<ide><path>lib/arel/visitors/dot.rb
<add># frozen_string_literal: true
<ide> module Arel
<ide> module Visitors
<ide> class Dot < Arel::Visitors::Visitor
<ide> def to_dot
<ide> label = "<f0>#{node.name}"
<ide>
<ide> node.fields.each_with_index do |field, i|
<del> label << "|<f#{i + 1}>#{quote field}"
<add> label += "|<f#{i + 1}>#{quote field}"
<ide> end
<ide>
<ide> "#{node.id} [label=\"#{label}\"];"
<ide><path>lib/arel/visitors/ibm_db.rb
<add># frozen_string_literal: true
<ide> module Arel
<ide> module Visitors
<ide> class IBM_DB < Arel::Visitors::ToSql
<ide><path>lib/arel/visitors/informix.rb
<add># frozen_string_literal: true
<ide> module Arel
<ide> module Visitors
<ide> class Informix < Arel::Visitors::ToSql
<ide><path>lib/arel/visitors/mssql.rb
<add># frozen_string_literal: true
<ide> module Arel
<ide> module Visitors
<ide> class MSSQL < Arel::Visitors::ToSql
<ide><path>lib/arel/visitors/mysql.rb
<add># frozen_string_literal: true
<ide> module Arel
<ide> module Visitors
<ide> class MySQL < Arel::Visitors::ToSql
<ide><path>lib/arel/visitors/oracle.rb
<add># frozen_string_literal: true
<ide> module Arel
<ide> module Visitors
<ide> class Oracle < Arel::Visitors::ToSql
<ide> def split_order_string(string)
<ide> array[i] << ',' << part
<ide> else
<ide> # to ensure that array[i] will be String and not Arel::Nodes::SqlLiteral
<del> array[i] = '' << part
<add> array[i] = part.to_s
<ide> end
<ide> i += 1 if array[i].count('(') == array[i].count(')')
<ide> end
<ide><path>lib/arel/visitors/oracle12.rb
<add># frozen_string_literal: true
<ide> module Arel
<ide> module Visitors
<ide> class Oracle12 < Arel::Visitors::ToSql
<ide><path>lib/arel/visitors/postgresql.rb
<add># frozen_string_literal: true
<ide> module Arel
<ide> module Visitors
<ide> class PostgreSQL < Arel::Visitors::ToSql
<ide><path>lib/arel/visitors/sqlite.rb
<add># frozen_string_literal: true
<ide> module Arel
<ide> module Visitors
<ide> class SQLite < Arel::Visitors::ToSql
<ide><path>lib/arel/visitors/to_sql.rb
<add># frozen_string_literal: true
<ide> require 'bigdecimal'
<ide> require 'date'
<ide> require 'arel/visitors/reduce'
<ide><path>lib/arel/visitors/where_sql.rb
<add># frozen_string_literal: true
<ide> module Arel
<ide> module Visitors
<ide> class WhereSql < Arel::Visitors::ToSql | 12 |
Javascript | Javascript | remove code duplication | 01b10d7a24b371e667dfd5b081e98a690b0fc426 | <ide><path>src/jqLite.js
<ide> forEach({
<ide> var eventFns = events[type];
<ide>
<ide> if (!eventFns) {
<del> if (type == 'mouseenter' || type == 'mouseleave') {
<del> events[type] = [];
<add> events[type] = [];
<ide>
<add> if (type == 'mouseenter' || type == 'mouseleave') {
<ide> // Refer to jQuery's implementation of mouseenter & mouseleave
<ide> // Read about mouseenter and mouseleave:
<ide> // http://www.quirksmode.org/js/events_mouse.html#link8
<ide> forEach({
<ide>
<ide> } else {
<ide> addEventListenerFn(element, type, handle);
<del> events[type] = [];
<ide> }
<ide> eventFns = events[type];
<ide> } | 1 |
Text | Text | fix error on pr #45x | 62a5edf3d194baba8c09cf6ef701555f7dc16898 | <ide><path>README.md
<ide> Table of Contents
<ide> - [Getting Started](#getting-started)
<ide> - [Obtaining API Keys](#obtaining-api-keys)
<ide> - [Project Structure](#project-structure)
<del>- [Useful Tools](#use-tools)
<add>- [Useful Tools](#useful-tools)
<ide> - [Recommended Design](#recommended-design)
<ide> - [Recommended Node.js Libraries](#recommended-nodejs-libraries)
<ide> - [Recommended Client-Side libraries](#recommended-client-side-libraries) | 1 |
Python | Python | add add_special_tokens=true for input examples | 3c28a2daac43386dbc63b0bd014a966f22888850 | <ide><path>transformers/modeling_bert.py
<ide> class BertModel(BertPreTrainedModel):
<ide>
<ide> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
<ide> model = BertModel.from_pretrained('bert-base-uncased')
<del> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1
<add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1
<ide> outputs = model(input_ids)
<ide> last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple
<ide>
<ide> class BertForPreTraining(BertPreTrainedModel):
<ide>
<ide> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
<ide> model = BertForPreTraining.from_pretrained('bert-base-uncased')
<del> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1
<add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1
<ide> outputs = model(input_ids)
<ide> prediction_scores, seq_relationship_scores = outputs[:2]
<ide>
<ide> class BertForMaskedLM(BertPreTrainedModel):
<ide>
<ide> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
<ide> model = BertForMaskedLM.from_pretrained('bert-base-uncased')
<del> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1
<add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1
<ide> outputs = model(input_ids, masked_lm_labels=input_ids)
<ide> loss, prediction_scores = outputs[:2]
<ide>
<ide> class BertForNextSentencePrediction(BertPreTrainedModel):
<ide>
<ide> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
<ide> model = BertForNextSentencePrediction.from_pretrained('bert-base-uncased')
<del> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1
<add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1
<ide> outputs = model(input_ids)
<ide> seq_relationship_scores = outputs[0]
<ide>
<ide> class BertForSequenceClassification(BertPreTrainedModel):
<ide>
<ide> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
<ide> model = BertForSequenceClassification.from_pretrained('bert-base-uncased')
<del> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1
<add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1
<ide> labels = torch.tensor([1]).unsqueeze(0) # Batch size 1
<ide> outputs = model(input_ids, labels=labels)
<ide> loss, logits = outputs[:2]
<ide> class BertForMultipleChoice(BertPreTrainedModel):
<ide> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
<ide> model = BertForMultipleChoice.from_pretrained('bert-base-uncased')
<ide> choices = ["Hello, my dog is cute", "Hello, my cat is amazing"]
<del> input_ids = torch.tensor([tokenizer.encode(s) for s in choices]).unsqueeze(0) # Batch size 1, 2 choices
<add> input_ids = torch.tensor([tokenizer.encode(s, add_special_tokens=True) for s in choices]).unsqueeze(0) # Batch size 1, 2 choices
<ide> labels = torch.tensor(1).unsqueeze(0) # Batch size 1
<ide> outputs = model(input_ids, labels=labels)
<ide> loss, classification_scores = outputs[:2]
<ide> class BertForTokenClassification(BertPreTrainedModel):
<ide>
<ide> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
<ide> model = BertForTokenClassification.from_pretrained('bert-base-uncased')
<del> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1
<add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1
<ide> labels = torch.tensor([1] * input_ids.size(1)).unsqueeze(0) # Batch size 1
<ide> outputs = model(input_ids, labels=labels)
<ide> loss, scores = outputs[:2] | 1 |
Javascript | Javascript | use regex for openssl function name | c1ee66804c3605882410a7adfe7e44c7ad603b82 | <ide><path>test/parallel/test-crypto-scrypt.js
<ide> for (const options of bad) {
<ide>
<ide> for (const options of toobig) {
<ide> const expected = {
<del> message: /error:[^:]+:digital envelope routines:EVP_PBE_scrypt:memory limit exceeded/,
<add> message: new RegExp('error:[^:]+:digital envelope routines:' +
<add> '(?:EVP_PBE_scrypt|scrypt_alg):memory limit exceeded'),
<ide> type: Error,
<ide> };
<ide> common.expectsError(() => crypto.scrypt('pass', 'salt', 1, options, () => {}), | 1 |
Text | Text | remove a reference to an issue [ci skip] | 058d3c6183ef6e0e878bea37f4fe3f8f0d6758e2 | <ide><path>activerecord/CHANGELOG.md
<del>* Allow strings to specify the `#order` value. Fixes #10732.
<add>* Allow strings to specify the `#order` value.
<ide>
<ide> Example:
<ide> | 1 |
Javascript | Javascript | add note about browser compatibility | 9f68b0e29dfab351736c622119e6f07e51bd71ee | <ide><path>src/ng/directive/attrs.js
<ide> * A special directive is necessary because we cannot use interpolation inside the `open`
<ide> * attribute. See the {@link guide/interpolation interpolation guide} for more info.
<ide> *
<add> * ## A note about browser compatibility
<add> *
<add> * Edge, Firefox, and Internet Explorer do not support the `details` element, it is
<add> * recommended to use {@link ng.ngShow} and {@link ng.ngHide} instead.
<add> *
<ide> * @example
<ide> <example>
<ide> <file name="index.html"> | 1 |
Javascript | Javascript | fix version controller links (for realsies) | 6894b486d0486bd813af24fb4c27c4f5775e5fd8 | <ide><path>docs/source/_static/js/custom.js
<ide> function addGithubButton() {
<ide> function addVersionControl() {
<ide> // To grab the version currently in view, we parse the url
<ide> const parts = location.toString().split('/');
<del> let versionIndex = parts.length - 2
<add> let versionIndex = parts.length - 2;
<ide> // Index page may not have a last part with filename.html so we need to go up
<del> if (! parts[versionIndex].match(/\.html$/)) {
<del> versionIndex = parts.length - 1
<add> if (parts[parts.length - 1] != "" && ! parts[parts.length - 1].match(/\.html$/)) {
<add> versionIndex = parts.length - 1;
<ide> }
<ide> // Main classes and models are nested so we need to go deeper
<ide> else if (parts[versionIndex] == "main_classes" || parts[versionIndex] == "model_doc") {
<del> versionIndex = parts.length - 3
<add> versionIndex = versionIndex - 1;
<ide> }
<ide> const version = parts[versionIndex];
<ide>
<ide> function addVersionControl() {
<ide>
<ide> const htmlLines = [];
<ide> for (const [key, value] of Object.entries(versionMapping)) {
<del> var urlParts = parts.slice(0, versionIndex-1);
<add> let baseUrlIndex = (version == "transformers") ? versionIndex + 1: versionIndex;
<add> var urlParts = parts.slice(0, baseUrlIndex);
<ide> if (key != "") {
<ide> urlParts = urlParts.concat([key]);
<ide> }
<del> urlParts = urlParts.concat(parts.slice(versionIndex));
<add> urlParts = urlParts.concat(parts.slice(versionIndex+1));
<ide> htmlLines.push(`<a href="${urlParts.join('/')}">${value}</a>`);
<ide> }
<ide> | 1 |
Python | Python | remove unused import in tests folder | bfae0a61917f8cc7563db80051f89e178e8bfb1c | <ide><path>tests/keras/layers/normalization_test.py
<ide> import numpy as np
<ide> from numpy.testing import assert_allclose
<ide>
<del>from keras.layers import Dense, Activation, Input
<add>from keras.layers import Input
<ide> from keras.utils.test_utils import layer_test, keras_test
<ide> from keras.layers import normalization
<ide> from keras.models import Sequential, Model
<ide><path>tests/keras/utils/data_utils_test.py
<ide> from keras.utils.data_utils import get_file
<ide> from keras.utils.data_utils import validate_file
<ide> from keras.utils.data_utils import _hash_file
<del>from keras import activations
<del>from keras import regularizers
<ide>
<ide>
<ide> def test_data_utils():
<ide><path>tests/keras/wrappers/scikit_learn_test.py
<ide> import numpy as np
<ide>
<ide> from keras.utils.test_utils import get_test_data
<del>from keras.utils import np_utils
<del>from keras import backend as K
<ide>
<ide> from keras.models import Sequential
<ide> from keras.layers.core import Dense, Activation | 3 |
Javascript | Javascript | avoid more allocations for rtl text in bidi.js | b1cf4d98ad98cb80e1ce793cd384516a2f8a0c1c | <ide><path>src/core/bidi.js
<ide> var bidi = PDFJS.bidi = (function bidiClosure() {
<ide> // don't mirror as characters are already mirrored in the pdf
<ide>
<ide> // Finally, return string
<del> var result = '';
<ide> for (i = 0, ii = chars.length; i < ii; ++i) {
<ide> var ch = chars[i];
<del> if (ch !== '<' && ch !== '>') {
<del> result += ch;
<add> if (ch === '<' || ch === '>') {
<add> chars[i] = '';
<ide> }
<ide> }
<del> return createBidiText(result, isLTR);
<add> return createBidiText(chars.join(''), isLTR);
<ide> }
<ide>
<ide> return bidi; | 1 |
Python | Python | add a main_input_name attribute to all models | 33f36c869fa5db07bb35789d411cfed8bf9d3b0c | <ide><path>src/transformers/modeling_flax_utils.py
<ide> class FlaxPreTrainedModel(PushToHubMixin, FlaxGenerationMixin):
<ide> :class:`~transformers.PretrainedConfig` to use as configuration class for this model architecture.
<ide> - **base_model_prefix** (:obj:`str`) -- A string indicating the attribute associated to the base model in
<ide> derived classes of the same architecture adding modules on top of the base model.
<add> - **main_input_name** (:obj:`str`) -- The name of the principal input to the model (often :obj:`input_ids` for
<add> NLP models, :obj:`pixel_values` for vision models and :obj:`input_values` for speech models).
<ide> """
<ide> config_class = None
<ide> base_model_prefix = ""
<add> main_input_name = "input_ids"
<ide>
<ide> def __init__(
<ide> self,
<ide><path>src/transformers/modeling_tf_utils.py
<ide> class TFPreTrainedModel(tf.keras.Model, TFModelUtilsMixin, TFGenerationMixin, Pu
<ide> :class:`~transformers.PretrainedConfig` to use as configuration class for this model architecture.
<ide> - **base_model_prefix** (:obj:`str`) -- A string indicating the attribute associated to the base model in
<ide> derived classes of the same architecture adding modules on top of the base model.
<add> - **main_input_name** (:obj:`str`) -- The name of the principal input to the model (often :obj:`input_ids` for
<add> NLP models, :obj:`pixel_values` for vision models and :obj:`input_values` for speech models).
<ide> """
<ide> config_class = None
<ide> base_model_prefix = ""
<add> main_input_name = "input_ids"
<add>
<ide> # a list of re pattern of tensor names to ignore from the model when loading the model weights
<ide> # (and avoid unnecessary warnings).
<ide> _keys_to_ignore_on_load_missing = None
<ide><path>src/transformers/modeling_utils.py
<ide> import inspect
<ide> import os
<ide> import re
<del>import warnings
<ide> from contextlib import contextmanager
<ide> from dataclasses import dataclass
<ide> from functools import partial
<ide> def estimate_tokens(self, input_dict: Dict[str, Union[torch.Tensor, Any]]) -> in
<ide> Returns:
<ide> :obj:`int`: The total number of tokens.
<ide> """
<del> token_inputs = [tensor for key, tensor in input_dict.items() if "input" in key]
<del> if token_inputs:
<del> return sum([token_input.numel() for token_input in token_inputs])
<add> if self.main_input_name in input_dict:
<add> return input_dict[self.main_input_name].numel()
<ide> else:
<del> warnings.warn(
<add> logger.warn(
<ide> "Could not estimate the number of tokens of the input, floating-point operations will not be computed"
<ide> )
<ide> return 0
<ide> class PreTrainedModel(nn.Module, ModuleUtilsMixin, GenerationMixin, PushToHubMix
<ide> - **base_model_prefix** (:obj:`str`) -- A string indicating the attribute associated to the base model in
<ide> derived classes of the same architecture adding modules on top of the base model.
<ide> - **is_parallelizable** (:obj:`bool`) -- A flag indicating whether this model supports model parallelization.
<add> - **main_input_name** (:obj:`str`) -- The name of the principal input to the model (often :obj:`input_ids` for
<add> NLP models, :obj:`pixel_values` for vision models and :obj:`input_values` for speech models).
<ide> """
<ide> config_class = None
<ide> base_model_prefix = ""
<add> main_input_name = "input_ids"
<add>
<ide> # a list of re pattern of tensor names to ignore from the model when loading the model weights
<ide> # (and avoid unnecessary warnings).
<ide> _keys_to_ignore_on_load_missing = None
<ide><path>src/transformers/models/beit/modeling_beit.py
<ide> class BeitPreTrainedModel(PreTrainedModel):
<ide>
<ide> config_class = BeitConfig
<ide> base_model_prefix = "beit"
<add> main_input_name = "pixel_values"
<ide> supports_gradient_checkpointing = True
<ide>
<ide> def _init_weights(self, module):
<ide><path>src/transformers/models/beit/modeling_flax_beit.py
<ide> class FlaxBeitPreTrainedModel(FlaxPreTrainedModel):
<ide>
<ide> config_class = BeitConfig
<ide> base_model_prefix = "beit"
<add> main_input_name = "pixel_values"
<ide> module_class: nn.Module = None
<ide>
<ide> def __init__(self, config: BeitConfig, input_shape=None, seed: int = 0, dtype: jnp.dtype = jnp.float32, **kwargs):
<ide><path>src/transformers/models/clip/modeling_clip.py
<ide> def forward(
<ide>
<ide> class CLIPVisionModel(CLIPPreTrainedModel):
<ide> config_class = CLIPVisionConfig
<add> main_input_name = "pixel_values"
<ide>
<ide> def __init__(self, config: CLIPVisionConfig):
<ide> super().__init__(config)
<ide><path>src/transformers/models/clip/modeling_flax_clip.py
<ide> def __call__(
<ide>
<ide> class FlaxCLIPVisionPreTrainedModel(FlaxPreTrainedModel):
<ide> config_class = CLIPVisionConfig
<add> main_input_name = "pixel_values"
<ide> module_class: nn.Module = None
<ide>
<ide> def __init__(
<ide><path>src/transformers/models/deit/modeling_deit.py
<ide> class DeiTPreTrainedModel(PreTrainedModel):
<ide>
<ide> config_class = DeiTConfig
<ide> base_model_prefix = "deit"
<add> main_input_name = "pixel_values"
<ide> supports_gradient_checkpointing = True
<ide>
<ide> def _init_weights(self, module):
<ide><path>src/transformers/models/detr/modeling_detr.py
<ide> def forward(self, hidden_states: torch.Tensor):
<ide> class DetrPreTrainedModel(PreTrainedModel):
<ide> config_class = DetrConfig
<ide> base_model_prefix = "model"
<add> main_input_name = "pixel_values"
<ide>
<ide> def _init_weights(self, module):
<ide> std = self.config.init_std
<ide><path>src/transformers/models/hubert/modeling_hubert.py
<ide> class HubertPreTrainedModel(PreTrainedModel):
<ide>
<ide> config_class = HubertConfig
<ide> base_model_prefix = "hubert"
<add> main_input_name = "input_values"
<ide> supports_gradient_checkpointing = True
<ide> _keys_to_ignore_on_load_missing = [r"position_ids"]
<ide>
<ide><path>src/transformers/models/hubert/modeling_tf_hubert.py
<ide> class TFHubertPreTrainedModel(TFPreTrainedModel):
<ide>
<ide> config_class = HubertConfig
<ide> base_model_prefix = "hubert"
<add> main_input_name = "input_values"
<ide>
<ide> @property
<ide> def dummy_inputs(self) -> Dict[str, tf.Tensor]:
<ide><path>src/transformers/models/imagegpt/modeling_imagegpt.py
<ide> class ImageGPTPreTrainedModel(PreTrainedModel):
<ide> config_class = ImageGPTConfig
<ide> load_tf_weights = load_tf_weights_in_imagegpt
<ide> base_model_prefix = "transformer"
<add> main_input_name = "input_ids"
<ide> supports_gradient_checkpointing = True
<ide>
<ide> def __init__(self, *inputs, **kwargs):
<ide><path>src/transformers/models/perceiver/modeling_perceiver.py
<ide> class PerceiverPreTrainedModel(PreTrainedModel):
<ide>
<ide> config_class = PerceiverConfig
<ide> base_model_prefix = "perceiver"
<add> main_input_name = "inputs"
<ide>
<ide> def _init_weights(self, module):
<ide> """Initialize the weights"""
<ide><path>src/transformers/models/segformer/modeling_segformer.py
<ide> class SegformerPreTrainedModel(PreTrainedModel):
<ide>
<ide> config_class = SegformerConfig
<ide> base_model_prefix = "segformer"
<add> main_input_name = "pixel_values"
<ide>
<ide> def _init_weights(self, module):
<ide> """Initialize the weights"""
<ide><path>src/transformers/models/sew/modeling_sew.py
<ide> class SEWPreTrainedModel(PreTrainedModel):
<ide>
<ide> config_class = SEWConfig
<ide> base_model_prefix = "sew"
<add> main_input_name = "input_values"
<ide> supports_gradient_checkpointing = True
<ide> _keys_to_ignore_on_load_missing = [r"position_ids"]
<ide>
<ide><path>src/transformers/models/sew_d/modeling_sew_d.py
<ide> class SEWDPreTrainedModel(PreTrainedModel):
<ide>
<ide> config_class = SEWDConfig
<ide> base_model_prefix = "sew-d"
<add> main_input_name = "input_values"
<ide> _keys_to_ignore_on_load_missing = [r"position_ids"]
<ide> supports_gradient_checkpointing = True
<ide>
<ide><path>src/transformers/models/speech_encoder_decoder/modeling_speech_encoder_decoder.py
<ide> class SpeechEncoderDecoderModel(PreTrainedModel):
<ide> """
<ide> config_class = SpeechEncoderDecoderConfig
<ide> base_model_prefix = "speech_encoder_decoder"
<add> main_input_name = "input_values"
<ide>
<ide> def __init__(
<ide> self,
<ide><path>src/transformers/models/speech_to_text/modeling_speech_to_text.py
<ide> def forward(
<ide> class Speech2TextPreTrainedModel(PreTrainedModel):
<ide> config_class = Speech2TextConfig
<ide> base_model_prefix = "model"
<add> main_input_name = "input_features"
<ide> supports_gradient_checkpointing = True
<ide>
<ide> def _init_weights(self, module):
<ide><path>src/transformers/models/unispeech/modeling_unispeech.py
<ide> class UniSpeechPreTrainedModel(PreTrainedModel):
<ide>
<ide> config_class = UniSpeechConfig
<ide> base_model_prefix = "unispeech"
<add> main_input_name = "input_values"
<ide> _keys_to_ignore_on_load_missing = [r"position_ids"]
<ide> supports_gradient_checkpointing = True
<ide>
<ide><path>src/transformers/models/unispeech_sat/modeling_unispeech_sat.py
<ide> class UniSpeechSatPreTrainedModel(PreTrainedModel):
<ide>
<ide> config_class = UniSpeechSatConfig
<ide> base_model_prefix = "unispeech_sat"
<add> main_input_name = "input_values"
<ide> _keys_to_ignore_on_load_missing = [r"position_ids"]
<ide> supports_gradient_checkpointing = True
<ide>
<ide><path>src/transformers/models/vision_encoder_decoder/modeling_flax_vision_encoder_decoder.py
<ide> class FlaxVisionEncoderDecoderModel(FlaxPreTrainedModel):
<ide> """
<ide> config_class = VisionEncoderDecoderConfig
<ide> base_model_prefix = "vision_encoder_decoder"
<add> main_input_name = "pixel_values"
<ide> module_class = FlaxVisionEncoderDecoderModule
<ide>
<ide> def __init__(
<ide><path>src/transformers/models/vision_encoder_decoder/modeling_vision_encoder_decoder.py
<ide> class VisionEncoderDecoderModel(PreTrainedModel):
<ide> """
<ide> config_class = VisionEncoderDecoderConfig
<ide> base_model_prefix = "vision_encoder_decoder"
<add> main_input_name = "pixel_values"
<ide>
<ide> def __init__(
<ide> self,
<ide><path>src/transformers/models/vit/modeling_flax_vit.py
<ide> class FlaxViTPreTrainedModel(FlaxPreTrainedModel):
<ide>
<ide> config_class = ViTConfig
<ide> base_model_prefix = "vit"
<add> main_input_name = "pixel_values"
<ide> module_class: nn.Module = None
<ide>
<ide> def __init__(self, config: ViTConfig, input_shape=None, seed: int = 0, dtype: jnp.dtype = jnp.float32, **kwargs):
<ide><path>src/transformers/models/vit/modeling_tf_vit.py
<ide> class TFViTPreTrainedModel(TFPreTrainedModel):
<ide>
<ide> config_class = ViTConfig
<ide> base_model_prefix = "vit"
<add> main_input_name = "pixel_values"
<ide>
<ide> @property
<ide> def dummy_inputs(self) -> Dict[str, tf.Tensor]:
<ide><path>src/transformers/models/vit/modeling_vit.py
<ide> class ViTPreTrainedModel(PreTrainedModel):
<ide>
<ide> config_class = ViTConfig
<ide> base_model_prefix = "vit"
<add> main_input_name = "pixel_values"
<ide> supports_gradient_checkpointing = True
<ide>
<ide> def _init_weights(self, module):
<ide><path>src/transformers/models/wav2vec2/modeling_flax_wav2vec2.py
<ide> class FlaxWav2Vec2PreTrainedModel(FlaxPreTrainedModel):
<ide>
<ide> config_class = Wav2Vec2Config
<ide> base_model_prefix: str = "wav2vec2"
<add> main_input_name = "input_values"
<ide> module_class: nn.Module = None
<ide>
<ide> def __init__(
<ide><path>src/transformers/models/wav2vec2/modeling_tf_wav2vec2.py
<ide> class TFWav2Vec2PreTrainedModel(TFPreTrainedModel):
<ide>
<ide> config_class = Wav2Vec2Config
<ide> base_model_prefix = "wav2vec2"
<add> main_input_name = "input_values"
<ide>
<ide> @property
<ide> def dummy_inputs(self) -> Dict[str, tf.Tensor]:
<ide><path>src/transformers/models/wav2vec2/modeling_wav2vec2.py
<ide> class Wav2Vec2PreTrainedModel(PreTrainedModel):
<ide>
<ide> config_class = Wav2Vec2Config
<ide> base_model_prefix = "wav2vec2"
<add> main_input_name = "input_values"
<ide> _keys_to_ignore_on_load_missing = [r"position_ids"]
<ide> supports_gradient_checkpointing = True
<ide>
<ide><path>src/transformers/models/wavlm/modeling_wavlm.py
<ide> class WavLMPreTrainedModel(PreTrainedModel):
<ide>
<ide> config_class = WavLMConfig
<ide> base_model_prefix = "wavlm"
<add> main_input_name = "input_values"
<ide> _keys_to_ignore_on_load_missing = [r"position_ids"]
<ide> supports_gradient_checkpointing = True
<ide>
<ide><path>tests/test_modeling_common.py
<ide> def test_model_common_attributes(self):
<ide> x = model.get_output_embeddings()
<ide> self.assertTrue(x is None or isinstance(x, nn.Linear))
<ide>
<add> def test_model_main_input_name(self):
<add> for model_class in self.all_model_classes:
<add> model_signature = inspect.signature(getattr(model_class, "forward"))
<add> # The main input is the name of the argument after `self`
<add> observed_main_input_name = list(model_signature.parameters.keys())[1]
<add> self.assertEqual(model_class.main_input_name, observed_main_input_name)
<add>
<ide> def test_correct_missing_keys(self):
<ide> if not self.test_missing_keys:
<ide> return
<ide><path>tests/test_modeling_flax_common.py
<ide> def test_save_load_in_bf16(self):
<ide> for name, type_ in types.items():
<ide> self.assertEqual(type_, jnp.bfloat16, msg=f"param {name} is not in bf16.")
<ide>
<add> def test_model_main_input_name(self):
<add> for model_class in self.all_model_classes:
<add> model_signature = inspect.signature(getattr(model_class, "__call__"))
<add> # The main input is the name of the argument after `self`
<add> observed_main_input_name = list(model_signature.parameters.keys())[1]
<add> self.assertEqual(model_class.main_input_name, observed_main_input_name)
<add>
<ide> def test_headmasking(self):
<ide> if not self.test_head_masking:
<ide> return
<ide><path>tests/test_modeling_tf_common.py
<ide> def test_load_with_mismatched_shapes(self):
<ide> else:
<ide> new_model_without_prefix(input_ids)
<ide>
<add> def test_model_main_input_name(self):
<add> for model_class in self.all_model_classes:
<add> model_signature = inspect.signature(getattr(model_class, "call"))
<add> # The main input is the name of the argument after `self`
<add> observed_main_input_name = list(model_signature.parameters.keys())[1]
<add> self.assertEqual(model_class.main_input_name, observed_main_input_name)
<add>
<ide> def _generate_random_bad_tokens(self, num_bad_tokens, model):
<ide> # special tokens cannot be bad tokens
<ide> special_tokens = [] | 32 |
Python | Python | remove dirty patch | 6b31df3423688a3d01e53c05032205567bb695bd | <ide><path>libcloud/common/base.py
<ide> def request(self, action, params=None, data=None, headers=None,
<ide> headers=headers,
<ide> stream=stream)
<ide> else:
<del> if self.driver.type == 'openstack':
<del> # OpenStack is not working, this is a temp hack
<del> prefix = 'https' if self.secure else 'http'
<del> self.connection.host = '%s://%s:%s' % (prefix, self.host, self.port)
<ide> self.connection.request(method=method, url=url, body=data,
<ide> headers=headers, stream=stream)
<ide> except socket.gaierror: | 1 |
Javascript | Javascript | pass component stack to error boundary handler | f923adb5856a2c251039c8a435d77be9d0542a4f | <ide><path>src/renderers/shared/fiber/ReactFiberScheduler.js
<ide> export type CapturedError = {
<ide> willRetry : boolean,
<ide> };
<ide>
<add>export type HandleErrorInfo = {
<add> componentStack : string,
<add>};
<add>
<ide> var {
<ide> popContextProvider,
<ide> } = require('ReactFiberContext');
<ide> module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
<ide> switch (effectfulFiber.tag) {
<ide> case ClassComponent:
<ide> const instance = effectfulFiber.stateNode;
<add>
<add> const info : HandleErrorInfo = {
<add> componentStack: capturedError.componentStack,
<add> };
<add>
<ide> // Allow the boundary to handle the error, usually by scheduling
<ide> // an update to itself
<del> instance.unstable_handleError(error);
<add> instance.unstable_handleError(error, info);
<ide> return;
<ide> case HostRoot:
<ide> if (firstUncaughtError === null) { | 1 |
PHP | PHP | use psalm override | 1aa0cbfc3bfa0380aa4ef5470647217bbdd82670 | <ide><path>src/Core/PluginCollection.php
<ide> public function valid(): bool
<ide> * Filter the plugins to those with the named hook enabled.
<ide> *
<ide> * @param string $hook The hook to filter plugins by
<del> * @return \Generator|\Cake\Core\PluginInterface[] A generator containing matching plugins.
<add> * @return \Generator&\Cake\Core\PluginInterface[] A generator containing matching plugins.
<ide> * @throws \InvalidArgumentException on invalid hooks
<add> * @psalm-return \Generator<\Cake\Core\PluginInterface>
<ide> */
<ide> public function with(string $hook): Generator
<ide> { | 1 |
Python | Python | excuse emoji failure on narrow unicode builds | 8c945310fb16912a23ef8311cd4cd00aeb3798e2 | <ide><path>spacy/tests/tokenizer/test_exceptions.py
<ide> # coding: utf-8
<ide> from __future__ import unicode_literals
<ide>
<add>import sys
<ide> import pytest
<ide>
<ide>
<ide> def test_tokenizer_excludes_false_pos_emoticons(tokenizer, text, length):
<ide> tokens = tokenizer(text)
<ide> assert len(tokens) == length
<ide>
<del>
<ide> @pytest.mark.parametrize('text,length', [('can you still dunk?🍕🍔😵LOL', 8),
<ide> ('i💙you', 3), ('🤘🤘yay!', 4)])
<ide> def test_tokenizer_handles_emoji(tokenizer, text, length):
<del> tokens = tokenizer(text)
<del> assert len(tokens) == length
<add> # These break on narrow unicode builds, e.g. Windows
<add> if sys.maxunicode >= 1114111:
<add> tokens = tokenizer(text)
<add> assert len(tokens) == length | 1 |
Python | Python | simplify serialization slightly | 609014460861fdfe82054551790d6439292dde7b | <ide><path>rest_framework/fields.py
<ide> def get_value(self, dictionary):
<ide> return self.default_empty_html if (ret == '') else ret
<ide> return dictionary.get(self.field_name, empty)
<ide>
<del> def get_attribute(self, instance):
<add> def get_field_representation(self, instance):
<ide> """
<del> Given the *outgoing* object instance, return the value for this field
<del> that should be returned as a primative value.
<add> Given the outgoing object instance, return the primative value
<add> that should be used for this field.
<ide> """
<del> return get_attribute(instance, self.source_attrs)
<add> attribute = get_attribute(instance, self.source_attrs)
<add> if attribute is None:
<add> return None
<add> return self.to_representation(attribute)
<ide>
<ide> def get_default(self):
<ide> """
<ide><path>rest_framework/serializers.py
<ide> def to_representation(self, instance):
<ide> fields = [field for field in self.fields.values() if not field.write_only]
<ide>
<ide> for field in fields:
<del> native_value = field.get_attribute(instance)
<del> ret[field.field_name] = field.to_representation(native_value)
<add> ret[field.field_name] = field.get_field_representation(instance)
<ide>
<ide> return ret
<ide> | 2 |
Java | Java | exclude jdk package in shadowingclassloader | a07245caf8a5ba9debd11d3ace3b47e0b68d8422 | <ide><path>spring-context/src/main/java/org/springframework/instrument/classloading/ShadowingClassLoader.java
<ide> public class ShadowingClassLoader extends DecoratingClassLoader {
<ide>
<ide> /** Packages that are excluded by default. */
<ide> public static final String[] DEFAULT_EXCLUDED_PACKAGES =
<del> new String[] {"java.", "javax.", "sun.", "oracle.", "com.sun.", "com.ibm.", "COM.ibm.",
<add> new String[] {"java.", "javax.", "jdk.", "sun.", "oracle.", "com.sun.", "com.ibm.", "COM.ibm.",
<ide> "org.w3c.", "org.xml.", "org.dom4j.", "org.eclipse", "org.aspectj.", "net.sf.cglib",
<ide> "org.springframework.cglib", "org.apache.xerces.", "org.apache.commons.logging."};
<ide> | 1 |
PHP | PHP | apply fixes from styleci | 6fea6c271086e2ad017a6078e1ee457a2b8c398e | <ide><path>src/Illuminate/Console/Scheduling/ScheduleWorkCommand.php
<ide> public function handle()
<ide> $executions[] = $execution = new Process([
<ide> PHP_BINARY,
<ide> defined('ARTISAN_BINARY') ? ARTISAN_BINARY : 'artisan',
<del> 'schedule:run'
<add> 'schedule:run',
<ide> ]);
<ide>
<ide> $execution->start(); | 1 |
PHP | PHP | fix introspection on models in other plugins | c871d85f2b410b020aa4da8786c2c97c3d3e7c03 | <ide><path>lib/Cake/View/Helper/FormHelper.php
<ide> protected function _getModel($model) {
<ide> 'class' => $plugin . $this->request->params['models'][$model]['className'],
<ide> 'alias' => $model
<ide> ));
<add> } elseif (ClassRegistry::isKeySet($this->defaultModel)) {
<add> $defaultObject = ClassRegistry::getObject($this->defaultModel);
<add> if (in_array($model, array_keys($defaultObject->getAssociated()), true) && isset($defaultObject->{$model})) {
<add> $object = $defaultObject->{$model};
<add> }
<ide> } else {
<ide> $object = ClassRegistry::init($model, true);
<ide> }
<ide> public function create($model = null, $options = array()) {
<ide> $options = $model;
<ide> $model = null;
<ide> }
<add>
<ide> if (empty($model) && $model !== false && !empty($this->request->params['models'])) {
<ide> $model = key($this->request->params['models']);
<del> $this->defaultModel = $model;
<ide> } elseif (empty($model) && empty($this->request->params['models'])) {
<ide> $model = false;
<ide> }
<add> $this->defaultModel = $model;
<ide>
<ide> $key = null;
<ide> if ($model !== false) {
<ide> public function create($model = null, $options = array()) {
<ide> $options['action'] = $this->request->here(false);
<ide> } elseif (empty($options['url']) || is_array($options['url'])) {
<ide> if (empty($options['url']['controller'])) {
<del> if (!empty($model) && $model != $this->defaultModel) {
<add> if (!empty($model)) {
<ide> $options['url']['controller'] = Inflector::underscore(Inflector::pluralize($model));
<ide> } elseif (!empty($this->request->params['controller'])) {
<ide> $options['url']['controller'] = Inflector::underscore($this->request->params['controller']); | 1 |
Text | Text | add miladfarca to collaborators | d22f16d6e7b6c631ca3048dd097592f1cef69d00 | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> **Matteo Collina** <[email protected]> (he/him)
<ide> * [mhdawson](https://github.com/mhdawson) -
<ide> **Michael Dawson** <[email protected]> (he/him)
<add>* [miladfarca](https://github.com/miladfarca) -
<add>**Milad Fa** <[email protected]> (he/him)
<ide> * [mildsunrise](https://github.com/mildsunrise) -
<ide> **Alba Mendez** <[email protected]> (she/her)
<ide> * [misterdjules](https://github.com/misterdjules) - | 1 |
PHP | PHP | replace duplicate code with existing stub | 8a5b388a301727199a5e80d7ead26b990317c65e | <ide><path>src/TestSuite/Stub/ConsoleOutput.php
<ide> public function messages(): array
<ide> {
<ide> return $this->_out;
<ide> }
<add>
<add> /**
<add> * Get the output as a string
<add> *
<add> * @return string
<add> */
<add> public function output(): string
<add> {
<add> return implode("\n", $this->_out);
<add> }
<ide> }
<ide><path>tests/TestCase/Shell/CompletionShellTest.php
<ide> use Cake\Console\ConsoleIo;
<ide> use Cake\Console\ConsoleOutput;
<ide> use Cake\Core\Plugin;
<add>use Cake\TestSuite\Stub\ConsoleOutput as StubOutput;
<ide> use Cake\TestSuite\TestCase;
<ide>
<del>/**
<del> * TestCompletionStringOutput
<del> */
<del>class TestCompletionStringOutput extends ConsoleOutput
<del>{
<del>
<del> public $output = '';
<del>
<del> protected function _write($message)
<del> {
<del> $this->output .= $message;
<del> }
<del>}
<del>
<ide> /**
<ide> * CompletionShellTest
<ide> */
<ide> public function setUp()
<ide> static::setAppNamespace();
<ide> Plugin::load(['TestPlugin', 'TestPluginTwo']);
<ide>
<del> $this->out = new TestCompletionStringOutput();
<add> $this->out = new StubOutput();
<ide> $io = new ConsoleIo($this->out);
<ide>
<ide> $this->Shell = $this->getMockBuilder('Cake\Shell\CompletionShell')
<ide> public function tearDown()
<ide> public function testStartup()
<ide> {
<ide> $this->Shell->runCommand(['main']);
<del> $output = $this->out->output;
<add> $output = $this->out->output();
<ide>
<ide> $needle = 'Welcome to CakePHP';
<ide> $this->assertTextNotContains($needle, $output);
<ide> public function testStartup()
<ide> public function testMain()
<ide> {
<ide> $this->Shell->runCommand(['main']);
<del> $output = $this->out->output;
<add> $output = $this->out->output();
<ide>
<ide> $expected = '/This command is not intended to be called manually/';
<ide> $this->assertRegExp($expected, $output);
<ide> public function testMain()
<ide> public function testCommands()
<ide> {
<ide> $this->Shell->runCommand(['commands']);
<del> $output = $this->out->output;
<add> $output = $this->out->output();
<ide>
<ide> $expected = 'TestPlugin.example TestPlugin.sample TestPluginTwo.example unique welcome ' .
<ide> 'cache help i18n plugin routes schema_cache server version ' .
<del> "abort demo i18m integration merge sample shell_test testing_dispatch\n";
<add> "abort demo i18m integration merge sample shell_test testing_dispatch";
<ide> $this->assertTextEquals($expected, $output);
<ide> }
<ide>
<ide> public function testCommands()
<ide> public function testOptionsNoArguments()
<ide> {
<ide> $this->Shell->runCommand(['options']);
<del> $output = $this->out->output;
<add> $output = $this->out->output();
<ide>
<ide> $expected = '';
<ide> $this->assertTextEquals($expected, $output);
<ide> public function testOptionsNoArguments()
<ide> public function testOptionsNonExistingCommand()
<ide> {
<ide> $this->Shell->runCommand(['options', 'foo']);
<del> $output = $this->out->output;
<add> $output = $this->out->output();
<ide> $expected = '';
<ide> $this->assertTextEquals($expected, $output);
<ide> }
<ide> public function testOptionsNonExistingCommand()
<ide> public function testOptions()
<ide> {
<ide> $this->Shell->runCommand(['options', 'schema_cache']);
<del> $output = $this->out->output;
<add> $output = $this->out->output();
<ide>
<del> $expected = "--connection -c --help -h --quiet -q --verbose -v\n";
<add> $expected = "--connection -c --help -h --quiet -q --verbose -v";
<ide> $this->assertTextEquals($expected, $output);
<ide> }
<ide>
<ide> public function testOptions()
<ide> public function testOptionsTask()
<ide> {
<ide> $this->Shell->runCommand(['options', 'sample', 'sample']);
<del> $output = $this->out->output;
<add> $output = $this->out->output();
<ide>
<del> $expected = "--help -h --quiet -q --sample -s --verbose -v\n";
<add> $expected = "--help -h --quiet -q --sample -s --verbose -v";
<ide> $this->assertTextEquals($expected, $output);
<ide> }
<ide>
<ide> public function testOptionsTask()
<ide> public function testSubCommandsCorePlugin()
<ide> {
<ide> $this->Shell->runCommand(['subcommands', 'CORE.schema_cache']);
<del> $output = $this->out->output;
<add> $output = $this->out->output();
<ide>
<del> $expected = "build clear\n";
<add> $expected = "build clear";
<ide> $this->assertTextEquals($expected, $output);
<ide> }
<ide>
<ide> public function testSubCommandsCorePlugin()
<ide> public function testSubCommandsAppPlugin()
<ide> {
<ide> $this->Shell->runCommand(['subcommands', 'app.sample']);
<del> $output = $this->out->output;
<add> $output = $this->out->output();
<ide>
<del> $expected = "derp load returnValue sample withAbort\n";
<add> $expected = "derp load returnValue sample withAbort";
<ide> $this->assertTextEquals($expected, $output);
<ide> }
<ide>
<ide> public function testSubCommandsAppPlugin()
<ide> public function testSubCommandsPlugin()
<ide> {
<ide> $this->Shell->runCommand(['subcommands', 'welcome']);
<del> $output = $this->out->output;
<add> $output = $this->out->output();
<ide>
<del> $expected = "say_hello\n";
<add> $expected = "say_hello";
<ide> $this->assertTextEquals($expected, $output);
<ide> }
<ide>
<ide> public function testSubCommandsPlugin()
<ide> public function testSubCommandsPluginDotNotationBackwardCompatibility()
<ide> {
<ide> $this->Shell->runCommand(['subcommands', 'TestPluginTwo.welcome']);
<del> $output = $this->out->output;
<add> $output = $this->out->output();
<ide>
<del> $expected = "say_hello\n";
<add> $expected = "say_hello";
<ide> $this->assertTextEquals($expected, $output);
<ide> }
<ide>
<ide> public function testSubCommandsPluginDotNotationBackwardCompatibility()
<ide> public function testSubCommandsPluginDotNotation()
<ide> {
<ide> $this->Shell->runCommand(['subcommands', 'TestPluginTwo.example']);
<del> $output = $this->out->output;
<add> $output = $this->out->output();
<ide>
<del> $expected = "say_hello\n";
<add> $expected = "say_hello";
<ide> $this->assertTextEquals($expected, $output);
<ide> }
<ide>
<ide> public function testSubCommandsPluginDotNotation()
<ide> public function testSubCommandsAppDuplicatePluginNoDot()
<ide> {
<ide> $this->Shell->runCommand(['subcommands', 'sample']);
<del> $output = $this->out->output;
<add> $output = $this->out->output();
<ide>
<del> $expected = "derp load returnValue sample withAbort\n";
<add> $expected = "derp load returnValue sample withAbort";
<ide> $this->assertTextEquals($expected, $output);
<ide> }
<ide>
<ide> public function testSubCommandsAppDuplicatePluginNoDot()
<ide> public function testSubCommandsPluginDuplicateApp()
<ide> {
<ide> $this->Shell->runCommand(['subcommands', 'TestPlugin.sample']);
<del> $output = $this->out->output;
<add> $output = $this->out->output();
<ide>
<del> $expected = "example\n";
<add> $expected = "example";
<ide> $this->assertTextEquals($expected, $output);
<ide> }
<ide>
<ide> public function testSubCommandsPluginDuplicateApp()
<ide> public function testSubCommandsNoArguments()
<ide> {
<ide> $this->Shell->runCommand(['subcommands']);
<del> $output = $this->out->output;
<add> $output = $this->out->output();
<ide>
<ide> $expected = '';
<ide> $this->assertEquals($expected, $output);
<ide> public function testSubCommandsNoArguments()
<ide> public function testSubCommandsNonExistingCommand()
<ide> {
<ide> $this->Shell->runCommand(['subcommands', 'foo']);
<del> $output = $this->out->output;
<add> $output = $this->out->output();
<ide>
<ide> $expected = '';
<ide> $this->assertEquals($expected, $output);
<ide> public function testSubCommandsNonExistingCommand()
<ide> public function testSubCommands()
<ide> {
<ide> $this->Shell->runCommand(['subcommands', 'schema_cache']);
<del> $output = $this->out->output;
<add> $output = $this->out->output();
<ide>
<del> $expected = "build clear\n";
<add> $expected = "build clear";
<ide> $this->assertTextEquals($expected, $output);
<ide> }
<ide>
<ide> public function testSubCommands()
<ide> public function testFuzzy()
<ide> {
<ide> $this->Shell->runCommand(['fuzzy']);
<del> $output = $this->out->output;
<add> $output = $this->out->output();
<ide>
<ide> $expected = '';
<ide> $this->assertEquals($expected, $output); | 2 |
Python | Python | use variable names in formula for convolve | 9f8639aaf2791f3f6e2f5e9f28877314f35db1a3 | <ide><path>numpy/core/numeric.py
<ide> def convolve(a,v,mode='full'):
<ide> distributed according to the convolution of their individual
<ide> distributions.
<ide>
<add> If `v` is longer than `a`, the arrays are swapped before computation.
<add>
<ide> Parameters
<ide> ----------
<ide> a : (N,) array_like
<ide> def convolve(a,v,mode='full'):
<ide> -----
<ide> The discrete convolution operation is defined as
<ide>
<del> .. math:: (f * g)[n] = \\sum_{m = -\\infty}^{\\infty} f[m] g[n - m]
<add> .. math:: (a * v)[n] = \\sum_{m = -\\infty}^{\\infty} a[m] v[n - m]
<ide>
<ide> It can be shown that a convolution :math:`x(t) * y(t)` in time/space
<ide> is equivalent to the multiplication :math:`X(f) Y(f)` in the Fourier | 1 |
Javascript | Javascript | remove extra new line from html source | 19c3fd1e2fa983859ffc6d6aca71867ec9fe782e | <ide><path>gulpfile.js
<ide> function preprocessHTML(source, defines) {
<ide> fs.unlinkSync(outName);
<ide>
<ide> var i = source.lastIndexOf("/");
<del> return createStringSource(source.substr(i + 1), out);
<add> return createStringSource(source.substr(i + 1), `${out.trimEnd()}\n`);
<ide> }
<ide>
<ide> function buildGeneric(defines, dir) { | 1 |
Mixed | PHP | fix transaction handling for microsoft sql server | 13522832fb15dec1e09a979badae64238fc4a743 | <ide><path>readme.md
<ide> - Routes with too many leading or trailing slashes will now 404.
<ide> - Added `callSecure` test helper.
<ide> - Added `values` method to the `Collection` class.
<add>- Fix transaction handling for Microsoft SQL Server.
<ide>
<ide> ## Beta 3
<ide>
<ide><path>src/Illuminate/Database/SqlServerConnection.php
<ide>
<ide> class SqlServerConnection extends Connection {
<ide>
<add> /**
<add> * Execute a Closure within a transaction.
<add> *
<add> * @param Closure $callback
<add> * @return mixed
<add> */
<add> public function transaction(Closure $callback)
<add> {
<add> $this->pdo->exec('BEGIN TRAN');
<add>
<add> // We'll simply execute the given callback within a try / catch block
<add> // and if we catch any exception we can rollback the transaction
<add> // so that none of the changes are persisted to the database.
<add> try
<add> {
<add> $result = $callback($this);
<add>
<add> $this->pdo->exec('COMMIT TRAN');
<add> }
<add>
<add> // If we catch an exception, we will roll back so nothing gets messed
<add> // up in the database. Then we'll re-throw the exception so it can
<add> // be handled how the developer sees fit for their applications.
<add> catch (\Exception $e)
<add> {
<add> $this->pdo->exec('ROLLBACK TRAN');
<add>
<add> throw $e;
<add> }
<add>
<add> return $result;
<add> }
<add>
<ide> /**
<ide> * Get the default query grammar instance.
<ide> * | 2 |
Python | Python | add subclass matching to serializer field mapping | 82d4b2083292659358d5df4d03d2115576e8ae4e | <ide><path>rest_framework/serializers.py
<ide> def get_field(self, model_field):
<ide> try:
<ide> return self.field_mapping[model_field.__class__](**kwargs)
<ide> except KeyError:
<add> for model_field_class, serializer_field_class in self.field_mapping.items():
<add> if isinstance(model_field, model_field_class):
<add> return serializer_field_class(**kwargs)
<ide> return ModelField(model_field=model_field, **kwargs)
<ide>
<ide> def get_validation_exclusions(self, instance=None): | 1 |
Text | Text | update readme to link to the new docs | a15ccbc0fe04c64e2bb92fb3485f8d29c292f28f | <ide><path>packages/next/README.md
<ide> </a>
<ide> </p>
<ide>
<del><p align="center">
<del> <strong>
<del> Visit <a aria-label="next.js learn" href="https://nextjs.org/learn">https://nextjs.org/learn</a> to get started with Next.js.
<del> </strong>
<del></p>
<del>
<del>---
<del>
<del>**The below readme is the documentation for the `canary` (prerelease) branch. To view the documentation for the latest stable Next.js version visit [nextjs.org/docs](https://nextjs.org/docs).**
<del>
<del>---
<del>
<del><!-- START doctoc generated TOC please keep comment here to allow auto update -->
<del><!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
<del><!-- https://github.com/thlorenz/doctoc -->
<del>
<del>- [How to use](#how-to-use)
<del> - [Setup](#setup)
<del> - [Quick Start](#quick-start)
<del> - [Manual Setup](#manual-setup)
<del> - [Automatic code splitting](#automatic-code-splitting)
<del> - [CSS](#css)
<del> - [Built-in CSS support](#built-in-css-support)
<del> - [CSS-in-JS](#css-in-js)
<del> - [Importing CSS / Sass / Less / Stylus files](#importing-css--sass--less--stylus-files)
<del> - [Static file serving (e.g.: images)](#static-file-serving-eg-images)
<del> - [Dynamic Routing](#dynamic-routing)
<del> - [Populating `<head>`](#populating-head)
<del> - [Fetching data and component lifecycle](#fetching-data-and-component-lifecycle)
<del> - [Routing](#routing)
<del> - [With `<Link>`](#with-link)
<del> - [With URL object](#with-url-object)
<del> - [Replace instead of push url](#replace-instead-of-push-url)
<del> - [Using a component that supports `onClick`](#using-a-component-that-supports-onclick)
<del> - [Forcing the Link to expose `href` to its child](#forcing-the-link-to-expose-href-to-its-child)
<del> - [Disabling the scroll changes to top on page](#disabling-the-scroll-changes-to-top-on-page)
<del> - [Imperatively](#imperatively)
<del> - [Intercepting `popstate`](#intercepting-popstate)
<del> - [With URL object](#with-url-object-1)
<del> - [Router Events](#router-events)
<del> - [Shallow Routing](#shallow-routing)
<del> - [useRouter](#userouter)
<del> - [Using a Higher Order Component](#using-a-higher-order-component)
<del> - [Prefetching Pages](#prefetching-pages)
<del> - [With `<Link>`](#with-link-1)
<del> - [Imperatively](#imperatively-1)
<del> - [API Routes](#api-routes)
<del> - [Dynamic routes support](#dynamic-routes-support)
<del> - [API Middlewares](#api-middlewares)
<del> - [Helper Functions](#helper-functions)
<del> - [Custom server and routing](#custom-server-and-routing)
<del> - [Disabling file-system routing](#disabling-file-system-routing)
<del> - [Dynamic assetPrefix](#dynamic-assetprefix)
<del> - [Changing x-powered-by](#changing-x-powered-by)
<del> - [Dynamic Import](#dynamic-import)
<del> - [Basic Usage (Also does SSR)](#basic-usage-also-does-ssr)
<del> - [With named exports](#with-named-exports)
<del> - [With Custom Loading Component](#with-custom-loading-component)
<del> - [With No SSR](#with-no-ssr)
<del> - [Custom `<App>`](#custom-app)
<del> - [Custom `<Document>`](#custom-document)
<del> - [Customizing `renderPage`](#customizing-renderpage)
<del> - [Custom error handling](#custom-error-handling)
<del> - [Reusing the built-in error page](#reusing-the-built-in-error-page)
<del> - [Custom configuration](#custom-configuration)
<del> - [Setting a custom build directory](#setting-a-custom-build-directory)
<del> - [Disabling etag generation](#disabling-etag-generation)
<del> - [Configuring the onDemandEntries](#configuring-the-ondemandentries)
<del> - [Configuring extensions looked for when resolving pages in `pages`](#configuring-extensions-looked-for-when-resolving-pages-in-pages)
<del> - [Configuring the build ID](#configuring-the-build-id)
<del> - [Configuring next process script](#configuring-next-process-script)
<del> - [Customizing webpack config](#customizing-webpack-config)
<del> - [Customizing babel config](#customizing-babel-config)
<del> - [Exposing configuration to the server / client side](#exposing-configuration-to-the-server--client-side)
<del> - [Build-time configuration](#build-time-configuration)
<del> - [Runtime configuration](#runtime-configuration)
<del> - [Starting the server on alternative hostname](#starting-the-server-on-alternative-hostname)
<del> - [CDN support with Asset Prefix](#cdn-support-with-asset-prefix)
<del>- [Automatic Static Optimization](#automatic-static-optimization)
<del>- [Automatic Static Optimization Indicator](#automatic-static-optimization-indicator)
<del>- [Production deployment](#production-deployment)
<del> - [Compression](#compression)
<del> - [Serverless deployment](#serverless-deployment)
<del> - [One Level Lower](#one-level-lower)
<del> - [Summary](#summary)
<del>- [Browser support](#browser-support)
<del>- [TypeScript](#typescript)
<del> - [Exported types](#exported-types)
<del>- [AMP Support](#amp-support)
<del> - [Enabling AMP Support](#enabling-amp-support)
<del> - [AMP First Page](#amp-first-page)
<del> - [Hybrid AMP Page](#hybrid-amp-page)
<del> - [AMP Page Modes](#amp-page-modes)
<del> - [AMP Behavior with `next export`](#amp-behavior-with-next-export)
<del> - [Adding AMP Components](#adding-amp-components)
<del> - [AMP Validation](#amp-validation)
<del> - [TypeScript Support](#typescript-support)
<del>- [Static HTML export](#static-html-export)
<del> - [Usage](#usage)
<del> - [Limitation](#limitation)
<del>- [Multi Zones](#multi-zones)
<del> - [How to define a zone](#how-to-define-a-zone)
<del> - [How to merge them](#how-to-merge-them)
<del>- [FAQ](#faq)
<del>- [Contributing](#contributing)
<del>- [Authors](#authors)
<del>
<del><!-- END doctoc generated TOC please keep comment here to allow auto update -->
<del>
<del>## How to use
<del>
<del>### Setup
<del>
<del>#### Quick Start
<del>
<del>```bash
<del>npx create-next-app
<del>```
<del>
<del>_([npx](https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b) comes with npm 5.2+ and higher, see [instructions for older npm versions](https://gist.github.com/timer/833d9946fa8a05ba855729d05a38ac23))_
<del>
<del>#### Manual Setup
<del>
<del>Install it in your project:
<del>
<del>```bash
<del>npm install --save next react react-dom
<del>```
<del>
<del>and add a script to your package.json like this:
<del>
<del>```json
<del>{
<del> "scripts": {
<del> "dev": "next",
<del> "build": "next build",
<del> "start": "next start"
<del> }
<del>}
<del>```
<del>
<del>After that, the file-system is the main API. Every `.js` file becomes a route that gets automatically processed and rendered.
<del>
<del>Populate `./pages/index.js` inside your project:
<del>
<del>```jsx
<del>function Home() {
<del> return <div>Welcome to Next.js!</div>
<del>}
<del>
<del>export default Home
<del>```
<del>
<del>and then just run `npm run dev` and go to `http://localhost:3000`. To use another port, you can run `npm run dev -- -p <your port here>`.
<del>
<del>So far, we get:
<del>
<del>- Automatic transpilation and bundling (with webpack and babel)
<del>- Hot code reloading
<del>- Server rendering and indexing of `./pages/`
<del>- Static file serving. `./public/` is mapped to `/` (given you [create a `./public/` directory](#static-file-serving-eg-images) inside your project)
<del>
<del>### Automatic code splitting
<del>
<del>Every `import` you declare gets bundled and served with each page. That means pages never load unnecessary code!
<del>
<del>```jsx
<del>import cowsay from 'cowsay-browser'
<del>
<del>function CowsayHi() {
<del> return <pre>{cowsay.say({ text: 'hi there!' })}</pre>
<del>}
<del>
<del>export default CowsayHi
<del>```
<del>
<del>### CSS
<del>
<del>#### Built-in CSS support
<del>
<del><details>
<del> <summary><b>Examples</b></summary>
<del> <ul>
<del> <li><a href="/examples/basic-css">Basic css</a></li>
<del> </ul>
<del></details>
<del>
<del>We bundle [styled-jsx](https://github.com/zeit/styled-jsx) to provide support for isolated scoped CSS. The aim is to support "shadow CSS" similar to Web Components, which unfortunately [do not support server-rendering and are JS-only](https://github.com/w3c/webcomponents/issues/71).
<del>
<del>```jsx
<del>function HelloWorld() {
<del> return (
<del> <div>
<del> Hello world
<del> <p>scoped!</p>
<del> <style jsx>{`
<del> p {
<del> color: blue;
<del> }
<del> div {
<del> background: red;
<del> }
<del> @media (max-width: 600px) {
<del> div {
<del> background: blue;
<del> }
<del> }
<del> `}</style>
<del> <style global jsx>{`
<del> body {
<del> background: black;
<del> }
<del> `}</style>
<del> </div>
<del> )
<del>}
<del>
<del>export default HelloWorld
<del>```
<del>
<del>Please see the [styled-jsx documentation](https://www.npmjs.com/package/styled-jsx) for more examples.
<del>
<del>#### CSS-in-JS
<del>
<del><details>
<del> <summary>
<del> <b>Examples</b>
<del> </summary>
<del> <ul>
<del> <li><a href="/examples/with-styled-components">Styled components</a></li>
<del> <li><a href="/examples/with-styletron">Styletron</a></li>
<del> <li><a href="/examples/with-glamor">Glamor</a></li>
<del> <li><a href="/examples/with-cxs">Cxs</a></li>
<del> <li><a href="/examples/with-aphrodite">Aphrodite</a></li>
<del> <li><a href="/examples/with-fela">Fela</a></li>
<del> </ul>
<del></details>
<del>
<del>It's possible to use any existing CSS-in-JS solution. The simplest one is inline styles:
<del>
<del>```jsx
<del>function HiThere() {
<del> return <p style={{ color: 'red' }}>hi there</p>
<del>}
<del>
<del>export default HiThere
<del>```
<del>
<del>To use more sophisticated CSS-in-JS solutions, you typically have to implement style flushing for server-side rendering. We enable this by allowing you to define your own [custom `<Document>`](#custom-document) component that wraps each page.
<del>
<del>#### Importing CSS / Sass / Less / Stylus files
<del>
<del>To support importing `.css`, `.scss`, `.less` or `.styl` files you can use these modules, which configure sensible defaults for server rendered applications.
<del>
<del>- [@zeit/next-css](https://github.com/zeit/next-plugins/tree/master/packages/next-css)
<del>- [@zeit/next-sass](https://github.com/zeit/next-plugins/tree/master/packages/next-sass)
<del>- [@zeit/next-less](https://github.com/zeit/next-plugins/tree/master/packages/next-less)
<del>- [@zeit/next-stylus](https://github.com/zeit/next-plugins/tree/master/packages/next-stylus)
<del>
<del>### Static file serving (e.g.: images)
<del>
<del>Create a folder called `public` in your project root directory. From your code you can then reference those files starting from the baseURL `/`
<del>
<del>```jsx
<del>function MyImage() {
<del> return <img src="/my-image.png" alt="my image" />
<del>}
<del>
<del>export default MyImage
<del>```
<del>
<del>_Note: Don't name the `public` directory anything else. The name can't be changed and is the only directory that Next.js uses for serving static assets._
<del>
<del>### Dynamic Routing
<del>
<del><details>
<del> <summary><b>Examples</b></summary>
<del> <ul>
<del> <li><a href="/examples/dynamic-routing">Dynamic routing</a></li>
<del> </ul>
<del></details>
<del>
<del>Defining routes by using predefined paths is not always enough for complex applications, in Next.js you can add brackets to a page (`[param]`) to create a dynamic route (a.k.a. url slugs, pretty urls, et al).
<del>
<del>Consider the following page `pages/post/[pid].js`:
<del>
<del>```jsx
<del>import { useRouter } from 'next/router'
<del>
<del>const Post = () => {
<del> const router = useRouter()
<del> const { pid } = router.query
<del>
<del> return <p>Post: {pid}</p>
<del>}
<del>
<del>export default Post
<del>```
<del>
<del>Any route like `/post/1`, `/post/abc`, etc will be matched by `pages/post/[pid].js`.
<del>The matched path parameter will be sent as a query parameter to the page.
<del>
<del>For example, the route `/post/abc` will have the following `query` object: `{ pid: 'abc' }`.
<del>Similarly, the route `/post/abc?foo=bar` will have the `query` object: `{ foo: 'bar', pid: 'abc' }`.
<del>
<del>> Note: Multiple dynamic route segments work the same way.
<del>>
<del>> For example, `pages/post/[pid]/[comment].js` would match `/post/1/a-comment`.
<del>> Its `query` object would be: `{ pid: '1', comment: 'a-comment' }`.
<del>
<del>A `<Link>` for `/post/abc` looks like so:
<del>
<del>```jsx
<del><Link href="/post/[pid]" as="/post/abc">
<del> <a>First Post</a>
<del></Link>
<del>```
<del>
<del>- `href`: the path inside `pages` directory.
<del>- `as`: the path that will be rendered in the browser URL bar.
<del>
<del>As `href` is a filesystem path, it shouldn't change at runtime, instead, you will probably need to change `as`
<del>dynamically according to your needs. Here's an example to create a list of links:
<del>
<del>```jsx
<del>const pids = ['id1', 'id2', 'id3']
<del>{
<del> pids.map(pid => (
<del> <Link href="/post/[pid]" as={`/post/${pid}`}>
<del> <a>Post {pid}</a>
<del> </Link>
<del> ))
<del>}
<del>```
<del>
<del>> You can [read more about `<Link>` here](#with-link).
<del>
<del>However, if a query and route param name are the same, route parameters will override the matching query params.
<del>For example, `/post/abc?pid=bcd` will have the `query` object: `{ pid: 'abc' }`.
<del>
<del>> **Note**: Predefined routes take precedence over dynamic routes.
<del>> For example, if you have `pages/post/[pid].js` and `pages/post/create.js`, the route `/post/create` will be matched by `pages/post/create.js` instead of the dynamic route (`[pid]`).
<del>
<del>> **Note**: Pages that are statically optimized by [automatic static optimization](#automatic-static-optimization) will be hydrated without their route parameters provided (`query` will be empty, i.e. `{}`).
<del>> After hydration, Next.js will trigger an update to your application to provide the route parameters in the `query` object.
<del>> If your application cannot tolerate this behavior, you can opt-out of static optimization by capturing the query parameter in `getInitialProps`.
<del>
<del>> **Note**: If deploying to [ZEIT Now](https://zeit.co/now) dynamic routes will work out-of-the-box.
<del>> You do not need to configure custom routes in a `now.json` file.
<del>>
<del>> If you are new to ZEIT Now, you can learn how to deploy a Next.js app to it in the [_Deploying a Next.js App_ Learn section](https://nextjs.org/learn/basics/deploying-a-nextjs-app).
<del>
<del>### Populating `<head>`
<del>
<del><details>
<del><summary><b>Examples</b></summary>
<del><ul>
<del> <li><a href="/examples/head-elements">Head elements</a></li>
<del> <li><a href="/examples/layout-component">Layout component</a></li>
<del></ul>
<del></details>
<del>
<del>We expose a built-in component for appending elements to the `<head>` of the page.
<del>
<del>```jsx
<del>import Head from 'next/head'
<del>
<del>function IndexPage() {
<del> return (
<del> <div>
<del> <Head>
<del> <title>My page title</title>
<del> <meta name="viewport" content="initial-scale=1.0, width=device-width" />
<del> </Head>
<del> <p>Hello world!</p>
<del> </div>
<del> )
<del>}
<del>
<del>export default IndexPage
<del>```
<del>
<del>To avoid duplicate tags in your `<head>` you can use the `key` property, which will make sure the tag is only rendered once:
<del>
<del>```jsx
<del>import Head from 'next/head'
<del>
<del>function IndexPage() {
<del> return (
<del> <div>
<del> <Head>
<del> <title>My page title</title>
<del> <meta
<del> name="viewport"
<del> content="initial-scale=1.0, width=device-width"
<del> key="viewport"
<del> />
<del> </Head>
<del> <Head>
<del> <meta
<del> name="viewport"
<del> content="initial-scale=1.2, width=device-width"
<del> key="viewport"
<del> />
<del> </Head>
<del> <p>Hello world!</p>
<del> </div>
<del> )
<del>}
<del>
<del>export default IndexPage
<del>```
<del>
<del>In this case only the second `<meta name="viewport" />` is rendered.
<del>
<del>_Note: The contents of `<head>` get cleared upon unmounting the component, so make sure each page completely defines what it needs in `<head>`, without making assumptions about what other pages added._
<del>
<del>_Note: `<title>` and `<meta>` elements need to be contained as **direct** children of the `<Head>` element, or wrapped into maximum one level of `<React.Fragment>`, otherwise the metatags won't be correctly picked up on clientside navigation._
<del>
<del>### Fetching data and component lifecycle
<del>
<del><details>
<del> <summary><b>Examples</b></summary>
<del> <ul>
<del> <li><a href="/examples/data-fetch">Data fetch</a></li>
<del> </ul>
<del></details>
<del>
<del>When you need state, lifecycle hooks or **initial data population** you can export a function component that uses [Hooks](https://reactjs.org/docs/hooks-intro.html) or a [class component](https://reactjs.org/docs/react-component.html).
<del>
<del>Using a function component:
<del>
<del>```jsx
<del>import fetch from 'isomorphic-unfetch'
<del>
<del>function Page({ stars }) {
<del> return <div>Next stars: {stars}</div>
<del>}
<del>
<del>Page.getInitialProps = async ({ req }) => {
<del> const res = await fetch('https://api.github.com/repos/zeit/next.js')
<del> const json = await res.json()
<del> return { stars: json.stargazers_count }
<del>}
<del>
<del>export default Page
<del>```
<del>
<del>Using a class component:
<del>
<del>```jsx
<del>import React from 'react'
<del>
<del>class HelloUA extends React.Component {
<del> static async getInitialProps({ req }) {
<del> const userAgent = req ? req.headers['user-agent'] : navigator.userAgent
<del> return { userAgent }
<del> }
<del>
<del> render() {
<del> return <div>Hello World {this.props.userAgent}</div>
<del> }
<del>}
<del>
<del>export default HelloUA
<del>```
<del>
<del>Notice that to load data when the page loads, we use `getInitialProps` which is an [`async`](https://zeit.co/blog/async-and-await) static method. It can asynchronously fetch anything that resolves to a JavaScript plain `Object`, which populates `props`.
<del>
<del>Data returned from `getInitialProps` is serialized when server rendering, similar to a `JSON.stringify`. Make sure the returned object from `getInitialProps` is a plain `Object` and not using `Date`, `Map` or `Set`.
<del>
<del>For the initial page load, `getInitialProps` will execute on the server only. `getInitialProps` will only be executed on the client when navigating to a different route via the `Link` component or using the routing APIs.
<del>
<del><br/>
<del>
<del>> - `getInitialProps` can **not** be used in children components. Only in `pages`.
<del>> - If you are using some server only modules inside `getInitialProps`, make sure to [import them properly](https://arunoda.me/blog/ssr-and-server-only-modules), otherwise, it'll slow down your app.
<del>
<del><br/>
<del>
<del>`getInitialProps` receives a context object with the following properties:
<del>
<del>- `pathname` - Current route. That is the path of the page in `/pages`
<del>- `query` - Query string section of URL parsed as an object
<del>- `asPath` - `String` of the actual path (including the query) shows in the browser
<del>- `req` - HTTP request object (server only)
<del>- `res` - HTTP response object (server only)
<del>- `err` - Error object if any error is encountered during the rendering
<del>
<del>### Routing
<del>
<del>Next.js does not ship a routes manifest with every possible route in the application, so the current page is not aware of any other pages on the client side. All subsequent routes get lazy-loaded, for scalability sake.
<del>
<del>#### With `<Link>`
<del>
<del><details>
<del> <summary><b>Examples</b></summary>
<del> <ul>
<del> <li><a href="/examples/hello-world">Hello World</a></li>
<del> </ul>
<del></details>
<del>
<del>Client-side transitions between routes can be enabled via a `<Link>` component.
<del>
<del>> This component is not required for navigations to static pages that require a hard refresh, like when using [AMP](#amp-support).
<del>
<del>**Basic Example**
<del>
<del>Consider these two pages:
<del>
<del>```jsx
<del>// pages/index.js
<del>import Link from 'next/link'
<del>
<del>function Home() {
<del> return (
<del> <>
<del> <ul>
<del> <li>Home</li>
<del> <li>
<del> <Link href="/about">
<del> <a>About Us</a>
<del> </Link>
<del> </li>
<del> </ul>
<del>
<del> <h1>This is our homepage.</h1>
<del> </>
<del> )
<del>}
<del>
<del>export default Home
<del>```
<del>
<del>```jsx
<del>// pages/about.js
<del>import Link from 'next/link'
<del>
<del>function About() {
<del> return (
<del> <>
<del> <ul>
<del> <li>
<del> <Link href="/">
<del> <a>Home</a>
<del> </Link>
<del> </li>
<del> <li>About Us</li>
<del> </ul>
<del>
<del> <h1>About</h1>
<del> <p>We are a cool company.</p>
<del> </>
<del> )
<del>}
<del>
<del>export default About
<del>```
<del>
<del>Note: if passing a functional component as a child of `<Link>` you will need to wrap it in [`React.forwardRef`](https://reactjs.org/docs/react-api.html#reactforwardref)
<del>
<del>**Example with `React.forwardRef`**
<del>
<del>```jsx
<del>import React from 'react'
<del>import Link from 'next/link'
<del>
<del>// `onClick`, `href`, and `ref` need to be passed to the DOM element
<del>// for proper handling
<del>const MyButton = React.forwardRef(({ onClick, href }, ref) => (
<del> <a href={href} onClick={onClick} ref={ref}>
<del> Click Me
<del> </a>
<del>))
<del>
<del>export default () => (
<del> <>
<del> <Link href="/another">
<del> <MyButton />
<del> </Link>
<del> </>
<del>)
<del>```
<del>
<del>**Custom routes (using props from URL)**
<del>
<del>If you find that your use case is not covered by [Dynamic Routing](#dynamic-routing) then you can create a custom server and manually add dynamic routes.
<del>
<del>Example:
<del>
<del>1. Consider you have the URL `/post/:slug`.
<del>
<del>2. You created `pages/post.js`:
<del>
<del> ```jsx
<del> import { useRouter } from 'next/router'
<del>
<del> const Post = () => {
<del> const router = useRouter()
<del> const { slug } = router.query
<del>
<del> return <p>My Blog Post: {slug}</p>
<del> }
<del>
<del> export default Post
<del> ```
<del>
<del>3. You add the route to `express` (or any other server) on `server.js` file (this is only for SSR). This will route the url `/post/:slug` to `pages/post.js` and provide `slug` as part of the `query` object to the page.
<del>
<del> ```jsx
<del> server.get('/post/:slug', (req, res) => {
<del> return app.render(req, res, '/post', { slug: req.params.slug })
<del> })
<del> ```
<del>
<del>4. For client side routing, use `next/link`:
<del>
<del> ```jsx
<del> <Link href="/post?slug=something" as="/post/something">
<del> ```
<del>
<del> - `href`: the path inside `pages` directory
<del> - `as`: the path used by your server routes
<del>
<del>Client-side routing behaves exactly like the browser:
<del>
<del>1. The component is fetched.
<del>2. If it defines `getInitialProps`, data is fetched. If an error occurs, `_error.js` is rendered.
<del>3. After 1 and 2 complete, `pushState` is performed and the new component is rendered.
<del>
<del>To inject the `pathname`, `query` or `asPath` in your component, you can use the [useRouter](#userouter) hook, or [withRouter](#using-a-higher-order-component) for class components.
<del>
<del>##### With URL object
<del>
<del><details>
<del> <summary><b>Examples</b></summary>
<del> <ul>
<del> <li><a href="/examples/with-url-object-routing">With URL Object Routing</a></li>
<del> </ul>
<del></details>
<del>
<del>The component `<Link>` can also receive a URL object and it will automatically format it to create the URL string.
<del>
<del>```jsx
<del>// pages/index.js
<del>import Link from 'next/link'
<del>
<del>function Home() {
<del> return (
<del> <div>
<del> Click{' '}
<del> <Link href={{ pathname: '/about', query: { name: 'Zeit' } }}>
<del> <a>here</a>
<del> </Link>{' '}
<del> to read more
<del> </div>
<del> )
<del>}
<del>
<del>export default Home
<del>```
<del>
<del>That will generate the URL string `/about?name=Zeit`, you can use every property as defined in the [Node.js URL module documentation](https://nodejs.org/api/url.html#url_url_strings_and_url_objects).
<del>
<del>##### Replace instead of push url
<del>
<del>The default behaviour for the `<Link>` component is to `push` a new url into the stack. You can use the `replace` prop to prevent adding a new entry.
<del>
<del>```jsx
<del>// pages/index.js
<del>import Link from 'next/link'
<del>
<del>function Home() {
<del> return (
<del> <div>
<del> Click{' '}
<del> <Link href="/about" replace>
<del> <a>here</a>
<del> </Link>{' '}
<del> to read more
<del> </div>
<del> )
<del>}
<del>
<del>export default Home
<del>```
<del>
<del>##### Using a component that supports `onClick`
<del>
<del>`<Link>` supports any component that supports the `onClick` event. In case you don't provide an `<a>` tag, it will only add the `onClick` event handler and won't pass the `href` property.
<del>
<del>```jsx
<del>// pages/index.js
<del>import Link from 'next/link'
<del>
<del>function Home() {
<del> return (
<del> <div>
<del> Click{' '}
<del> <Link href="/about">
<del> <img src="/static/image.png" alt="image" />
<del> </Link>
<del> </div>
<del> )
<del>}
<del>
<del>export default Home
<del>```
<del>
<del>##### Forcing the Link to expose `href` to its child
<del>
<del>If child is an `<a>` tag and doesn't have a href attribute we specify it so that the repetition is not needed by the user. However, sometimes, you’ll want to pass an `<a>` tag inside of a wrapper and the `Link` won’t recognize it as a _hyperlink_, and, consequently, won’t transfer its `href` to the child. In cases like that, you should define a boolean `passHref` property to the `Link`, forcing it to expose its `href` property to the child.
<del>
<del>**Please note**: using a tag other than `a` and failing to pass `passHref` may result in links that appear to navigate correctly, but, when being crawled by search engines, will not be recognized as links (owing to the lack of `href` attribute). This may result in negative effects on your site’s SEO.
<del>
<del>```jsx
<del>import Link from 'next/link'
<del>import Unexpected_A from 'third-library'
<del>
<del>function NavLink({ href, name }) {
<del> return (
<del> <Link href={href} passHref>
<del> <Unexpected_A>{name}</Unexpected_A>
<del> </Link>
<del> )
<del>}
<del>
<del>export default NavLink
<del>```
<del>
<del>##### Disabling the scroll changes to top on page
<del>
<del>The default behaviour of `<Link>` is to scroll to the top of the page. When there is a hash defined it will scroll to the specific id, just like a normal `<a>` tag. To prevent scrolling to the top / hash `scroll={false}` can be added to `<Link>`:
<del>
<del>```jsx
<del><Link scroll={false} href="/?counter=10"><a>Disables scrolling</a></Link>
<del><Link href="/?counter=10"><a>Changes with scrolling to top</a></Link>
<del>```
<del>
<del>#### Imperatively
<del>
<del><details>
<del> <summary><b>Examples</b></summary>
<del> <ul>
<del> <li><a href="/examples/using-router">Basic routing</a></li>
<del> <li><a href="/examples/with-loading">With a page loading indicator</a></li>
<del> </ul>
<del></details>
<del>
<del>You can also do client-side page transitions using `next/router`:
<del>
<del>```jsx
<del>import Router from 'next/router'
<del>
<del>function ReadMore() {
<del> return (
<del> <div>
<del> Click <span onClick={() => Router.push('/about')}>here</span> to read more
<del> </div>
<del> )
<del>}
<del>
<del>export default ReadMore
<del>```
<del>
<del>#### Intercepting `popstate`
<del>
<del>In some cases (for example, if using a [custom router](#custom-server-and-routing)), you may wish
<del>to listen to [`popstate`](https://developer.mozilla.org/en-US/docs/Web/Events/popstate) and react before the router acts on it.
<del>For example, you could use this to manipulate the request, or force an SSR refresh.
<del>
<del>```jsx
<del>import Router from 'next/router'
<del>
<del>Router.beforePopState(({ url, as, options }) => {
<del> // I only want to allow these two routes!
<del> if (as !== '/' && as !== '/other') {
<del> // Have SSR render bad routes as a 404.
<del> window.location.href = as
<del> return false
<del> }
<del>
<del> return true
<del>})
<del>```
<del>
<del>If the function you pass into `beforePopState` returns `false`, `Router` will not handle `popstate`;
<del>you'll be responsible for handling it, in that case.
<del>See [Disabling File-System Routing](#disabling-file-system-routing).
<del>
<del>Above `Router` object comes with the following API:
<del>
<del>- `pathname` - `String` of the current route. That is the path of the page in `/pages`
<del>- `query` - `Object` with the parsed query string. Defaults to `{}`.
<del>- `asPath` - `String` of the actual path (including the query) shows in the browser
<del>- `push(url, as=url)` - performs a `pushState` call with the given url
<del>- `replace(url, as=url)` - performs a `replaceState` call with the given url
<del>- `beforePopState(cb=function)` - intercept popstate before router processes the event
<del>
<del>The second `as` parameter for `push` and `replace` is an optional _decoration_ of the URL. Useful if you configured custom routes on the server.
<del>
<del>##### With URL object
<del>
<del>You can use a URL object the same way you use it in a `<Link>` component to `push` and `replace` a URL.
<del>
<del>```jsx
<del>import Router from 'next/router'
<del>
<del>const handler = () => {
<del> Router.push({
<del> pathname: '/about',
<del> query: { name: 'Zeit' },
<del> })
<del>}
<del>
<del>function ReadMore() {
<del> return (
<del> <div>
<del> Click <span onClick={handler}>here</span> to read more
<del> </div>
<del> )
<del>}
<del>
<del>export default ReadMore
<del>```
<del>
<del>This uses the same exact parameters as [in the `<Link>` component](#with-url-object). The first parameter maps to `href` while the second parameter maps to `as` in the `<Link>` component as documented [here](#with-url-object).
<del>
<del>##### Router Events
<del>
<del>You can also listen to different events happening inside the Router.
<del>Here's a list of supported events:
<del>
<del>- `routeChangeStart(url)` - Fires when a route starts to change
<del>- `routeChangeComplete(url)` - Fires when a route changed completely
<del>- `routeChangeError(err, url)` - Fires when there's an error when changing routes, or a route load is cancelled
<del>- `beforeHistoryChange(url)` - Fires just before changing the browser's history
<del>- `hashChangeStart(url)` - Fires when the hash will change but not the page
<del>- `hashChangeComplete(url)` - Fires when the hash has changed but not the page
<del>
<del>> Here `url` is the URL shown in the browser. If you call `Router.push(url, as)` (or similar), then the value of `url` will be `as`.
<del>
<del>Here's how to properly listen to the router event `routeChangeStart`:
<del>
<del>```js
<del>const handleRouteChange = url => {
<del> console.log('App is changing to: ', url)
<del>}
<del>
<del>Router.events.on('routeChangeStart', handleRouteChange)
<del>```
<del>
<del>If you no longer want to listen to that event, you can unsubscribe with the `off` method:
<del>
<del>```js
<del>Router.events.off('routeChangeStart', handleRouteChange)
<del>```
<del>
<del>If a route load is cancelled (for example by clicking two links rapidly in succession), `routeChangeError` will fire. The passed `err` will contain a `cancelled` property set to `true`.
<del>
<del>```js
<del>Router.events.on('routeChangeError', (err, url) => {
<del> if (err.cancelled) {
<del> console.log(`Route to ${url} was cancelled!`)
<del> }
<del>})
<del>```
<del>
<del>> **Note**: Using router events in `getInitialProps` is discouraged as it may result in unexpected behavior.<br/>
<del>> Router events should be registered when a component mounts (`useEffect` or `componentDidMount`/`componentWillUnmount`) or imperatively when an event happens.
<del>>
<del>> ```js
<del>> useEffect(() => {
<del>> const handleRouteChange = url => {
<del>> console.log('App is changing to: ', url)
<del>> }
<del>>
<del>> Router.events.on('routeChangeStart', handleRouteChange)
<del>> return () => {
<del>> Router.events.off('routeChangeStart', handleRouteChange)
<del>> }
<del>> }, [])
<del>> ```
<del>
<del>##### Shallow Routing
<del>
<del><details>
<del> <summary><b>Examples</b></summary>
<del> <ul>
<del> <li><a href="/examples/with-shallow-routing">Shallow Routing</a></li>
<del> </ul>
<del></details>
<del>
<del>Shallow routing allows you to change the URL without running `getInitialProps`. You'll receive the updated `pathname` and the `query` via the `router` prop (injected by using [`useRouter`](#userouter) or [`withRouter`](#using-a-higher-order-component)), without losing state.
<del>
<del>You can do this by invoking either `Router.push` or `Router.replace` with the `shallow: true` option. Here's an example:
<del>
<del>```js
<del>// Current URL is "/"
<del>const href = '/?counter=10'
<del>const as = href
<del>Router.push(href, as, { shallow: true })
<del>```
<del>
<del>Now, the URL is updated to `/?counter=10`. You can see the updated URL with `this.props.router.query` inside the `Component` (make sure you are using [`withRouter`](#using-a-higher-order-component) around your `Component` to inject the `router` prop).
<del>
<del>You can watch for URL changes via [`componentDidUpdate`](https://reactjs.org/docs/react-component.html#componentdidupdate) hook as shown below:
<del>
<del>```js
<del>componentDidUpdate(prevProps) {
<del> const { pathname, query } = this.props.router
<del> // verify props have changed to avoid an infinite loop
<del> if (query.id !== prevProps.router.query.id) {
<del> // fetch data based on the new query
<del> }
<del>}
<del>```
<del>
<del>> NOTES:
<del>>
<del>> Shallow routing works **only** for same page URL changes. For an example, let's assume we have another page called `about`, and you run this:
<del>>
<del>> ```js
<del>> Router.push('/?counter=10', '/about?counter=10', { shallow: true })
<del>> ```
<del>>
<del>> Since that's a new page, it'll unload the current page, load the new one and call `getInitialProps` even though we asked to do shallow routing.
<del>
<del>#### useRouter
<del>
<del><details>
<del> <summary><b>Examples</b></summary>
<del> <ul>
<del> <li><a href="/examples/dynamic-routing">Dynamic routing</a></li>
<del> </ul>
<del></details>
<del>
<del>If you want to access the `router` object inside any functional component in your app, you can use the `useRouter` hook, here's how to use it:
<del>
<del>```jsx
<del>import { useRouter } from 'next/router'
<del>
<del>export default function ActiveLink({ children, href }) {
<del> const router = useRouter()
<del> const style = {
<del> marginRight: 10,
<del> color: router.pathname === href ? 'red' : 'black',
<del> }
<del>
<del> const handleClick = e => {
<del> e.preventDefault()
<del> router.push(href)
<del> }
<del>
<del> return (
<del> <a href={href} onClick={handleClick} style={style}>
<del> {children}
<del> </a>
<del> )
<del>}
<del>```
<del>
<del>> **Note**: `useRouter` is a React hook, meaning it cannot be used with classes.
<del>> You can either use [`withRouter`](#using-a-higher-order-component) (a higher order component) or wrap your class in a functional component.
<del>
<del>The above `router` object comes with an API similar to [`next/router`](#imperatively).
<del>
<del>#### Using a Higher Order Component
<del>
<del><details>
<del> <summary><b>Examples</b></summary>
<del> <ul>
<del> <li><a href="/examples/using-with-router">Using the `withRouter` utility</a></li>
<del> </ul>
<del></details>
<del>
<del>If [useRouter](#userouter) is not the best fit for you, `withRouter` can also add the same `router` object to any component, here's how to use it:
<del>
<del>```jsx
<del>import { withRouter } from 'next/router'
<del>
<del>function Page({ router }) {
<del> return <p>{router.pathname}</p>
<del>}
<del>
<del>export default withRouter(Page)
<del>```
<del>
<del>### Prefetching Pages
<del>
<del>⚠️ This is a production only feature ⚠️
<del>
<del><details>
<del> <summary><b>Examples</b></summary>
<del> <ul>
<del> <li><a href="/examples/with-prefetching">Prefetching</a></li>
<del> </ul>
<del></details>
<del>
<del>Next.js has an API which allows you to prefetch pages.
<del>
<del>Since Next.js server-renders your pages, this allows all the future interaction paths of your app to be instant. Effectively Next.js gives you the great initial download performance of a _website_, with the ahead-of-time download capabilities of an _app_. [Read more](https://zeit.co/blog/next#anticipation-is-the-key-to-performance).
<del>
<del>> With prefetching Next.js only downloads JS code. When the page is getting rendered, you may need to wait for the data.
<del>
<del>> Automatic prefetching is disabled if your device is connected with 2G network or [Save-Data](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Save-Data) header is `on`.
<del>
<del>> `<link rel="preload">` is used for prefetching. Sometimes browsers will show a warning if the resource is not used within 3 seconds, these warnings can be ignored as per https://github.com/zeit/next.js/issues/6517#issuecomment-469063892.
<del>
<del>#### With `<Link>`
<del>
<del>`<Link>` will automatically prefetch pages in the background as they appear in the view. If certain pages are rarely visited you can manually set `prefetch` to `false`, here's how:
<del>
<del>```jsx
<del><Link href="/about" prefetch={false}>
<del> <a>About</a>
<del></Link>
<del>```
<del>
<del>#### Imperatively
<del>
<del>Most prefetching needs are addressed by `<Link />`, but we also expose an imperative API for advanced usage:
<del>
<del>```jsx
<del>import { useRouter } from 'next/router'
<del>
<del>export default function MyLink() {
<del> const router = useRouter()
<del>
<del> return (
<del> <>
<del> <a onClick={() => setTimeout(() => router.push('/dynamic'), 100)}>
<del> A route transition will happen after 100ms
<del> </a>
<del> {// and we can prefetch it!
<del> router.prefetch('/dynamic')}
<del> </>
<del> )
<del>}
<del>```
<del>
<del>`router` methods should be only used inside the client side of your app though. In order to prevent any error regarding this subject use the imperative `prefetch` method in the `useEffect()` hook:
<del>
<del>```jsx
<del>import { useRouter } from 'next/router'
<del>
<del>export default function MyLink() {
<del> const router = useRouter()
<del>
<del> useEffect(() => {
<del> router.prefetch('/dynamic')
<del> })
<del>
<del> return (
<del> <a onClick={() => setTimeout(() => router.push('/dynamic'), 100)}>
<del> A route transition will happen after 100ms
<del> </a>
<del> )
<del>}
<del>```
<del>
<del>You can also add it to the `componentDidMount()` lifecycle method when using `React.Component`:
<del>
<del>```jsx
<del>import React from 'react'
<del>import { withRouter } from 'next/router'
<del>
<del>class MyLink extends React.Component {
<del> componentDidMount() {
<del> const { router } = this.props
<del> router.prefetch('/dynamic')
<del> }
<del>
<del> render() {
<del> const { router } = this.props
<del>
<del> return (
<del> <a onClick={() => setTimeout(() => router.push('/dynamic'), 100)}>
<del> A route transition will happen after 100ms
<del> </a>
<del> )
<del> }
<del>}
<del>
<del>export default withRouter(MyLink)
<del>```
<del>
<del>### API Routes
<del>
<del><details>
<del> <summary><b>Examples</b></summary>
<del> <ul>
<del> <li><a href="/examples/api-routes">Basic API routes</a></li>
<del> <li><a href="/examples/api-routes-micro">API routes with micro</a></li>
<del> <li><a href="/examples/api-routes-middleware">API routes with middleware</a></li>
<del> <li><a href="/examples/api-routes-graphql">API routes with GraphQL server</a></li>
<del> <li><a href="/examples/api-routes-rest">API routes with REST</a></li>
<del> </ul>
<del></details>
<del>
<del>API routes provide a straightforward solution to build your **API** with Next.js.
<del>Start by creating the `api/` folder inside the `./pages/` folder.
<del>
<del>Every file inside `./pages/api` is mapped to `/api/*`.
<del>For example, `./pages/api/posts.js` is mapped to the route `/api/posts`.
<del>
<del>Here's an example API route file:
<del>
<del>```js
<del>export default (req, res) => {
<del> res.setHeader('Content-Type', 'application/json')
<del> res.statusCode = 200
<del> res.end(JSON.stringify({ name: 'Nextjs' }))
<del>}
<del>```
<del>
<del>- `req` refers to [NextApiRequest](https://github.com/zeit/next.js/blob/v9.0.0/packages/next-server/lib/utils.ts#L143-L158) which extends [http.IncomingMessage](https://nodejs.org/api/http.html#http_class_http_incomingmessage)
<del>
<del>- `res` refers to [NextApiResponse](https://github.com/zeit/next.js/blob/v9.0.0/packages/next-server/lib/utils.ts#L168-L178) which extends [http.ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse)
<del>
<del>For [API routes](#api-routes) there are built-in types `NextApiRequest` and `NextApiResponse`, which extend the `Node.js` request and response objects.
<del>
<del>```ts
<del>import { NextApiRequest, NextApiResponse } from 'next'
<del>
<del>export default (req: NextApiRequest, res: NextApiResponse) => {
<del> res.status(200).json({ title: 'Next.js' })
<del>}
<del>```
<del>
<del>To handle different HTTP methods for API calls you can access `req.method` in your resolver function:
<del>
<del>```js
<del>export default (req, res) => {
<del> if (req.method === 'POST') {
<del> // Process your POST request
<del> } else {
<del> // Handle the rest of your HTTP methods
<del> }
<del>}
<del>```
<del>
<del>> **Note**: API Routes [do not specify CORS headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS), so they'll be **same-origin only** by default.
<del>> You can customize this behavior by wrapping your export with CORS middleware.
<del>> We provide an [example of this below](#api-middlewares).
<del>
<del>API Routes do not increase your client-side bundle size. They are server-side only bundles.
<del>
<del>#### Dynamic routes support
<del>
<del>API pages support [dynamic routing](#dynamic-routing), so you can use all benefits mentioned already above.
<del>
<del>Consider the following page `./pages/api/post/[pid].js`, here is how you get parameters inside the resolver method:
<del>
<del>```js
<del>export default (req, res) => {
<del> const {
<del> query: { pid },
<del> } = req
<del>
<del> res.end(`Post: ${pid}`)
<del>}
<del>```
<del>
<del>#### API Middlewares
<del>
<del>API routes provides built in middlewares which parse the incoming `req`.
<del>Those middlewares are:
<del>
<del>- `req.cookies` - an object containing the cookies sent by the request. Defaults to `{}`
<del>- `req.query` - an object containing the [query string](https://en.wikipedia.org/wiki/Query_string). Defaults to `{}`
<del>- `req.body` - an object containing the body parsed by `content-type`, or `null` if no body is sent
<del>
<del>Body parsing is enabled by default with a size limit of `1mb` for the parsed body.
<del>You can opt-out of automatic body parsing if you need to consume it as a `Stream`:
<del>
<del>```js
<del>// ./pages/api/my-endpoint.js
<del>export default (req, res) => {
<del> // ...
<del>}
<del>
<del>export const config = {
<del> api: {
<del> bodyParser: false,
<del> },
<del>}
<del>```
<del>
<del>You can adjust size of parsed body by adding `sizeLimit` key to `bodyParser`, supported values are by [bytes](https://github.com/visionmedia/bytes.js) library.
<del>
<del>```js
<del>// ./pages/api/my-endpoint.js
<del>export default (req, res) => {
<del> // ...
<del>}
<del>
<del>export const config = {
<del> api: {
<del> bodyParser: {
<del> sizeLimit: '1mb',
<del> },
<del> },
<del>}
<del>```
<del>
<del>As an added bonus, you can also use any [Micro](https://github.com/zeit/micro) compatible [middleware](https://github.com/amio/awesome-micro)!
<del>
<del>For example, [configuring CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) for your API endpoint can be done leveraging `micro-cors`.
<del>
<del>First, install `micro-cors`:
<del>
<del>```bash
<del>npm i micro-cors
<del># or
<del>yarn add micro-cors
<del>```
<del>
<del>Then, import `micro-cors` and [configure it](https://github.com/possibilities/micro-cors#readme). Finally, wrap your exported function in the middleware:
<del>
<del>```js
<del>import Cors from 'micro-cors'
<del>
<del>const cors = Cors({
<del> allowMethods: ['GET', 'HEAD'],
<del>})
<del>
<del>function Endpoint(req, res) {
<del> res.json({ message: 'Hello Everyone!' })
<del>}
<del>
<del>export default cors(Endpoint)
<del>```
<del>
<del>#### Helper Functions
<del>
<del>We're providing a set of Express.js-like methods to improve the developer experience and increase the speed of creating new API endpoints:
<del>
<del>```js
<del>export default (req, res) => {
<del> res.status(200).json({ name: 'Next.js' })
<del>}
<del>```
<del>
<del>- `res.status(code)` - a function to set the status code. `code` must be a valid [HTTP status code](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes)
<del>- `res.json(json)` - Sends a `JSON` response. `json` must be a valid `JSON` object
<del>- `res.send(body)` - Sends the HTTP response. `body` can be a `string`, an `object` or a `Buffer`
<del>
<del>### Custom server and routing
<del>
<del><details>
<del> <summary><b>Examples</b></summary>
<del> <ul>
<del> <li><a href="/examples/custom-server">Basic custom server</a></li>
<del> <li><a href="/examples/custom-server-express">Express integration</a></li>
<del> <li><a href="/examples/custom-server-hapi">Hapi integration</a></li>
<del> <li><a href="/examples/custom-server-koa">Koa integration</a></li>
<del> <li><a href="/examples/ssr-caching">SSR caching</a></li>
<del> </ul>
<del></details>
<del>
<del>Typically you start your next server with `next start`. It's possible, however, to start a server 100% programmatically in order to customize routes, use route patterns, etc.
<del>
<del>When using a custom server with a server file, for example called `server.js`, make sure you update the scripts key in `package.json` to:
<del>
<del>```json
<del>{
<del> "scripts": {
<del> "dev": "node server.js",
<del> "build": "next build",
<del> "start": "NODE_ENV=production node server.js"
<del> }
<del>}
<del>```
<del>
<del>This example makes `/a` resolve to `./pages/b`, and `/b` resolve to `./pages/a`:
<del>
<del>```js
<del>// This file doesn't go through babel or webpack transformation.
<del>// Make sure the syntax and sources this file requires are compatible with the current node version you are running
<del>// See https://github.com/zeit/next.js/issues/1245 for discussions on Universal Webpack or universal Babel
<del>const { createServer } = require('http')
<del>const { parse } = require('url')
<del>const next = require('next')
<del>
<del>const dev = process.env.NODE_ENV !== 'production'
<del>const app = next({ dev })
<del>const handle = app.getRequestHandler()
<del>
<del>app.prepare().then(() => {
<del> createServer((req, res) => {
<del> // Be sure to pass `true` as the second argument to `url.parse`.
<del> // This tells it to parse the query portion of the URL.
<del> const parsedUrl = parse(req.url, true)
<del> const { pathname, query } = parsedUrl
<del>
<del> if (pathname === '/a') {
<del> app.render(req, res, '/b', query)
<del> } else if (pathname === '/b') {
<del> app.render(req, res, '/a', query)
<del> } else {
<del> handle(req, res, parsedUrl)
<del> }
<del> }).listen(3000, err => {
<del> if (err) throw err
<del> console.log('> Ready on http://localhost:3000')
<del> })
<del>})
<del>```
<del>
<del>The `next` API is as follows:
<del>
<del>- `next(opts: object)`
<del>
<del>Supported options:
<del>
<del>- `dev` (`bool`) whether to launch Next.js in dev mode - default `false`
<del>- `dir` (`string`) where the Next project is located - default `'.'`
<del>- `quiet` (`bool`) Hide error messages containing server information - default `false`
<del>- `conf` (`object`) the same object you would use in `next.config.js` - default `{}`
<del>
<del>Then, change your `start` script to `NODE_ENV=production node server.js`.
<del>
<del>#### Disabling file-system routing
<del>
<del>By default, `Next` will serve each file in `/pages` under a pathname matching the filename (eg, `/pages/some-file.js` is served at `site.com/some-file`.
<del>
<del>If your project uses custom routing, this behavior may result in the same content being served from multiple paths, which can present problems with SEO and UX.
<del>
<del>To disable this behavior & prevent routing based on files in `/pages`, simply set the following option in your `next.config.js`:
<del>
<del>```js
<del>// next.config.js
<del>module.exports = {
<del> useFileSystemPublicRoutes: false,
<del>}
<del>```
<del>
<del>Note that `useFileSystemPublicRoutes` simply disables filename routes from SSR; client-side routing may still access those paths. If using this option, you should guard against navigation to routes you do not want programmatically.
<del>
<del>You may also wish to configure the client-side Router to disallow client-side redirects to filename routes; please refer to [Intercepting `popstate`](#intercepting-popstate).
<del>
<del>#### Dynamic assetPrefix
<del>
<del>Sometimes we need to set the `assetPrefix` dynamically. This is useful when changing the `assetPrefix` based on incoming requests.
<del>For that, we can use `app.setAssetPrefix`.
<del>
<del>Here's an example usage of it:
<del>
<del>```js
<del>const next = require('next')
<del>const http = require('http')
<del>
<del>const dev = process.env.NODE_ENV !== 'production'
<del>const app = next({ dev })
<del>const handleNextRequests = app.getRequestHandler()
<del>
<del>app.prepare().then(() => {
<del> const server = new http.Server((req, res) => {
<del> // Add assetPrefix support based on the hostname
<del> if (req.headers.host === 'my-app.com') {
<del> app.setAssetPrefix('http://cdn.com/myapp')
<del> } else {
<del> app.setAssetPrefix('')
<del> }
<del>
<del> handleNextRequests(req, res)
<del> })
<del>
<del> server.listen(port, err => {
<del> if (err) {
<del> throw err
<del> }
<del>
<del> console.log(`> Ready on http://localhost:${port}`)
<del> })
<del>})
<del>```
<del>
<del>#### Changing x-powered-by
<del>
<del>By default Next.js will add `x-powered-by` to the request headers. There's an optional way to opt-out of this:
<del>
<del>```js
<del>// next.config.js
<del>module.exports = {
<del> poweredByHeader: false,
<del>}
<del>```
<del>
<del>### Dynamic Import
<del>
<del><details>
<del> <summary><b>Examples</b></summary>
<del> <ul>
<del> <li><a href="/examples/with-dynamic-import">With Dynamic Import</a></li>
<del> </ul>
<del></details>
<del>
<del>Next.js supports ES2020 [dynamic `import()`](https://github.com/tc39/proposal-dynamic-import) for JavaScript.
<del>With that, you could import JavaScript modules (inc. React Components) dynamically and work with them.
<del>
<del>You can think dynamic imports as another way to split your code into manageable chunks.
<del>Since Next.js supports dynamic imports with SSR, you could do amazing things with it.
<del>
<del>Here are a few ways to use dynamic imports.
<del>
<del>#### Basic Usage (Also does SSR)
<del>
<del>```jsx
<del>import dynamic from 'next/dynamic'
<del>
<del>const DynamicComponent = dynamic(() => import('../components/hello'))
<del>
<del>function Home() {
<del> return (
<del> <div>
<del> <Header />
<del> <DynamicComponent />
<del> <p>HOME PAGE is here!</p>
<del> </div>
<del> )
<del>}
<del>
<del>export default Home
<del>```
<del>
<del>#### With named exports
<del>
<del>```jsx
<del>// components/hello.js
<del>export function Hello() {
<del> return <p>Hello!</p>
<del>}
<del>```
<del>
<del>```jsx
<del>import dynamic from 'next/dynamic'
<del>
<del>const DynamicComponent = dynamic(() =>
<del> import('../components/hello').then(mod => mod.Hello)
<del>)
<del>
<del>function Home() {
<del> return (
<del> <div>
<del> <Header />
<del> <DynamicComponent />
<del> <p>HOME PAGE is here!</p>
<del> </div>
<del> )
<del>}
<del>
<del>export default Home
<del>```
<del>
<del>#### With Custom Loading Component
<del>
<del>```jsx
<del>import dynamic from 'next/dynamic'
<del>
<del>const DynamicComponentWithCustomLoading = dynamic(
<del> () => import('../components/hello2'),
<del> { loading: () => <p>...</p> }
<del>)
<del>
<del>function Home() {
<del> return (
<del> <div>
<del> <Header />
<del> <DynamicComponentWithCustomLoading />
<del> <p>HOME PAGE is here!</p>
<del> </div>
<del> )
<del>}
<del>
<del>export default Home
<del>```
<del>
<del>#### With No SSR
<del>
<del>```jsx
<del>import dynamic from 'next/dynamic'
<del>
<del>const DynamicComponentWithNoSSR = dynamic(
<del> () => import('../components/hello3'),
<del> { ssr: false }
<del>)
<del>
<del>function Home() {
<del> return (
<del> <div>
<del> <Header />
<del> <DynamicComponentWithNoSSR />
<del> <p>HOME PAGE is here!</p>
<del> </div>
<del> )
<del>}
<del>
<del>export default Home
<del>```
<del>
<del>### Custom `<App>`
<del>
<del><details>
<del> <summary><b>Examples</b></summary>
<del> <ul>
<del> <li><a href="/examples/with-app-layout">Using `_app.js` for layout</a></li>
<del> <li><a href="/examples/with-componentdidcatch">Using `_app.js` to override `componentDidCatch`</a></li>
<del> </ul>
<del></details>
<del>
<del>Next.js uses the `App` component to initialize pages. You can override it and control the page initialization. Which allows you to do amazing things like:
<del>
<del>- Persisting layout between page changes
<del>- Keeping state when navigating pages
<del>- Inject additional data into pages (for example by processing GraphQL queries)
<del>
<del>To override, create the `./pages/_app.js` file and override the App class as shown below:
<del>
<del>```js
<del>function MyApp({ Component, pageProps }) {
<del> return <Component {...pageProps} />
<del>}
<del>
<del>// Only uncomment this method if you have blocking data requirements for
<del>// every single page in your application. This disables the ability to
<del>// perform automatic static optimization, causing every page in your app to
<del>// be server-side rendered.
<del>//
<del>// MyApp.getInitialProps = async (appContext) => {
<del>// // calls page's `getInitialProps` and fills `appProps.pageProps`
<del>// const appProps = await App.getInitialProps(appContext);
<del>//
<del>// return { ...appProps }
<del>// }
<del>
<del>export default MyApp
<del>```
<del>
<del>> **Note:** Adding a custom `getInitialProps` in App will affect [Automatic Static Optimization](#automatic-static-optimization)
<del>
<del>### Custom `<Document>`
<del>
<del><details>
<del> <summary><b>Examples</b></summary>
<del> <ul>
<del> <li><a href="/examples/with-styled-components">Styled components custom document</a></li>
<del> </ul>
<del></details>
<del>
<del>A custom `<Document>` is commonly used to augment your application's `<html>` and `<body>` tags.
<del>This is necessary because Next.js pages skip the definition of the surrounding document's markup.
<del>
<del>This allows you to support Server-Side Rendering for CSS-in-JS libraries like
<del>[styled-components](/examples/with-styled-components) or [emotion](/examples/with-emotion).
<del>Note, [styled-jsx](https://github.com/zeit/styled-jsx) is included in Next.js by default.
<del>
<del>A custom `<Document>` can also include `getInitialProps` for expressing asynchronous server-rendering data requirements.
<del>
<del>> **Note**: `<Document>`'s `getInitialProps` function is not called during client-side transitions,
<del>> nor when a page is [automatically statically optimized](#automatic-static-optimization).
<del>
<del>> **Note**: Make sure to check if `ctx.req` / `ctx.res` are defined in `getInitialProps`.
<del>> These variables will be `undefined` when a page is being statically exported for `next export` or [automatic static optimization](#automatic-static-optimization).
<del>
<del>To use a custom `<Document>`, you must create a file at `./pages/_document.js` and extend the `Document` class:
<del>
<del>```jsx
<del>// _document is only rendered on the server side and not on the client side
<del>// Event handlers like onClick can't be added to this file
<del>
<del>// ./pages/_document.js
<del>import Document, { Html, Head, Main, NextScript } from 'next/document'
<del>
<del>class MyDocument extends Document {
<del> static async getInitialProps(ctx) {
<del> const initialProps = await Document.getInitialProps(ctx)
<del> return { ...initialProps }
<del> }
<del>
<del> render() {
<del> return (
<del> <Html>
<del> <Head />
<del> <body>
<del> <Main />
<del> <NextScript />
<del> </body>
<del> </Html>
<del> )
<del> }
<del>}
<del>
<del>export default MyDocument
<del>```
<del>
<del>All of `<Html>`, `<Head />`, `<Main />` and `<NextScript />` are required for page to be properly rendered.
<del>
<del>**Note: React-components outside of `<Main />` will not be initialised by the browser. Do _not_ add application logic here. If you need shared components in all your pages (like a menu or a toolbar), take a look at the [`<App>`](#custom-app) component instead.**
<del>
<del>The `ctx` object is equivalent to the one received in all [`getInitialProps`](#fetching-data-and-component-lifecycle) hooks, with one addition:
<del>
<del>- `renderPage` (`Function`) a callback that executes the actual React rendering logic (synchronously). It's useful to decorate this function in order to support server-rendering wrappers like Aphrodite's [`renderStatic`](https://github.com/Khan/aphrodite#server-side-rendering).
<del>
<del>#### Customizing `renderPage`
<del>
<del>🚧 It should be noted that the only reason you should be customizing `renderPage` is for usage with css-in-js libraries
<del>that need to wrap the application to properly work with server-rendering. 🚧
<del>
<del>- It takes as argument an options object for further customization:
<del>
<del>```js
<del>import Document from 'next/document'
<del>
<del>class MyDocument extends Document {
<del> static async getInitialProps(ctx) {
<del> const originalRenderPage = ctx.renderPage
<del>
<del> ctx.renderPage = () =>
<del> originalRenderPage({
<del> // useful for wrapping the whole react tree
<del> enhanceApp: App => App,
<del> // useful for wrapping in a per-page basis
<del> enhanceComponent: Component => Component,
<del> })
<del>
<del> // Run the parent `getInitialProps` using `ctx` that now includes our custom `renderPage`
<del> const initialProps = await Document.getInitialProps(ctx)
<del>
<del> return initialProps
<del> }
<del>}
<del>
<del>export default MyDocument
<del>```
<del>
<del>### Custom error handling
<del>
<del>404 or 500 errors are handled both client and server side by a default component `error.js`. If you wish to override it, define a `_error.js` in the pages folder:
<del>
<del>⚠️ The `pages/_error.js` component is only used in production. In development you get an error with call stack to know where the error originated from. ⚠️
<del>
<del>```jsx
<del>import React from 'react'
<del>
<del>function Error({ statusCode }) {
<del> return (
<del> <p>
<del> {statusCode
<del> ? `An error ${statusCode} occurred on server`
<del> : 'An error occurred on client'}
<del> </p>
<del> )
<del>}
<del>
<del>Error.getInitialProps = ({ res, err }) => {
<del> const statusCode = res ? res.statusCode : err ? err.statusCode : 404
<del> return { statusCode }
<del>}
<del>
<del>export default Error
<del>```
<del>
<del>### Reusing the built-in error page
<del>
<del>If you want to render the built-in error page you can by using `next/error`:
<del>
<del>```jsx
<del>import React from 'react'
<del>import Error from 'next/error'
<del>import fetch from 'isomorphic-unfetch'
<del>
<del>const Page = ({ errorCode, stars }) => {
<del> if (errorCode) {
<del> return <Error statusCode={errorCode} />
<del> }
<del>
<del> return <div>Next stars: {stars}</div>
<del>}
<del>
<del>Page.getInitialProps = async () => {
<del> const res = await fetch('https://api.github.com/repos/zeit/next.js')
<del> const errorCode = res.statusCode > 200 ? res.statusCode : false
<del> const json = await res.json()
<del>
<del> return { errorCode, stars: json.stargazers_count }
<del>}
<del>
<del>export default Page
<del>```
<del>
<del>> If you have created a custom error page you have to import your own `_error` component from `./_error` instead of `next/error`.
<del>
<del>The Error component also takes `title` as a property if you want to pass in a text message along with a `statusCode`.
<del>
<del>### Custom configuration
<del>
<del>For custom advanced behavior of Next.js, you can create a `next.config.js` in the root of your project directory (next to `pages/` and `package.json`).
<del>
<del>Note: `next.config.js` is a regular Node.js module, not a JSON file. It gets used by the Next server and build phases, and not included in the browser build.
<del>
<del>```js
<del>// next.config.js
<del>module.exports = {
<del> /* config options here */
<del>}
<del>```
<del>
<del>Or use a function:
<del>
<del>```js
<del>module.exports = (phase, { defaultConfig }) => {
<del> return {
<del> /* config options here */
<del> }
<del>}
<del>```
<del>
<del>`phase` is the current context in which the configuration is loaded. You can see all phases here: [constants](/packages/next/next-server/lib/constants.ts)
<del>Phases can be imported from `next/constants`:
<del>
<del>```js
<del>const { PHASE_DEVELOPMENT_SERVER } = require('next/constants')
<del>module.exports = (phase, { defaultConfig }) => {
<del> if (phase === PHASE_DEVELOPMENT_SERVER) {
<del> return {
<del> /* development only config options here */
<del> }
<del> }
<del>
<del> return {
<del> /* config options for all phases except development here */
<del> }
<del>}
<del>```
<del>
<del>#### Setting a custom build directory
<del>
<del>You can specify a name to use for a custom build directory. For example, the following config will create a `build` folder instead of a `.next` folder. If no configuration is specified then next will create a `.next` folder.
<del>
<del>```js
<del>// next.config.js
<del>module.exports = {
<del> distDir: 'build',
<del>}
<del>```
<del>
<del>#### Disabling etag generation
<del>
<del>You can disable etag generation for HTML pages depending on your cache strategy. If no configuration is specified then Next will generate etags for every page.
<del>
<del>```js
<del>// next.config.js
<del>module.exports = {
<del> generateEtags: false,
<del>}
<del>```
<del>
<del>#### Configuring the onDemandEntries
<del>
<del>Next exposes some options that give you some control over how the server will dispose or keep in memories pages built:
<del>
<del>```js
<del>module.exports = {
<del> onDemandEntries: {
<del> // period (in ms) where the server will keep pages in the buffer
<del> maxInactiveAge: 25 * 1000,
<del> // number of pages that should be kept simultaneously without being disposed
<del> pagesBufferLength: 2,
<del> },
<del>}
<del>```
<del>
<del>This is development-only feature. If you want to cache SSR pages in production, please see [SSR-caching](https://github.com/zeit/next.js/tree/canary/examples/ssr-caching) example.
<del>
<del>#### Configuring extensions looked for when resolving pages in `pages`
<del>
<del>Aimed at modules like [`@next/mdx`](https://github.com/zeit/next.js/tree/canary/packages/next-mdx), that add support for pages ending with `.mdx`. `pageExtensions` allows you to configure the extensions looked for in the `pages` directory when resolving pages.
<del>
<del>```js
<del>// next.config.js
<del>module.exports = {
<del> pageExtensions: ['mdx', 'jsx', 'js'],
<del>}
<del>```
<del>
<del>#### Configuring the build ID
<del>
<del>Next.js uses a constant generated at build time to identify which version of your application is being served. This can cause problems in multi-server deployments when `next build` is ran on every server. In order to keep a static build id between builds you can provide the `generateBuildId` function:
<del>
<del>```js
<del>// next.config.js
<del>module.exports = {
<del> generateBuildId: async () => {
<del> // For example get the latest git commit hash here
<del> return 'my-build-id'
<del> },
<del>}
<del>```
<del>
<del>To fall back to the default of generating a unique id return `null` from the function:
<del>
<del>```js
<del>module.exports = {
<del> generateBuildId: async () => {
<del> // When process.env.YOUR_BUILD_ID is undefined we fall back to the default
<del> if (process.env.YOUR_BUILD_ID) {
<del> return process.env.YOUR_BUILD_ID
<del> }
<del>
<del> return null
<del> },
<del>}
<del>```
<del>
<del>#### Configuring next process script
<del>
<del>You can pass any node arguments to `next` CLI command.
<del>
<del>```bash
<del>NODE_OPTIONS="--throw-deprecation" next
<del>NODE_OPTIONS="-r esm" next
<del>NODE_OPTIONS="--inspect" next
<del>```
<del>
<del>### Customizing webpack config
<del>
<del><details>
<del> <summary><b>Examples</b></summary>
<del> <ul>
<del> <li><a href="/examples/with-webpack-bundle-analyzer">Custom webpack bundle analyzer</a></li>
<del> </ul>
<del></details>
<del>
<del>Some commonly asked for features are available as modules:
<del>
<del>- [@zeit/next-css](https://github.com/zeit/next-plugins/tree/master/packages/next-css)
<del>- [@zeit/next-sass](https://github.com/zeit/next-plugins/tree/master/packages/next-sass)
<del>- [@zeit/next-less](https://github.com/zeit/next-plugins/tree/master/packages/next-less)
<del>- [@zeit/next-preact](https://github.com/zeit/next-plugins/tree/master/packages/next-preact)
<del>- [@next/mdx](https://github.com/zeit/next.js/tree/canary/packages/next-mdx)
<del>
<del>> **Warning:** The `webpack` function is executed twice, once for the server and once for the client. This allows you to distinguish between client and server configuration using the `isServer` property.
<del>
<del>Multiple configurations can be combined together with function composition. For example:
<del>
<del>```js
<del>const withMDX = require('@next/mdx')
<del>const withSass = require('@zeit/next-sass')
<del>
<del>module.exports = withMDX(
<del> withSass({
<del> webpack(config, options) {
<del> // Further custom configuration here
<del> return config
<del> },
<del> })
<del>)
<del>```
<del>
<del>In order to extend our usage of `webpack`, you can define a function that extends its config via `next.config.js`.
<del>
<del>```js
<del>// next.config.js is not transformed by Babel. So you can only use javascript features supported by your version of Node.js.
<del>
<del>module.exports = {
<del> webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
<del> // Note: we provide webpack above so you should not `require` it
<del> // Perform customizations to webpack config
<del> // Important: return the modified config
<del>
<del> // Example using webpack option
<del> config.plugins.push(new webpack.IgnorePlugin(/\/__tests__\//))
<del> return config
<del> },
<del> webpackDevMiddleware: config => {
<del> // Perform customizations to webpack dev middleware config
<del> // Important: return the modified config
<del> return config
<del> },
<del>}
<del>```
<del>
<del>The second argument to `webpack` is an object containing properties useful when customizing its configuration:
<del>
<del>- `buildId` - `String` the build id used as a unique identifier between builds
<del>- `dev` - `Boolean` shows if the compilation is done in development mode
<del>- `isServer` - `Boolean` shows if the resulting configuration will be used for server side (`true`), or client side compilation (`false`)
<del>- `defaultLoaders` - `Object` Holds loader objects Next.js uses internally, so that you can use them in custom configuration
<del> - `babel` - `Object` the `babel-loader` configuration for Next.js
<del>
<del>Example usage of `defaultLoaders.babel`:
<del>
<del>```js
<del>// Example next.config.js for adding a loader that depends on babel-loader
<del>// This source was taken from the @next/mdx plugin source:
<del>// https://github.com/zeit/next.js/tree/canary/packages/next-mdx
<del>module.exports = {
<del> webpack: (config, options) => {
<del> config.module.rules.push({
<del> test: /\.mdx/,
<del> use: [
<del> options.defaultLoaders.babel,
<del> {
<del> loader: '@mdx-js/loader',
<del> options: pluginOptions.options,
<del> },
<del> ],
<del> })
<del>
<del> return config
<del> },
<del>}
<del>```
<del>
<del>### Customizing babel config
<del>
<del><details>
<del> <summary><b>Examples</b></summary>
<del> <ul>
<del> <li><a href="/examples/with-custom-babel-config">Custom babel configuration</a></li>
<del> </ul>
<del></details>
<del>
<del>In order to extend our usage of `babel`, you can simply define a `.babelrc` file at the root of your app. This file is optional.
<del>
<del>If found, we're going to consider it the _source of truth_, therefore it needs to define what next needs as well, which is the `next/babel` preset.
<del>
<del>This is designed so that you are not surprised by modifications we could make to the babel configurations.
<del>
<del>Here's an example `.babelrc` file:
<del>
<del>```json
<del>{
<del> "presets": ["next/babel"],
<del> "plugins": []
<del>}
<del>```
<del>
<del>The `next/babel` preset includes everything needed to transpile React applications. This includes:
<del>
<del>- preset-env
<del>- preset-react
<del>- preset-typescript
<del>- plugin-proposal-class-properties
<del>- plugin-proposal-object-rest-spread
<del>- plugin-transform-runtime
<del>- styled-jsx
<del>
<del>These presets / plugins **should not** be added to your custom `.babelrc`. Instead, you can configure them on the `next/babel` preset:
<del>
<del>```json
<del>{
<del> "presets": [
<del> [
<del> "next/babel",
<del> {
<del> "preset-env": {},
<del> "transform-runtime": {},
<del> "styled-jsx": {},
<del> "class-properties": {}
<del> }
<del> ]
<del> ],
<del> "plugins": []
<del>}
<del>```
<del>
<del>The `modules` option on `"preset-env"` should be kept to `false` otherwise webpack code splitting is disabled.
<del>
<del>### Exposing configuration to the server / client side
<del>
<del>There is a common need in applications to provide configuration values.
<del>
<del>Next.js supports 2 ways of providing configuration:
<del>
<del>- Build-time configuration
<del>- Runtime configuration
<del>
<del>#### Build-time configuration
<del>
<del>The way build-time configuration works is by inlining the provided values into the Javascript bundle.
<del>
<del>You can add the `env` key in `next.config.js`:
<del>
<del>```js
<del>// next.config.js
<del>module.exports = {
<del> env: {
<del> customKey: 'value',
<del> },
<del>}
<del>```
<del>
<del>This will allow you to use `process.env.customKey` in your code. For example:
<del>
<del>```jsx
<del>// pages/index.js
<del>function Index() {
<del> return <h1>The value of customKey is: {process.env.customKey}</h1>
<del>}
<del>
<del>export default Index
<del>```
<del>
<del>> **Warning:** Note that it is not possible to destructure process.env variables due to the webpack `DefinePlugin` replacing process.env.XXXX inline at build time.
<del>
<del>```js
<del>// Will not work
<del>const { CUSTOM_KEY, CUSTOM_SECRET } = process.env
<del>AuthMethod({ key: CUSTOM_KEY, secret: CUSTOM_SECRET })
<del>
<del>// Will work as replaced inline
<del>AuthMethod({ key: process.env.CUSTOM_KEY, secret: process.env.CUSTOM_SECRET })
<del>```
<del>
<del>#### Runtime configuration
<del>
<del>> **Warning:** Note that these options are not available when using `target: 'serverless'`
<del>
<del>> **Warning:** Generally you want to use build-time configuration to provide your configuration.
<del>> The reason for this is that runtime configuration adds rendering / initialization overhead and is **incompatible with [automatic static optimization](#automatic-static-optimization)**.
<del>
<del>The `next/config` module gives your app access to the `publicRuntimeConfig` and `serverRuntimeConfig` stored in your `next.config.js`.
<del>
<del>Place any server-only runtime config under a `serverRuntimeConfig` property.
<del>
<del>Anything accessible to both client and server-side code should be under `publicRuntimeConfig`.
<del>
<del>> **Note**: A page that relies on `publicRuntimeConfig` **must** use `getInitialProps` to opt-out of [automatic static optimization](#automatic-static-optimization).
<del>> You can also de-optimize your entire application by creating a [Custom `<App>`](#custom-app) with `getInitialProps`.
<del>
<del>```js
<del>// next.config.js
<del>module.exports = {
<del> serverRuntimeConfig: {
<del> // Will only be available on the server side
<del> mySecret: 'secret',
<del> secondSecret: process.env.SECOND_SECRET, // Pass through env variables
<del> },
<del> publicRuntimeConfig: {
<del> // Will be available on both server and client
<del> staticFolder: '/static',
<del> },
<del>}
<del>```
<del>
<del>```js
<del>// pages/index.js
<del>import getConfig from 'next/config'
<del>// Only holds serverRuntimeConfig and publicRuntimeConfig from next.config.js nothing else.
<del>const { serverRuntimeConfig, publicRuntimeConfig } = getConfig()
<del>
<del>console.log(serverRuntimeConfig.mySecret) // Will only be available on the server side
<del>console.log(publicRuntimeConfig.staticFolder) // Will be available on both server and client
<del>
<del>function MyImage() {
<del> return (
<del> <div>
<del> <img src={`${publicRuntimeConfig.staticFolder}/logo.png`} alt="logo" />
<del> </div>
<del> )
<del>}
<del>
<del>export default MyImage
<del>```
<del>
<del>### Starting the server on alternative hostname
<del>
<del>To start the development server using a different default hostname you can use `--hostname hostname_here` or `-H hostname_here` option with next dev. This will start a TCP server listening for connections on the provided host.
<del>
<del>### CDN support with Asset Prefix
<del>
<del>To set up a CDN, you can set up the `assetPrefix` setting and configure your CDN's origin to resolve to the domain that Next.js is hosted on.
<del>
<del>```js
<del>const isProd = process.env.NODE_ENV === 'production'
<del>module.exports = {
<del> // You may only need to add assetPrefix in the production.
<del> assetPrefix: isProd ? 'https://cdn.mydomain.com' : '',
<del>}
<del>```
<del>
<del>Note: Next.js will automatically use that prefix in the scripts it loads, but this has no effect whatsoever on `/static`. If you want to serve those assets over the CDN, you'll have to introduce the prefix yourself. One way of introducing a prefix that works inside your components and varies by environment is documented [in this example](https://github.com/zeit/next.js/tree/master/examples/with-universal-configuration-build-time).
<del>
<del>If your CDN is on a separate domain and you would like assets to be requested using a [CORS aware request](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) you can set a config option for that.
<del>
<del>```js
<del>// next.config.js
<del>module.exports = {
<del> crossOrigin: 'anonymous',
<del>}
<del>```
<del>
<del>## Automatic Static Optimization
<del>
<del>Next.js automatically determines that a page is static (can be prerendered) if it has no blocking data requirements.
<del>This determination is made by the absence of `getInitialProps` in the page.
<del>
<del>If `getInitialProps` is present, Next.js will not statically optimize the page.
<del>Instead, Next.js will use its default behavior and render the page on-demand, per-request (meaning Server-Side Rendering).
<del>
<del>If `getInitialProps` is absent, Next.js will **statically optimize** your page automatically by prerendering it to static HTML. During prerendering, the router's `query` object will be empty since we do not have `query` information to provide during this phase. Any `query` values will be populated client side after hydration.
<del>
<del>This feature allows Next.js to emit hybrid applications that contain **both server-rendered and statically generated pages**.
<del>This ensures Next.js always emits applications that are **fast by default**.
<del>
<del>> **Note**: Statically generated pages are still reactive: Next.js will hydrate your application client-side to give it full interactivity.
<del>
<del>This feature provides many benefits.
<del>For example, optimized pages require no server-side computation and can be instantly streamed to the end-user from CDN locations.
<del>
<del>The result is an _ultra fast_ loading experience for your users.
<del>
<del>`next build` will emit `.html` files for statically optimized pages.
<del>The result will be a file named `.next/server/static/${BUILD_ID}/about.html` instead of `.next/server/static/${BUILD_ID}/about.js`.
<del>This behavior is similar for `target: 'serverless'`.
<del>
<del>The built-in Next.js server (`next start`) and programmatic API (`app.getRequestHandler()`) both support this build output transparently.
<del>There is no configuration or special handling required.
<del>
<del>> **Note**: If you have a [custom `<App>`](#custom-app) with `getInitialProps` then this optimization will be disabled.
<del>
<del>> **Note**: If you have a [custom `<Document>`](#custom-document) with `getInitialProps` be sure you check if `ctx.req` is defined before assuming the page is server-side rendered.
<del>> `ctx.req` will be `undefined` for pages that are prerendered.
<del>
<del>## Automatic Static Optimization Indicator
<del>
<del>When a page qualifies for automatic static optimization we show an indicator to let you know.
<del>This is helpful since the automatic static optimization can be very beneficial and knowing immediately in development if it qualifies can be useful.
<del>See above for information on the benefits of this optimization.
<del>
<del>In some cases this indicator might not be as useful like when working on electron applications. For these cases you can disable the indicator in your `next.config.js` by setting
<del>
<del>```js
<del>module.exports = {
<del> devIndicators: {
<del> autoPrerender: false,
<del> },
<del>}
<del>```
<del>
<del>## Production deployment
<del>
<del>To deploy, instead of running `next`, you want to build for production usage ahead of time. Therefore, building and starting are separate commands:
<del>
<del>```bash
<del>next build
<del>next start
<del>```
<del>
<del>To deploy Next.js with [ZEIT Now](https://zeit.co/now) see the [ZEIT Guide for Deploying Next.js](https://zeit.co/guides/deploying-nextjs-with-now/) or the [Next.js Learn section about deploying on ZEIT Now](https://nextjs.org/learn/basics/deploying-a-nextjs-app/deploying-to-zeit-now).
<del>
<del>Next.js can be deployed to other hosting solutions too. Please have a look at the ['Deployment'](https://github.com/zeit/next.js/wiki/Deployment) section of the wiki.
<del>
<del>Note: `NODE_ENV` is properly configured by the `next` subcommands, if absent, to maximize performance. if you’re using Next.js [programmatically](#custom-server-and-routing), it’s your responsibility to set `NODE_ENV=production` manually!
<del>
<del>Note: we recommend putting `.next`, or your [custom dist folder](https://github.com/zeit/next.js#custom-configuration), in `.gitignore` or `.npmignore`. Otherwise, use `files` or `now.files` to opt-into a whitelist of files you want to deploy, excluding `.next` or your custom dist folder.
<del>
<del>### Compression
<del>
<del>Next.js provides [gzip](https://tools.ietf.org/html/rfc6713#section-3) compression to compress rendered content and static files. Compression only works with the `server` target. In general you will want to enable compression on a HTTP proxy like [nginx](https://www.nginx.com/), to offload load from the `Node.js` process.
<del>
<del>To disable **compression** in Next.js, set `compress` to `false` in `next.config.js`:
<del>
<del>```js
<del>// next.config.js
<del>module.exports = {
<del> compress: false,
<del>}
<del>```
<del>
<del>### Serverless deployment
<del>
<del><details>
<del> <summary><b>Examples</b></summary>
<del> <ul>
<del> <li><a href="https://github.com/zeit/now-examples/tree/master/nextjs">now.sh</a></li>
<del> <li><a href="https://github.com/TejasQ/anna-artemov.now.sh">anna-artemov.now.sh</a></li>
<del> <li>We encourage contributing more examples to this section</li>
<del> </ul>
<del></details>
<del>
<del>Serverless deployment dramatically improves reliability and scalability by splitting your application into smaller parts (also called [**lambdas**](https://zeit.co/docs/v2/deployments/concepts/lambdas/)).
<del>In the case of Next.js, each page in the `pages` directory becomes a serverless lambda.
<del>
<del>There are [a number of benefits](https://zeit.co/blog/serverless-express-js-lambdas-with-now-2#benefits-of-serverless-express) to serverless.
<del>The referenced link talks about some of them in the context of Express, but the principles apply universally:
<del>serverless allows for distributed points of failure, infinite scalability, and is incredibly affordable with a "pay for what you use" model.
<del>
<del>To enable **serverless mode** in Next.js, add the `serverless` build `target` in `next.config.js`:
<del>
<del>```js
<del>// next.config.js
<del>module.exports = {
<del> target: 'serverless',
<del>}
<del>```
<del>
<del>The `serverless` target will output a single lambda or [HTML file](#automatic-static-optimization) per page.
<del>This file is completely standalone and doesn't require any dependencies to run:
<del>
<del>- `pages/index.js` => `.next/serverless/pages/index.js`
<del>- `pages/about.js` => `.next/serverless/pages/about.js`
<del>- `pages/blog.js` => `.next/serverless/pages/blog.html`
<del>
<del>The signature of the Next.js Serverless function is similar to the Node.js HTTP server callback:
<del>
<del>```ts
<del>export function render(req: http.IncomingMessage, res: http.ServerResponse) => void
<del>```
<del>
<del>- [http.IncomingMessage](https://nodejs.org/api/http.html#http_class_http_incomingmessage)
<del>- [http.ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse)
<del>- `void` refers to the function not having a return value and is equivalent to JavaScript's `undefined`. Calling the function will finish the request.
<del>
<del>The static HTML files are ready to be served as-is.
<del>You can read more about this feature, including how to opt-out, in the [Automatic Static Optimization section](#automatic-static-optimization).
<del>
<del>Using the serverless target, you can deploy Next.js to [ZEIT Now](https://zeit.co/now) with all of the benefits and added ease of control like for example; [custom routes](https://zeit.co/guides/custom-next-js-server-to-routes/) and caching headers. See the [ZEIT Guide for Deploying Next.js with Now](https://zeit.co/guides/deploying-nextjs-with-now/) for more information.
<del>
<del>#### One Level Lower
<del>
<del>Next.js provides low-level APIs for serverless deployments as hosting platforms have different function signatures. In general you will want to wrap the output of a Next.js serverless build with a compatibility layer.
<del>
<del>For example if the platform supports the Node.js [`http.Server`](https://nodejs.org/api/http.html#http_class_http_server) class:
<del>
<del>```js
<del>const http = require('http')
<del>const page = require('./.next/serverless/pages/about.js')
<del>const server = new http.Server((req, res) => page.render(req, res))
<del>server.listen(3000, () => console.log('Listening on http://localhost:3000'))
<del>```
<del>
<del>For specific platform examples see [the examples section above](#serverless-deployment).
<del>
<del>#### Summary
<del>
<del>- Low-level API for implementing serverless deployment
<del>- Every page in the `pages` directory becomes a serverless function (lambda)
<del>- Creates the smallest possible serverless function (50Kb base zip size)
<del>- Optimized for fast [cold start](https://zeit.co/blog/serverless-ssr#cold-start) of the function
<del>- The serverless function has 0 dependencies (they are included in the function bundle)
<del>- Uses the [http.IncomingMessage](https://nodejs.org/api/http.html#http_class_http_incomingmessage) and [http.ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse) from Node.js
<del>- opt-in using `target: 'serverless'` in `next.config.js`
<del>- Does not load `next.config.js` when executing the function, note that this means `publicRuntimeConfig` / `serverRuntimeConfig` are not supported
<del>
<del>## Browser support
<del>
<del>Next.js supports IE11 and all modern browsers out of the box using [`@babel/preset-env`](https://new.babeljs.io/docs/en/next/babel-preset-env.html). In order to support IE11 Next.js adds a global `Promise` polyfill. In cases where your own code or any external NPM dependencies you are using requires features not supported by your target browsers you will need to implement polyfills.
<del>
<del>The [polyfills](https://github.com/zeit/next.js/tree/canary/examples/with-polyfills) example demonstrates the recommended approach to implement polyfills.
<del>
<del>## TypeScript
<del>
<del>Next.js provides an integrated TypeScript experience out of the box, similar to an IDE.
<del>
<del>To get started, create a empty `tsconfig.json` file in the root of your project:
<del>
<del>```bash
<del>touch tsconfig.json
<del>```
<del>
<del>Next.js will automatically configure this file with default values (providing [your own `tsconfig.json`](https://www.typescriptlang.org/docs/handbook/compiler-options.html) is also supported).
<del>
<del>Then, run `next dev` (normally `npm run dev`) and Next.js will guide you through installing the necessary packages to complete setup.
<del>
<del>```bash
<del>npm run dev
<del>
<del># You'll see instructions like these:
<del>#
<del># Please install typescript, @types/react, and @types/node by running:
<del>#
<del># yarn add --dev typescript @types/react @types/node
<del>#
<del># ...
<del>```
<del>
<del>You're now ready to start converting files from `.js` to `.tsx` and leveraging the benefits TypeScript provides!
<del>
<del>To learn more about TypeScript checkout its [documentation](https://www.typescriptlang.org/).
<del>
<del>> **Note**: Next.js will create a file named `next-env.d.ts` in the root of your project.
<del>> This file ensures Next.js' types are picked up by the TypeScript compiler.
<del>>
<del>> **You cannot remove this file, however, you can edit it (but don't need to).**
<del>
<del>> **Note**: Next.js does not enable TypeScript's `strict` mode by default.
<del>> When you feel comfortable with TypeScript, you may turn this option on in your `tsconfig.json`.
<del>
<del>> **Note**: By default, Next.js reports TypeScript errors during development for pages you are actively working on.
<del>> TypeScript errors for inactive pages **do not** block the development process.
<del>>
<del>> If you don't want to leverage this behavior and instead, e.g. prefer your editor's integration, you can set the following option in `next.config.js`:
<del>>
<del>> ```js
<del>> // next.config.js
<del>> module.exports = {
<del>> typescript: {
<del>> ignoreDevErrors: true,
<del>> },
<del>> }
<del>> ```
<del>>
<del>> Next.js will still fail your **production build** (`next build`) when TypeScript errors are present in your project.
<del>>
<del>> If you'd like Next.js to dangerously produce production code even when your application is broken, you can set the following option in your `next.config.js`.
<del>> Be sure you are running type checks as part of your build or deploy process!
<del>>
<del>> ```js
<del>> // next.config.js
<del>> module.exports = {
<del>> typescript: {
<del>> // !! WARN !!
<del>> // Dangerously allow production builds to successfully complete even if
<del>> // your project has type errors.
<del>> //
<del>> // This option is rarely needed, and should be reserved for advanced
<del>> // setups. You may be looking for `ignoreDevErrors` instead.
<del>> // !! WARN !!
<del>> ignoreBuildErrors: true,
<del>> },
<del>> }
<del>> ```
<del>
<del>### Exported types
<del>
<del>Next.js provides `NextPage` type that can be used for pages in the `pages` directory. `NextPage` adds definitions for [`getInitialProps`](#fetching-data-and-component-lifecycle) so that it can be used without any extra typing needed.
<del>
<del>```tsx
<del>import { NextPage } from 'next'
<del>
<del>interface Props {
<del> userAgent?: string
<del>}
<del>
<del>const Page: NextPage<Props> = ({ userAgent }) => (
<del> <main>Your user agent: {userAgent}</main>
<del>)
<del>
<del>Page.getInitialProps = async ({ req }) => {
<del> const userAgent = req ? req.headers['user-agent'] : navigator.userAgent
<del> return { userAgent }
<del>}
<del>
<del>export default Page
<del>```
<del>
<del>For `React.Component` you can use `NextPageContext`:
<del>
<del>```tsx
<del>import React from 'react'
<del>import { NextPageContext } from 'next'
<del>
<del>interface Props {
<del> userAgent?: string
<del>}
<del>
<del>export default class Page extends React.Component<Props> {
<del> static async getInitialProps({ req }: NextPageContext) {
<del> const userAgent = req ? req.headers['user-agent'] : navigator.userAgent
<del> return { userAgent }
<del> }
<del>
<del> render() {
<del> const { userAgent } = this.props
<del> return <main>Your user agent: {userAgent}</main>
<del> }
<del>}
<del>```
<del>
<del>## AMP Support
<del>
<del><details>
<del> <summary><b>Examples</b></summary>
<del> <ul>
<del> <li><a href="https://github.com/zeit/next.js/tree/canary/examples/amp">amp</a></li>
<del> </ul>
<del></details>
<del>
<del>### Enabling AMP Support
<del>
<del>To enable AMP support for a page, add `export const config = { amp: true }` to your page.
<del>
<del>### AMP First Page
<del>
<del>```js
<del>// pages/about.js
<del>export const config = { amp: true }
<del>
<del>export default function AboutPage(props) {
<del> return <h3>My AMP About Page!</h3>
<del>}
<del>```
<del>
<del>### Hybrid AMP Page
<del>
<del>```js
<del>// pages/hybrid-about.js
<del>import { useAmp } from 'next/amp'
<del>
<del>export const config = { amp: 'hybrid' }
<del>
<del>export default function AboutPage(props) {
<del> return (
<del> <div>
<del> <h3>My AMP Page</h3>
<del> {useAmp() ? (
<del> <amp-img
<del> width="300"
<del> height="300"
<del> src="/my-img.jpg"
<del> alt="a cool image"
<del> layout="responsive"
<del> />
<del> ) : (
<del> <img width="300" height="300" src="/my-img.jpg" alt="a cool image" />
<del> )}
<del> </div>
<del> )
<del>}
<del>```
<del>
<del>### AMP Page Modes
<del>
<del>AMP pages can specify two modes:
<del>
<del>- AMP-only (default)
<del> - Pages have no Next.js or React client-side runtime
<del> - Pages are automatically optimized with [AMP Optimizer](https://github.com/ampproject/amp-toolbox/tree/master/packages/optimizer), an optimizer that applies the same transformations as AMP caches (improves performance by up to 42%)
<del> - Pages have a user-accessible (optimized) version of the page and a search-engine indexable (unoptimized) version of the page
<del> - Opt-in via `export const config = { amp: true }`
<del>- Hybrid
<del> - Pages are able to be rendered as traditional HTML (default) and AMP HTML (by adding `?amp=1` to the URL)
<del> - The AMP version of the page only has valid optimizations applied with AMP Optimizer so that it is indexable by search-engines
<del> - Opt-in via `export const config = { amp: 'hybrid' }`
<del> - Able to differentiate between modes using `useAmp` from `next/amp`
<del>
<del>Both of these page modes provide a consistently fast experience for users accessing pages through search engines.
<del>
<del>### AMP Behavior with `next export`
<del>
<del>When using `next export` to statically prerender pages Next.js will detect if the page supports AMP and change the exporting behavior based on that.
<del>
<del>Hybrid AMP (`pages/about.js`) would output:
<del>
<del>- `out/about.html` - with client-side React runtime
<del>- `out/about.amp.html` - AMP page
<del>
<del>AMP-only (`pages/about.js`) would output:
<del>
<del>- `out/about.html` - Optimized AMP page
<del>
<del>During export Next.js automatically detects if a page is hybrid AMP and outputs the AMP version to `page.amp.html`. We also automatically insert the `<link rel="amphtml" href="/page.amp" />` and `<link rel="canonical" href="/" />` tags for you.
<del>
<del>> **Note**: When using `exportTrailingSlash: true` in `next.config.js`, output will be different. For Hybrid AMP pages, output will be `out/page/index.html` and `out/page.amp/index.html`, and for AMP-only pages, output will be `out/page/index.html`
<del>
<del>### Adding AMP Components
<del>
<del>The AMP community provides [many components](https://amp.dev/documentation/components/) to make AMP pages more interactive. You can add these components to your page by using `next/head`:
<del>
<del>```js
<del>// pages/hello.js
<del>import Head from 'next/head'
<del>
<del>export const config = { amp: true }
<del>
<del>export default function MyAmpPage() {
<del> return (
<del> <div>
<del> <Head>
<del> <script
<del> async
<del> key="amp-timeago"
<del> custom-element="amp-timeago"
<del> src="https://cdn.ampproject.org/v0/amp-timeago-0.1.js"
<del> />
<del> </Head>
<del>
<del> <p>Some time: {date.toJSON()}</p>
<del> <amp-timeago
<del> width="0"
<del> height="15"
<del> datetime={date.toJSON()}
<del> layout="responsive"
<del> >
<del> .
<del> </amp-timeago>
<del> </div>
<del> )
<del>}
<del>```
<del>
<del>### AMP Validation
<del>
<del>AMP pages are automatically validated with [amphtml-validator](https://www.npmjs.com/package/amphtml-validator) during development. Errors and warnings will appear in the terminal where you started Next.js.
<del>
<del>Pages are also validated during `next export` and any warnings / errors will be printed to the terminal.
<del>Any AMP errors will cause `next export` to exit with status code `1` because the export is not valid AMP.
<del>
<del>### TypeScript Support
<del>
<del>AMP currently doesn't have built-in types for TypeScript, but it's in their roadmap ([#13791](https://github.com/ampproject/amphtml/issues/13791)). As a workaround you can manually add the types to `amp.d.ts` like [here](https://stackoverflow.com/a/50601125).
<del>
<del>## Static HTML export
<del>
<del><details>
<del> <summary><b>Examples</b></summary>
<del> <ul>
<del> <li><a href="/examples/with-static-export">Static export</a></li>
<del> </ul>
<del></details>
<del>
<del>`next export` is a way to run your Next.js app as a standalone static app without the need for a Node.js server.
<del>The exported app supports almost every feature of Next.js, including dynamic urls, prefetching, preloading and dynamic imports.
<del>
<del>The way `next export` works is by prerendering all pages possible to HTML. It does so based on a mapping of `pathname` key to page object. This mapping is called the `exportPathMap`.
<del>
<del>The page object has 2 values:
<del>
<del>- `page` - `String` the page inside the `pages` directory to render
<del>- `query` - `Object` the `query` object passed to `getInitialProps` when prerendering. Defaults to `{}`
<del>
<del>### Usage
<del>
<del>Simply develop your app as you normally do with Next.js. Then run:
<del>
<del>```
<del>next build
<del>next export
<del>```
<del>
<del>By default `next export` doesn't require any configuration. It will generate a default `exportPathMap` containing the routes to pages inside the `pages` directory. This default mapping is available as `defaultPathMap` in the example below.
<del>
<del>If your application has dynamic routes you can add a dynamic `exportPathMap` in `next.config.js`.
<del>This function is asynchronous and gets the default `exportPathMap` as a parameter.
<del>
<del>```js
<del>// next.config.js
<del>module.exports = {
<del> exportPathMap: async function(
<del> defaultPathMap,
<del> { dev, dir, outDir, distDir, buildId }
<del> ) {
<del> return {
<del> '/': { page: '/' },
<del> '/about': { page: '/about' },
<del> '/readme.md': { page: '/readme' },
<del> '/p/hello-nextjs': { page: '/post', query: { title: 'hello-nextjs' } },
<del> '/p/learn-nextjs': { page: '/post', query: { title: 'learn-nextjs' } },
<del> '/p/deploy-nextjs': { page: '/post', query: { title: 'deploy-nextjs' } },
<del> }
<del> },
<del>}
<del>```
<del>
<del>The pages will be exported as html files, i.e. `/about` will become `/about.html`.
<del>
<del>It is possible to configure Next.js to export pages as `index.html` files and require trailing slashes, i.e. `/about` becomes `/about/index.html` and is routable via `/about/`.
<del>This was the default behavior prior to Next.js 9.
<del>You can use the following `next.config.js` to switch back to this behavior:
<del>
<del>```js
<del>// next.config.js
<del>module.exports = {
<del> exportTrailingSlash: true,
<del>}
<del>```
<del>
<del>> **Note**: If the export path is a filename (e.g. `/readme.md`) and is different than `.html`, you may need to set the `Content-Type` header to `text/html` when serving this content.
<del>
<del>The second argument is an `object` with:
<del>
<del>- `dev` - `true` when `exportPathMap` is being called in development. `false` when running `next export`. In development `exportPathMap` is used to define routes.
<del>- `dir` - Absolute path to the project directory
<del>- `outDir` - Absolute path to the `out/` directory (configurable with `-o` or `--outdir`). When `dev` is `true` the value of `outDir` will be `null`.
<del>- `distDir` - Absolute path to the `.next/` directory (configurable using the `distDir` config key)
<del>- `buildId` - The `buildId` the export is running for
<del>
<del>Then simply run these commands:
<del>
<del>```bash
<del>next build
<del>next export
<del>```
<del>
<del>For that you may need to add a NPM script to `package.json` like this:
<del>
<del>```json
<del>{
<del> "scripts": {
<del> "build": "next build",
<del> "export": "npm run build && next export"
<del> }
<del>}
<del>```
<del>
<del>And run it at once with:
<del>
<del>```bash
<del>npm run export
<del>```
<del>
<del>Then you have a static version of your app in the `out` directory.
<del>
<del>> You can also customize the output directory. For that run `next export -h` for the help.
<del>
<del>Now you can deploy the `out` directory to any static hosting service. Note that there is an additional step for deploying to GitHub Pages, [documented here](https://github.com/zeit/next.js/wiki/Deploying-a-Next.js-app-into-GitHub-Pages).
<del>
<del>For an example, simply visit the `out` directory and run following command to deploy your app to [ZEIT Now](https://zeit.co/now).
<del>
<del>```bash
<del>now
<del>```
<del>
<del>### Limitation
<del>
<del>With `next export`, we build a HTML version of your app. At export time we will run `getInitialProps` of your pages.
<del>
<del>The `req` and `res` fields of the `context` object passed to `getInitialProps` are empty objects during export as there is no server running.
<del>
<del>> **Note**: If your pages don't have `getInitialProps` you may not need `next export` at all, `next build` is already enough thanks to [automatic static optimization](#automatic-static-optimization).
<del>
<del>> You won't be able to render HTML dynamically when static exporting, as we pre-build the HTML files. If you want to do dynamic rendering use `next start` or the custom server API
<del>
<del>## Multi Zones
<del>
<del><details>
<del> <summary><b>Examples</b></summary>
<del> <ul>
<del> <li><a href="/examples/with-zones">With Zones</a></li>
<del> </ul>
<del></details>
<del>
<del>A zone is a single deployment of a Next.js app. Just like that, you can have multiple zones and then you can merge them as a single app.
<del>
<del>For an example, you can have two zones like this:
<del>
<del>- An app for serving `/blog/**`
<del>- Another app for serving all other pages
<del>
<del>With multi zones support, you can merge both these apps into a single one allowing your customers to browse it using a single URL, but you can develop and deploy both apps independently.
<del>
<del>> This is exactly the same concept of microservices, but for frontend apps.
<del>
<del>### How to define a zone
<del>
<del>There are no special zones related APIs. You only need to do following:
<del>
<del>- Make sure to keep only the pages you need in your app, meaning that an app can't have pages from another app, if app `A` has `/blog` then app `B` shouldn't have it too.
<del>- Make sure to add an [assetPrefix](https://github.com/zeit/next.js#cdn-support-with-asset-prefix) to avoid conflicts with static files.
<del>
<del>### How to merge them
<del>
<del>You can merge zones using any HTTP proxy.
<del>
<del>You can use [now dev](https://zeit.co/docs/v2/development/basics) as your local development server. It allows you to easily define routing routes for multiple apps like below:
<del>
<del>```json
<del>{
<del> "version": 2,
<del> "builds": [
<del> { "src": "docs/next.config.js", "use": "@now/next" },
<del> { "src": "home/next.config.js", "use": "@now/next" }
<del> ],
<del> "routes": [
<del> { "src": "/docs(.*)", "dest": "docs$1", "continue": true },
<del> { "src": "(?!/?docs)(.*)", "dest": "home$1", "continue": true }
<del> ]
<del>}
<del>```
<del>
<del>For the production deployment, you can use the same configuration and run `now` to do the deployment with [ZEIT Now](https://zeit.co/now). Otherwise you can also configure a proxy server to route using a set of routes like the ones above, e.g deploy the docs app to `https://docs.example.com` and the home app to `https://home.example.com` and then add a proxy server for both apps in `https://example.com`.
<del>
<del>## FAQ
<del>
<del><details>
<del> <summary>Is this production ready?</summary>
<del> Next.js has been powering https://zeit.co since its inception.
<del>
<del>We’re ecstatic about both the developer experience and end-user performance, so we decided to share it with the community.
<del>
<del></details>
<del>
<del><details>
<del> <summary>How big is it?</summary>
<del>
<del>The client side bundle size should be measured in a per-app basis.
<del>A small Next main bundle is around 65kb gzipped.
<del>
<del></details>
<del>
<del><details>
<del> <summary>Is this like `create-react-app`?</summary>
<del>
<del>Yes and No.
<del>
<del>Yes in that both make your life easier.
<del>
<del>No in that it enforces a _structure_ so that we can do more advanced things like:
<del>
<del>- Server side rendering
<del>- Automatic code splitting
<del>
<del>In addition, Next.js provides two built-in features that are critical for every single website:
<del>
<del>- Routing with lazy component loading: `<Link>` (by importing `next/link`)
<del>- A way for components to alter `<head>`: `<Head>` (by importing `next/head`)
<del>
<del>If you want to create re-usable React components that you can embed in your Next.js app or other React applications, using `create-react-app` is a great idea. You can later `import` it and keep your codebase clean!
<del>
<del></details>
<del>
<del><details>
<del> <summary>How do I use CSS-in-JS solutions?</summary>
<del>
<del>Next.js bundles [styled-jsx](https://github.com/zeit/styled-jsx) supporting scoped css. However you can use any CSS-in-JS solution in your Next app by just including your favorite library [as mentioned before](#css-in-js) in the document.
<del>
<del></details>
<del>
<del><details>
<del> <summary>What syntactic features are transpiled? How do I change them?</summary>
<del>
<del>We track V8. Since V8 has wide support for ES6 and `async` and `await`, we transpile those. Since V8 doesn’t support class decorators, we don’t transpile those.
<del>
<del>See the documentation about [customizing the babel config](#customizing-babel-config) and [next/preset](/packages/next/build/babel/preset.ts) for more information.
<del>
<del></details>
<del>
<del><details>
<del> <summary>Why a new Router?</summary>
<del>
<del>Next.js is special in that:
<del>
<del>- Routes don’t need to be known ahead of time
<del>- Routes are always lazy-loadable
<del>- Top-level components can define `getInitialProps` that should _block_ the loading of the route (either when server-rendering or lazy-loading)
<del>
<del>As a result, we were able to introduce a very simple approach to routing that consists of two pieces:
<del>
<del>- Every top level component receives a `url` object to inspect the url or perform modifications to the history
<del>- A `<Link />` component is used to wrap elements like anchors (`<a/>`) to perform client-side transitions
<del>
<del></details>
<del>
<del><details>
<del><summary>How do I define a custom fancy route?</summary>
<del>
<del>Next.js provide [dynamic routing](#dynamic-routing) solution out of the box. This allows to use pretty links in url.
<del>
<del>You can check an [example](https://github.com/zeit/next.js/tree/canary/examples/dynamic-routing) to see how it works.
<del>
<del></details>
<del>
<del><details>
<del><summary>How do I fetch data?</summary>
<del>
<del>It’s up to you. `getInitialProps` is an `async` function (or a regular function that returns a `Promise`). It can retrieve data from anywhere.
<del>
<del></details>
<del>
<del><details>
<del> <summary>Can I use it with GraphQL?</summary>
<del>
<del>Yes! Here's an example with [Apollo](/examples/with-apollo).
<del>
<del></details>
<del>
<del><details>
<del><summary>Can I use it with Redux and thunk?</summary>
<del>
<del>Yes! Here's an [example](/examples/with-redux-thunk).
<del>
<del></details>
<del>
<del><details>
<del><summary>Can I use it with Redux?</summary>
<del>
<del>Yes! Here's an [example](/examples/with-redux).
<del>
<del></details>
<del>
<del><details>
<del><summary>Can I use Next with my favorite Javascript library or toolkit?</summary>
<del>
<del>Since our first release we've had **many** example contributions, you can check them out in the [examples](/examples) directory.
<del>
<del></details>
<del>
<del><details>
<del><summary>What is this inspired by?</summary>
<del>
<del>Many of the goals we set out to accomplish were the ones listed in [The 7 principles of Rich Web Applications](http://rauchg.com/2014/7-principles-of-rich-web-applications/) by Guillermo Rauch.
<del>
<del>The ease-of-use of PHP is a great inspiration. We feel Next.js is a suitable replacement for many scenarios where you otherwise would use PHP to output HTML.
<add>## Getting Started
<ide>
<del>Unlike PHP, we benefit from the ES6 module system and every file exports a **component or function** that can be easily imported for lazy evaluation or testing.
<add>Visit <a aria-label="next.js learn" href="https://nextjs.org/learn">https://nextjs.org/learn</a> to get started with Next.js.
<ide>
<del>As we were researching options for server-rendering React that didn’t involve a large number of steps, we came across [react-page](https://github.com/facebookarchive/react-page) (now deprecated), a similar approach to Next.js by the creator of React Jordan Walke.
<add>## Documentation
<ide>
<del></details>
<add>Visit <a aria-label="next.js learn" href="https://nextjs.org/docs">https://nextjs.org/docs</a> to view the documentation.
<ide>
<ide> ## Contributing
<ide> | 1 |
Javascript | Javascript | remove unused var | b99ddfd3bfb7a83cdefc04e2a34d91ee640ca524 | <ide><path>src/text-editor-component.js
<ide> class LinesTileComponent {
<ide> this.renderHighlights(),
<ide> this.renderLines()
<ide> )
<del>
<ide> }
<ide>
<ide> renderHighlights () {
<del> const {measuredContent, top, height, width, lineHeight, highlightDecorations} = this.props
<add> const {top, height, width, lineHeight, highlightDecorations} = this.props
<ide>
<ide> if (!this.highlightsVnode) {
<ide> let children = null | 1 |
Ruby | Ruby | push the before filter lambdas to factory methods | bd95ff84f3199fba2c35c2727182672ac75c08b2 | <ide><path>activesupport/lib/active_support/callbacks.rb
<ide> class Before
<ide> def self.build(next_callback, user_callback, user_conditions, chain_config, filter)
<ide> if chain_config.key?(:terminator) && user_conditions.any?
<ide> halted_lambda = eval "lambda { |result| #{chain_config[:terminator]} }"
<del> lambda { |env|
<del> target = env.target
<del> value = env.value
<del> halted = env.halted
<del>
<del> if !halted && user_conditions.all? { |c| c.call(target, value) }
<del> result = user_callback.call target, value
<del> env.halted = halted_lambda.call result
<del> if env.halted
<del> target.send :halted_callback_hook, filter
<del> end
<del> end
<del> next_callback.call env
<del> }
<add> terminal_and_conditional(next_callback, user_callback, user_conditions, halted_lambda, filter)
<ide> elsif chain_config.key? :terminator
<ide> halted_lambda = eval "lambda { |result| #{chain_config[:terminator]} }"
<del> lambda { |env|
<del> target = env.target
<del> value = env.value
<del> halted = env.halted
<add> terminal(next_callback, user_callback, halted_lambda, filter)
<add> elsif user_conditions.any?
<add> conditional(next_callback, user_callback, user_conditions)
<add> else
<add> simple next_callback, user_callback
<add> end
<add> end
<add>
<add> private
<add>
<add> def self.terminal_and_conditional(next_callback, user_callback, user_conditions, halted_lambda, filter)
<add> lambda { |env|
<add> target = env.target
<add> value = env.value
<add> halted = env.halted
<ide>
<del> if !halted
<del> result = user_callback.call target, value
<del> env.halted = halted_lambda.call result
<del> if env.halted
<del> target.send :halted_callback_hook, filter
<del> end
<add> if !halted && user_conditions.all? { |c| c.call(target, value) }
<add> result = user_callback.call target, value
<add> env.halted = halted_lambda.call result
<add> if env.halted
<add> target.send :halted_callback_hook, filter
<ide> end
<del> next_callback.call env
<del> }
<del> elsif user_conditions.any?
<del> lambda { |env|
<del> target = env.target
<del> value = env.value
<add> end
<add> next_callback.call env
<add> }
<add> end
<ide>
<del> if user_conditions.all? { |c| c.call(target, value) }
<del> user_callback.call target, value
<add> def self.terminal(next_callback, user_callback, halted_lambda, filter)
<add> lambda { |env|
<add> target = env.target
<add> value = env.value
<add> halted = env.halted
<add>
<add> if !halted
<add> result = user_callback.call target, value
<add> env.halted = halted_lambda.call result
<add> if env.halted
<add> target.send :halted_callback_hook, filter
<ide> end
<del> next_callback.call env
<del> }
<del> else
<del> lambda { |env|
<del> user_callback.call env.target, env.value
<del> next_callback.call env
<del> }
<del> end
<add> end
<add> next_callback.call env
<add> }
<add> end
<add>
<add> def self.conditional(next_callback, user_callback, user_conditions)
<add> lambda { |env|
<add> target = env.target
<add> value = env.value
<add>
<add> if user_conditions.all? { |c| c.call(target, value) }
<add> user_callback.call target, value
<add> end
<add> next_callback.call env
<add> }
<add> end
<add>
<add> def self.simple(next_callback, user_callback)
<add> lambda { |env|
<add> user_callback.call env.target, env.value
<add> next_callback.call env
<add> }
<ide> end
<ide> end
<ide> end | 1 |
Text | Text | update context example for react-router v4 beta | 564fa646262300683e2c0212fe12bcb0ae5e7daf | <ide><path>docs/docs/context.md
<ide> If `contextTypes` is not defined, then `context` will be an empty object.
<ide>
<ide> ## Parent-Child Coupling
<ide>
<del>Context can also let you build an API where parents and children communicate. For example, one library that works this way is [React Router V4](https://react-router.now.sh/basic):
<add>Context can also let you build an API where parents and children communicate. For example, one library that works this way is [React Router V4](https://reacttraining.com/react-router):
<ide>
<ide> ```javascript
<add>import { Router, Route, Link } from 'react-router-dom';
<add>
<ide> const BasicExample = () => (
<ide> <Router>
<ide> <div>
<ide> const BasicExample = () => (
<ide> <li><Link to="/topics">Topics</Link></li>
<ide> </ul>
<ide>
<del> <hr/>
<add> <hr />
<ide>
<del> <Match exactly pattern="/" component={Home} />
<del> <Match pattern="/about" component={About} />
<del> <Match pattern="/topics" component={Topics} />
<add> <Route exact path="/" component={Home} />
<add> <Route path="/about" component={About} />
<add> <Route path="/topics" component={Topics} />
<ide> </div>
<ide> </Router>
<del>)
<add>);
<ide> ```
<ide>
<del>By passing down some information from the `Router` component, each `Link` and `Match` can communicate back to the containing `Router`.
<add>By passing down some information from the `Router` component, each `Link` and `Route` can communicate back to the containing `Router`.
<ide>
<ide> Before you build components with an API similar to this, consider if there are cleaner alternatives. For example, you can pass entire React component as props if you'd like to.
<ide> | 1 |
PHP | PHP | fix more tests | aa7cac185a1e2a320615bf6e8605abba3472898a | <ide><path>lib/Cake/Test/TestCase/TestSuite/HtmlCoverageReportTest.php
<ide> <?php
<ide> /**
<del> * Test case for HtmlCoverageReport
<del> *
<ide> * PHP5
<ide> *
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> * @link http://cakephp.org CakePHP(tm) Project
<del> * @package Cake.Test.Case.TestSuite
<ide> * @since CakePHP(tm) v 2.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide> /**
<ide> * Class HtmlCoverageReportTest
<ide> *
<del> * @package Cake.Test.Case.TestSuite
<ide> */
<ide> class HtmlCoverageReportTest extends TestCase {
<ide>
<ide> public function testGetPathFilter() {
<ide> */
<ide> public function testFilterCoverageDataByPathRemovingElements() {
<ide> $data = array(
<del> CAKE . 'dispatcher.php' => array(
<add> CAKE . 'Dispatcher.php' => array(
<ide> 10 => -1,
<ide> 12 => 1
<ide> ),
<del> APP . 'app_model.php' => array(
<add> APP . 'AppModel.php' => array(
<ide> 50 => 1,
<ide> 52 => -1
<ide> )
<ide> );
<ide> $this->Coverage->setCoverage($data);
<del> $result = $this->Coverage->filterCoverageDataByPath(CAKE);
<del> $this->assertTrue(isset($result[CAKE . 'dispatcher.php']));
<del> $this->assertFalse(isset($result[APP . 'app_model.php']));
<add> $result = $this->Coverage->filterCoverageDataByPath(APP);
<add> $this->assertArrayNotHasKey(CAKE . 'Dispatcher.php', $result);
<add> $this->assertArrayHasKey(APP . 'AppModel.php', $result);
<ide> }
<ide>
<ide> /** | 1 |
Ruby | Ruby | remove trailing whitespace | 8f7621edb85ba73a7532b39869425a188bb6c77b | <ide><path>Library/Homebrew/cmd/tap.rb
<ide> def tap
<ide> opoo "`brew tap --full` is now a no-op!"
<ide> # odeprecated "`brew tap --full`"
<ide> end
<del>
<add>
<ide> if args.shallow?
<ide> opoo "`brew tap --shallow` is now a no-op!"
<ide> # odeprecated "`brew tap --shallow`" | 1 |
Ruby | Ruby | relocate requirement tests | 62984b956e4e2fc1dced4998dc913421babde8bf | <ide><path>Library/Homebrew/test/java_requirement_spec.rb
<del># typed: false
<del># frozen_string_literal: true
<del>
<del>require "cli/args"
<del>require "requirements/java_requirement"
<del>
<del>describe JavaRequirement do
<del> subject { described_class.new([]) }
<del>
<del> before do
<del> ENV["JAVA_HOME"] = nil
<del> end
<del>
<del> describe "#message" do
<del> its(:message) { is_expected.to match(/Java is required for this software./) }
<del> end
<del>
<del> describe "#inspect" do
<del> subject { described_class.new(%w[1.7+]) }
<del>
<del> its(:inspect) { is_expected.to eq('#<JavaRequirement: version="1.7+" []>') }
<del> end
<del>
<del> describe "#display_s" do
<del> context "without specific version" do
<del> its(:display_s) { is_expected.to eq("Java") }
<del> end
<del>
<del> context "with version 1.8" do
<del> subject { described_class.new(%w[1.8]) }
<del>
<del> its(:display_s) { is_expected.to eq("Java = 1.8") }
<del> end
<del>
<del> context "with version 1.8+" do
<del> subject { described_class.new(%w[1.8+]) }
<del>
<del> its(:display_s) { is_expected.to eq("Java >= 1.8") }
<del> end
<del> end
<del>
<del> describe "#satisfied?" do
<del> subject { described_class.new(%w[1.8]) }
<del>
<del> it "returns false if no `java` executable can be found" do
<del> allow(File).to receive(:executable?).and_return(false)
<del> expect(subject).not_to be_satisfied
<del> end
<del>
<del> it "returns true if #preferred_java returns a path" do
<del> allow(subject).to receive(:preferred_java).and_return(Pathname.new("/usr/bin/java"))
<del> expect(subject).to be_satisfied
<del> end
<del>
<del> context "when #possible_javas contains paths" do
<del> let(:path) { mktmpdir }
<del> let(:java) { path/"java" }
<del>
<del> def setup_java_with_version(version)
<del> IO.write java, <<~SH
<del> #!/bin/sh
<del> echo 'java version "#{version}"' 1>&2
<del> SH
<del> FileUtils.chmod "+x", java
<del> end
<del>
<del> before do
<del> allow(subject).to receive(:possible_javas).and_return([java])
<del> end
<del>
<del> context "and 1.7 is required" do
<del> subject { described_class.new(%w[1.7]) }
<del>
<del> it "returns false if all are lower" do
<del> setup_java_with_version "1.6.0_5"
<del> expect(subject).not_to be_satisfied
<del> end
<del>
<del> it "returns true if one is equal" do
<del> setup_java_with_version "1.7.0_5"
<del> expect(subject).to be_satisfied
<del> end
<del>
<del> it "returns false if all are higher" do
<del> setup_java_with_version "1.8.0_5"
<del> expect(subject).not_to be_satisfied
<del> end
<del> end
<del>
<del> context "and 1.7+ is required" do
<del> subject { described_class.new(%w[1.7+]) }
<del>
<del> it "returns false if all are lower" do
<del> setup_java_with_version "1.6.0_5"
<del> expect(subject).not_to be_satisfied
<del> end
<del>
<del> it "returns true if one is equal" do
<del> setup_java_with_version "1.7.0_5"
<del> expect(subject).to be_satisfied
<del> end
<del>
<del> it "returns true if one is higher" do
<del> setup_java_with_version "1.8.0_5"
<del> expect(subject).to be_satisfied
<del> end
<del> end
<del> end
<del> end
<del>
<del> describe "#suggestion" do
<del> context "without specific version" do
<del> its(:suggestion) { is_expected.to match(/brew cask install adoptopenjdk/) }
<del> its(:cask) { is_expected.to eq("adoptopenjdk") }
<del> end
<del>
<del> context "with version 1.8" do
<del> subject { described_class.new(%w[1.8]) }
<del>
<del> its(:suggestion) { is_expected.to match(%r{brew cask install homebrew/cask-versions/adoptopenjdk8}) }
<del> its(:cask) { is_expected.to eq("homebrew/cask-versions/adoptopenjdk8") }
<del> end
<del>
<del> context "with version 1.8+" do
<del> subject { described_class.new(%w[1.8+]) }
<del>
<del> its(:suggestion) { is_expected.to match(/brew cask install adoptopenjdk/) }
<del> its(:cask) { is_expected.to eq("adoptopenjdk") }
<del> end
<del> end
<del>end
<ide><path>Library/Homebrew/test/requirements/java_requirement_spec.rb
<ide> # typed: false
<ide> # frozen_string_literal: true
<ide>
<add>require "cli/args"
<ide> require "requirements/java_requirement"
<ide>
<ide> describe JavaRequirement do
<del> describe "initialize" do
<add> subject { described_class.new([]) }
<add>
<add> before do
<add> ENV["JAVA_HOME"] = nil
<add> end
<add>
<add> describe "#initialize" do
<ide> it "parses '1.8' tag correctly" do
<ide> req = described_class.new(["1.8"])
<ide> expect(req.display_s).to eq("Java = 1.8")
<ide> expect(req.display_s).to eq("Java")
<ide> end
<ide> end
<add>
<add> describe "#message" do
<add> its(:message) { is_expected.to match(/Java is required for this software./) }
<add> end
<add>
<add> describe "#inspect" do
<add> subject { described_class.new(%w[1.7+]) }
<add>
<add> its(:inspect) { is_expected.to eq('#<JavaRequirement: version="1.7+" []>') }
<add> end
<add>
<add> describe "#display_s" do
<add> context "without specific version" do
<add> its(:display_s) { is_expected.to eq("Java") }
<add> end
<add>
<add> context "with version 1.8" do
<add> subject { described_class.new(%w[1.8]) }
<add>
<add> its(:display_s) { is_expected.to eq("Java = 1.8") }
<add> end
<add>
<add> context "with version 1.8+" do
<add> subject { described_class.new(%w[1.8+]) }
<add>
<add> its(:display_s) { is_expected.to eq("Java >= 1.8") }
<add> end
<add> end
<add>
<add> describe "#satisfied?" do
<add> subject(:requirement) { described_class.new(%w[1.8]) }
<add>
<add> it "returns false if no `java` executable can be found" do
<add> allow(File).to receive(:executable?).and_return(false)
<add> expect(requirement).not_to be_satisfied
<add> end
<add>
<add> it "returns true if #preferred_java returns a path" do
<add> allow(requirement).to receive(:preferred_java).and_return(Pathname.new("/usr/bin/java"))
<add> expect(requirement).to be_satisfied
<add> end
<add>
<add> context "when #possible_javas contains paths" do
<add> let(:path) { mktmpdir }
<add> let(:java) { path/"java" }
<add>
<add> def setup_java_with_version(version)
<add> IO.write java, <<~SH
<add> #!/bin/sh
<add> echo 'java version "#{version}"' 1>&2
<add> SH
<add> FileUtils.chmod "+x", java
<add> end
<add>
<add> before do
<add> allow(requirement).to receive(:possible_javas).and_return([java])
<add> end
<add>
<add> context "and 1.7 is required" do
<add> subject(:requirement) { described_class.new(%w[1.7]) }
<add>
<add> it "returns false if all are lower" do
<add> setup_java_with_version "1.6.0_5"
<add> expect(requirement).not_to be_satisfied
<add> end
<add>
<add> it "returns true if one is equal" do
<add> setup_java_with_version "1.7.0_5"
<add> expect(requirement).to be_satisfied
<add> end
<add>
<add> it "returns false if all are higher" do
<add> setup_java_with_version "1.8.0_5"
<add> expect(requirement).not_to be_satisfied
<add> end
<add> end
<add>
<add> context "and 1.7+ is required" do
<add> subject(:requirement) { described_class.new(%w[1.7+]) }
<add>
<add> it "returns false if all are lower" do
<add> setup_java_with_version "1.6.0_5"
<add> expect(requirement).not_to be_satisfied
<add> end
<add>
<add> it "returns true if one is equal" do
<add> setup_java_with_version "1.7.0_5"
<add> expect(requirement).to be_satisfied
<add> end
<add>
<add> it "returns true if one is higher" do
<add> setup_java_with_version "1.8.0_5"
<add> expect(requirement).to be_satisfied
<add> end
<add> end
<add> end
<add> end
<add>
<add> describe "#suggestion" do
<add> context "without specific version" do
<add> its(:suggestion) { is_expected.to match(/brew cask install adoptopenjdk/) }
<add> its(:cask) { is_expected.to eq("adoptopenjdk") }
<add> end
<add>
<add> context "with version 1.8" do
<add> subject { described_class.new(%w[1.8]) }
<add>
<add> its(:suggestion) { is_expected.to match(%r{brew cask install homebrew/cask-versions/adoptopenjdk8}) }
<add> its(:cask) { is_expected.to eq("homebrew/cask-versions/adoptopenjdk8") }
<add> end
<add>
<add> context "with version 1.8+" do
<add> subject { described_class.new(%w[1.8+]) }
<add>
<add> its(:suggestion) { is_expected.to match(/brew cask install adoptopenjdk/) }
<add> its(:cask) { is_expected.to eq("adoptopenjdk") }
<add> end
<add> end
<ide> end
<add><path>Library/Homebrew/test/requirements/x11_requirement_spec.rb
<del><path>Library/Homebrew/test/x11_requirement_spec.rb
<ide> require "requirements/x11_requirement"
<ide>
<ide> describe X11Requirement do
<add> subject(:requirement) { described_class.new([]) }
<add>
<ide> let(:default_name) { "x11" }
<ide>
<ide> describe "#name" do
<ide> it "defaults to x11" do
<del> expect(subject.name).to eq(default_name)
<add> expect(requirement.name).to eq(default_name)
<ide> end
<ide> end
<ide>
<ide> describe "#eql?" do
<ide> it "returns true if the requirements are equal" do
<ide> other = described_class.new
<del> expect(subject).to eql(other)
<add> expect(requirement).to eql(other)
<ide> end
<ide> end
<ide>
<ide> describe "#modify_build_environment" do
<ide> it "calls ENV#x11" do
<del> allow(subject).to receive(:satisfied?).and_return(true)
<add> allow(requirement).to receive(:satisfied?).and_return(true)
<ide> expect(ENV).to receive(:x11)
<del> subject.modify_build_environment
<add> requirement.modify_build_environment
<ide> end
<ide> end
<ide>
<ide> describe "#satisfied?", :needs_macos do
<ide> it "returns true if X11 is installed" do
<ide> expect(MacOS::XQuartz).to receive(:version).and_return("2.7.5")
<ide> expect(MacOS::XQuartz).to receive(:installed?).and_return(true)
<del> expect(subject).to be_satisfied
<add> expect(requirement).to be_satisfied
<ide> end
<ide>
<ide> it "returns false if X11 is not installed" do
<ide> expect(MacOS::XQuartz).to receive(:installed?).and_return(false)
<del> expect(subject).not_to be_satisfied
<add> expect(requirement).not_to be_satisfied
<ide> end
<ide> end
<ide> end | 3 |
Go | Go | add debug infos | ccac5b138253ab87846089cb5af9b4b77a7fd9d5 | <ide><path>commands.go
<ide> func (srv *Server) CmdAttach(stdin io.ReadCloser, stdout io.Writer, args ...stri
<ide> return err
<ide> }
<ide> wg.Add(1)
<del> go func() { io.Copy(cStdin, stdin); wg.Add(-1) }()
<add> go func() {
<add> Debugf("Begin stdin pipe [attach]")
<add> io.Copy(cStdin, stdin)
<add> wg.Add(-1)
<add> Debugf("End of stdin pipe [attach]")
<add> }()
<ide> }
<ide> cStdout, err := container.StdoutPipe()
<ide> if err != nil {
<ide> return err
<ide> }
<ide> wg.Add(1)
<del> go func() { io.Copy(stdout, cStdout); wg.Add(-1) }()
<add> go func() {
<add> Debugf("Begin stdout pipe [attach]")
<add> io.Copy(stdout, cStdout)
<add> wg.Add(-1)
<add> Debugf("End of stdout pipe [attach]")
<add> }()
<ide> cStderr, err := container.StderrPipe()
<ide> if err != nil {
<ide> return err
<ide> }
<ide> wg.Add(1)
<del> go func() { io.Copy(stdout, cStderr); wg.Add(-1) }()
<add> go func() {
<add> Debugf("Begin stderr pipe [attach]")
<add> io.Copy(stdout, cStderr)
<add> wg.Add(-1)
<add> Debugf("End of stderr pipe [attach]")
<add> }()
<ide> wg.Wait()
<ide> return nil
<ide> }
<ide><path>container.go
<ide> func (container *Container) startPty() error {
<ide> // Copy the PTYs to our broadcasters
<ide> go func() {
<ide> defer container.stdout.Close()
<add> Debugf("[startPty] Begin of stdout pipe")
<ide> io.Copy(container.stdout, stdoutMaster)
<add> Debugf("[startPty] End of stdout pipe")
<ide> }()
<ide>
<ide> go func() {
<ide> defer container.stderr.Close()
<add> Debugf("[startPty] Begin of stderr pipe")
<ide> io.Copy(container.stderr, stderrMaster)
<add> Debugf("[startPty] End of stderr pipe")
<ide> }()
<ide>
<ide> // stdin
<ide> func (container *Container) startPty() error {
<ide> // container.cmd.SysProcAttr = &syscall.SysProcAttr{Setctty: true, Setsid: true}
<ide> go func() {
<ide> defer container.stdin.Close()
<add> Debugf("[startPty] Begin of stdin pipe")
<ide> io.Copy(stdinMaster, container.stdin)
<add> Debugf("[startPty] End of stdin pipe")
<ide> }()
<ide> }
<ide> if err := container.cmd.Start(); err != nil {
<ide> func (container *Container) start() error {
<ide> }
<ide> go func() {
<ide> defer stdin.Close()
<add> Debugf("Begin of stdin pipe [start]")
<ide> io.Copy(stdin, container.stdin)
<add> Debugf("End of stdin pipe [start]")
<ide> }()
<ide> }
<ide> return container.cmd.Start()
<ide> func (container *Container) releaseNetwork() error {
<ide>
<ide> func (container *Container) monitor() {
<ide> // Wait for the program to exit
<add> Debugf("Waiting for process")
<ide> container.cmd.Wait()
<add> Debugf("Process finished")
<add>
<ide> exitCode := container.cmd.ProcessState.Sys().(syscall.WaitStatus).ExitStatus()
<ide>
<ide> // Cleanup | 2 |
Java | Java | delete dead code in spring-webmvc | 2c648379abc56f5ce5ad83f2522d63b24ad72ffb | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java
<ide> import org.springframework.beans.factory.InitializingBean;
<ide> import org.springframework.beans.factory.config.BeanDefinition;
<ide> import org.springframework.beans.factory.config.BeanDefinitionHolder;
<del>import org.springframework.beans.factory.config.BeanReference;
<ide> import org.springframework.beans.factory.config.RuntimeBeanReference;
<ide> import org.springframework.beans.factory.parsing.BeanComponentDefinition;
<ide> import org.springframework.beans.factory.parsing.CompositeComponentDefinition;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.ClassUtils;
<del>import org.springframework.util.StringUtils;
<ide> import org.springframework.util.xml.DomUtils;
<ide> import org.springframework.web.HttpRequestHandler;
<ide> import org.springframework.web.accept.ContentNegotiationManager;
<ide> private ManagedList<Object> extractBeanSubElements(Element parentElement, Parser
<ide> return list;
<ide> }
<ide>
<del> private ManagedList<BeanReference> extractBeanRefSubElements(Element parentElement, ParserContext parserContext){
<del> ManagedList<BeanReference> list = new ManagedList<>();
<del> list.setSource(parserContext.extractSource(parentElement));
<del> for (Element refElement : DomUtils.getChildElementsByTagName(parentElement, "ref")) {
<del> BeanReference reference;
<del> if (StringUtils.hasText("bean")) {
<del> reference = new RuntimeBeanReference(refElement.getAttribute("bean"),false);
<del> list.add(reference);
<del> }
<del> else if (StringUtils.hasText("parent")){
<del> reference = new RuntimeBeanReference(refElement.getAttribute("parent"),true);
<del> list.add(reference);
<del> }
<del> else {
<del> parserContext.getReaderContext().error("'bean' or 'parent' attribute is required for <ref> element",
<del> parserContext.extractSource(parentElement));
<del> }
<del> }
<del> return list;
<del> }
<del>
<ide>
<ide> /**
<ide> * A FactoryBean for a CompositeUriComponentsContributor that obtains the | 1 |
Mixed | Text | remove mips support" | eaddb22d920d092f13a034a11ed1e4516c3f602a | <ide><path>configure.py
<ide>
<ide> valid_os = ('win', 'mac', 'solaris', 'freebsd', 'openbsd', 'linux',
<ide> 'android', 'aix', 'cloudabi')
<del>valid_arch = ('arm', 'arm64', 'ia32', 'ppc',
<add>valid_arch = ('arm', 'arm64', 'ia32', 'mips', 'mipsel', 'mips64el', 'ppc',
<ide> 'ppc64', 'x32','x64', 'x86', 'x86_64', 's390', 's390x')
<ide> valid_arm_float_abi = ('soft', 'softfp', 'hard')
<ide> valid_arm_fpu = ('vfp', 'vfpv3', 'vfpv3-d16', 'neon')
<add>valid_mips_arch = ('loongson', 'r1', 'r2', 'r6', 'rx')
<add>valid_mips_fpu = ('fp32', 'fp64', 'fpxx')
<add>valid_mips_float_abi = ('soft', 'hard')
<ide> valid_intl_modes = ('none', 'small-icu', 'full-icu', 'system-icu')
<ide> with open ('tools/icu/icu_versions.json') as f:
<ide> icu_versions = json.load(f)
<ide> help='ARM FPU mode ({0}) [default: %default]'.format(
<ide> ', '.join(valid_arm_fpu)))
<ide>
<add>parser.add_option('--with-mips-arch-variant',
<add> action='store',
<add> dest='mips_arch_variant',
<add> default='r2',
<add> choices=valid_mips_arch,
<add> help='MIPS arch variant ({0}) [default: %default]'.format(
<add> ', '.join(valid_mips_arch)))
<add>
<add>parser.add_option('--with-mips-fpu-mode',
<add> action='store',
<add> dest='mips_fpu_mode',
<add> default='fp32',
<add> choices=valid_mips_fpu,
<add> help='MIPS FPU mode ({0}) [default: %default]'.format(
<add> ', '.join(valid_mips_fpu)))
<add>
<add>parser.add_option('--with-mips-float-abi',
<add> action='store',
<add> dest='mips_float_abi',
<add> default='hard',
<add> choices=valid_mips_float_abi,
<add> help='MIPS floating-point ABI ({0}) [default: %default]'.format(
<add> ', '.join(valid_mips_float_abi)))
<add>
<ide> parser.add_option('--with-dtrace',
<ide> action='store_true',
<ide> dest='with_dtrace',
<ide> def host_arch_cc():
<ide> '__aarch64__' : 'arm64',
<ide> '__arm__' : 'arm',
<ide> '__i386__' : 'ia32',
<add> '__MIPSEL__' : 'mipsel',
<add> '__mips__' : 'mips',
<ide> '__PPC64__' : 'ppc64',
<ide> '__PPC__' : 'ppc64',
<ide> '__x86_64__' : 'x64',
<ide> def host_arch_cc():
<ide> if rtn != 's390':
<ide> break
<ide>
<add> if rtn == 'mipsel' and '_LP64' in k:
<add> rtn = 'mips64el'
<add>
<ide> return rtn
<ide>
<ide>
<ide> def host_arch_win():
<ide> 'AMD64' : 'x64',
<ide> 'x86' : 'ia32',
<ide> 'arm' : 'arm',
<add> 'mips' : 'mips',
<ide> }
<ide>
<ide> return matchup.get(arch, 'ia32')
<ide> def configure_arm(o):
<ide> o['variables']['arm_fpu'] = options.arm_fpu or arm_fpu
<ide>
<ide>
<add>def configure_mips(o):
<add> can_use_fpu_instructions = (options.mips_float_abi != 'soft')
<add> o['variables']['v8_can_use_fpu_instructions'] = b(can_use_fpu_instructions)
<add> o['variables']['v8_use_mips_abi_hardfloat'] = b(can_use_fpu_instructions)
<add> o['variables']['mips_arch_variant'] = options.mips_arch_variant
<add> o['variables']['mips_fpu_mode'] = options.mips_fpu_mode
<add>
<add>
<ide> def gcc_version_ge(version_checked):
<ide> for compiler in [(CC, 'c'), (CXX, 'c++')]:
<ide> ok, is_clang, clang_version, compiler_version = \
<ide> def configure_node(o):
<ide>
<ide> if target_arch == 'arm':
<ide> configure_arm(o)
<add> elif target_arch in ('mips', 'mipsel', 'mips64el'):
<add> configure_mips(o)
<ide>
<ide> if flavor == 'aix':
<ide> o['variables']['node_target_type'] = 'static_library'
<ide><path>doc/api/process.md
<ide> added: v0.5.0
<ide> The `process.arch` property returns a string identifying the operating system
<ide> CPU architecture for which the Node.js binary was compiled.
<ide>
<del>The current possible values are: `'arm'`, `'arm64'`, `'ia32'`,
<del>`'ppc'`, `'ppc64'`, `'s390'`, `'s390x'`, `'x32'`, and `'x64'`.
<add>The current possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,
<add>`'mipsel'`, `'ppc'`, `'ppc64'`, `'s390'`, `'s390x'`, `'x32'`, and `'x64'`.
<ide>
<ide> ```js
<ide> console.log(`This processor architecture is ${process.arch}`);
<ide><path>doc/onboarding-extras.md
<ide> need to be attached anymore, as only important bugfixes will be included.
<ide> * `macos`, `windows`, `smartos`, `aix`
<ide> * No linux, linux is the implied default
<ide> * Architecture labels
<del> * `arm`, `s390`, `ppc`
<add> * `arm`, `mips`, `s390`, `ppc`
<ide> * No x86{_64}, since that is the implied default | 3 |
Java | Java | bind implementation of map, cast, timestamp | 60ac55f587500fbef42338c06d541e1720c27ec9 | <ide><path>rxjava-core/src/main/java/rx/Observable.java
<ide> import rx.operators.OperationAverage;
<ide> import rx.operators.OperationBuffer;
<ide> import rx.operators.OperationCache;
<del>import rx.operators.OperationCast;
<add>import rx.operators.OperatorCast;
<ide> import rx.operators.OperationCombineLatest;
<ide> import rx.operators.OperationConcat;
<ide> import rx.operators.OperationDebounce;
<ide> import rx.operators.OperationInterval;
<ide> import rx.operators.OperationJoin;
<ide> import rx.operators.OperationJoinPatterns;
<del>import rx.operators.OperationMap;
<add>import rx.operators.OperatorMap;
<ide> import rx.operators.OperationMaterialize;
<ide> import rx.operators.OperationMerge;
<ide> import rx.operators.OperationMergeDelayError;
<ide> import rx.operators.OperationTimeInterval;
<ide> import rx.operators.OperationTimeout;
<ide> import rx.operators.OperationTimer;
<del>import rx.operators.OperationTimestamp;
<add>import rx.operators.OperatorTimestamp;
<ide> import rx.operators.OperationToMap;
<ide> import rx.operators.OperationToMultimap;
<ide> import rx.operators.OperationToObservableFuture;
<ide> public final Observable<T> cache() {
<ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211842.aspx">MSDN: Observable.Cast</a>
<ide> */
<ide> public final <R> Observable<R> cast(final Class<R> klass) {
<del> return create(OperationCast.cast(this, klass));
<add> return bind(new OperatorCast<T, R>(klass));
<ide> }
<ide>
<ide> /**
<ide> public final Long call(Long t1, T t2) {
<ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh244306.aspx">MSDN: Observable.Select</a>
<ide> */
<ide> public final <R> Observable<R> map(Func1<? super T, ? extends R> func) {
<del> return create(OperationMap.map(this, func));
<add> return bind(new OperatorMap<T, R>(func));
<ide> }
<ide>
<ide> /**
<ide> public final <R> Observable<R> mapMany(Func1<? super T, ? extends Observable<? e
<ide> }
<ide>
<ide> /**
<add><<<<<<< HEAD
<ide> * Returns an Observable that applies the specified function to each item emitted by an
<ide> * Observable and emits the results of these function applications.
<ide> * <p>
<ide> public final <R> Observable<R> mapWithIndex(Func2<? super T, Integer, ? extends
<ide> /**
<ide> * Turns all of the emissions and notifications from a source Observable into emissions marked
<ide> * with their original types within {@link Notification} objects.
<add>=======
<add> * Turns all of the emissions and notifications from a source Observable
<add> * into emissions marked with their original types within {@link Notification} objects.
<add>>>>>>>> Bind implementation of Map, Cast, Timestamp
<ide> * <p>
<ide> * <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/materialize.png">
<ide> *
<ide> public final Observable<T> timeout(long timeout, TimeUnit timeUnit, Scheduler sc
<ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229003.aspx">MSDN: Observable.Timestamp</a>
<ide> */
<ide> public final Observable<Timestamped<T>> timestamp() {
<del> return create(OperationTimestamp.timestamp(this));
<add> return timestamp(Schedulers.immediate());
<ide> }
<ide>
<ide> /**
<ide> public final Observable<Timestamped<T>> timestamp() {
<ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229003.aspx">MSDN: Observable.Timestamp</a>
<ide> */
<ide> public final Observable<Timestamped<T>> timestamp(Scheduler scheduler) {
<del> return create(OperationTimestamp.timestamp(this, scheduler));
<add> return bind(new OperatorTimestamp<T>(scheduler));
<ide> }
<ide>
<ide> /**
<ide><path>rxjava-core/src/main/java/rx/operators/OperationCast.java
<del>/**
<del> * Copyright 2014 Netflix, Inc.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>package rx.operators;
<del>
<del>import rx.Observable;
<del>import rx.Observable.OnSubscribeFunc;
<del>import rx.util.functions.Func1;
<del>
<del>/**
<del> * Converts the elements of an observable sequence to the specified type.
<del> */
<del>public class OperationCast {
<del>
<del> public static <T, R> OnSubscribeFunc<R> cast(
<del> Observable<? extends T> source, final Class<R> klass) {
<del> return OperationMap.map(source, new Func1<T, R>() {
<del> public R call(T t) {
<del> return klass.cast(t);
<del> }
<del> });
<del> }
<del>}
<ide><path>rxjava-core/src/main/java/rx/operators/OperationMap.java
<del>/**
<del> * Copyright 2014 Netflix, Inc.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>package rx.operators;
<del>
<del>import rx.Observable;
<del>import rx.Observable.OnSubscribeFunc;
<del>import rx.Observer;
<del>import rx.Subscription;
<del>import rx.util.functions.Func1;
<del>import rx.util.functions.Func2;
<del>
<del>/**
<del> * Applies a function of your choosing to every item emitted by an Observable, and returns this
<del> * transformation as a new Observable.
<del> * <p>
<del> * <img width="640" src="https://github.com/Netflix/RxJava/wiki/images/rx-operators/map.png">
<del> */
<del>public final class OperationMap {
<del>
<del> /**
<del> * Accepts a sequence and a transformation function. Returns a sequence that is the result of
<del> * applying the transformation function to each item in the sequence.
<del> *
<del> * @param sequence
<del> * the input sequence.
<del> * @param func
<del> * a function to apply to each item in the sequence.
<del> * @param <T>
<del> * the type of the input sequence.
<del> * @param <R>
<del> * the type of the output sequence.
<del> * @return a sequence that is the result of applying the transformation function to each item in the input sequence.
<del> */
<del> public static <T, R> OnSubscribeFunc<R> map(final Observable<? extends T> sequence, final Func1<? super T, ? extends R> func) {
<del> return mapWithIndex(sequence, new Func2<T, Integer, R>() {
<del> @Override
<del> public R call(T value, @SuppressWarnings("unused") Integer unused) {
<del> return func.call(value);
<del> }
<del> });
<del> }
<del>
<del> /**
<del> * Accepts a sequence and a transformation function. Returns a sequence that is the result of
<del> * applying the transformation function to each item in the sequence.
<del> *
<del> * @param sequence
<del> * the input sequence.
<del> * @param func
<del> * a function to apply to each item in the sequence. The function gets the index of the emitted item
<del> * as additional parameter.
<del> * @param <T>
<del> * the type of the input sequence.
<del> * @param <R>
<del> * the type of the output sequence.
<del> * @return a sequence that is the result of applying the transformation function to each item in the input sequence.
<del> * @deprecated
<del> */
<del> public static <T, R> OnSubscribeFunc<R> mapWithIndex(final Observable<? extends T> sequence, final Func2<? super T, Integer, ? extends R> func) {
<del> return new OnSubscribeFunc<R>() {
<del> @Override
<del> public Subscription onSubscribe(Observer<? super R> observer) {
<del> return new MapObservable<T, R>(sequence, func).onSubscribe(observer);
<del> }
<del> };
<del> }
<del>
<del> /**
<del> * An observable sequence that is the result of applying a transformation to each item in an input sequence.
<del> *
<del> * @param <T>
<del> * the type of the input sequence.
<del> * @param <R>
<del> * the type of the output sequence.
<del> */
<del> private static class MapObservable<T, R> implements OnSubscribeFunc<R> {
<del> public MapObservable(Observable<? extends T> sequence, Func2<? super T, Integer, ? extends R> func) {
<del> this.sequence = sequence;
<del> this.func = func;
<del> }
<del>
<del> private final Observable<? extends T> sequence;
<del> private final Func2<? super T, Integer, ? extends R> func;
<del> private int index;
<del>
<del> @Override
<del> public Subscription onSubscribe(final Observer<? super R> observer) {
<del> final SafeObservableSubscription subscription = new SafeObservableSubscription();
<del> return subscription.wrap(sequence.subscribe(new SafeObserver<T>(subscription, new Observer<T>() {
<del> @Override
<del> public void onNext(T value) {
<del> observer.onNext(func.call(value, index));
<del> index++;
<del> }
<del>
<del> @Override
<del> public void onError(Throwable ex) {
<del> observer.onError(ex);
<del> }
<del>
<del> @Override
<del> public void onCompleted() {
<del> observer.onCompleted();
<del> }
<del> })));
<del> }
<del> }
<del>}
<ide><path>rxjava-core/src/main/java/rx/operators/OperatorCast.java
<add>/**
<add> * Copyright 2014 Netflix, Inc.
<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>package rx.operators;
<add>
<add>import rx.Observable.OperatorSubscription;
<add>import rx.Observer;
<add>import rx.util.functions.Func2;
<add>
<add>/**
<add> * Converts the elements of an observable sequence to the specified type.
<add> */
<add>public class OperatorCast<T, R> implements Func2<Observer<? super R>, OperatorSubscription, Observer<? super T>> {
<add>
<add> private final Class<R> castClass;
<add>
<add> public OperatorCast(Class<R> castClass) {
<add> this.castClass = castClass;
<add> }
<add>
<add> @Override
<add> public Observer<? super T> call(final Observer<? super R> o, OperatorSubscription os) {
<add> return new Observer<T>() {
<add>
<add> @Override
<add> public void onCompleted() {
<add> o.onCompleted();
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> o.onError(e);
<add> }
<add>
<add> @Override
<add> public void onNext(T t) {
<add> o.onNext(castClass.cast(t));
<add> }
<add> };
<add> }
<add>}
<ide><path>rxjava-core/src/main/java/rx/operators/OperatorMap.java
<add>/**
<add> * Copyright 2014 Netflix, Inc.
<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>package rx.operators;
<add>
<add>import rx.Observable.OperatorSubscription;
<add>import rx.Observer;
<add>import rx.util.functions.Func1;
<add>import rx.util.functions.Func2;
<add>
<add>/**
<add> * Applies a function of your choosing to every item emitted by an Observable, and returns this
<add> * transformation as a new Observable.
<add> * <p>
<add> * <img width="640" src="https://github.com/Netflix/RxJava/wiki/images/rx-operators/map.png">
<add> */
<add>public final class OperatorMap<T, R> implements Func2<Observer<? super R>, OperatorSubscription, Observer<? super T>> {
<add>
<add> private final Func1<? super T, ? extends R> transformer;
<add>
<add> public OperatorMap(Func1<? super T, ? extends R> transformer) {
<add> this.transformer = transformer;
<add> }
<add>
<add> @Override
<add> public Observer<? super T> call(final Observer<? super R> o, OperatorSubscription os) {
<add> return new Observer<T>() {
<add>
<add> @Override
<add> public void onCompleted() {
<add> o.onCompleted();
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> o.onError(e);
<add> }
<add>
<add> @Override
<add> public void onNext(T t) {
<add> try {
<add> o.onNext(transformer.call(t));
<add> } catch (Throwable e) {
<add> onError(e);
<add> }
<add> }
<add>
<add> };
<add> }
<add>
<add>}
<add><path>rxjava-core/src/main/java/rx/operators/OperatorTimestamp.java
<del><path>rxjava-core/src/main/java/rx/operators/OperationTimestamp.java
<ide> */
<ide> package rx.operators;
<ide>
<del>import rx.Observable;
<del>import rx.Observable.OnSubscribeFunc;
<add>import rx.Observable.OperatorSubscription;
<add>import rx.Observer;
<ide> import rx.Scheduler;
<ide> import rx.util.Timestamped;
<del>import rx.util.functions.Func1;
<add>import rx.util.functions.Func2;
<ide>
<ide> /**
<ide> * Wraps each item emitted by a source Observable in a {@link Timestamped} object.
<ide> * <p>
<ide> * <img width="640" src="https://github.com/Netflix/RxJava/wiki/images/rx-operators/timestamp.png">
<ide> */
<del>public final class OperationTimestamp {
<add>public final class OperatorTimestamp<T> implements Func2<Observer<? super Timestamped<T>>, OperatorSubscription, Observer<? super T>> {
<add>
<add> private final Scheduler scheduler;
<add>
<add> public OperatorTimestamp(Scheduler scheduler) {
<add> this.scheduler = scheduler;
<add> }
<ide>
<ide> /**
<del> * Accepts a sequence and adds timestamps to each item in it.
<del> *
<del> * @param sequence
<del> * the input sequence.
<del> * @param <T>
<del> * the type of the input sequence.
<ide> * @return a sequence of timestamped values created by adding timestamps to each item in the input sequence.
<ide> */
<del> public static <T> OnSubscribeFunc<Timestamped<T>> timestamp(Observable<? extends T> sequence) {
<del> return OperationMap.map(sequence, new Func1<T, Timestamped<T>>() {
<add> @Override
<add> public Observer<? super T> call(final Observer<? super Timestamped<T>> o, OperatorSubscription os) {
<add> return new Observer<T>() {
<add>
<ide> @Override
<del> public Timestamped<T> call(T value) {
<del> return new Timestamped<T>(System.currentTimeMillis(), value);
<add> public void onCompleted() {
<add> o.onCompleted();
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> o.onError(e);
<ide> }
<del> });
<del> }
<ide>
<del> /**
<del> * Timestamp the source elements based on the timing provided by the scheduler.
<del> */
<del> public static <T> OnSubscribeFunc<Timestamped<T>> timestamp(Observable<? extends T> source, final Scheduler scheduler) {
<del> return OperationMap.map(source, new Func1<T, Timestamped<T>>() {
<ide> @Override
<del> public Timestamped<T> call(T value) {
<del> return new Timestamped<T>(scheduler.now(), value);
<add> public void onNext(T t) {
<add> o.onNext(new Timestamped<T>(scheduler.now(), t));
<ide> }
<del> });
<add>
<add> };
<ide> }
<add>
<ide> }
<ide><path>rxjava-core/src/perf/java/rx/operators/OperatorMapPerformance.java
<ide> public void call() {
<ide> /**
<ide> * Observable.from(1L).map((l) -> { l+1})
<ide> *
<del> * Run: 10 - 7,377,982 ops/sec
<del> * Run: 11 - 7,714,715 ops/sec
<del> * Run: 12 - 7,783,579 ops/sec
<del> * Run: 13 - 7,693,372 ops/sec
<del> * Run: 14 - 7,567,777 ops/sec
<add> * Run: 10 - 10,699,215 ops/sec
<add> * Run: 11 - 10,554,267 ops/sec
<add> * Run: 12 - 10,663,481 ops/sec
<add> * Run: 13 - 10,500,032 ops/sec
<add> * Run: 14 - 10,556,629 ops/sec
<ide> */
<ide> public long timeMapPlusOne() {
<ide>
<add><path>rxjava-core/src/test/java/rx/operators/OperatorCastTest.java
<del><path>rxjava-core/src/test/java/rx/operators/OperationCastTest.java
<ide> package rx.operators;
<ide>
<ide> import static org.mockito.Mockito.*;
<del>import static rx.operators.OperationCast.*;
<ide>
<ide> import org.junit.Test;
<ide>
<ide> import rx.Observable;
<ide> import rx.Observer;
<ide>
<del>public class OperationCastTest {
<add>public class OperatorCastTest {
<ide>
<ide> @Test
<ide> public void testCast() {
<ide> Observable<?> source = Observable.from(1, 2);
<del> Observable<Integer> observable = Observable.create(cast(source,
<del> Integer.class));
<add> Observable<Integer> observable = source.cast(Integer.class);
<ide>
<ide> @SuppressWarnings("unchecked")
<ide> Observer<Integer> aObserver = mock(Observer.class);
<ide> public void testCast() {
<ide> @Test
<ide> public void testCastWithWrongType() {
<ide> Observable<?> source = Observable.from(1, 2);
<del> Observable<Boolean> observable = Observable.create(cast(source,
<del> Boolean.class));
<add> Observable<Boolean> observable = source.cast(Boolean.class);
<ide>
<ide> @SuppressWarnings("unchecked")
<ide> Observer<Boolean> aObserver = mock(Observer.class);
<add><path>rxjava-core/src/test/java/rx/operators/OperatorMapTest.java
<del><path>rxjava-core/src/test/java/rx/operators/OperationMapTest.java
<ide> import static org.junit.Assert.*;
<ide> import static org.mockito.Matchers.*;
<ide> import static org.mockito.Mockito.*;
<del>import static rx.operators.OperationMap.*;
<add>import static rx.operators.OperatorMap.*;
<ide>
<ide> import java.util.HashMap;
<ide> import java.util.Map;
<ide> import rx.util.functions.Func1;
<ide> import rx.util.functions.Func2;
<ide>
<del>public class OperationMapTest {
<add>public class OperatorMapTest {
<ide>
<ide> @Mock
<ide> Observer<String> stringObserver;
<ide> public void testMap() {
<ide> Map<String, String> m2 = getMap("Two");
<ide> Observable<Map<String, String>> observable = Observable.from(m1, m2);
<ide>
<del> Observable<String> m = Observable.create(map(observable, new Func1<Map<String, String>, String>() {
<add> Observable<String> m = observable.bind(new OperatorMap<Map<String, String>, String>(new Func1<Map<String, String>, String>() {
<ide>
<ide> @Override
<ide> public String call(Map<String, String> map) {
<ide> public String call(Map<String, String> map) {
<ide> verify(stringObserver, times(1)).onCompleted();
<ide> }
<ide>
<del> @Test
<del> public void testMapWithIndex() {
<del> Observable<String> w = Observable.from("a", "b", "c");
<del> Observable<String> m = Observable.create(mapWithIndex(w, APPEND_INDEX));
<del> m.subscribe(stringObserver);
<del> InOrder inOrder = inOrder(stringObserver);
<del> inOrder.verify(stringObserver, times(1)).onNext("a0");
<del> inOrder.verify(stringObserver, times(1)).onNext("b1");
<del> inOrder.verify(stringObserver, times(1)).onNext("c2");
<del> inOrder.verify(stringObserver, times(1)).onCompleted();
<del> verify(stringObserver, never()).onError(any(Throwable.class));
<del> }
<del>
<del> @Test
<del> public void testMapWithIndexAndMultipleSubscribers() {
<del> Observable<String> w = Observable.from("a", "b", "c");
<del> Observable<String> m = Observable.create(mapWithIndex(w, APPEND_INDEX));
<del> m.subscribe(stringObserver);
<del> m.subscribe(stringObserver2);
<del> InOrder inOrder = inOrder(stringObserver);
<del> inOrder.verify(stringObserver, times(1)).onNext("a0");
<del> inOrder.verify(stringObserver, times(1)).onNext("b1");
<del> inOrder.verify(stringObserver, times(1)).onNext("c2");
<del> inOrder.verify(stringObserver, times(1)).onCompleted();
<del> verify(stringObserver, never()).onError(any(Throwable.class));
<del>
<del> InOrder inOrder2 = inOrder(stringObserver2);
<del> inOrder2.verify(stringObserver2, times(1)).onNext("a0");
<del> inOrder2.verify(stringObserver2, times(1)).onNext("b1");
<del> inOrder2.verify(stringObserver2, times(1)).onNext("c2");
<del> inOrder2.verify(stringObserver2, times(1)).onCompleted();
<del> verify(stringObserver2, never()).onError(any(Throwable.class));
<del> }
<del>
<ide> @Test
<ide> public void testMapMany() {
<ide> /* simulate a top-level async call which returns IDs */
<ide> public Observable<String> call(Integer id) {
<ide> }
<ide>
<ide> /* simulate kicking off the async call and performing a select on it to transform the data */
<del> return Observable.create(map(subObservable, new Func1<Map<String, String>, String>() {
<add> return subObservable.map(new Func1<Map<String, String>, String>() {
<ide> @Override
<ide> public String call(Map<String, String> map) {
<ide> return map.get("firstName");
<ide> }
<del> }));
<add> });
<ide> }
<ide>
<ide> });
<ide> public void testMapMany2() {
<ide>
<ide> @Override
<ide> public Observable<String> call(Observable<Map<String, String>> o) {
<del> return Observable.create(map(o, new Func1<Map<String, String>, String>() {
<add> return o.map(new Func1<Map<String, String>, String>() {
<ide>
<ide> @Override
<ide> public String call(Map<String, String> map) {
<ide> return map.get("firstName");
<ide> }
<del> }));
<add> });
<ide> }
<ide>
<ide> });
<ide> public String call(Map<String, String> map) {
<ide> @Test
<ide> public void testMapWithError() {
<ide> Observable<String> w = Observable.from("one", "fail", "two", "three", "fail");
<del> Observable<String> m = Observable.create(map(w, new Func1<String, String>() {
<add> Observable<String> m = w.bind(new OperatorMap<String, String>(new Func1<String, String>() {
<ide> @Override
<ide> public String call(String s) {
<ide> if ("fail".equals(s)) {
<ide> public void testMapContainingErrorWithSequenceThatDoesntUnsubscribe() {
<ide> Observable<String> w = Observable.from("one", "fail", "two", "three", "fail");
<ide> final AtomicInteger c1 = new AtomicInteger();
<ide> final AtomicInteger c2 = new AtomicInteger();
<del> Observable<String> m = Observable.create(map(w, new Func1<String, String>() {
<add> Observable<String> m = w.bind(new OperatorMap<String, String>(new Func1<String, String>() {
<ide> @Override
<ide> public String call(String s) {
<ide> if ("fail".equals(s))
<ide> public String call(String s) {
<ide>
<ide> @Test(expected = IllegalArgumentException.class)
<ide> public void testMapWithIssue417() {
<del> Observable.from(1).observeOn(Schedulers.threadPoolForComputation())
<add> Observable.from(1).observeOn(Schedulers.computation())
<ide> .map(new Func1<Integer, Integer>() {
<ide> public Integer call(Integer arg0) {
<ide> throw new IllegalArgumentException("any error");
<ide> public void testMapWithErrorInFuncAndThreadPoolScheduler() throws InterruptedExc
<ide> // If map does not handle it, the error will disappear.
<ide> // so map needs to handle the error by itself.
<ide> Observable<String> m = Observable.from("one")
<del> .observeOn(Schedulers.threadPoolForComputation())
<add> .observeOn(Schedulers.computation())
<ide> .map(new Func1<String, String>() {
<ide> public String call(String arg0) {
<ide> throw new IllegalArgumentException("any error");
<add><path>rxjava-core/src/test/java/rx/operators/OperatorTimestampTest.java
<del><path>rxjava-core/src/test/java/rx/operators/OperationTimestampTest.java
<ide> import rx.subjects.PublishSubject;
<ide> import rx.util.Timestamped;
<ide>
<del>public class OperationTimestampTest {
<add>public class OperatorTimestampTest {
<ide> @Mock
<ide> Observer<Object> observer;
<ide> | 10 |
PHP | PHP | add store() and fix cookie expiration/overwrite | a9e1d0858d1e857e67dc88847e96fa80b96687a6 | <ide><path>src/Http/Cookie/CookieCollection.php
<ide> namespace Cake\Http\Cookie;
<ide>
<ide> use ArrayIterator;
<add>use Cake\Http\Client\Response as ClientResponse;
<ide> use Countable;
<ide> use DateTime;
<ide> use InvalidArgumentException;
<ide> public function __construct(array $cookies = [])
<ide> {
<ide> $this->checkCookies($cookies);
<ide> foreach ($cookies as $cookie) {
<del> $name = $cookie->getName();
<del> $key = mb_strtolower($name);
<del> $this->cookies[$key] = $cookie;
<add> $this->cookies[$cookie->getId()] = $cookie;
<ide> }
<ide> }
<ide>
<ide> public function count()
<ide> /**
<ide> * Add a cookie and get an updated collection.
<ide> *
<del> * Cookie names do not have to be unique in a collection, but
<del> * having duplicate cookie names will change how get() behaves.
<add> * Cookies are stored by id. This means that there can be duplicate
<add> * cookies if a cookie collection is used for cookies across multiple
<add> * domains. This can impact how get(), has() and remove() behave.
<ide> *
<ide> * @param \Cake\Http\Cookie\CookieInterface $cookie Cookie instance to add.
<ide> * @return static
<ide> */
<ide> public function add(CookieInterface $cookie)
<ide> {
<ide> $new = clone $this;
<del> $new->cookies[] = $cookie;
<add> $new->cookies[$cookie->getId()] = $cookie;
<ide>
<ide> return $new;
<ide> }
<ide> public function addFromResponse(ResponseInterface $response, RequestInterface $r
<ide>
<ide> $header = $response->getHeader('Set-Cookie');
<ide> $cookies = $this->parseSetCookieHeader($header);
<add> $cookies = $this->setRequestDefaults($cookies, $host, $path);
<ide> $new = clone $this;
<add> foreach ($cookies as $cookie) {
<add> $new->cookies[$cookie->getId()] = $cookie;
<add> }
<add> $new->removeExpiredCookies($host, $path);
<add>
<add> return $new;
<add> }
<add>
<add> /**
<add> * Apply path and host to the set of cookies if they are not set.
<add> *
<add> * @param array $cookies An array of cookies to update.
<add> * @param string $host The host to set.
<add> * @param string $path The path to set.
<add> * @return array An array of updated cookies.
<add> */
<add> protected function setRequestDefaults(array $cookies, $host, $path)
<add> {
<add> $out = [];
<ide> foreach ($cookies as $name => $cookie) {
<del> // Apply path/domain from request if the cookie
<del> // didn't have one.
<ide> if (!$cookie->getDomain()) {
<ide> $cookie = $cookie->withDomain($host);
<ide> }
<ide> if (!$cookie->getPath()) {
<ide> $cookie = $cookie->withPath($path);
<ide> }
<del>
<del> $expires = $cookie->getExpiry();
<del> // Don't store expired cookies
<del> if ($expires && $expires <= time()) {
<del> continue;
<del> }
<del> $new->cookies[] = $cookie;
<add> $out[] = $cookie;
<ide> }
<ide>
<del> return $new;
<add> return $out;
<ide> }
<ide>
<ide> /**
<ide> protected function parseSetCookieHeader($values)
<ide>
<ide> return $cookies;
<ide> }
<add>
<add> /**
<add> * Remove expired cookies from the collection.
<add> *
<add> * @param string $host The host to check for expired cookies on.
<add> * @param string $path The path to check for expired cookies on.
<add> * @return void
<add> */
<add> private function removeExpiredCookies($host, $path)
<add> {
<add> $time = time();
<add> $hostPattern = '/' . preg_quote($host, '/') . '$/';
<add>
<add> foreach ($this->cookies as $i => $cookie) {
<add> $expires = $cookie->getExpiry();
<add> $expired = ($expires > 0 && $expires < $time);
<add>
<add> $pathMatches = strpos($path, $cookie->getPath()) === 0;
<add> $hostMatches = preg_match($hostPattern, $cookie->getDomain());
<add> if ($pathMatches && $hostMatches && $expired) {
<add> unset($this->cookies[$i]);
<add> }
<add> }
<add> }
<add>
<add> /**
<add> * Store the cookies contained in a response
<add> *
<add> * This method operates on the collection in a mutable way for backwards
<add> * compatibility reasons. This method should not be used and is only
<add> * provided for backwards compatibility.
<add> *
<add> * @param \Cake\Http\Client\Response $response The response to read cookies from
<add> * @param string $url The request URL used for default host/path values.
<add> * @return void
<add> * @deprecated 3.5.0 Will be removed in 4.0.0. Use `addFromResponse()` instead.
<add> */
<add> public function store(ClientResponse $response, $url)
<add> {
<add> $host = parse_url($url, PHP_URL_HOST);
<add> $path = parse_url($url, PHP_URL_PATH);
<add> $path = $path ?: '/';
<add>
<add> $header = $response->getHeader('Set-Cookie');
<add> $cookies = $this->parseSetCookieHeader($header);
<add> $cookies = $this->setRequestDefaults($cookies, $host, $path);
<add> foreach ($cookies as $cookie) {
<add> $this->cookies[] = $cookie;
<add> }
<add> $this->removeExpiredCookies($host, $path);
<add> }
<add>
<add> /**
<add> * Get all cookie data as arrays.
<add> *
<add> * This method should not be used and is only provided for backwards compatibility.
<add> *
<add> * @return array
<add> * @deprecated 3.5.0 Will be removed in 4.0.0
<add> */
<add> public function getAll()
<add> {
<add> $out = [];
<add> foreach ($this->cookies as $cookie) {
<add> $out[] = [
<add> 'name' => $cookie->getName(),
<add> 'value' => $cookie->getValue(),
<add> 'path' => $cookie->getPath(),
<add> 'domain' => $cookie->getDomain(),
<add> 'secure' => $cookie->isSecure(),
<add> 'httponly' => $cookie->isHttpOnly(),
<add> 'expires' => $cookie->getExpiry()
<add> ];
<add> }
<add>
<add> return $out;
<add> }
<ide> }
<ide><path>tests/TestCase/Http/Cookie/CookieCollectionTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Http\Cookie;
<ide>
<add>use Cake\Http\Client\Response as ClientResponse;
<ide> use Cake\Http\Cookie\Cookie;
<ide> use Cake\Http\Cookie\CookieCollection;
<ide> use Cake\Http\Response;
<ide> public function testAdd()
<ide> public function testAddDuplicates()
<ide> {
<ide> $remember = new Cookie('remember_me', 'yes');
<del> $rememberNo = new Cookie('remember_me', 'no');
<add> $rememberNo = new Cookie('remember_me', 'no', null, '/path2');
<add> $this->assertNotEquals($remember->getId(), $rememberNo->getId(), 'Cookies should have different ids');
<add>
<ide> $collection = new CookieCollection([]);
<ide> $new = $collection->add($remember)->add($rememberNo);
<ide>
<del> $this->assertCount(2, $new);
<add> $this->assertCount(2, $new, 'Cookies with different ids create duplicates.');
<ide> $this->assertNotSame($new, $collection);
<ide> $this->assertSame($remember, $new->get('remember_me'), 'get() fetches first cookie');
<ide> }
<ide> public function testAddFromResponseIgnoreExpired()
<ide> $this->assertFalse($new->has('expired'), 'Should drop expired cookies');
<ide> }
<ide>
<add> /**
<add> * Test adding cookies from a response removes existing cookies if
<add> * the new response marks them as expired.
<add> *
<add> * @return void
<add> */
<add> public function testAddFromResponseRemoveExpired()
<add> {
<add> $collection = new CookieCollection([
<add> new Cookie('expired', 'not yet', null, '/', 'example.com')
<add> ]);
<add> $request = new ServerRequest([
<add> 'url' => '/app',
<add> 'environment' => [
<add> 'HTTP_HOST' => 'example.com'
<add> ]
<add> ]);
<add> $response = (new Response())
<add> ->withAddedHeader('Set-Cookie', 'test=value')
<add> ->withAddedHeader('Set-Cookie', 'expired=soon; Expires=Wed, 09-Jun-2012 10:18:14 GMT; Path=/;');
<add> $new = $collection->addFromResponse($response, $request);
<add> $this->assertFalse($new->has('expired'), 'Should drop expired cookies');
<add> }
<add>
<add> /**
<add> * Test adding cookies from responses updates cookie values.
<add> *
<add> * @return void
<add> */
<add> public function testAddFromResponseUpdateExisting()
<add> {
<add> $collection = new CookieCollection([
<add> new Cookie('key', 'old value', null, '/', 'example.com')
<add> ]);
<add> $request = new ServerRequest([
<add> 'url' => '/',
<add> 'environment' => [
<add> 'HTTP_HOST' => 'example.com'
<add> ]
<add> ]);
<add> $response = (new Response())->withAddedHeader('Set-Cookie', 'key=new value');
<add> $new = $collection->addFromResponse($response, $request);
<add> $this->assertTrue($new->has('key'));
<add> $this->assertSame('new value', $new->get('key')->getValue());
<add> }
<add>
<ide> /**
<ide> * Test adding cookies from the collection to request.
<ide> *
<ide> public function testAddToRequestSecureCrumb()
<ide> $request = $collection->addToRequest($request);
<ide> $this->assertSame(['public' => 'b'], $request->getCookieParams());
<ide> }
<add>
<add> /**
<add> * Test that store() provides backwards compat behavior.
<add> *
<add> * @return void
<add> */
<add> public function testStoreCompatibility()
<add> {
<add> $collection = new CookieCollection();
<add> $response = (new ClientResponse())
<add> ->withAddedHeader('Set-Cookie', 'test=value')
<add> ->withAddedHeader('Set-Cookie', 'expired=soon; Expires=Wed, 09-Jun-2012 10:18:14 GMT; Path=/;');
<add> $result = $collection->store($response, 'http://example.com/blog');
<add>
<add> $this->assertNull($result);
<add> $this->assertCount(1, $collection, 'Should store 1 cookie');
<add> $this->assertTrue($collection->has('test'));
<add> $this->assertFalse($collection->has('expired'));
<add> }
<add>
<add> /**
<add> * Test that get() provides backwards compat behavior.
<add> *
<add> * When the parameter is a string that looks like a URL
<add> *
<add> * @return void
<add> */
<add> public function testGetBackwardsCompatibility()
<add> {
<add> $this->markTestIncomplete();
<add> }
<add>
<add> /**
<add> * Test that getAll() provides backwards compat behavior.
<add> *
<add> * @return void
<add> */
<add> public function testGetAllBackwardsCompatibility()
<add> {
<add> $expires = new DateTime('-2 seconds');
<add> $cookies = [
<add> new Cookie('test', 'value', $expires, '/api', 'example.com', true, true),
<add> new Cookie('test_two', 'value_two', null, '/blog', 'blog.example.com', true, true),
<add> ];
<add> $collection = new CookieCollection($cookies);
<add> $expected = [
<add> [
<add> 'name' => 'test',
<add> 'value' => 'value',
<add> 'path' => '/api',
<add> 'domain' => 'example.com',
<add> 'secure' => true,
<add> 'httponly' => true,
<add> 'expires' => $expires->format('U'),
<add> ],
<add> [
<add> 'name' => 'test_two',
<add> 'value' => 'value_two',
<add> 'path' => '/blog',
<add> 'domain' => 'blog.example.com',
<add> 'secure' => true,
<add> 'httponly' => true,
<add> 'expires' => 0
<add> ],
<add> ];
<add> $this->assertEquals($expected, $collection->getAll());
<add> }
<ide> } | 2 |
Ruby | Ruby | use inject rather than lasgn | 12f67a70697212b55cde66f89ccd4caf0e9f4dad | <ide><path>activerecord/lib/active_record/associations/class_methods/join_dependency/join_association.rb
<ide> def join_target_table(relation, *conditions)
<ide> # If the target table is an STI model then we must be sure to only include records of
<ide> # its type and its sub-types.
<ide> unless active_record.descends_from_active_record?
<del> sti_column = target_table[active_record.inheritance_column]
<del>
<add> sti_column = target_table[active_record.inheritance_column]
<add> subclasses = active_record.descendants
<ide> sti_condition = sti_column.eq(active_record.sti_name)
<del> active_record.descendants.each do |subclass|
<del> sti_condition = sti_condition.or(sti_column.eq(subclass.sti_name))
<del> end
<ide>
<del> conditions << sti_condition
<add> conditions << subclasses.inject(sti_condition) { |attr,subclass|
<add> attr.or(sti_column.eq(subclass.sti_name))
<add> }
<ide> end
<ide>
<ide> # If the reflection has conditions, add them | 1 |
Text | Text | use relative path to create the index | 4d7b88da36054cb37692be8dddeb03d977b8aeaa | <ide><path>CONTRIBUTING.md
<ide>
<ide> ## 1. Index
<ide>
<del>1. [Index](https://github.com/gero3/three.js/blob/patch-6/CONTRIBUTING.md#2-Index)
<del>2. [Having a problem](https://github.com/gero3/three.js/blob/patch-6/CONTRIBUTING.md#2-having-a-problem)
<del> * [How to report](https://github.com/gero3/three.js/blob/patch-6/CONTRIBUTING.md#how-to-report)
<del> * [Migrating problems](https://github.com/gero3/three.js/blob/patch-6/CONTRIBUTING.md#migrating-problems)
<add>1. [Index](#2-Index)
<add>2. [Having a problem](#2-having-a-problem)
<add> * [How to report](#how-to-report)
<add> * [Migrating problems](#migrating-problems)
<ide>
<ide> ## 2. Having a problem
<ide> | 1 |
Go | Go | fix inconsistency in ip address parsing errors | a30fd7a962f8486df0d0dbd3334c7621d22c1aec | <ide><path>opts/ip.go
<ide> func NewIpOpt(ref *net.IP, defaultVal string) *IpOpt {
<ide> func (o *IpOpt) Set(val string) error {
<ide> ip := net.ParseIP(val)
<ide> if ip == nil {
<del> return fmt.Errorf("incorrect IP format")
<add> return fmt.Errorf("%s is not an ip address", val)
<ide> }
<ide> (*o.IP) = net.ParseIP(val)
<ide> return nil | 1 |
Javascript | Javascript | remove duplicate @param annotation | c995b09b77696ebb4b7806f681ad616705fb4a49 | <ide><path>src/ng/directive/form.js
<ide> function FormController(element, attrs, $scope, $animate) {
<ide> </file>
<ide> </example>
<ide> *
<del> * @param {string=} name Name of the form. If specified, the form controller will be published into
<del> * related scope, under this name.
<ide> */
<ide> var formDirectiveFactory = function(isNgForm) {
<ide> return ['$timeout', function($timeout) { | 1 |
PHP | PHP | bring the pluralization rules back | b2d997dcfb73347670e6261f6d6cae3980aa9181 | <ide><path>src/Illuminate/Translation/MessageSelector.php
<ide> class MessageSelector
<ide> *
<ide> * @param string $line
<ide> * @param int $number
<add> * @param string $locale
<ide> * @return mixed
<ide> */
<del> public function choose($line, $number)
<add> public function choose($line, $number, $locale)
<ide> {
<ide> $segments = explode('|', $line);
<ide>
<ide> public function choose($line, $number)
<ide>
<ide> $segments = $this->stripConditions($segments);
<ide>
<del> return count($segments) == 1 || $number == 1
<del> ? $segments[0] : $segments[1];
<add> $pluralIndex = $this->getPluralIndex($locale, $number);
<add>
<add> if (count($segments) == 1 || ! isset($segments[$pluralIndex])) {
<add> return $segments[0];
<add> }
<add>
<add> return $segments[$pluralIndex];
<ide> }
<ide>
<ide> /**
<ide> private function stripConditions($segments)
<ide> return preg_replace('/^[\{\[]([^\[\]\{\}]*)[\}\]]/', '', $part);
<ide> })->all();
<ide> }
<add>
<add> /**
<add> * Get the index to use for pluralization.
<add> *
<add> * The plural rules are derived from code of the Zend Framework (2010-09-25), which
<add> * is subject to the new BSD license (http://framework.zend.com/license/new-bsd).
<add> * Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
<add> *
<add> * @param string $locale
<add> * @param int $number
<add> *
<add> * @return int
<add> */
<add> public function getPluralIndex($locale, $number){
<add> switch ($locale) {
<add> case 'az':
<add> case 'bo':
<add> case 'dz':
<add> case 'id':
<add> case 'ja':
<add> case 'jv':
<add> case 'ka':
<add> case 'km':
<add> case 'kn':
<add> case 'ko':
<add> case 'ms':
<add> case 'th':
<add> case 'tr':
<add> case 'vi':
<add> case 'zh':
<add> return 0;
<add> break;
<add> case 'af':
<add> case 'bn':
<add> case 'bg':
<add> case 'ca':
<add> case 'da':
<add> case 'de':
<add> case 'el':
<add> case 'en':
<add> case 'eo':
<add> case 'es':
<add> case 'et':
<add> case 'eu':
<add> case 'fa':
<add> case 'fi':
<add> case 'fo':
<add> case 'fur':
<add> case 'fy':
<add> case 'gl':
<add> case 'gu':
<add> case 'ha':
<add> case 'he':
<add> case 'hu':
<add> case 'is':
<add> case 'it':
<add> case 'ku':
<add> case 'lb':
<add> case 'ml':
<add> case 'mn':
<add> case 'mr':
<add> case 'nah':
<add> case 'nb':
<add> case 'ne':
<add> case 'nl':
<add> case 'nn':
<add> case 'no':
<add> case 'om':
<add> case 'or':
<add> case 'pa':
<add> case 'pap':
<add> case 'ps':
<add> case 'pt':
<add> case 'so':
<add> case 'sq':
<add> case 'sv':
<add> case 'sw':
<add> case 'ta':
<add> case 'te':
<add> case 'tk':
<add> case 'ur':
<add> case 'zu':
<add> return ($number == 1) ? 0 : 1;
<add> case 'am':
<add> case 'bh':
<add> case 'fil':
<add> case 'fr':
<add> case 'gun':
<add> case 'hi':
<add> case 'hy':
<add> case 'ln':
<add> case 'mg':
<add> case 'nso':
<add> case 'xbr':
<add> case 'ti':
<add> case 'wa':
<add> return (($number == 0) || ($number == 1)) ? 0 : 1;
<add> case 'be':
<add> case 'bs':
<add> case 'hr':
<add> case 'ru':
<add> case 'sr':
<add> case 'uk':
<add> return (($number % 10 == 1) && ($number % 100 != 11)) ? 0 : ((($number % 10 >= 2) && ($number % 10 <= 4) && (($number % 100 < 10) || ($number % 100 >= 20))) ? 1 : 2);
<add> case 'cs':
<add> case 'sk':
<add> return ($number == 1) ? 0 : ((($number >= 2) && ($number <= 4)) ? 1 : 2);
<add> case 'ga':
<add> return ($number == 1) ? 0 : (($number == 2) ? 1 : 2);
<add> case 'lt':
<add> return (($number % 10 == 1) && ($number % 100 != 11)) ? 0 : ((($number % 10 >= 2) && (($number % 100 < 10) || ($number % 100 >= 20))) ? 1 : 2);
<add> case 'sl':
<add> return ($number % 100 == 1) ? 0 : (($number % 100 == 2) ? 1 : ((($number % 100 == 3) || ($number % 100 == 4)) ? 2 : 3));
<add> case 'mk':
<add> return ($number % 10 == 1) ? 0 : 1;
<add> case 'mt':
<add> return ($number == 1) ? 0 : ((($number == 0) || (($number % 100 > 1) && ($number % 100 < 11))) ? 1 : ((($number % 100 > 10) && ($number % 100 < 20)) ? 2 : 3));
<add> case 'lv':
<add> return ($number == 0) ? 0 : ((($number % 10 == 1) && ($number % 100 != 11)) ? 1 : 2);
<add> case 'pl':
<add> return ($number == 1) ? 0 : ((($number % 10 >= 2) && ($number % 10 <= 4) && (($number % 100 < 12) || ($number % 100 > 14))) ? 1 : 2);
<add> case 'cy':
<add> return ($number == 1) ? 0 : (($number == 2) ? 1 : ((($number == 8) || ($number == 11)) ? 2 : 3));
<add> case 'ro':
<add> return ($number == 1) ? 0 : ((($number == 0) || (($number % 100 > 0) && ($number % 100 < 20))) ? 1 : 2);
<add> case 'ar':
<add> return ($number == 0) ? 0 : (($number == 1) ? 1 : (($number == 2) ? 2 : ((($number % 100 >= 3) && ($number % 100 <= 10)) ? 3 : ((($number % 100 >= 11) && ($number % 100 <= 99)) ? 4 : 5))));
<add> default:
<add> return 0;
<add> }
<add> }
<ide> }
<ide><path>src/Illuminate/Translation/Translator.php
<ide> public function choice($key, $number, array $replace = [], $locale = null)
<ide> $replace['count'] = $number;
<ide>
<ide> return $this->makeReplacements(
<del> $this->getSelector()->choose($line, $number), $replace
<add> $this->getSelector()->choose($line, $number, $locale), $replace
<ide> );
<ide> }
<ide>
<ide><path>tests/Translation/TranslationMessageSelectorTest.php
<ide> public function testChoose($expected, $id, $number)
<ide> {
<ide> $selector = new MessageSelector();
<ide>
<del> $this->assertEquals($expected, $selector->choose($id, $number));
<add> $this->assertEquals($expected, $selector->choose($id, $number, 'en'));
<ide> }
<ide>
<ide> public function chooseTestData()
<ide><path>tests/Translation/TranslationTranslatorTest.php
<ide> public function testChoiceMethodProperlyLoadsAndRetrievesItem()
<ide> $t = $this->getMockBuilder('Illuminate\Translation\Translator')->setMethods(['get'])->setConstructorArgs([$this->getLoader(), 'en'])->getMock();
<ide> $t->expects($this->once())->method('get')->with($this->equalTo('foo'), $this->equalTo(['replace']), $this->equalTo('en'))->will($this->returnValue('line'));
<ide> $t->setSelector($selector = m::mock('Illuminate\Translation\MessageSelector'));
<del> $selector->shouldReceive('choose')->once()->with('line', 10)->andReturn('choiced');
<add> $selector->shouldReceive('choose')->once()->with('line', 10, 'en')->andReturn('choiced');
<ide>
<ide> $t->choice('foo', 10, ['replace']);
<ide> }
<ide> public function testChoiceMethodProperlyCountsCollectionsAndLoadsAndRetrievesIte
<ide> $t = $this->getMockBuilder('Illuminate\Translation\Translator')->setMethods(['get'])->setConstructorArgs([$this->getLoader(), 'en'])->getMock();
<ide> $t->expects($this->exactly(2))->method('get')->with($this->equalTo('foo'), $this->equalTo(['replace']), $this->equalTo('en'))->will($this->returnValue('line'));
<ide> $t->setSelector($selector = m::mock('Illuminate\Translation\MessageSelector'));
<del> $selector->shouldReceive('choose')->twice()->with('line', 3)->andReturn('choiced');
<add> $selector->shouldReceive('choose')->twice()->with('line', 3, 'en')->andReturn('choiced');
<ide>
<ide> $values = ['foo', 'bar', 'baz'];
<ide> $t->choice('foo', $values, ['replace']); | 4 |
Python | Python | extract api versions per resource | 83e6f51d03ad9010093f44b29491a84cabb09858 | <ide><path>libcloud/compute/drivers/azure_arm.py
<ide>
<ide>
<ide> RESOURCE_API_VERSION = "2016-04-30-preview"
<add>DISK_API_VERSION = "2018-06-01"
<add>IMAGES_API_VERSION = "2015-06-15"
<add>INSTANCE_VIEW_API_VERSION = "2015-06-15"
<add>IP_API_VERSION = "2019-06-01"
<add>LOCATIONS_API_VERSION = "2015-01-01"
<add>NIC_API_VERSION = "2018-06-01"
<add>NSG_API_VERSION = "2016-09-01"
<add>RATECARD_API_VERSION = "2016-08-31-preview"
<add>RESOURCE_GROUP_API_VERSION = "2016-09-01"
<add>SNAPSHOT_API_VERSION = "2016-04-30-preview"
<add>STORAGE_ACCOUNT_API_VERSION = "2015-05-01-preview"
<add>SUBNET_API_VERSION = "2015-06-15"
<add>TAG_API_VERSION = "2018-06-01"
<add>VIRTUAL_NETWORK_API_VERSION = "2018-06-01"
<add>VM_API_VERSION = "2021-11-01"
<add>VM_EXTENSION_API_VERSION = "2015-06-15"
<add>VM_SIZE_API_VERSION = "2015-06-15" # this API is deprecated
<ide>
<ide>
<ide> class AzureImage(NodeImage):
<ide> def list_locations(self):
<ide> action = "/subscriptions/%s/providers/Microsoft.Compute" % (
<ide> self.subscription_id
<ide> )
<del> r = self.connection.request(action, params={"api-version": "2015-01-01"})
<add> r = self.connection.request(action, params={"api-version": LOCATIONS_API_VERSION})
<ide>
<ide> for rt in r.object["resourceTypes"]:
<ide> if rt["resourceType"] == "virtualMachines":
<ide> def list_sizes(self, location=None):
<ide> "/subscriptions/%s/providers/Microsoft"
<ide> ".Compute/locations/%s/vmSizes" % (self.subscription_id, location.id)
<ide> )
<del> r = self.connection.request(action, params={"api-version": "2015-06-15"})
<add> r = self.connection.request(action, params={"api-version": VM_SIZE_API_VERSION})
<ide> return [self._to_node_size(d) for d in r.object["value"]]
<ide>
<ide> def list_images(
<ide> def list_nodes(
<ide> "/subscriptions/%s/providers/Microsoft.Compute/"
<ide> "virtualMachines" % (self.subscription_id)
<ide> )
<del> r = self.connection.request(action, params={"api-version": "2015-06-15"})
<add> r = self.connection.request(action, params={"api-version": VM_API_VERSION})
<ide> return [
<ide> self._to_node(
<ide> n, fetch_nic=ex_fetch_nic, fetch_power_state=ex_fetch_power_state
<ide> def create_node(
<ide>
<ide> r = self.connection.request(
<ide> target,
<del> params={"api-version": "2021-07-01"},
<add> params={"api-version": VM_API_VERSION},
<ide> data=data,
<ide> method="PUT",
<ide> )
<ide> def reboot_node(self, node):
<ide> target = "%s/restart" % node.id
<ide> try:
<ide> self.connection.request(
<del> target, params={"api-version": RESOURCE_API_VERSION}, method="POST"
<add> target, params={"api-version": VM_API_VERSION}, method="POST"
<ide> )
<ide> return True
<ide> except BaseHTTPError as h:
<ide> def destroy_node(
<ide> # failure.
<ide> try:
<ide> self.connection.request(
<del> node.id, params={"api-version": "2015-06-15"}, method="DELETE"
<add> node.id, params={"api-version": VM_API_VERSION}, method="DELETE"
<ide> )
<ide> except BaseHTTPError as h:
<ide> if h.code == 202:
<ide> def destroy_node(
<ide> try:
<ide> time.sleep(ex_poll_wait)
<ide> self.connection.request(
<del> node.id, params={"api-version": RESOURCE_API_VERSION}
<add> node.id, params={"api-version": VM_API_VERSION}
<ide> )
<ide> retries -= 1
<ide> except BaseHTTPError as h:
<ide> def create_volume(
<ide> response = self.connection.request(
<ide> action,
<ide> method="PUT",
<del> params={"api-version": RESOURCE_API_VERSION},
<add> params={"api-version": DISK_API_VERSION},
<ide> data=data,
<ide> )
<ide>
<ide> def list_volumes(self, ex_resource_group=None):
<ide> )
<ide>
<ide> response = self.connection.request(
<del> action, method="GET", params={"api-version": RESOURCE_API_VERSION}
<add> action, method="GET", params={"api-version": DISK_API_VERSION}
<ide> )
<ide> return [self._to_volume(volume) for volume in response.object["value"]]
<ide>
<ide> def attach_volume(
<ide> self.connection.request(
<ide> action,
<ide> method="PUT",
<del> params={"api-version": RESOURCE_API_VERSION},
<add> params={"api-version": VM_API_VERSION},
<ide> data={
<ide> "properties": {"storageProfile": {"dataDisks": disks}},
<ide> "location": location,
<ide> def ex_resize_volume(self, volume, new_size, resource_group):
<ide> }
<ide>
<ide> response = self.connection.request(
<del> action, method="PUT", params={"api-version": "2018-06-01"}, data=data
<add> action, method="PUT", params={"api-version": DISK_API_VERSION}, data=data
<ide> )
<ide>
<ide> return self._to_volume(
<ide> def detach_volume(self, volume, ex_node=None):
<ide> self.connection.request(
<ide> action,
<ide> method="PUT",
<del> params={"api-version": RESOURCE_API_VERSION},
<add> params={"api-version": VM_API_VERSION},
<ide> data={
<ide> "properties": {"storageProfile": {"dataDisks": disks}},
<ide> "location": location,
<ide> def create_volume_snapshot(
<ide> snapshot_id,
<ide> method="PUT",
<ide> data=data,
<del> params={"api-version": RESOURCE_API_VERSION},
<add> params={"api-version": SNAPSHOT_API_VERSION},
<ide> )
<ide>
<ide> return self._to_snapshot(
<ide> def list_snapshots(self, ex_resource_group=None):
<ide> )
<ide>
<ide> response = self.connection.request(
<del> action, method="GET", params={"api-version": RESOURCE_API_VERSION}
<add> action, method="GET", params={"api-version": SNAPSHOT_API_VERSION}
<ide> )
<ide> return [self._to_snapshot(snap) for snap in response.object["value"]]
<ide>
<ide> def ex_get_ratecard(
<ide> self.subscription_id,
<ide> )
<ide> params = {
<del> "api-version": "2016-08-31-preview",
<add> "api-version": RATECARD_API_VERSION,
<ide> "$filter": "OfferDurableId eq 'MS-AZR-%s' and "
<ide> "Currency eq '%s' and "
<ide> "Locale eq '%s' and "
<ide> def ex_list_publishers(self, location=None):
<ide> "/subscriptions/%s/providers/Microsoft.Compute/"
<ide> "locations/%s/publishers" % (self.subscription_id, location.id)
<ide> )
<del> r = self.connection.request(action, params={"api-version": "2015-06-15"})
<add> r = self.connection.request(action, params={"api-version": IMAGES_API_VERSION})
<ide> return [(p["id"], p["name"]) for p in r.object]
<ide>
<ide> def ex_list_offers(self, publisher):
<ide> def ex_list_offers(self, publisher):
<ide> """
<ide>
<ide> action = "%s/artifacttypes/vmimage/offers" % (publisher)
<del> r = self.connection.request(action, params={"api-version": "2015-06-15"})
<add> r = self.connection.request(action, params={"api-version": IMAGES_API_VERSION})
<ide> return [(p["id"], p["name"]) for p in r.object]
<ide>
<ide> def ex_list_skus(self, offer):
<ide> def ex_list_skus(self, offer):
<ide> """
<ide>
<ide> action = "%s/skus" % offer
<del> r = self.connection.request(action, params={"api-version": "2015-06-15"})
<add> r = self.connection.request(action, params={"api-version": IMAGES_API_VERSION})
<ide> return [(sku["id"], sku["name"]) for sku in r.object]
<ide>
<ide> def ex_list_image_versions(self, sku):
<ide> def ex_list_image_versions(self, sku):
<ide> """
<ide>
<ide> action = "%s/versions" % (sku)
<del> r = self.connection.request(action, params={"api-version": "2015-06-15"})
<add> r = self.connection.request(action, params={"api-version": IMAGES_API_VERSION})
<ide> return [(img["id"], img["name"]) for img in r.object]
<ide>
<ide> def ex_list_resource_groups(self):
<ide> def ex_list_resource_groups(self):
<ide> """
<ide>
<ide> action = "/subscriptions/%s/resourceGroups/" % (self.subscription_id)
<del> r = self.connection.request(action, params={"api-version": "2016-09-01"})
<add> r = self.connection.request(action, params={"api-version": RESOURCE_GROUP_API_VERSION})
<ide> return [
<ide> AzureResourceGroup(
<ide> grp["id"], grp["name"], grp["location"], grp["properties"]
<ide> def ex_list_network_security_groups(self, resource_group):
<ide> "Microsoft.Network/networkSecurityGroups"
<ide> % (self.subscription_id, resource_group)
<ide> )
<del> r = self.connection.request(action, params={"api-version": "2015-06-15"})
<add> r = self.connection.request(action, params={"api-version": NSG_API_VERSION})
<ide> return [
<ide> AzureNetworkSecurityGroup(
<ide> net["id"], net["name"], net["location"], net["properties"]
<ide> def ex_create_network_security_group(self, name, resource_group, location=None):
<ide> "location": location.id,
<ide> }
<ide> self.connection.request(
<del> target, params={"api-version": "2016-09-01"}, data=data, method="PUT"
<add> target, params={"api-version": NSG_API_VERSION}, data=data, method="PUT"
<ide> )
<ide>
<ide> def ex_delete_network_security_group(self, name, resource_group, location=None):
<ide> def ex_delete_network_security_group(self, name, resource_group, location=None):
<ide> "location": location.id,
<ide> }
<ide> self.connection.request(
<del> target, params={"api-version": "2016-09-01"}, data=data, method="DELETE"
<add> target, params={"api-version": NSG_API_VERSION}, data=data, method="DELETE"
<ide> )
<ide>
<ide> def ex_list_networks(self):
<ide> def ex_list_networks(self):
<ide> action = "/subscriptions/%s/providers/" "Microsoft.Network/virtualnetworks" % (
<ide> self.subscription_id
<ide> )
<del> r = self.connection.request(action, params={"api-version": "2015-06-15"})
<add> r = self.connection.request(action, params={"api-version": VIRTUAL_NETWORK_API_VERSION})
<ide> return [
<ide> AzureNetwork(net["id"], net["name"], net["location"], net["properties"])
<ide> for net in r.object["value"]
<ide> def ex_list_subnets(self, network):
<ide> """
<ide>
<ide> action = "%s/subnets" % (network.id)
<del> r = self.connection.request(action, params={"api-version": "2015-06-15"})
<add> r = self.connection.request(action, params={"api-version": SUBNET_API_VERSION})
<ide> return [
<ide> AzureSubnet(net["id"], net["name"], net["properties"])
<ide> for net in r.object["value"]
<ide> def ex_list_nics(self, resource_group=None):
<ide> "/Microsoft.Network/networkInterfaces"
<ide> % (self.subscription_id, resource_group)
<ide> )
<del> r = self.connection.request(action, params={"api-version": "2015-06-15"})
<add> r = self.connection.request(action, params={"api-version": NIC_API_VERSION})
<ide> return [self._to_nic(net) for net in r.object["value"]]
<ide>
<ide> def ex_get_nic(self, id):
<ide> def ex_get_nic(self, id):
<ide> :rtype: :class:`.AzureNic`
<ide> """
<ide>
<del> r = self.connection.request(id, params={"api-version": "2015-06-15"})
<add> r = self.connection.request(id, params={"api-version": NIC_API_VERSION})
<ide> return self._to_nic(r.object)
<ide>
<ide> def ex_update_nic_properties(self, network_interface, resource_group, properties):
<ide> def ex_update_nic_properties(self, network_interface, resource_group, properties
<ide> }
<ide>
<ide> r = self.connection.request(
<del> target, params={"api-version": "2018-06-01"}, data=data, method="PUT"
<add> target, params={"api-version": NIC_API_VERSION}, data=data, method="PUT"
<ide> )
<ide> return AzureNic(
<ide> r.object["id"],
<ide> def ex_update_network_profile_of_node(self, node, network_profile):
<ide> self.connection.request(
<ide> action,
<ide> method="PUT",
<del> params={"api-version": "2018-06-01"},
<add> params={"api-version": VM_API_VERSION},
<ide> data={
<ide> "id": node.id,
<ide> "name": node.name,
<ide> def ex_destroy_nic(self, nic):
<ide>
<ide> try:
<ide> self.connection.request(
<del> nic.id, params={"api-version": "2015-06-15"}, method="DELETE"
<add> nic.id, params={"api-version": NIC_API_VERSION}, method="DELETE"
<ide> )
<ide> return True
<ide> except BaseHTTPError as h:
<ide> def ex_check_ip_address_availability(self, resource_group, network, ip_address):
<ide> :param ip_address: The private IP address to be verified.
<ide> :type ip_address: ``str``
<ide> """
<del> params = {"api-version": "2018-06-01"}
<add> params = {"api-version": VIRTUAL_NETWORK_API_VERSION}
<ide> action = (
<ide> "/subscriptions/%s/resourceGroups/%s/providers"
<ide> "/Microsoft.Network/virtualNetworks/%s/"
<ide> def ex_get_node(self, id):
<ide> :rtype: :class:`.Node`
<ide> """
<ide>
<del> r = self.connection.request(id, params={"api-version": RESOURCE_API_VERSION})
<add> r = self.connection.request(id, params={"api-version": VM_API_VERSION})
<ide> return self._to_node(r.object)
<ide>
<ide> def ex_get_volume(self, id):
<ide> def ex_get_volume(self, id):
<ide> :rtype: :class:`.StorageVolume`
<ide> """
<ide>
<del> r = self.connection.request(id, params={"api-version": RESOURCE_API_VERSION})
<add> r = self.connection.request(id, params={"api-version": DISK_API_VERSION})
<ide> return self._to_volume(r.object)
<ide>
<ide> def ex_get_snapshot(self, id):
<ide> def ex_get_snapshot(self, id):
<ide> :rtype: :class:`.VolumeSnapshot`
<ide> """
<ide>
<del> r = self.connection.request(id, params={"api-version": RESOURCE_API_VERSION})
<add> r = self.connection.request(id, params={"api-version": SNAPSHOT_API_VERSION})
<ide> return self._to_snapshot(r.object)
<ide>
<ide> def ex_get_public_ip(self, id):
<ide> def ex_get_public_ip(self, id):
<ide> :rtype: :class:`.AzureIPAddress`
<ide> """
<ide>
<del> r = self.connection.request(id, params={"api-version": "2015-06-15"})
<add> r = self.connection.request(id, params={"api-version": IP_API_VERSION})
<ide> return self._to_ip_address(r.object)
<ide>
<ide> def ex_list_public_ips(self, resource_group):
<ide> def ex_list_public_ips(self, resource_group):
<ide> "providers/Microsoft.Network/publicIPAddresses"
<ide> % (self.subscription_id, resource_group)
<ide> )
<del> r = self.connection.request(action, params={"api-version": "2015-06-15"})
<add> r = self.connection.request(action, params={"api-version": IP_API_VERSION})
<ide> return [self._to_ip_address(net) for net in r.object["value"]]
<ide>
<ide> def ex_create_public_ip(
<ide> def ex_create_public_ip(
<ide> data["properties"]["publicIPAllocationMethod"] = "Static"
<ide>
<ide> r = self.connection.request(
<del> target, params={"api-version": "2015-06-15"}, data=data, method="PUT"
<add> target, params={"api-version": IP_API_VERSION}, data=data, method="PUT"
<ide> )
<ide> return self._to_ip_address(r.object)
<ide>
<ide> def ex_delete_public_ip(self, public_ip):
<ide> :type public_ip: `.AzureIPAddress`
<ide> """
<ide> # NOTE: This operation requires API version 2018-11-01 so
<del> # "ex_delete_resource" won't for for deleting an IP address
<add> # "ex_delete_resource" won't work for deleting an IP address
<ide> resource = public_ip.id
<ide> r = self.connection.request(
<ide> resource,
<ide> method="DELETE",
<del> params={"api-version": "2019-06-01"},
<add> params={"api-version": IP_API_VERSION},
<ide> )
<ide>
<ide> return r.status in [200, 202, 204]
<ide> def ex_create_network_interface(
<ide> ip_config["properties"]["publicIPAddress"] = {"id": public_ip.id}
<ide>
<ide> r = self.connection.request(
<del> target, params={"api-version": "2015-06-15"}, data=data, method="PUT"
<add> target, params={"api-version": NIC_API_VERSION}, data=data, method="PUT"
<ide> )
<ide> return AzureNic(
<ide> r.object["id"],
<ide> def ex_create_tags(self, resource, tags, replace=False):
<ide>
<ide> if not isinstance(resource, basestring):
<ide> resource = resource.id
<del> r = self.connection.request(resource, params={"api-version": "2018-06-01"})
<add> r = self.connection.request(resource, params={"api-version": TAG_API_VERSION})
<ide> if replace:
<ide> r.object["tags"] = tags
<ide> else:
<ide> r.object["tags"].update(tags)
<ide> self.connection.request(
<ide> resource,
<ide> data={"tags": r.object["tags"]},
<del> params={"api-version": "2018-06-01"},
<add> params={"api-version": TAG_API_VERSION},
<ide> method="PATCH",
<ide> )
<ide>
<ide> def start_node(self, node):
<ide>
<ide> target = "%s/start" % node.id
<ide> r = self.connection.request(
<del> target, params={"api-version": "2015-06-15"}, method="POST"
<add> target, params={"api-version": VM_API_VERSION}, method="POST"
<ide> )
<ide> return r.object
<ide>
<ide> def stop_node(self, node, ex_deallocate=True):
<ide> else:
<ide> target = "%s/powerOff" % node.id
<ide> r = self.connection.request(
<del> target, params={"api-version": "2015-06-15"}, method="POST"
<add> target, params={"api-version": VM_API_VERSION}, method="POST"
<ide> )
<ide> return r.object
<ide>
<ide> def ex_get_storage_account_keys(self, resource_group, storage_account):
<ide> )
<ide>
<ide> r = self.connection.request(
<del> action, params={"api-version": "2015-05-01-preview"}, method="POST"
<add> action, params={"api-version": STORAGE_ACCOUNT_API_VERSION}, method="POST"
<ide> )
<ide> return r.object
<ide>
<ide> def ex_run_command(
<ide> }
<ide>
<ide> r = self.connection.request(
<del> target, params={"api-version": "2015-06-15"}, data=data, method="PUT"
<add> target, params={"api-version": VM_EXTENSION_API_VERSION}, data=data, method="PUT"
<ide> )
<ide> return r.object
<ide>
<ide> def _fetch_power_state(self, data):
<ide> state = NodeState.UNKNOWN
<ide> try:
<ide> action = "%s/InstanceView" % (data["id"])
<del> r = self.connection.request(action, params={"api-version": "2015-06-15"})
<add> r = self.connection.request(action, params={"api-version": INSTANCE_VIEW_API_VERSION})
<ide> for status in r.object["statuses"]:
<ide> if status["code"] in ["ProvisioningState/creating"]:
<ide> state = NodeState.PENDING | 1 |
Java | Java | refine brokeravailabilityevent behavior | 6bcbb94abac229b70a8b0a89b12ce461d4321a8b | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/broker/AbstractBrokerMessageHandler.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.springframework.messaging.MessageHandler;
<ide> import org.springframework.util.CollectionUtils;
<ide>
<add>
<ide> /**
<del> * Abstract base class for a {@link MessageHandler} that manages subscriptions and
<del> * propagates messages to subscribers.
<add> * Abstract base class for a {@link MessageHandler} that broker messages to
<add> * registered subscribers.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.0
<ide>
<ide> protected final Log logger = LogFactory.getLog(getClass());
<ide>
<del> private Collection<String> destinationPrefixes;
<add> private final Collection<String> destinationPrefixes;
<ide>
<ide> private ApplicationEventPublisher eventPublisher;
<ide>
<ide> private volatile boolean running = false;
<ide>
<ide>
<add> public AbstractBrokerMessageHandler() {
<add> this(Collections.<String>emptyList());
<add> }
<add>
<ide> public AbstractBrokerMessageHandler(Collection<String> destinationPrefixes) {
<del> this.destinationPrefixes = (destinationPrefixes != null)
<del> ? destinationPrefixes : Collections.<String>emptyList();
<add> destinationPrefixes = (destinationPrefixes != null) ? destinationPrefixes : Collections.<String>emptyList();
<add> this.destinationPrefixes = Collections.unmodifiableCollection(destinationPrefixes);
<ide> }
<ide>
<ide>
<ide> public int getPhase() {
<ide> return Integer.MAX_VALUE;
<ide> }
<ide>
<add> /**
<add> * Check whether this message handler is currently running.
<add> *
<add> * <p>Note that even when this message handler is running the
<add> * {@link #isBrokerAvailable()} flag may still independently alternate between
<add> * being on and off depending on the concrete sub-class implementation.
<add> */
<ide> @Override
<ide> public final boolean isRunning() {
<ide> synchronized (this.lifecycleMonitor) {
<ide> return this.running;
<ide> }
<ide> }
<ide>
<add> /**
<add> * Whether the message broker is currently available and able to process messages.
<add> *
<add> * <p>Note that this is in addition to the {@link #isRunning()} flag, which
<add> * indicates whether this message handler is running. In other words the message
<add> * handler must first be running and then the {@link #isBrokerAvailable()} flag
<add> * may still independently alternate between being on and off depending on the
<add> * concrete sub-class implementation.
<add> *
<add> * <p>Application components may implement
<add> * {@link org.springframework.context.ApplicationListener<BrokerAvailabilityEvent>>}
<add> * to receive notifications when broker becomes available and unavailable.
<add> */
<add> public boolean isBrokerAvailable() {
<add> return this.brokerAvailable.get();
<add> }
<add>
<ide> @Override
<ide> public final void start() {
<ide> synchronized (this.lifecycleMonitor) {
<ide> protected boolean checkDestinationPrefix(String destination) {
<ide> }
<ide>
<ide> protected void publishBrokerAvailableEvent() {
<del> if ((this.eventPublisher != null) && this.brokerAvailable.compareAndSet(false, true)) {
<del> if (logger.isTraceEnabled()) {
<del> logger.trace("Publishing BrokerAvailabilityEvent (available)");
<add> boolean shouldPublish = this.brokerAvailable.compareAndSet(false, true);
<add> if (this.eventPublisher != null && shouldPublish) {
<add> if (logger.isDebugEnabled()) {
<add> logger.debug("Publishing BrokerAvailabilityEvent (available)");
<ide> }
<ide> this.eventPublisher.publishEvent(new BrokerAvailabilityEvent(true, this));
<ide> }
<ide> }
<ide>
<ide> protected void publishBrokerUnavailableEvent() {
<del> if ((this.eventPublisher != null) && this.brokerAvailable.compareAndSet(true, false)) {
<del> if (logger.isTraceEnabled()) {
<del> logger.trace("Publishing BrokerAvailabilityEvent (unavailable)");
<add> boolean shouldPublish = this.brokerAvailable.compareAndSet(true, false);
<add> if (this.eventPublisher != null && shouldPublish) {
<add> if (logger.isDebugEnabled()) {
<add> logger.debug("Publishing BrokerAvailabilityEvent (unavailable)");
<ide> }
<ide> this.eventPublisher.publishEvent(new BrokerAvailabilityEvent(false, this));
<ide> }
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/broker/SimpleBrokerMessageHandler.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/config/AbstractMessageBrokerConfiguration.java
<ide> public Validator getValidator() {
<ide> }
<ide>
<ide>
<del> private static final AbstractBrokerMessageHandler noopBroker = new AbstractBrokerMessageHandler(null) {
<add> private static final AbstractBrokerMessageHandler noopBroker = new AbstractBrokerMessageHandler() {
<ide>
<ide> @Override
<ide> protected void startInternal() {
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandler.java
<ide> public StompBrokerRelayMessageHandler(SubscribableChannel clientInChannel, Messa
<ide> Assert.notNull(clientOutChannel, "'clientOutChannel' must not be null");
<ide> Assert.notNull(brokerChannel, "'brokerChannel' must not be null");
<ide>
<del>
<ide> this.clientInboundChannel = clientInChannel;
<ide> this.clientOutboundChannel = clientOutChannel;
<ide> this.brokerChannel = brokerChannel;
<ide> protected void startInternal() {
<ide> }
<ide>
<ide> if (logger.isDebugEnabled()) {
<del> logger.debug("Initializing \"system\" TCP connection");
<add> logger.debug("Initializing \"system\" connection");
<ide> }
<ide>
<ide> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECT);
<ide> protected void startInternal() {
<ide> @Override
<ide> protected void stopInternal() {
<ide>
<add> publishBrokerUnavailableEvent();
<add>
<ide> this.clientInboundChannel.unsubscribe(this);
<ide> this.brokerChannel.unsubscribe(this);
<ide>
<ide> protected void stopInternal() {
<ide> logger.error("Failed to close connection in session " + handler.getSessionId() + ": " + t.getMessage());
<ide> }
<ide> }
<add>
<ide> try {
<ide> this.tcpClient.shutdown();
<ide> }
<ide> protected void handleMessageInternal(Message<?> message) {
<ide>
<ide> StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
<ide> String sessionId = headers.getSessionId();
<add>
<add> if (!isBrokerAvailable()) {
<add> if (sessionId == null || sessionId == SystemStompConnectionHandler.SESSION_ID) {
<add> throw new MessageDeliveryException("Message broker is not active.");
<add> }
<add> if (logger.isTraceEnabled()) {
<add> logger.trace("Message broker is not active. Ignoring message id=" + message.getHeaders().getId());
<add> }
<add> return;
<add> }
<add>
<ide> String destination = headers.getDestination();
<ide> StompCommand command = headers.getCommand();
<ide> SimpMessageType messageType = headers.getMessageType();
<ide> protected void handleMessageInternal(Message<?> message) {
<ide> return;
<ide> }
<ide>
<add> if (logger.isTraceEnabled()) {
<add> logger.trace("Processing message=" + message);
<add> }
<add>
<ide> if (SimpMessageType.CONNECT.equals(messageType)) {
<del> logger.debug("Processing CONNECT in session=" + sessionId +
<del> ", number of connections=" + this.connectionHandlers.size());
<add> if (logger.isDebugEnabled()) {
<add> logger.debug("Processing CONNECT (total connected=" + this.connectionHandlers.size() + ")");
<add> }
<ide> headers.setLogin(this.clientLogin);
<ide> headers.setPasscode(this.clientPasscode);
<ide> if (getVirtualHost() != null) {
<ide> else if (SimpMessageType.DISCONNECT.equals(messageType)) {
<ide> StompConnectionHandler handler = this.connectionHandlers.get(sessionId);
<ide> if (handler == null) {
<ide> if (logger.isTraceEnabled()) {
<del> logger.trace("Connection already removed for sessionId=" + sessionId);
<add> logger.trace("Connection already removed for sessionId '" + sessionId + "'");
<ide> }
<ide> return;
<ide> }
<ide> else if (SimpMessageType.DISCONNECT.equals(messageType)) {
<ide> StompConnectionHandler handler = this.connectionHandlers.get(sessionId);
<ide> if (handler == null) {
<ide> if (logger.isWarnEnabled()) {
<del> logger.warn("Connection for sessionId=" + sessionId + " not found. Ignoring message");
<add> logger.warn("Connection for sessionId '" + sessionId + "' not found. Ignoring message");
<ide> }
<ide> return;
<ide> }
<ide> public String getSessionId() {
<ide> @Override
<ide> public void afterConnected(TcpConnection<byte[]> connection) {
<ide> if (logger.isDebugEnabled()) {
<del> logger.debug("Established TCP connection to broker in session=" + this.sessionId);
<add> logger.debug("Established TCP connection to broker in session '" + this.sessionId + "'");
<ide> }
<ide> this.tcpConnection = connection;
<ide> connection.send(MessageBuilder.withPayload(EMPTY_PAYLOAD).setHeaders(this.connectHeaders).build());
<ide> public void afterConnectFailure(Throwable ex) {
<ide> */
<ide> protected void handleTcpConnectionFailure(String errorMessage, Throwable ex) {
<ide> if (logger.isErrorEnabled()) {
<del> logger.error(errorMessage + ", sessionId=" + this.sessionId, ex);
<add> logger.error(errorMessage + ", sessionId '" + this.sessionId + "'", ex);
<ide> }
<ide> try {
<ide> sendStompErrorToClient(errorMessage);
<ide> public void handleMessage(Message<byte[]> message) {
<ide> logger.trace("Received broker heartbeat");
<ide> }
<ide> else if (logger.isDebugEnabled()) {
<del> logger.debug("Received broker message in session=" + this.sessionId);
<add> logger.debug("Received message from broker in session '" + this.sessionId + "'");
<ide> }
<ide>
<ide> if (StompCommand.CONNECTED == headers.getCommand()) {
<ide> public void afterConnectionClosed() {
<ide> return;
<ide> }
<ide> try {
<add> if (logger.isDebugEnabled()) {
<add> logger.debug("TCP connection to broker closed in session '" + this.sessionId + "'");
<add> }
<ide> sendStompErrorToClient("Connection to broker closed");
<ide> }
<ide> finally {
<ide> public void clearConnection() {
<ide> }
<ide> finally {
<ide> if (this.isRemoteClientSession) {
<add> if (logger.isDebugEnabled()) {
<add> logger.debug("Removing session '" + sessionId + "' (total remaining=" +
<add> (StompBrokerRelayMessageHandler.this.connectionHandlers.size() - 1) + ")");
<add> }
<ide> StompBrokerRelayMessageHandler.this.connectionHandlers.remove(this.sessionId);
<ide> }
<ide> }
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/broker/BrokerMessageHandlerTests.java
<add>/*
<add> * Copyright 2002-2014 the original author or authors.
<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>
<add>package org.springframework.messaging.simp.broker;
<add>
<add>import org.junit.Before;
<add>import org.junit.Test;
<add>import org.mockito.MockitoAnnotations;
<add>import org.springframework.context.ApplicationEvent;
<add>import org.springframework.context.ApplicationEventPublisher;
<add>import org.springframework.messaging.Message;
<add>import org.springframework.messaging.support.GenericMessage;
<add>
<add>import java.util.ArrayList;
<add>import java.util.Arrays;
<add>import java.util.Collections;
<add>import java.util.List;
<add>
<add>import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertFalse;
<add>import static org.junit.Assert.assertTrue;
<add>
<add>/**
<add> * Unit tests for {@link org.springframework.messaging.simp.broker.AbstractBrokerMessageHandler}.
<add> *
<add> * @author Rossen Stoyanchev
<add> */
<add>public class BrokerMessageHandlerTests {
<add>
<add> private TestBrokerMesageHandler handler;
<add>
<add>
<add> @Before
<add> public void setup() {
<add> MockitoAnnotations.initMocks(this);
<add> this.handler = new TestBrokerMesageHandler();
<add> }
<add>
<add>
<add> @Test
<add> public void startShouldUpdateIsRunning() {
<add> assertFalse(this.handler.isRunning());
<add> this.handler.start();
<add> assertTrue(this.handler.isRunning());
<add> }
<add>
<add> @Test
<add> public void stopShouldUpdateIsRunning() {
<add>
<add> this.handler.start();
<add> assertTrue(this.handler.isRunning());
<add>
<add> this.handler.stop();
<add> assertFalse(this.handler.isRunning());
<add> }
<add>
<add> @Test
<add> public void stopShouldPublishBrokerAvailabilityEvent() {
<add> this.handler.start();
<add> this.handler.stop();
<add> assertEquals(Arrays.asList(true, false), this.handler.availabilityEvents);
<add> }
<add>
<add> @Test
<add> public void handleMessageWhenBrokerNotRunning() {
<add> this.handler.handleMessage(new GenericMessage<Object>("payload"));
<add> assertEquals(Collections.emptyList(), this.handler.messages);
<add> }
<add>
<add> @Test
<add> public void publishBrokerAvailableEvent() {
<add>
<add> assertFalse(this.handler.isBrokerAvailable());
<add> assertEquals(Collections.emptyList(), this.handler.availabilityEvents);
<add>
<add> this.handler.publishBrokerAvailableEvent();
<add>
<add> assertTrue(this.handler.isBrokerAvailable());
<add> assertEquals(Arrays.asList(true), this.handler.availabilityEvents);
<add> }
<add>
<add> @Test
<add> public void publishBrokerAvailableEventWhenAlreadyAvailable() {
<add>
<add> this.handler.publishBrokerAvailableEvent();
<add> this.handler.publishBrokerAvailableEvent();
<add>
<add> assertEquals(Arrays.asList(true), this.handler.availabilityEvents);
<add> }
<add>
<add> @Test
<add> public void publishBrokerUnavailableEvent() {
<add>
<add> this.handler.publishBrokerAvailableEvent();
<add> assertTrue(this.handler.isBrokerAvailable());
<add>
<add> this.handler.publishBrokerUnavailableEvent();
<add> assertFalse(this.handler.isBrokerAvailable());
<add>
<add> assertEquals(Arrays.asList(true, false), this.handler.availabilityEvents);
<add> }
<add>
<add> @Test
<add> public void publishBrokerUnavailableEventWhenAlreadyUnvailable() {
<add>
<add> this.handler.publishBrokerAvailableEvent();
<add> this.handler.publishBrokerUnavailableEvent();
<add> this.handler.publishBrokerUnavailableEvent();
<add>
<add> assertEquals(Arrays.asList(true, false), this.handler.availabilityEvents);
<add> }
<add>
<add>
<add> private static class TestBrokerMesageHandler extends AbstractBrokerMessageHandler
<add> implements ApplicationEventPublisher {
<add>
<add> private final List<Message<?>> messages = new ArrayList<>();
<add>
<add> private final List<Boolean> availabilityEvents = new ArrayList<>();
<add>
<add>
<add> private TestBrokerMesageHandler() {
<add> setApplicationEventPublisher(this);
<add> }
<add>
<add> @Override
<add> protected void startInternal() {
<add> publishBrokerAvailableEvent();
<add> }
<add>
<add> @Override
<add> protected void handleMessageInternal(Message<?> message) {
<add> this.messages.add(message);
<add> }
<add>
<add> @Override
<add> public void publishEvent(ApplicationEvent event) {
<add> if (event instanceof BrokerAvailabilityEvent) {
<add> this.availabilityEvents.add(((BrokerAvailabilityEvent) event).isBrokerAvailable());
<add> }
<add> }
<add> }
<add>
<add>}
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/broker/SimpleBrokerMessageHandlerTests.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> /**
<add> * Unit tests for SimpleBrokerMessageHandler.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.0
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/config/StompBrokerRelayRegistrationTests.java
<ide> import org.springframework.messaging.SubscribableChannel;
<ide> import org.springframework.messaging.simp.stomp.StompBrokerRelayMessageHandler;
<ide>
<add>import java.util.ArrayList;
<ide> import java.util.Arrays;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<ide> public void test() {
<ide>
<ide> StompBrokerRelayMessageHandler relayMessageHandler = registration.getMessageHandler(brokerChannel);
<ide>
<del> assertEquals(Arrays.asList(destinationPrefixes), relayMessageHandler.getDestinationPrefixes());
<add> assertEquals(Arrays.asList(destinationPrefixes),
<add> new ArrayList<String>(relayMessageHandler.getDestinationPrefixes()));
<add>
<ide> assertEquals("clientlogin", relayMessageHandler.getClientLogin());
<ide> assertEquals("clientpasscode", relayMessageHandler.getClientPasscode());
<ide> assertEquals("syslogin", relayMessageHandler.getSystemLogin());
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java
<ide> public void publishSubscribe() throws Exception {
<ide> this.responseHandler.awaitAndAssert();
<ide> }
<ide>
<del> @Test
<del> public void brokerUnvailableErrorFrameOnConnect() throws Exception {
<del>
<del> stopActiveMqBrokerAndAwait();
<del>
<del> MessageExchange connect = MessageExchangeBuilder.connectWithError("sess1").build();
<del> this.responseHandler.expect(connect);
<del>
<del> this.relay.handleMessage(connect.message);
<del> this.responseHandler.awaitAndAssert();
<del> }
<del>
<ide> @Test(expected=MessageDeliveryException.class)
<ide> public void messageDeliverExceptionIfSystemSessionForwardFails() throws Exception {
<ide> stopActiveMqBrokerAndAwait();
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerTests.java
<ide> import java.util.Arrays;
<ide> import java.util.List;
<ide> import java.util.concurrent.Callable;
<add>import java.util.concurrent.CountDownLatch;
<add>import java.util.concurrent.TimeUnit;
<ide>
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<add>import org.springframework.context.ApplicationEvent;
<add>import org.springframework.context.ApplicationEventPublisher;
<ide> import org.springframework.messaging.Message;
<ide> import org.springframework.messaging.StubMessageChannel;
<ide> import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
<ide> import org.springframework.messaging.simp.SimpMessageType;
<add>import org.springframework.messaging.simp.broker.BrokerAvailabilityEvent;
<ide> import org.springframework.messaging.support.MessageBuilder;
<ide> import org.springframework.messaging.tcp.ReconnectStrategy;
<ide> import org.springframework.messaging.tcp.TcpConnection;
<ide> public class StompBrokerRelayMessageHandlerTests {
<ide>
<ide> @Before
<ide> public void setup() {
<add>
<ide> this.tcpClient = new StubTcpOperations();
<add>
<ide> this.brokerRelay = new StompBrokerRelayMessageHandler(new StubMessageChannel(),
<del> new StubMessageChannel(), new StubMessageChannel(), Arrays.asList("/topic"));
<add> new StubMessageChannel(), new StubMessageChannel(), Arrays.asList("/topic")) {
<add>
<add> @Override
<add> protected void startInternal() {
<add> publishBrokerAvailableEvent(); // Force this, since we'll never actually connect
<add> super.startInternal();
<add> }
<add> };
<add>
<ide> this.brokerRelay.setTcpClient(this.tcpClient);
<ide> }
<ide>
<ide>
<ide> @Test
<del> public void testVirtualHostHeader() {
<add> public void testVirtualHostHeader() throws Exception {
<ide>
<ide> String virtualHost = "ABC";
<del> String sessionId = "sess1";
<add> this.brokerRelay.setVirtualHost(virtualHost);
<add> this.brokerRelay.start();
<ide>
<add> String sessionId = "sess1";
<ide> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECT);
<ide> headers.setSessionId(sessionId);
<del>
<del> this.brokerRelay.setVirtualHost(virtualHost);
<del> this.brokerRelay.start();
<ide> this.brokerRelay.handleMessage(MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build());
<ide>
<ide> List<Message<byte[]>> sent = this.tcpClient.connection.messages;
<ide> public void testVirtualHostHeader() {
<ide> }
<ide>
<ide> @Test
<del> public void testLoginPasscode() {
<del>
<del> String sessionId = "sess1";
<del>
<del> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECT);
<del> headers.setSessionId(sessionId);
<add> public void testLoginPasscode() throws Exception {
<ide>
<ide> this.brokerRelay.setClientLogin("clientlogin");
<ide> this.brokerRelay.setClientPasscode("clientpasscode");
<ide> public void testLoginPasscode() {
<ide> this.brokerRelay.setSystemPasscode("syspasscode");
<ide>
<ide> this.brokerRelay.start();
<add>
<add> String sessionId = "sess1";
<add> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECT);
<add> headers.setSessionId(sessionId);
<ide> this.brokerRelay.handleMessage(MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build());
<ide>
<ide> List<Message<byte[]>> sent = this.tcpClient.connection.messages;
<ide> public void testLoginPasscode() {
<ide> }
<ide>
<ide> @Test
<del> public void testDestinationExcluded() {
<add> public void testDestinationExcluded() throws Exception {
<add>
<add> this.brokerRelay.start();
<ide>
<ide> SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
<ide> headers.setSessionId("sess1");
<ide> headers.setDestination("/user/daisy/foo");
<del>
<del> this.brokerRelay.start();
<ide> this.brokerRelay.handleMessage(MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build());
<ide>
<ide> List<Message<byte[]>> sent = this.tcpClient.connection.messages;
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/config/MessageBrokerBeanDefinitionParserTests.java
<ide>
<ide> package org.springframework.web.socket.config;
<ide>
<add>import java.util.ArrayList;
<ide> import java.util.Arrays;
<add>import java.util.Collections;
<ide> import java.util.List;
<ide>
<ide> import org.hamcrest.Matchers;
<ide> public void simpleBroker() {
<ide>
<ide> SimpleBrokerMessageHandler brokerMessageHandler = this.appContext.getBean(SimpleBrokerMessageHandler.class);
<ide> assertNotNull(brokerMessageHandler);
<del> assertEquals(Arrays.asList("/topic", "/queue"), brokerMessageHandler.getDestinationPrefixes());
<add> assertEquals(Arrays.asList("/topic", "/queue"),
<add> new ArrayList<String>(brokerMessageHandler.getDestinationPrefixes()));
<ide>
<ide> List<Class<? extends MessageHandler>> subscriberTypes =
<ide> Arrays.<Class<? extends MessageHandler>>asList(SimpAnnotationMethodMessageHandler.class, | 10 |
Ruby | Ruby | fix unscoping `default_scope` for `preloader` | 9aa04315febfb37b50f52471a2837c40313a2d5f | <ide><path>activerecord/lib/active_record/associations/preloader/association.rb
<ide> def reflection_scope
<ide> @reflection_scope ||= reflection.scope_for(klass)
<ide> end
<ide>
<add> def klass_scope
<add> current_scope = klass.current_scope
<add>
<add> if current_scope && current_scope.empty_scope?
<add> klass.unscoped
<add> else
<add> klass.default_scoped
<add> end
<add> end
<add>
<ide> def build_scope
<del> scope = klass.default_scoped
<add> scope = klass_scope
<ide>
<ide> if reflection.type
<ide> scope.where!(reflection.type => model.base_class.sti_name)
<ide><path>activerecord/test/cases/scoping/default_scoping_test.rb
<ide> def test_sti_association_with_unscoped_not_affected_by_default_scope
<ide> assert_equal post, Post.joins(:special_comments).find(post.id)
<ide> assert_equal comments, Post.joins(:special_comments).find(post.id).special_comments
<ide> assert_equal comments, Post.eager_load(:special_comments).find(post.id).special_comments
<add> assert_equal comments, Post.includes(:special_comments).find(post.id).special_comments
<add> assert_equal comments, Post.preload(:special_comments).find(post.id).special_comments
<ide> end
<ide> end
<ide> | 2 |
Text | Text | update changelog.md for 2.11.2 | bd96be28693d82dff6b0659a24c5c33b6a8124bb | <ide><path>CHANGELOG.md
<ide> - [#14852](https://github.com/emberjs/ember.js/pull/14852) [PERF] only `LOG_TRANSITIONS` and `LOG_TRANSITIONS_INTERNAL` in debug
<ide> - [#14854](https://github.com/emberjs/ember.js/pull/14854) [PER] only `LOG_ACTIVE_GENERATION` and `LOG_RESOLVER` in debug
<ide>
<add>### 2.11.2 (February 19, 2017)
<add>
<add>- [#14937](https://github.com/emberjs/ember.js/pull/14937) [BUGFIX] Fix issue preventing `ember generate *` from creating test files as appropriate.
<add>
<ide> ### 2.11.1 (February 16, 2017)
<ide>
<ide> - [#14762](https://github.com/emberjs/ember.js/pull/14762) [BUGFIX] Make ember-template-compiler handle {{input}} helpers with sub-expression "type" | 1 |
Go | Go | remove non-ascii characters from name generator | c38386d876aab1c1e3391de2180cb03f083f8955 | <ide><path>namesgenerator/names-generator.go
<ide> var (
<ide> // http://en.wikipedia.org/wiki/John_Bardeen
<ide> // http://en.wikipedia.org/wiki/Walter_Houser_Brattain
<ide> // http://en.wikipedia.org/wiki/William_Shockley
<del> right = [...]string{"lovelace", "franklin", "tesla", "einstein", "bohr", "davinci", "pasteur", "nobel", "curie", "darwin", "turing", "ritchie", "torvalds", "pike", "thompson", "wozniak", "galileo", "euclide", "newton", "fermat", "archimede", "poincare", "heisenberg", "feynmann", "hawkings", "fermi", "paré", "mccarthy", "engelbart", "babbage", "albattani", "ptolemy", "bell", "wright", "lumiere", "morse", "mclean", "brown", "bardeen", "brattain", "shockley"}
<add> right = [...]string{"lovelace", "franklin", "tesla", "einstein", "bohr", "davinci", "pasteur", "nobel", "curie", "darwin", "turing", "ritchie", "torvalds", "pike", "thompson", "wozniak", "galileo", "euclide", "newton", "fermat", "archimede", "poincare", "heisenberg", "feynmann", "hawkings", "fermi", "pare", "mccarthy", "engelbart", "babbage", "albattani", "ptolemy", "bell", "wright", "lumiere", "morse", "mclean", "brown", "bardeen", "brattain", "shockley"}
<ide> )
<ide>
<ide> func GenerateRandomName(checker NameChecker) (string, error) { | 1 |
Javascript | Javascript | fix paths for windows | 25ef1f882f314ce2cd03b9558c7f0f7482751270 | <ide><path>test/ContextReplacementPlugin.test.js
<ide> describe("ContextReplacementPlugin", () => {
<ide> let obj = buildPluginWithParams(/selector/, "./folder", true, /filter/);
<ide>
<ide> let x = (nothing, result) => {
<del> result.resource.should.containEql('/selector/folder')
<add> result.resource.should.containEql('selector')
<add> result.resource.should.containEql('folder')
<ide> };
<ide>
<ide> let spy = sinon.spy(x);
<ide> describe("ContextReplacementPlugin", () => {
<ide> }, true, /filter/);
<ide>
<ide> let x = (nothing, result) => {
<del> result.resource.should.containEql('selector/imadifferentselector')
<add> result.resource.should.containEql('selector')
<add> result.resource.should.containEql('imadifferentselector')
<ide> };
<ide>
<ide> let spy = sinon.spy(x); | 1 |
Java | Java | fix subject subscriptionmanager | 4e4c165d59f3196044a7a79d35e40e32126d153b | <ide><path>rxjava-core/src/main/java/rx/subjects/SubjectSubscriptionManager.java
<ide> import rx.Observer;
<ide> import rx.Subscription;
<ide> import rx.operators.SafeObservableSubscription;
<add>import rx.subscriptions.Subscriptions;
<ide> import rx.util.functions.Action1;
<ide>
<ide> /* package */class SubjectSubscriptionManager<T> {
<ide> public void call(Observer<? super T> actualObserver) {
<ide> State<T> current;
<ide> State<T> newState = null;
<ide> boolean addedObserver = false;
<add> Subscription s;
<ide> do {
<ide> current = state.get();
<ide> if (current.terminated) {
<ide> // we are terminated so don't need to do anything
<add> s = Subscriptions.empty();
<ide> addedObserver = false;
<ide> // break out and don't try to modify state
<ide> newState = current;
<ide> public void call(Observer<? super T> actualObserver) {
<ide> }
<ide> break;
<ide> } else {
<del> final SafeObservableSubscription subscription = new SafeObservableSubscription();
<del> actualObserver.add(subscription); // add to parent if the Subject itself is unsubscribed
<ide> addedObserver = true;
<del> subscription.wrap(new Subscription() {
<add> s = new Subscription() {
<ide> @Override
<ide> public void unsubscribe() {
<ide> State<T> current;
<ide> State<T> newState;
<ide> do {
<ide> current = state.get();
<ide> // on unsubscribe remove it from the map of outbound observers to notify
<del> newState = current.removeObserver(subscription);
<add> newState = current.removeObserver(this);
<ide> } while (!state.compareAndSet(current, newState));
<ide> }
<del> });
<add> };
<ide>
<ide> // on subscribe add it to the map of outbound observers to notify
<del> newState = current.addObserver(subscription, observer);
<add> newState = current.addObserver(s, observer);
<ide> }
<ide> } while (!state.compareAndSet(current, newState));
<ide>
<ide> public void unsubscribe() {
<ide> if (newState.terminated && !addedObserver) {
<ide> onTerminated.call(observer);
<ide> }
<add>
<add> actualObserver.add(s);
<ide> }
<ide>
<ide> };
<ide> }
<ide>
<del> @SuppressWarnings({ "unchecked", "rawtypes" })
<ide> protected void terminate(Action1<Collection<SubjectObserver<? super T>>> onTerminate) {
<ide> State<T> current;
<ide> State<T> newState = null;
<ide> protected void terminate(Action1<Collection<SubjectObserver<? super T>>> onTermi
<ide> *
<ide> * @return the array of current observers
<ide> */
<del> @SuppressWarnings("unchecked")
<ide> public SubjectObserver<Object>[] rawSnapshot() {
<ide> return state.get().observers;
<ide> }
<ide> public State<T> removeObserver(Subscription s) {
<ide> protected volatile boolean caughtUp = false;
<ide>
<ide> SubjectObserver(Observer<? super T> actual) {
<add> super(actual);
<ide> this.actual = actual;
<ide> }
<ide>
<ide> public void onNext(T v) {
<ide>
<ide> }
<ide>
<del>}
<add>}
<ide>\ No newline at end of file | 1 |
Python | Python | enable ftptos3operator to transfer several files | 8e56ed234bf48775d553744c792fadc3ad63fbf7 | <ide><path>airflow/providers/amazon/aws/transfers/ftp_to_s3.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide> from tempfile import NamedTemporaryFile
<add>from typing import List, Optional, Union
<ide>
<ide> from airflow.models import BaseOperator
<ide> from airflow.providers.amazon.aws.hooks.s3 import S3Hook
<ide>
<ide> class FTPToS3Operator(BaseOperator):
<ide> """
<del> This operator enables the transferring of files from FTP server to S3.
<add> This operator enables the transfer of files from a FTP server to S3. It can be used to
<add> transfer one or multiple files.
<ide>
<del> :param s3_bucket: The targeted s3 bucket in which upload the file to
<add> :param ftp_path: The ftp remote path. For one file it is mandatory to include the file as well.
<add> For multiple files, it is the route where the files will be found.
<add> :type ftp_path: str
<add> :param s3_bucket: The targeted s3 bucket in which to upload the file(s).
<ide> :type s3_bucket: str
<del> :param s3_key: The targeted s3 key. This is the specified file path for
<del> uploading the file to S3.
<add> :param s3_key: The targeted s3 key. For one file it must include the file path. For several,
<add> it must end with "/".
<ide> :type s3_key: str
<del> :param ftp_path: The ftp remote path, including the file.
<del> :type ftp_path: str
<add> :param ftp_filenames: Only used if you want to move multiple files. You can pass a list
<add> with exact filenames present in the ftp path, or a prefix that all files must meet. It
<add> can also be the string '*' for moving all the files within the ftp path.
<add> :type ftp_filenames: Union(str, list)
<add> :param s3_filenames: Only used if you want to move multiple files and name them different from
<add> the originals from the ftp. It can be a list of filenames or file prefix (that will replace
<add> the ftp prefix).
<add> :type s3_filenames: Union(str, list)
<ide> :param ftp_conn_id: The ftp connection id. The name or identifier for
<ide> establishing a connection to the FTP server.
<ide> :type ftp_conn_id: str
<ide> :param aws_conn_id: The s3 connection id. The name or identifier for
<del> establishing a connection to S3
<add> establishing a connection to S3.
<ide> :type aws_conn_id: str
<ide> :param replace: A flag to decide whether or not to overwrite the key
<ide> if it already exists. If replace is False and the key exists, an
<ide> class FTPToS3Operator(BaseOperator):
<ide> :type acl_policy: str
<ide> """
<ide>
<del> template_fields = (
<del> 's3_bucket',
<del> 's3_key',
<del> 'ftp_path',
<del> )
<add> template_fields = ('ftp_path', 's3_bucket', 's3_key', 'ftp_filenames', 's3_filenames')
<ide>
<ide> def __init__(
<ide> self,
<del> s3_bucket,
<del> s3_key,
<del> ftp_path,
<del> ftp_conn_id='ftp_default',
<del> aws_conn_id='aws_default',
<del> replace=False,
<del> encrypt=False,
<del> gzip=False,
<del> acl_policy=None,
<del> *args,
<add> *,
<add> ftp_path: str,
<add> s3_bucket: str,
<add> s3_key: str,
<add> ftp_filenames: Optional[Union[str, List[str]]] = None,
<add> s3_filenames: Optional[Union[str, List[str]]] = None,
<add> ftp_conn_id: str = 'ftp_default',
<add> aws_conn_id: str = 'aws_default',
<add> replace: bool = False,
<add> encrypt: bool = False,
<add> gzip: bool = False,
<add> acl_policy: str = None,
<ide> **kwargs,
<ide> ):
<del> super().__init__(*args, **kwargs)
<add> super().__init__(**kwargs)
<add> self.ftp_path = ftp_path
<ide> self.s3_bucket = s3_bucket
<ide> self.s3_key = s3_key
<del> self.ftp_path = ftp_path
<add> self.ftp_filenames = ftp_filenames
<add> self.s3_filenames = s3_filenames
<ide> self.aws_conn_id = aws_conn_id
<ide> self.ftp_conn_id = ftp_conn_id
<ide> self.replace = replace
<ide> self.encrypt = encrypt
<ide> self.gzip = gzip
<ide> self.acl_policy = acl_policy
<add> self.s3_hook = None
<add> self.ftp_hook = None
<ide>
<del> def execute(self, context):
<del> s3_hook = S3Hook(self.aws_conn_id)
<del> ftp_hook = FTPHook(ftp_conn_id=self.ftp_conn_id)
<del>
<add> def __upload_to_s3_from_ftp(self, remote_filename, s3_file_key):
<ide> with NamedTemporaryFile() as local_tmp_file:
<del> ftp_hook.retrieve_file(
<del> remote_full_path=self.ftp_path, local_full_path_or_buffer=local_tmp_file.name
<add> self.ftp_hook.retrieve_file(
<add> remote_full_path=remote_filename, local_full_path_or_buffer=local_tmp_file.name
<ide> )
<ide>
<del> s3_hook.load_file(
<add> self.s3_hook.load_file(
<ide> filename=local_tmp_file.name,
<del> key=self.s3_key,
<add> key=s3_file_key,
<ide> bucket_name=self.s3_bucket,
<ide> replace=self.replace,
<ide> encrypt=self.encrypt,
<ide> gzip=self.gzip,
<ide> acl_policy=self.acl_policy,
<ide> )
<add> self.log.info(f'File upload to {s3_file_key}')
<add>
<add> def execute(self, context):
<add> self.ftp_hook = FTPHook(ftp_conn_id=self.ftp_conn_id)
<add> self.s3_hook = S3Hook(self.aws_conn_id)
<add>
<add> if self.ftp_filenames:
<add> if isinstance(self.ftp_filenames, str):
<add> self.log.info(f'Getting files in {self.ftp_path}')
<add>
<add> list_dir = self.ftp_hook.list_directory(
<add> path=self.ftp_path,
<add> )
<add>
<add> if self.ftp_filenames == '*':
<add> files = list_dir
<add> else:
<add> files = list(filter(lambda file: self.ftp_filenames in file, list_dir))
<add>
<add> for file in files:
<add> self.log.info(f'Moving file {file}')
<add>
<add> if self.s3_filenames:
<add> filename = file.replace(self.ftp_filenames, self.s3_filenames)
<add> else:
<add> filename = file
<add>
<add> s3_file_key = f'{self.s3_key}{filename}'
<add> self.__upload_to_s3_from_ftp(file, s3_file_key)
<add>
<add> else:
<add> if self.s3_filenames:
<add> for ftp_file, s3_file in zip(self.ftp_filenames, self.s3_filenames):
<add> self.__upload_to_s3_from_ftp(self.ftp_path + ftp_file, self.s3_key + s3_file)
<add> else:
<add> for ftp_file in self.ftp_filenames:
<add> self.__upload_to_s3_from_ftp(self.ftp_path + ftp_file, self.s3_key + ftp_file)
<add> else:
<add> self.__upload_to_s3_from_ftp(self.ftp_path, self.s3_key)
<ide><path>tests/providers/amazon/aws/transfers/test_ftp_to_s3.py
<ide> FTP_PATH = '/tmp/remote_path.txt'
<ide> AWS_CONN_ID = 'aws_default'
<ide> FTP_CONN_ID = 'ftp_default'
<add>S3_KEY_MULTIPLE = 'test/'
<add>FTP_PATH_MULTIPLE = '/tmp/'
<ide>
<ide>
<ide> class TestFTPToS3Operator(unittest.TestCase):
<del> @mock.patch("airflow.providers.ftp.hooks.ftp.FTPHook.retrieve_file")
<del> @mock.patch("airflow.providers.amazon.aws.hooks.s3.S3Hook.load_file")
<del> @mock.patch("airflow.providers.amazon.aws.transfers.ftp_to_s3.NamedTemporaryFile")
<del> def test_execute(self, mock_local_tmp_file, mock_s3_hook_load_file, mock_ftp_hook_retrieve_file):
<del> operator = FTPToS3Operator(task_id=TASK_ID, s3_bucket=BUCKET, s3_key=S3_KEY, ftp_path=FTP_PATH)
<del> operator.execute(None)
<add> def assert_execute(
<add> self, mock_local_tmp_file, mock_s3_hook_load_file, mock_ftp_hook_retrieve_file, ftp_file, s3_file
<add> ):
<ide>
<ide> mock_local_tmp_file_value = mock_local_tmp_file.return_value.__enter__.return_value
<ide> mock_ftp_hook_retrieve_file.assert_called_once_with(
<del> local_full_path_or_buffer=mock_local_tmp_file_value.name, remote_full_path=operator.ftp_path
<add> local_full_path_or_buffer=mock_local_tmp_file_value.name, remote_full_path=ftp_file
<ide> )
<ide>
<ide> mock_s3_hook_load_file.assert_called_once_with(
<ide> filename=mock_local_tmp_file_value.name,
<del> key=operator.s3_key,
<del> bucket_name=operator.s3_bucket,
<add> key=s3_file,
<add> bucket_name=BUCKET,
<ide> acl_policy=None,
<ide> encrypt=False,
<ide> gzip=False,
<ide> replace=False,
<ide> )
<add>
<add> @mock.patch("airflow.providers.ftp.hooks.ftp.FTPHook.retrieve_file")
<add> @mock.patch("airflow.providers.amazon.aws.hooks.s3.S3Hook.load_file")
<add> @mock.patch("airflow.providers.amazon.aws.transfers.ftp_to_s3.NamedTemporaryFile")
<add> def test_execute(self, mock_local_tmp_file, mock_s3_hook_load_file, mock_ftp_hook_retrieve_file):
<add> operator = FTPToS3Operator(task_id=TASK_ID, s3_bucket=BUCKET, s3_key=S3_KEY, ftp_path=FTP_PATH)
<add> operator.execute(None)
<add>
<add> self.assert_execute(
<add> mock_local_tmp_file,
<add> mock_s3_hook_load_file,
<add> mock_ftp_hook_retrieve_file,
<add> ftp_file=operator.ftp_path,
<add> s3_file=operator.s3_key,
<add> )
<add>
<add> @mock.patch("airflow.providers.ftp.hooks.ftp.FTPHook.retrieve_file")
<add> @mock.patch("airflow.providers.amazon.aws.hooks.s3.S3Hook.load_file")
<add> @mock.patch("airflow.providers.amazon.aws.transfers.ftp_to_s3.NamedTemporaryFile")
<add> def test_execute_multiple_files_different_names(
<add> self, mock_local_tmp_file, mock_s3_hook_load_file, mock_ftp_hook_retrieve_file
<add> ):
<add>
<add> operator = FTPToS3Operator(
<add> task_id=TASK_ID,
<add> s3_bucket=BUCKET,
<add> s3_key=S3_KEY_MULTIPLE,
<add> ftp_path=FTP_PATH_MULTIPLE,
<add> ftp_filenames=['test1.txt'],
<add> s3_filenames=['test1_s3.txt'],
<add> )
<add> operator.execute(None)
<add>
<add> self.assert_execute(
<add> mock_local_tmp_file,
<add> mock_s3_hook_load_file,
<add> mock_ftp_hook_retrieve_file,
<add> ftp_file=operator.ftp_path + operator.ftp_filenames[0],
<add> s3_file=operator.s3_key + operator.s3_filenames[0],
<add> )
<add>
<add> @mock.patch("airflow.providers.ftp.hooks.ftp.FTPHook.retrieve_file")
<add> @mock.patch("airflow.providers.amazon.aws.hooks.s3.S3Hook.load_file")
<add> @mock.patch("airflow.providers.amazon.aws.transfers.ftp_to_s3.NamedTemporaryFile")
<add> def test_execute_multiple_files_same_names(
<add> self, mock_local_tmp_file, mock_s3_hook_load_file, mock_ftp_hook_retrieve_file
<add> ):
<add>
<add> operator = FTPToS3Operator(
<add> task_id=TASK_ID,
<add> s3_bucket=BUCKET,
<add> s3_key=S3_KEY_MULTIPLE,
<add> ftp_path=FTP_PATH_MULTIPLE,
<add> ftp_filenames=['test1.txt'],
<add> )
<add> operator.execute(None)
<add>
<add> self.assert_execute(
<add> mock_local_tmp_file,
<add> mock_s3_hook_load_file,
<add> mock_ftp_hook_retrieve_file,
<add> ftp_file=operator.ftp_path + operator.ftp_filenames[0],
<add> s3_file=operator.s3_key + operator.ftp_filenames[0],
<add> )
<add>
<add> @mock.patch("airflow.providers.ftp.hooks.ftp.FTPHook.list_directory")
<add> def test_execute_multiple_files_prefix(
<add> self,
<add> mock_ftp_hook_list_directory,
<add> ):
<add>
<add> operator = FTPToS3Operator(
<add> task_id=TASK_ID,
<add> s3_bucket=BUCKET,
<add> s3_key=S3_KEY_MULTIPLE,
<add> ftp_path=FTP_PATH_MULTIPLE,
<add> ftp_filenames='test_prefix',
<add> s3_filenames='s3_prefix',
<add> )
<add> operator.execute(None)
<add>
<add> mock_ftp_hook_list_directory.assert_called_once_with(path=FTP_PATH_MULTIPLE) | 2 |
Text | Text | clarify .next in .gitignore text | 7e67152232f30d7c7ef8b178e60a36f54f3d594e | <ide><path>readme.md
<ide> Next.js can be deployed to other hosting solutions too. Please have a look at th
<ide>
<ide> Note: `NODE_ENV` is properly configured by the `next` subcommands, if absent, to maximize performance. if you’re using Next.js [programmatically](#custom-server-and-routing), it’s your responsibility to set `NODE_ENV=production` manually!
<ide>
<del>Note: we recommend putting `.next`, or your custom dist folder (Please have a look at ['Custom Config'](https://github.com/zeit/next.js#custom-configuration)). You can set a custom folder in config, `.npmignore`, or `.gitignore`. Otherwise, use `files` or `now.files` to opt-into a whitelist of files you want to deploy (and obviously exclude `.next` or your custom dist folder).
<add>Note: we recommend putting `.next`, or your [custom dist folder](https://github.com/zeit/next.js#custom-configuration), in `.gitignore` or `.npmignore`. Otherwise, use `files` or `now.files` to opt-into a whitelist of files you want to deploy, excluding `.next` or your custom dist folder.
<ide>
<ide> ## Static HTML export
<ide> | 1 |
Python | Python | use int_shape where appropriate | 2a3d4722c21d99d882b2cbc2da451108147fe1c4 | <ide><path>keras/layers/normalization.py
<ide> def build(self, input_shape):
<ide> def call(self, x, mask=None):
<ide> if self.mode == 0 or self.mode == 2:
<ide> assert self.built, 'Layer must be built before being called'
<del> input_shape = self.input_spec[0].shape
<add> input_shape = K.int_shape(x)
<ide>
<ide> reduction_axes = list(range(len(input_shape)))
<ide> del reduction_axes[self.axis]
<ide><path>keras/layers/recurrent.py
<ide> def call(self, x, mask=None):
<ide> # input shape: (nb_samples, time (padded with zeros), input_dim)
<ide> # note that the .build() method of subclasses MUST define
<ide> # self.input_spec with a complete input shape.
<del> input_shape = self.input_spec[0].shape
<add> input_shape = K.int_shape(x)
<ide> if self.unroll and input_shape[1] is None:
<ide> raise ValueError('Cannot unroll a RNN if the '
<ide> 'time dimension is undefined. \n'
<ide> def reset_states(self):
<ide>
<ide> def preprocess_input(self, x):
<ide> if self.consume_less == 'cpu':
<del> input_shape = self.input_spec[0].shape
<add> input_shape = K.int_shape(x)
<ide> input_dim = input_shape[2]
<ide> timesteps = input_shape[1]
<ide> return time_distributed_dense(x, self.W, self.b, self.dropout_W,
<ide> def get_constants(self, x):
<ide> else:
<ide> constants.append(K.cast_to_floatx(1.))
<ide> if self.consume_less == 'cpu' and 0 < self.dropout_W < 1:
<del> input_shape = self.input_spec[0].shape
<add> input_shape = K.int_shape(x)
<ide> input_dim = input_shape[-1]
<ide> ones = K.ones_like(K.reshape(x[:, 0, 0], (-1, 1)))
<ide> ones = K.tile(ones, (1, int(input_dim)))
<ide> def reset_states(self):
<ide>
<ide> def preprocess_input(self, x):
<ide> if self.consume_less == 'cpu':
<del> input_shape = self.input_spec[0].shape
<add> input_shape = K.int_shape(x)
<ide> input_dim = input_shape[2]
<ide> timesteps = input_shape[1]
<ide>
<ide> def get_constants(self, x):
<ide> constants.append([K.cast_to_floatx(1.) for _ in range(3)])
<ide>
<ide> if 0 < self.dropout_W < 1:
<del> input_shape = self.input_spec[0].shape
<add> input_shape = K.int_shape(x)
<ide> input_dim = input_shape[-1]
<ide> ones = K.ones_like(K.reshape(x[:, 0, 0], (-1, 1)))
<ide> ones = K.tile(ones, (1, int(input_dim)))
<ide> def preprocess_input(self, x):
<ide> dropout = self.dropout_W
<ide> else:
<ide> dropout = 0
<del> input_shape = self.input_spec[0].shape
<add> input_shape = K.int_shape(x)
<ide> input_dim = input_shape[2]
<ide> timesteps = input_shape[1]
<ide>
<ide> def get_constants(self, x):
<ide> constants.append([K.cast_to_floatx(1.) for _ in range(4)])
<ide>
<ide> if 0 < self.dropout_W < 1:
<del> input_shape = self.input_spec[0].shape
<add> input_shape = K.int_shape(x)
<ide> input_dim = input_shape[-1]
<ide> ones = K.ones_like(K.reshape(x[:, 0, 0], (-1, 1)))
<ide> ones = K.tile(ones, (1, int(input_dim)))
<ide><path>keras/layers/wrappers.py
<ide> def get_output_shape_for(self, input_shape):
<ide> return (child_output_shape[0], timesteps) + child_output_shape[1:]
<ide>
<ide> def call(self, X, mask=None):
<del> input_shape = self.input_spec[0].shape
<add> input_shape = K.int_shape(X)
<ide> if input_shape[0]:
<ide> # batch size matters, use rnn-based implementation
<ide> def step(x, states):
<ide> def step(x, states):
<ide> input_length = input_shape[1]
<ide> if not input_length:
<ide> input_length = K.shape(X)[1]
<del> X = K.reshape(X, (-1, ) + input_shape[2:]) # (nb_samples * timesteps, ...)
<add> X = K.reshape(X, (-1,) + input_shape[2:]) # (nb_samples * timesteps, ...)
<ide> y = self.layer.call(X) # (nb_samples * timesteps, ...)
<ide> # (nb_samples, timesteps, ...)
<ide> output_shape = self.get_output_shape_for(input_shape) | 3 |
Javascript | Javascript | extract updateattribute from updateobject | e29f28d6486eb2d49f62122d9cc7d7f92e05fac1 | <ide><path>src/renderers/webgl/WebGLObjects.js
<ide> THREE.WebGLObjects = function ( gl, properties, info ) {
<ide> for ( var name in attributes ) {
<ide>
<ide> var attribute = attributes[ name ];
<add> updateAttribute( attribute, name );
<ide>
<del> var bufferType = ( name === 'index' ) ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER;
<add> }
<ide>
<del> var data = ( attribute instanceof THREE.InterleavedBufferAttribute ) ? attribute.data : attribute;
<add> }
<ide>
<del> var attributeProperties = properties.get( data );
<add> function updateAttribute ( attribute, name ) {
<ide>
<del> if ( attributeProperties.__webglBuffer === undefined ) {
<add> var bufferType = ( name === 'index' ) ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER;
<ide>
<del> attributeProperties.__webglBuffer = gl.createBuffer();
<del> gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
<add> var data = ( attribute instanceof THREE.InterleavedBufferAttribute ) ? attribute.data : attribute;
<ide>
<del> var usage = gl.STATIC_DRAW;
<add> var attributeProperties = properties.get( data );
<ide>
<del> if ( data instanceof THREE.DynamicBufferAttribute
<del> || ( data instanceof THREE.InstancedBufferAttribute && data.dynamic === true )
<del> || ( data instanceof THREE.InterleavedBuffer && data.dynamic === true ) ) {
<add> if ( attributeProperties.__webglBuffer === undefined ) {
<ide>
<del> usage = gl.DYNAMIC_DRAW;
<add> attributeProperties.__webglBuffer = gl.createBuffer();
<add> gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
<ide>
<del> }
<add> var usage = gl.STATIC_DRAW;
<ide>
<del> gl.bufferData( bufferType, data.array, usage );
<add> if ( data instanceof THREE.DynamicBufferAttribute
<add> || ( data instanceof THREE.InstancedBufferAttribute && data.dynamic === true )
<add> || ( data instanceof THREE.InterleavedBuffer && data.dynamic === true ) ) {
<ide>
<del> data.needsUpdate = false;
<add> usage = gl.DYNAMIC_DRAW;
<ide>
<del> } else if ( data.needsUpdate === true ) {
<add> }
<ide>
<del> gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
<add> gl.bufferData( bufferType, data.array, usage );
<ide>
<del> if ( data.updateRange === undefined || data.updateRange.count === -1 ) { // Not using update ranges
<add> data.needsUpdate = false;
<ide>
<del> gl.bufferSubData( bufferType, 0, data.array );
<add> } else if ( data.needsUpdate === true ) {
<ide>
<del> } else if ( data.updateRange.count === 0 ) {
<add> gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
<ide>
<del> console.error( 'THREE.WebGLRenderer.updateObject: using updateRange for THREE.DynamicBufferAttribute and marked as needsUpdate but count is 0, ensure you are using set methods or updating manually.' );
<add> if ( data.updateRange === undefined || data.updateRange.count === -1 ) { // Not using update ranges
<ide>
<del> } else {
<add> gl.bufferSubData( bufferType, 0, data.array );
<ide>
<del> gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT,
<del> data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) );
<add> } else if ( data.updateRange.count === 0 ) {
<ide>
<del> data.updateRange.count = 0; // reset range
<add> console.error( 'THREE.WebGLRenderer.updateObject: using updateRange for THREE.DynamicBufferAttribute and marked as needsUpdate but count is 0, ensure you are using set methods or updating manually.' );
<ide>
<del> }
<add> } else {
<ide>
<del> data.needsUpdate = false;
<add> gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT,
<add> data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) );
<add>
<add> data.updateRange.count = 0; // reset range
<ide>
<ide> }
<ide>
<add> data.needsUpdate = false;
<add>
<ide> }
<ide>
<del> };
<add> }
<add>
<add>
<ide>
<ide> // returns the webgl buffer for a specified attribute
<ide> this.getAttributeBuffer = function ( attribute ) { | 1 |
Mixed | Go | add support for ambient capabilities | 199e19548e93262ab00873c1d761b0d05f866042 | <ide><path>docs/reference/run.md
<ide> since Docker 1.12. In Docker 1.10 and 1.11 this did not happen and it may be nec
<ide> to use a custom seccomp profile or use `--security-opt seccomp=unconfined` when adding
<ide> capabilities.
<ide>
<add>It is only possible to grant capabilities to a container running as a user other than `root`
<add>on a system with a Linux kernel version of 4.3 or later, as this requires "ambient capabilities"
<add>to be granted. These will be added if the kernel allows it from Docker version 1.13.
<add>
<ide> ## Logging drivers (--log-driver)
<ide>
<ide> The container can have a different logging driver than the Docker daemon. Use
<ide><path>docs/security/security.md
<ide> capability removal, or less secure through the addition of capabilities.
<ide> The best practice for users would be to remove all capabilities except
<ide> those explicitly required for their processes.
<ide>
<add>Linux kernel versions since 4.3 allow Docker to grant capabilities to
<add>container processes running as a non root user. This adds an extra
<add>layer of protection as the process can then be denied access to be able
<add>to write files belonging to the root uid, for example. User namespaces
<add>also allow capabilities to be granted to processes that are effectively
<add>non root, but these capabilities are limited to resources created in the
<add>user namespace, so they have limitations.
<add>
<ide> ## Other kernel security features
<ide>
<ide> Capabilities are just one of the many security features provided by
<ide><path>integration-cli/docker_cli_run_unix_test.go
<ide> func (s *DockerSuite) TestRunNoNewPrivSetuid(c *check.C) {
<ide> }
<ide> }
<ide>
<add>func (s *DockerSuite) TestRunAmbientCapabilities(c *check.C) {
<add> testRequires(c, DaemonIsLinux, ambientCapabilities)
<add>
<add> // test that a non root user can gain capabilities
<add> runCmd := exec.Command(dockerBinary, "run", "--user", "1000", "--cap-add", "chown", "busybox", "chown", "100", "/tmp")
<add> _, _, err := runCommandWithOutput(runCmd)
<add> c.Assert(err, check.IsNil)
<add> // test that non root user has default capabilities
<add> runCmd = exec.Command(dockerBinary, "run", "--user", "1000", "busybox", "chown", "100", "/tmp")
<add> _, _, err = runCommandWithOutput(runCmd)
<add> c.Assert(err, check.IsNil)
<add> // test this fails without cap_chown
<add> runCmd = exec.Command(dockerBinary, "run", "--user", "1000", "--cap-drop", "chown", "busybox", "chown", "100", "/tmp")
<add> out, _, err := runCommandWithOutput(runCmd)
<add> c.Assert(err, checker.NotNil, check.Commentf(out))
<add> c.Assert(strings.TrimSpace(out), checker.Equals, "chown: /tmp: Operation not permitted")
<add>}
<add>
<ide> func (s *DockerSuite) TestRunApparmorProcDirectory(c *check.C) {
<ide> testRequires(c, SameHostDaemon, Apparmor)
<ide>
<ide><path>integration-cli/requirements_unix.go
<ide> var (
<ide> },
<ide> "Test cannot be run with 'sysctl kernel.unprivileged_userns_clone' = 0",
<ide> }
<add> ambientCapabilities = testRequirement{
<add> func() bool {
<add> content, err := ioutil.ReadFile("/proc/self/status")
<add> if err == nil && strings.Contains(string(content), "CapAmb:") {
<add> return true
<add> }
<add> return false
<add> },
<add> "Test cannot be run without a kernel (4.3+) supporting ambient capabilities",
<add> }
<ide> )
<ide>
<ide> func init() { | 4 |
PHP | PHP | fix multi-version assertion | dd8a8cb9a7fb2dc796246a6263e37e5b7383a04d | <ide><path>tests/TestCase/Error/ErrorHandlerTest.php
<ide> public function testHandleErrorLoggingTrace(): void
<ide>
<ide> $messages = $this->logger->read();
<ide> $this->assertMatchesRegularExpression('/^(notice|debug|warning)/', $messages[0]);
<del> if (version_compare(PHP_VERSION, '8.0.0-dev', '<')) {
<del> $this->assertStringContainsString(
<del> 'Notice (8): Undefined variable: out in [' . __FILE__ . ', line ' . (__LINE__ - 8) . ']',
<del> $messages[0]
<del> );
<del> } else {
<del> $this->assertStringContainsString(
<del> 'Warning (2): Undefined variable $out in [' . __FILE__ . ', line ' . (__LINE__ - 12) . ']',
<del> $messages[0]
<del> );
<del> }
<add> $this->assertMatchesRegularExpression('/Undefined variable\:? \$?out in/', $messages[0]);
<add> $this->assertStringContainsString('[' . __FILE__ . ', line ' . (__LINE__ - 6) . ']', $messages[0]);
<ide> $this->assertStringContainsString('Trace:', $messages[0]);
<ide> $this->assertStringContainsString(__NAMESPACE__ . '\ErrorHandlerTest::testHandleErrorLoggingTrace()', $messages[0]);
<ide> $this->assertStringContainsString('Request URL:', $messages[0]); | 1 |
Python | Python | add bigquery copy operator | 6c9d27daca030eefa380592c262bb89d0a811d5d | <ide><path>airflow/contrib/hooks/bigquery_hook.py
<ide> def run_extract(self, source_dataset_table, destination_cloud_storage_uris, comp
<ide>
<ide> return self.run_with_configuration(configuration)
<ide>
<add> def run_copy(self, source_dataset_tables, destination_project_dataset_table, write_disposition='WRITE_EMPTY', create_disposition='CREATE_IF_NEEDED'):
<add> """
<add> Executes a BigQuery copy command to copy data from one BigQuery table
<add> to another. See here:
<add>
<add> https://cloud.google.com/bigquery/docs/reference/v2/jobs#configuration.copy
<add>
<add> For more details about these parameters.
<add>
<add> :param source_dataset_tables: One or more dotted <dataset>.<table>
<add> BigQuery tables to use as the source data. Use a list if there are
<add> multiple source tables.
<add> :type source_dataset_tables: list|string
<add> :param destination_project_dataset_table: The destination BigQuery
<add> table. Format is: <project>.<dataset>.<table>
<add> :type destination_project_dataset_table: string
<add> :param write_disposition: The write disposition if the table already exists.
<add> :type write_disposition: string
<add> :param create_disposition: The create disposition if the table doesn't exist.
<add> :type create_disposition: string
<add> """
<add> source_dataset_tables = [source_dataset_tables] if not isinstance(source_dataset_tables, list) else source_dataset_tables
<add> source_project_dataset_tables = []
<add>
<add> for source_dataset_table in source_dataset_tables:
<add> assert '.' in source_dataset_table, \
<add> 'Expected source_dataset_table in the format of <dataset>.<table>. Got: {}'.format(source_dataset_table)
<add>
<add> source_dataset, source_table = source_dataset_table.split('.', 1)
<add> source_project_dataset_tables.append({
<add> 'projectId': self.project_id,
<add> 'datasetId': source_dataset,
<add> 'tableId': source_table
<add> })
<add>
<add> assert 3 == len(destination_project_dataset_table.split('.')), \
<add> 'Expected destination_project_dataset_table in the format of <project>.<dataset>.<table>. Got: {}'.format(destination_project_dataset_table)
<add>
<add> destination_project, destination_dataset, destination_table = destination_project_dataset_table.split('.', 2)
<add> configuration = {
<add> 'copy': {
<add> 'createDisposition': create_disposition,
<add> 'writeDisposition': write_disposition,
<add> 'sourceTables': source_project_dataset_tables,
<add> 'destinationTable': {
<add> 'projectId': destination_project,
<add> 'datasetId': destination_dataset,
<add> 'tableId': destination_table
<add> }
<add> }
<add> }
<add>
<add> return self.run_with_configuration(configuration)
<add>
<ide> def run_with_configuration(self, configuration):
<ide> """
<ide> Executes a BigQuery SQL query. See here:
<ide><path>airflow/contrib/operators/bigquery_to_bigquery.py
<add>import logging
<add>
<add>from airflow.contrib.hooks.bigquery_hook import BigQueryHook
<add>from airflow.models import BaseOperator
<add>from airflow.utils import apply_defaults
<add>
<add>class BigQueryToBigQueryOperator(BaseOperator):
<add> """
<add> Copy a BigQuery table to another BigQuery table.
<add> """
<add> template_fields = ('source_dataset_tables','destination_project_dataset_table',)
<add> template_ext = ('.sql',)
<add> ui_color = '#e6f0e4'
<add>
<add> @apply_defaults
<add> def __init__(
<add> self,
<add> source_dataset_tables,
<add> destination_project_dataset_table,
<add> write_disposition='WRITE_EMPTY',
<add> create_disposition='CREATE_IF_NEEDED',
<add> bigquery_conn_id='bigquery_default',
<add> delegate_to=None,
<add> *args,
<add> **kwargs):
<add> """
<add> Copies data from one BigQuery table to another. See here:
<add>
<add> https://cloud.google.com/bigquery/docs/reference/v2/jobs#configuration.copy
<add>
<add> For more details about these parameters.
<add>
<add> :param source_dataset_tables: One or more dotted <dataset>.<table>
<add> BigQuery tables to use as the source data. Use a list if there are
<add> multiple source tables.
<add> :type source_dataset_tables: list|string
<add> :param destination_project_dataset_table: The destination BigQuery
<add> table. Format is: <project>.<dataset>.<table>
<add> :type destination_project_dataset_table: string
<add> :param write_disposition: The write disposition if the table already exists.
<add> :type write_disposition: string
<add> :param create_disposition: The create disposition if the table doesn't exist.
<add> :type create_disposition: string
<add> :param bigquery_conn_id: reference to a specific BigQuery hook.
<add> :type bigquery_conn_id: string
<add> :param delegate_to: The account to impersonate, if any.
<add> For this to work, the service account making the request must have domain-wide delegation enabled.
<add> :type delegate_to: string
<add> """
<add> super(BigQueryToBigQueryOperator, self).__init__(*args, **kwargs)
<add> self.source_dataset_tables = source_dataset_tables
<add> self.destination_project_dataset_table = destination_project_dataset_table
<add> self.write_disposition = write_disposition
<add> self.create_disposition = create_disposition
<add> self.bigquery_conn_id = bigquery_conn_id
<add> self.delegate_to = delegate_to
<add>
<add> def execute(self, context):
<add> logging.info('Executing copy of %s into: %s', self.source_dataset_tables, self.destination_project_dataset_table)
<add> hook = BigQueryHook(bigquery_conn_id=self.bigquery_conn_id, delegate_to=self.delegate_to)
<add> conn = hook.get_conn()
<add> cursor = conn.cursor()
<add> cursor.run_copy(
<add> self.source_dataset_tables,
<add> self.destination_project_dataset_table,
<add> self.write_disposition,
<add> self.create_disposition) | 2 |
Javascript | Javascript | make schedulerminheap flow strict | 7a7e792a6fd7668b37e475bf39e58fdb24e4ad81 | <ide><path>packages/scheduler/src/SchedulerMinHeap.js
<ide> * This source code is licensed under the MIT license found in the
<ide> * LICENSE file in the root directory of this source tree.
<ide> *
<del> * @flow
<add> * @flow strict
<ide> */
<ide>
<ide> type Heap = Array<Node>;
<ide> export function pop(heap: Heap): Node | null {
<ide> }
<ide> }
<ide>
<del>function siftUp(heap, node, index) {
<add>function siftUp(heap, node, i) {
<add> let index = i;
<ide> while (true) {
<ide> const parentIndex = Math.floor((index - 1) / 2);
<ide> const parent = heap[parentIndex];
<ide> function siftUp(heap, node, index) {
<ide> }
<ide> }
<ide>
<del>function siftDown(heap, node, index) {
<add>function siftDown(heap, node, i) {
<add> let index = i;
<ide> const length = heap.length;
<ide> while (index < length) {
<ide> const leftIndex = (index + 1) * 2 - 1; | 1 |
PHP | PHP | add bootstrap 5 styled pagination | 73d0ee647dc10f7f8fd452e15c171239a1f59e59 | <ide><path>src/Illuminate/Pagination/AbstractPaginator.php
<ide> public static function useTailwind()
<ide> static::defaultSimpleView('pagination::simple-tailwind');
<ide> }
<ide>
<add> /**
<add> * Indicate that Bootstrap 5 styling should be used for generated links.
<add> *
<add> * @return void
<add> */
<add> public static function useBootstrapFive()
<add> {
<add> static::defaultView('pagination::bootstrap-5');
<add> static::defaultSimpleView('pagination::simple-bootstrap-5');
<add> }
<add>
<ide> /**
<ide> * Indicate that Bootstrap 4 styling should be used for generated links.
<ide> *
<ide><path>src/Illuminate/Pagination/resources/views/bootstrap-5.blade.php
<add>@if ($paginator->hasPages())
<add> <nav class="d-flex justify-items-center justify-content-between">
<add> <div class="d-flex justify-content-between flex-fill d-sm-none">
<add> <ul class="pagination">
<add> {{-- Previous Page Link --}}
<add> @if ($paginator->onFirstPage())
<add> <li class="page-item disabled" aria-disabled="true">
<add> <span class="page-link">@lang('pagination.previous')</span>
<add> </li>
<add> @else
<add> <li class="page-item">
<add> <a class="page-link" href="{{ $paginator->previousPageUrl() }}" rel="prev">@lang('pagination.previous')</a>
<add> </li>
<add> @endif
<add>
<add> {{-- Next Page Link --}}
<add> @if ($paginator->hasMorePages())
<add> <li class="page-item">
<add> <a class="page-link" href="{{ $paginator->nextPageUrl() }}" rel="next">@lang('pagination.next')</a>
<add> </li>
<add> @else
<add> <li class="page-item disabled" aria-disabled="true">
<add> <span class="page-link">@lang('pagination.next')</span>
<add> </li>
<add> @endif
<add> </ul>
<add> </div>
<add>
<add> <div class="d-none flex-sm-fill d-sm-flex align-items-sm-center justify-content-sm-between">
<add> <div>
<add> <p class="small text-muted">
<add> {!! __('Showing') !!}
<add> <span class="font-medium">{{ $paginator->firstItem() }}</span>
<add> {!! __('to') !!}
<add> <span class="font-medium">{{ $paginator->lastItem() }}</span>
<add> {!! __('of') !!}
<add> <span class="font-medium">{{ $paginator->total() }}</span>
<add> {!! __('results') !!}
<add> </p>
<add> </div>
<add>
<add> <div>
<add> <ul class="pagination">
<add> {{-- Previous Page Link --}}
<add> @if ($paginator->onFirstPage())
<add> <li class="page-item disabled" aria-disabled="true" aria-label="@lang('pagination.previous')">
<add> <span class="page-link" aria-hidden="true">‹</span>
<add> </li>
<add> @else
<add> <li class="page-item">
<add> <a class="page-link" href="{{ $paginator->previousPageUrl() }}" rel="prev" aria-label="@lang('pagination.previous')">‹</a>
<add> </li>
<add> @endif
<add>
<add> {{-- Pagination Elements --}}
<add> @foreach ($elements as $element)
<add> {{-- "Three Dots" Separator --}}
<add> @if (is_string($element))
<add> <li class="page-item disabled" aria-disabled="true"><span class="page-link">{{ $element }}</span></li>
<add> @endif
<add>
<add> {{-- Array Of Links --}}
<add> @if (is_array($element))
<add> @foreach ($element as $page => $url)
<add> @if ($page == $paginator->currentPage())
<add> <li class="page-item active" aria-current="page"><span class="page-link">{{ $page }}</span></li>
<add> @else
<add> <li class="page-item"><a class="page-link" href="{{ $url }}">{{ $page }}</a></li>
<add> @endif
<add> @endforeach
<add> @endif
<add> @endforeach
<add>
<add> {{-- Next Page Link --}}
<add> @if ($paginator->hasMorePages())
<add> <li class="page-item">
<add> <a class="page-link" href="{{ $paginator->nextPageUrl() }}" rel="next" aria-label="@lang('pagination.next')">›</a>
<add> </li>
<add> @else
<add> <li class="page-item disabled" aria-disabled="true" aria-label="@lang('pagination.next')">
<add> <span class="page-link" aria-hidden="true">›</span>
<add> </li>
<add> @endif
<add> </ul>
<add> </div>
<add> </div>
<add> </nav>
<add>@endif
<ide><path>src/Illuminate/Pagination/resources/views/simple-bootstrap-5.blade.php
<add>@if ($paginator->hasPages())
<add> <nav role="navigation" aria-label="Pagination Navigation">
<add> <ul class="pagination">
<add> {{-- Previous Page Link --}}
<add> @if ($paginator->onFirstPage())
<add> <li class="page-item disabled" aria-disabled="true">
<add> <span class="page-link">{!! __('pagination.previous') !!}</span>
<add> </li>
<add> @else
<add> <li class="page-item">
<add> <a class="page-link" href="{{ $paginator->previousPageUrl() }}" rel="prev">
<add> {!! __('pagination.previous') !!}
<add> </a>
<add> </li>
<add> @endif
<add>
<add> {{-- Next Page Link --}}
<add> @if ($paginator->hasMorePages())
<add> <li class="page-item">
<add> <a class="page-link" href="{{ $paginator->nextPageUrl() }}" rel="next">{!! __('pagination.next') !!}</a>
<add> </li>
<add> @else
<add> <li class="page-item disabled" aria-disabled="true">
<add> <span class="page-link">{!! __('pagination.next') !!}</span>
<add> </li>
<add> @endif
<add> </ul>
<add> </nav>
<add>@endif | 3 |
Javascript | Javascript | add test for issue | e7d37ee45ac48b0ff2a3d43f7236d316be6c241e | <ide><path>test/ng/directive/ngRepeatSpec.js
<ide> describe('ngRepeat', function() {
<ide> }));
<ide>
<ide>
<del> it('should ngRepeat over array of primitive correctly', inject(function($rootScope, $compile) {
<add> it('should ngRepeat over array of primitives', inject(function($rootScope, $compile) {
<ide> element = $compile(
<ide> '<ul>' +
<del> '<li ng-repeat="item in items" ng-init="suffix = \';\'" ng-bind="item + suffix"></li>' +
<add> '<li ng-repeat="item in items">{{item}};</li>' +
<ide> '</ul>')($rootScope);
<ide>
<ide> Array.prototype.extraProperty = "should be ignored";
<ide> describe('ngRepeat', function() {
<ide> $rootScope.$digest();
<ide> expect(element.find('li').length).toEqual(1);
<ide> expect(element.text()).toEqual('test;');
<del>
<add>
<ide> $rootScope.items = ['same', 'value'];
<ide> $rootScope.$digest();
<ide> expect(element.find('li').length).toEqual(2);
<ide> expect(element.text()).toEqual('same;value;');
<del>
<del> // number
<add>
<add> // number
<ide> $rootScope.items = [12, 12, 12];
<ide> $rootScope.$digest();
<ide> expect(element.find('li').length).toEqual(3);
<ide> describe('ngRepeat', function() {
<ide> expect(element.text()).toEqual('misko:swe;shyam:set;');
<ide> }));
<ide>
<del>
<del> it('should ngRepeat over object with primitive value correctly', inject(function($rootScope, $compile) {
<add>
<add> it('should ngRepeat over object with changing primitive value',
<add> inject(function($rootScope, $compile) {
<add>
<ide> element = $compile(
<ide> '<ul>' +
<del> '<li ng-repeat="(key, value) in items" ng-bind="key + \':\' + value + \';\' "></li>' +
<add> '<li ng-repeat="(key, value) in items">' +
<add> '{{key}}:{{value}};' +
<add> '<input type="checkbox" ng-model="items[key]">' +
<add> '</li>' +
<ide> '</ul>')($rootScope);
<del> $rootScope.items = {misko:'true', shyam:'true', zhenbo: 'true'};
<add>
<add> $rootScope.items = {misko: true, shyam: true, zhenbo:true};
<ide> $rootScope.$digest();
<ide> expect(element.find('li').length).toEqual(3);
<ide> expect(element.text()).toEqual('misko:true;shyam:true;zhenbo:true;');
<del>
<del> $rootScope.items = {misko:'false', shyam:'true', zhenbo: 'true'};
<del> $rootScope.$digest();
<del> expect(element.find('li').length).toEqual(3);
<add>
<add> browserTrigger(element.find('input').eq(0), 'click');
<add>
<ide> expect(element.text()).toEqual('misko:false;shyam:true;zhenbo:true;');
<del>
<del> $rootScope.items = {misko:'false', shyam:'false', zhenbo: 'false'};
<del> $rootScope.$digest();
<del> expect(element.find('li').length).toEqual(3);
<del> expect(element.text()).toEqual('misko:false;shyam:false;zhenbo:false;');
<del>
<del> $rootScope.items = {misko:'true'};
<del> $rootScope.$digest();
<del> expect(element.find('li').length).toEqual(1);
<del> expect(element.text()).toEqual('misko:true;');
<add> expect(element.find('input')[0].checked).toBe(false);
<add> expect(element.find('input')[1].checked).toBe(true);
<add> expect(element.find('input')[2].checked).toBe(true);
<ide>
<del> $rootScope.items = {shyam:'true', zhenbo: 'false'};
<add> browserTrigger(element.find('input').eq(0), 'click');
<add> expect(element.text()).toEqual('misko:true;shyam:true;zhenbo:true;');
<add> expect(element.find('input')[0].checked).toBe(true);
<add> expect(element.find('input')[1].checked).toBe(true);
<add> expect(element.find('input')[2].checked).toBe(true);
<add>
<add> browserTrigger(element.find('input').eq(1), 'click');
<add> expect(element.text()).toEqual('misko:true;shyam:false;zhenbo:true;');
<add> expect(element.find('input')[0].checked).toBe(true);
<add> expect(element.find('input')[1].checked).toBe(false);
<add> expect(element.find('input')[2].checked).toBe(true);
<add>
<add> $rootScope.items = {misko: false, shyam: true, zhenbo: true};
<ide> $rootScope.$digest();
<del> expect(element.find('li').length).toEqual(2);
<del> expect(element.text()).toEqual('shyam:true;zhenbo:false;');
<add> expect(element.text()).toEqual('misko:false;shyam:true;zhenbo:true;');
<add> expect(element.find('input')[0].checked).toBe(false);
<add> expect(element.find('input')[1].checked).toBe(true);
<add> expect(element.find('input')[2].checked).toBe(true);
<ide> }));
<ide>
<ide> | 1 |
Python | Python | update links to new weights | 6be46a6e6422d7ab34984d6fbcaadad0323e5349 | <ide><path>transformers/configuration_gpt2.py
<ide>
<ide> GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP = {"gpt2": "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-config.json",
<ide> "gpt2-medium": "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-medium-config.json",
<del> "gpt2-large": "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-large-config.json"}
<add> "gpt2-large": "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-large-config.json",
<add> "distilgpt2": "https://s3.amazonaws.com/models.huggingface.co/bert/distilgpt2-config.json",}
<ide>
<ide> class GPT2Config(PretrainedConfig):
<ide> """Configuration class to store the configuration of a `GPT2Model`.
<ide><path>transformers/modeling_gpt2.py
<ide>
<ide> GPT2_PRETRAINED_MODEL_ARCHIVE_MAP = {"gpt2": "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-pytorch_model.bin",
<ide> "gpt2-medium": "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-medium-pytorch_model.bin",
<del> "gpt2-large": "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-large-pytorch_model.bin"}
<add> "gpt2-large": "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-large-pytorch_model.bin",
<add> "distilgpt2": "https://s3.amazonaws.com/models.huggingface.co/bert/distilgpt2-pytorch_model.bin",}
<ide>
<ide> def load_tf_weights_in_gpt2(model, config, gpt2_checkpoint_path):
<ide> """ Load tf checkpoints in a pytorch model
<ide><path>transformers/modeling_tf_gpt2.py
<ide>
<ide> TF_GPT2_PRETRAINED_MODEL_ARCHIVE_MAP = {"gpt2": "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-tf_model.h5",
<ide> "gpt2-medium": "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-medium-tf_model.h5",
<del> "gpt2-large": "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-large-tf_model.h5"}
<add> "gpt2-large": "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-large-tf_model.h5",
<add> "distilgpt2": "https://s3.amazonaws.com/models.huggingface.co/bert/distilgpt2-tf_model.h5",}
<ide>
<ide>
<ide> def load_gpt2_pt_weights_in_tf2(tf_model, pytorch_checkpoint_path):
<ide><path>transformers/tokenization_gpt2.py
<ide> def lru_cache():
<ide> 'gpt2': "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-vocab.json",
<ide> 'gpt2-medium': "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-medium-vocab.json",
<ide> 'gpt2-large': "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-large-vocab.json",
<add> 'distilgpt2': "https://s3.amazonaws.com/models.huggingface.co/bert/distilgpt2-vocab.json",
<ide> },
<ide> 'merges_file':
<ide> {
<ide> 'gpt2': "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-merges.txt",
<ide> 'gpt2-medium': "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-medium-merges.txt",
<ide> 'gpt2-large': "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-large-merges.txt",
<add> 'distilgpt2': "https://s3.amazonaws.com/models.huggingface.co/bert/distilgpt2-merges.txt",
<ide> },
<ide> }
<ide>
<ide> PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
<ide> 'gpt2': 1024,
<ide> 'gpt2-medium': 1024,
<ide> 'gpt2-large': 1024,
<add> 'distilgpt2': 1024,
<ide> }
<ide>
<ide> @lru_cache() | 4 |
Javascript | Javascript | remove message argument in cluster setup test | 6563e56aef5287646aa433bfe088a73a2bea855d | <ide><path>test/parallel/test-cluster-setup-master-cumulative.js
<ide> const cluster = require('cluster');
<ide>
<ide> assert(cluster.isMaster);
<ide>
<del>assert.deepStrictEqual(
<del> cluster.settings,
<del> {},
<del> 'cluster.settings should not be initialized until needed'
<del>);
<add>// cluster.settings should not be initialized until needed
<add>assert.deepStrictEqual(cluster.settings, {});
<ide>
<ide> cluster.setupMaster();
<ide> assert.deepStrictEqual(cluster.settings, { | 1 |
Ruby | Ruby | add more information to comments | 6b248f6ea56b318d39b8c28b2a9f69a7d420f1fb | <ide><path>railties/lib/rails/commands.rb
<ide> Rails::Console.start(Rails.application)
<ide>
<ide> when 'server'
<del> # try to guess application's path if there is no config.ru file in current dir
<del> # it allows to run script/rails server from other directories
<add> # Change to the application's path if there is no config.ru file in current dir.
<add> # This allows us to run script/rails server from other directories, but still get
<add> # the main config.ru and properly set the tmp directory.
<ide> Dir.chdir(File.expand_path('../../', APP_PATH)) unless File.exists?(File.expand_path("config.ru"))
<ide>
<ide> require 'rails/commands/server'
<ide> Rails::Server.new.tap { |server|
<del> # we need to require application after the server sets environment
<add> # We need to require application after the server sets environment,
<add> # otherwise the --environment option given to the server won't propagate.
<ide> require APP_PATH
<ide> Dir.chdir(Rails.application.root)
<ide> server.start | 1 |
Mixed | Python | add `unauthenticated` exception | 4c17d1441f184eabea9000155f07445bcc2aa14c | <ide><path>docs/api-guide/exceptions.md
<ide> Raised if the request contains malformed data when accessing `request.DATA` or `
<ide>
<ide> By default this exception results in a response with the HTTP status code "400 Bad Request".
<ide>
<add>## Unauthenticated
<add>
<add>**Signature:** `Unauthenticated(detail=None)`
<add>
<add>Raised when an unauthenticated incoming request fails the permission checks.
<add>
<add>By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the [authentication documentation][authentication] for more details.
<add>
<ide> ## PermissionDenied
<ide>
<ide> **Signature:** `PermissionDenied(detail=None)`
<ide>
<del>Raised when an incoming request fails the permission checks.
<add>Raised when an authenticated incoming request fails the permission checks.
<ide>
<ide> By default this exception results in a response with the HTTP status code "403 Forbidden".
<ide>
<ide> Raised when an incoming request fails the throttling checks.
<ide>
<ide> By default this exception results in a response with the HTTP status code "429 Too Many Requests".
<ide>
<del>[cite]: http://www.doughellmann.com/articles/how-tos/python-exception-handling/index.html
<ide>\ No newline at end of file
<add>[cite]: http://www.doughellmann.com/articles/how-tos/python-exception-handling/index.html
<add>[authentication]: authentication.md
<ide>\ No newline at end of file
<ide><path>rest_framework/exceptions.py
<ide> def __init__(self, detail=None):
<ide> self.detail = detail or self.default_detail
<ide>
<ide>
<add>class Unauthenticated(APIException):
<add> status_code = status.HTTP_401_UNAUTHENTICATED
<add> default_detail = 'Incorrect or absent authentication credentials.'
<add>
<add> def __init__(self, detail=None):
<add> self.detail = detail or self.default_detail
<add>
<add>
<ide> class PermissionDenied(APIException):
<ide> status_code = status.HTTP_403_FORBIDDEN
<ide> default_detail = 'You do not have permission to perform this action.' | 2 |
PHP | PHP | add support for named route generation | 40a81b5b7e6a95d000c92dd619cc38fef07b4d75 | <ide><path>lib/Cake/Routing/RouteCollection.php
<ide> public function promote($which) {
<ide> }
<ide>
<ide> /**
<del> * Get a route out of the collection.
<add> * Get route(s) out of the collection.
<ide> *
<del> * @param int $index The index of the route you want.
<add> * If a string argument is provided, the first matching
<add> * route for the provided name will be returned.
<add> *
<add> * If an integer argument is provided, the route
<add> * with that index will be returned.
<add> *
<add> * @param mixed $index The index or name of the route you want.
<ide> * @return mixed Either the route object or null.
<ide> */
<ide> public function get($index) {
<add> if (is_string($index)) {
<add> $routes = isset($this->_routeTable[$index]) ? $this->_routeTable[$index] : array(null);
<add> return $routes[0];
<add> }
<ide> return isset($this->_routes[$index]) ? $this->_routes[$index] : null;
<ide> }
<ide>
<ide><path>lib/Cake/Routing/Router.php
<ide> public static function url($url = null, $options = false) {
<ide> 'plugin' => $params['plugin']
<ide> );
<ide> $output = self::$_routes->match($url, $params);
<del> } elseif (is_string($url) && !$hasLeadingSlash && !$hasColonSlash) {
<add> } elseif (
<add> is_string($url) &&
<add> !$hasLeadingSlash &&
<add> !$hasColonSlash
<add> ) {
<ide> // named route.
<del>
<add> $route = self::$_routes->get($url);
<add> if (!$route) {
<add> throw new Error\Exception(__d(
<add> 'cake_dev',
<add> 'No route matching the name "%s" was found.',
<add> $url
<add> ));
<add> }
<add> $url = $options + $route->defaults + array('_name' => $url);
<add> $output = self::$_routes->match($url, $params);
<ide> } else {
<ide> // String urls.
<ide> if (
<ide><path>lib/Cake/Test/TestCase/Routing/RouterTest.php
<ide> public function testUrlGenerationNamedRoute() {
<ide> );
<ide> $url = Router::url('test', array('name' => 'mark'));
<ide> $this->assertEquals('/users/mark', $url);
<add>
<add> $url = Router::url('test', array('name' => 'mark', 'page' => 1, 'sort' => 'title', 'dir' => 'desc'));
<add> $this->assertEquals('/users/mark?page=1&sort=title&dir=desc', $url);
<add> }
<add>
<add>/**
<add> * Test that using invalid names causes exceptions.
<add> *
<add> * @expectedException Cake\Error\Exception
<add> * @return void
<add> */
<add> public function testNamedRouteException() {
<add> Router::connect(
<add> '/users/:name',
<add> array('controller' => 'users', 'action' => 'view'),
<add> array('_name' => 'test')
<add> );
<add> $url = Router::url('junk', array('name' => 'mark'));
<ide> }
<ide>
<ide> /** | 3 |
PHP | PHP | fix cs errors that fixers missed | 81c025bd21d086c338c4587d82d5c53364837b74 | <ide><path>src/Database/Driver/Sqlite.php
<ide> public function connect()
<ide> *
<ide> * @return bool true if it is valid to use this driver
<ide> */
<del>
<ide> public function enabled()
<ide> {
<ide> return in_array('sqlite', PDO::getAvailableDrivers());
<ide><path>src/Model/Behavior/TranslateBehavior.php
<ide> public function beforeFind(Event $event, Query $query, $options)
<ide> $select
<ide> );
<ide>
<del> if ($changeFilter) {
<del> $filter = $options['filterByCurrentLocale'] ? 'INNER' : 'LEFT';
<del> $contain[$alias . '_' . $field . '_translation']['joinType'] = $filter;
<del> }
<add> if ($changeFilter) {
<add> $filter = $options['filterByCurrentLocale'] ? 'INNER' : 'LEFT';
<add> $contain[$alias . '_' . $field . '_translation']['joinType'] = $filter;
<add> }
<ide> }
<ide>
<ide> $query->contain($contain);
<ide><path>src/Network/Request.php
<ide> public function accepts($type = null)
<ide> * Generally you want to use Cake\Network\Request::accept() to get a simple list
<ide> * of the accepted content types.
<ide> *
<del> * @return array An array of prefValue => array(content/types)
<add> * @return array An array of prefValue => [content/types]
<ide> */
<ide> public function parseAccept()
<ide> {
<ide><path>src/Utility/Hash.php
<ide> public static function extract(array $data, $path)
<ide> }
<ide> return $context[$_key];
<ide> }
<add>
<ide> /**
<ide> * Split token conditions
<ide> *
<ide> * @param string $token the token being splitted.
<del> * @return array array(token, conditions) with token splitted
<add> * @return array [token, conditions] with token splitted
<ide> */
<ide> protected static function _splitConditions($token)
<ide> {
<ide><path>src/Validation/Validation.php
<ide> public static function cc($check, $type = 'fast', $deep = false, $regex = null)
<ide> }
<ide> $cards = array(
<ide> 'all' => array(
<del> 'amex' => '/^3[4|7]\\d{13}$/',
<del> 'bankcard' => '/^56(10\\d\\d|022[1-5])\\d{10}$/',
<del> 'diners' => '/^(?:3(0[0-5]|[68]\\d)\\d{11})|(?:5[1-5]\\d{14})$/',
<del> 'disc' => '/^(?:6011|650\\d)\\d{12}$/',
<del> 'electron' => '/^(?:417500|4917\\d{2}|4913\\d{2})\\d{10}$/',
<del> 'enroute' => '/^2(?:014|149)\\d{11}$/',
<del> 'jcb' => '/^(3\\d{4}|2100|1800)\\d{11}$/',
<del> 'maestro' => '/^(?:5020|6\\d{3})\\d{12}$/',
<del> 'mc' => '/^5[1-5]\\d{14}$/',
<del> 'solo' => '/^(6334[5-9][0-9]|6767[0-9]{2})\\d{10}(\\d{2,3})?$/',
<del> 'switch' =>
<del> '/^(?:49(03(0[2-9]|3[5-9])|11(0[1-2]|7[4-9]|8[1-2])|36[0-9]{2})\\d{10}(\\d{2,3})?)|(?:564182\\d{10}(\\d{2,3})?)|(6(3(33[0-4][0-9])|759[0-9]{2})\\d{10}(\\d{2,3})?)$/',
<del> 'visa' => '/^4\\d{12}(\\d{3})?$/',
<del> 'voyager' => '/^8699[0-9]{11}$/'
<add> 'amex' => '/^3[4|7]\\d{13}$/',
<add> 'bankcard' => '/^56(10\\d\\d|022[1-5])\\d{10}$/',
<add> 'diners' => '/^(?:3(0[0-5]|[68]\\d)\\d{11})|(?:5[1-5]\\d{14})$/',
<add> 'disc' => '/^(?:6011|650\\d)\\d{12}$/',
<add> 'electron' => '/^(?:417500|4917\\d{2}|4913\\d{2})\\d{10}$/',
<add> 'enroute' => '/^2(?:014|149)\\d{11}$/',
<add> 'jcb' => '/^(3\\d{4}|2100|1800)\\d{11}$/',
<add> 'maestro' => '/^(?:5020|6\\d{3})\\d{12}$/',
<add> 'mc' => '/^5[1-5]\\d{14}$/',
<add> 'solo' => '/^(6334[5-9][0-9]|6767[0-9]{2})\\d{10}(\\d{2,3})?$/',
<add> 'switch' => '/^(?:49(03(0[2-9]|3[5-9])|11(0[1-2]|7[4-9]|8[1-2])|36[0-9]{2})\\d{10}(\\d{2,3})?)|(?:564182\\d{10}(\\d{2,3})?)|(6(3(33[0-4][0-9])|759[0-9]{2})\\d{10}(\\d{2,3})?)$/',
<add> 'visa' => '/^4\\d{12}(\\d{3})?$/',
<add> 'voyager' => '/^8699[0-9]{11}$/'
<ide> ),
<del> 'fast' =>
<del> '/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$/'
<add> 'fast' => '/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$/'
<ide> );
<ide>
<ide> if (is_array($type)) {
<ide><path>src/View/Helper/FormHelper.php
<ide> public function create($model = null, array $options = [])
<ide> case 'get':
<ide> $htmlAttributes['method'] = 'get';
<ide> break;
<add> // Set enctype for form
<ide> case 'file':
<ide> $htmlAttributes['enctype'] = 'multipart/form-data';
<ide> $options['type'] = ($isCreate) ? 'post' : 'put';
<add> // Move on
<ide> case 'post':
<add> // Move on
<ide> case 'put':
<add> // Move on
<ide> case 'delete':
<add> // Set patch method
<ide> case 'patch':
<ide> $append .= $this->hidden('_method', array(
<ide> 'name' => '_method',
<ide> 'value' => strtoupper($options['type']),
<ide> 'secure' => static::SECURE_SKIP
<ide> ));
<add> // Default to post method
<ide> default:
<ide> $htmlAttributes['method'] = 'post';
<ide> }
<ide><path>tests/TestCase/Network/SocketTest.php
<ide> public function testConstruct()
<ide> $this->Socket = new Socket();
<ide> $config = $this->Socket->config();
<ide> $this->assertSame($config, array(
<del> 'persistent' => false,
<del> 'host' => 'localhost',
<del> 'protocol' => 'tcp',
<del> 'port' => 80,
<del> 'timeout' => 30
<add> 'persistent' => false,
<add> 'host' => 'localhost',
<add> 'protocol' => 'tcp',
<add> 'port' => 80,
<add> 'timeout' => 30
<ide> ));
<ide>
<ide> $this->Socket->reset();
<ide><path>tests/TestCase/ORM/TableTest.php
<ide> function ($article) {
<ide> public function testInitializeEvent()
<ide> {
<ide> $count = 0;
<del> $cb = function ($event) use (&$count){
<add> $cb = function ($event) use (&$count) {
<ide> $count++;
<ide> };
<ide> EventManager::instance()->attach($cb, 'Model.initialize');
<ide> public function testHasFinder()
<ide> public function testBuildValidatorEvent()
<ide> {
<ide> $count = 0;
<del> $cb = function ($event) use (&$count){
<add> $cb = function ($event) use (&$count) {
<ide> $count++;
<ide> };
<ide> EventManager::instance()->attach($cb, 'Model.buildValidator');
<ide><path>tests/test_app/config/acl.php
<ide> // Roles
<ide> // -------------------------------------
<ide> $config['roles'] = array(
<del> 'Role/admin' => null,
<del> 'Role/data_acquirer' => null,
<del> 'Role/accounting' => null,
<del> 'Role/database_manager' => null,
<del> 'Role/sales' => null,
<del> 'Role/data_analyst' => 'Role/data_acquirer, Role/database_manager',
<del> 'Role/reports' => 'Role/data_analyst',
<add> 'Role/admin' => null,
<add> 'Role/data_acquirer' => null,
<add> 'Role/accounting' => null,
<add> 'Role/database_manager' => null,
<add> 'Role/sales' => null,
<add> 'Role/data_analyst' => 'Role/data_acquirer, Role/database_manager',
<add> 'Role/reports' => 'Role/data_analyst',
<ide> // allow inherited roles to be defined as an array or comma separated list
<del> 'Role/manager' => array(
<add> 'Role/manager' => array(
<ide> 'Role/accounting',
<ide> 'Role/sales',
<ide> ),
<del> 'Role/accounting_manager' => 'Role/accounting',
<add> 'Role/accounting_manager' => 'Role/accounting',
<ide> // managers
<del> 'User/hardy' => 'Role/accounting_manager, Role/reports',
<del> 'User/stan' => 'Role/manager',
<add> 'User/hardy' => 'Role/accounting_manager, Role/reports',
<add> 'User/stan' => 'Role/manager',
<ide> // accountants
<del> 'User/peter' => 'Role/accounting',
<del> 'User/jeff' => 'Role/accounting',
<add> 'User/peter' => 'Role/accounting',
<add> 'User/jeff' => 'Role/accounting',
<ide> // admins
<del> 'User/jan' => 'Role/admin',
<add> 'User/jan' => 'Role/admin',
<ide> // database
<del> 'User/db_manager_1' => 'Role/database_manager',
<del> 'User/db_manager_2' => 'Role/database_manager',
<add> 'User/db_manager_1' => 'Role/database_manager',
<add> 'User/db_manager_2' => 'Role/database_manager',
<ide> );
<ide>
<ide> //------------------------------------- | 9 |
Javascript | Javascript | initialize lensflares rotation at 0 | 28ba50e8c9f146e54facc40147f2f75556528652 | <ide><path>src/objects/LensFlare.js
<ide> THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, co
<ide> distance = Math.min( distance, Math.max( 0, distance ) );
<ide>
<ide> this.lensFlares.push( {
<del> texture: texture, // THREE.Texture
<del> size: size, // size in pixels (-1 = use texture.width)
<del> distance: distance, // distance (0-1) from light source (0=at light source)
<del> x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
<del> scale: 1, // scale
<del> rotation: 1, // rotation
<del> opacity: opacity, // opacity
<del> color: color, // color
<del> blending: blending // blending
<add> texture: texture, // THREE.Texture
<add> size: size, // size in pixels (-1 = use texture.width)
<add> distance: distance, // distance (0-1) from light source (0=at light source)
<add> x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
<add> scale: 1, // scale
<add> rotation: 0, // rotation
<add> opacity: opacity, // opacity
<add> color: color, // color
<add> blending: blending // blending
<ide> } );
<ide>
<ide> }; | 1 |
PHP | PHP | remove some comment bloat | 216a38c574b5b49d9330268a39f0373ffaa07361 | <ide><path>laravel/uri.php
<ide> public static function current()
<ide> $uri = static::remove($uri, $index);
<ide> }
<ide>
<del> // Format the final request URI. If there is nothing left, we will just
<del> // return a single forward slash. Otherwise, we'll remove all of the
<del> // leading and trailing spaces from the URI before returning it.
<ide> static::$uri = static::format($uri);
<ide>
<ide> static::$segments = explode('/', static::$uri); | 1 |
Ruby | Ruby | fix typo in resources documentation. closes [yon] | 7de21cc1c5ae899207f9aab9e111eda265bb2f32 | <ide><path>actionpack/lib/action_controller/resources.rb
<ide> module ActionController
<ide> # POST /posts # with => { :title => "My Whizzy New Post", :body => "I've got a brand new combine harvester" }
<ide> #
<ide> # # A PUT request on a single Post resource is asking for a Post to be updated
<del> # POST /posts # with => { :id => 1, :title => "Changed Whizzy Title" }
<add> # PUT /posts # with => { :id => 1, :title => "Changed Whizzy Title" }
<ide> #
<ide> # # A DELETE request on a single Post resource is asking for it to be deleted
<ide> # DELETE /posts # with => { :id => 1 } | 1 |
Java | Java | refine tests for spr-14066 | 411ff8450fbf386b5a88f01777ab1e49aaa33a8d | <ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockMvcWebClientBuilderTests.java
<ide> public String contextPath(HttpServletRequest request) {
<ide>
<ide> @RestController
<ide> static class CookieController {
<del> @RequestMapping("/")
<add> @RequestMapping(value="/", produces="text/plain")
<ide> public String cookie(@CookieValue("cookie") String cookie) {
<ide> return cookie;
<ide> }
<ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/webdriver/MockMvcHtmlUnitDriverBuilderTests.java
<ide> public String contextPath(HttpServletRequest request) {
<ide>
<ide> @RestController
<ide> static class CookieController {
<del> @RequestMapping("/")
<add> @RequestMapping(value="/", produces="text/plain")
<ide> public String cookie(@CookieValue("cookie") String cookie) {
<ide> return cookie;
<ide> } | 2 |
Ruby | Ruby | add reselect method | 00c50c2b5966fa1d719c8a58564811c672a0e8c6 | <ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> def _select!(*fields) # :nodoc:
<ide> self
<ide> end
<ide>
<add> # Allows you to change a previously set select statement.
<add> #
<add> # Post.select(:title, :body)
<add> # # SELECT `posts.title`, `posts.body` FROM `posts`
<add> #
<add> # Post.select(:title, :body).reselect(:created_at)
<add> # # SELECT `posts.created_at` FROM `posts`
<add> #
<add> # This is short-hand for <tt>unscope(:select).select(fields)</tt>.
<add> # Note that we're unscoping the entire select statement.
<add> def reselect(*fields)
<add> unscope(:select).select(*fields)
<add> end
<add>
<ide> # Allows to specify a group attribute:
<ide> #
<ide> # User.group(:name)
<ide><path>activerecord/test/cases/relation/select_test.rb
<ide> def test_select_with_nil_argument
<ide> expected = Post.select(:title).to_sql
<ide> assert_equal expected, Post.select(nil).select(:title).to_sql
<ide> end
<add>
<add> def test_reselect
<add> expected = Post.select(:title).to_sql
<add> assert_equal expected, Post.select(:title, :body).reselect(:title).to_sql
<add> end
<ide> end
<ide> end | 2 |
Text | Text | add event handling guide for vue.js | ca29fb664ef40fc543df3db590c9929344c8a9d1 | <ide><path>guide/english/vue/event-handling/index.md
<add>---
<add>title: Event Handling
<add>---
<add>
<add>## Creating an Event
<add>We can create an event using the directive `v-on`:
<add>
<add>```html
<add><div id="app">
<add> <button v-on:click="buttonClicked">Click Me</button>
<add></div>
<add>```
<add>
<add>```javascript
<add>var app = new Vue({
<add> el: '#app',
<add> methods: {
<add> buttonClicked: function (event) {
<add> alert("You clicked on a " + event.target.tagName + " element");
<add> }
<add> }
<add>})
<add>```
<add>
<add>Note: A shorthand for any event handler is using the `@` symbol and the event name. For example `@click` is short for `v-on:click`. | 1 |
Python | Python | bloom minor changes on tokenizer | 18c263c4b6b82726a3f2699e2dfee89383804391 | <ide><path>src/transformers/models/bloom/tokenization_bloom_fast.py
<ide> },
<ide> }
<ide>
<del>PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
<del> "bigscience/tokenizer": 1024,
<del> "bigscience/bloom-350m": 1024,
<del> "bigscience/bloom-760m": 1024,
<del> "bigscience/bloom-1b3": 1024,
<del> "bigscience/bloom-2b5": 1024,
<del> "bigscience/bloom-6b3": 1024,
<del> "bigscience/bloom": 1024,
<del>}
<del>
<ide>
<ide> class BloomTokenizerFast(PreTrainedTokenizerFast):
<ide> """
<ide> class BloomTokenizerFast(PreTrainedTokenizerFast):
<ide>
<ide> vocab_files_names = VOCAB_FILES_NAMES
<ide> pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
<del> max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
<ide> model_input_names = ["input_ids", "attention_mask"]
<ide> slow_tokenizer_class = None
<add> # No `max_model_input_sizes` as BLOOM uses ALiBi positional embeddings
<ide>
<ide> def __init__(
<ide> self,
<ide> def __init__(
<ide> add_prefix_space=add_prefix_space,
<ide> **kwargs,
<ide> )
<del>
<ide> pre_tok_state = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
<ide> if pre_tok_state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
<ide> pre_tok_class = getattr(pre_tokenizers, pre_tok_state.pop("type"))
<ide><path>tests/models/bloom/test_modeling_bloom.py
<ide> def test_batch_generation_padd(self):
<ide> tokenizer.decode(greedy_output_without_pad[0, :-3], skip_special_tokens=True),
<ide> )
<ide>
<add> @slow
<add> def test_right_left_batched_input(self):
<add> path_1b3 = "bigscience/bloom-1b3"
<add> model = BloomForCausalLM.from_pretrained(path_1b3, use_cache=True)
<add> model = model.eval()
<add>
<add> tokenizer = BloomTokenizerFast.from_pretrained(path_1b3)
<add> tokenizer.padding_side = "right"
<add>
<add> inputs = ["Hello there", "Joe Biden is the president of the"]
<add> inputs_right = tokenizer(inputs, return_tensors="pt", padding=True)
<add>
<add> tokenizer.padding_side = "left"
<add> inputs_left = tokenizer(inputs, return_tensors="pt", padding=True)
<add>
<add> # test token values are different
<add> self.assertNotEqual(inputs_right["input_ids"].tolist(), inputs_left["input_ids"].tolist())
<add>
<add> # test reconstructions are the same
<add> outputs_right = model.generate(**inputs_right, max_length=10, do_sample=False)
<add> outputs_left = model.generate(**inputs_left, max_length=10, do_sample=False)
<add>
<add> self.assertEqual(
<add> tokenizer.decode(outputs_right[0], skip_special_tokens=True),
<add> tokenizer.decode(outputs_left[0], skip_special_tokens=True),
<add> )
<add>
<ide>
<ide> @require_torch
<ide> class BloomEmbeddingTest(unittest.TestCase):
<ide><path>tests/models/bloom/test_tokenization_bloom.py
<ide> def test_encodings_from_xnli_dataset(self):
<ide> output_tokens = list(map(tokenizer.encode, input_text))
<ide> predicted_text = list(map(lambda x: tokenizer.decode(x, clean_up_tokenization_spaces=False), output_tokens))
<ide> self.assertListEqual(predicted_text, input_text)
<add>
<add> def test_pretrained_model_lists(self):
<add> # The test has to be overriden because BLOOM uses ALiBi positional embeddings that does not have
<add> # any sequence length constraints. This test of the parent class will fail since it relies on the
<add> # maximum sequence length of the positoonal embeddings.
<add> self.assertGreaterEqual(len(self.tokenizer_class.pretrained_vocab_files_map), 1)
<add> self.assertGreaterEqual(len(list(self.tokenizer_class.pretrained_vocab_files_map.values())[0]), 1) | 3 |
Python | Python | fix a tf test name (layoutlmmodeltest) | b6bdb943b214050c466a0cb52481c7a051144b2e | <ide><path>tests/layoutlm/test_modeling_tf_layoutlm.py
<ide> def prepare_config_and_inputs_for_common(self):
<ide>
<ide>
<ide> @require_tf
<del>class LayoutLMModelTest(TFModelTesterMixin, unittest.TestCase):
<add>class TFLayoutLMModelTest(TFModelTesterMixin, unittest.TestCase):
<ide>
<ide> all_model_classes = (
<ide> (TFLayoutLMModel, TFLayoutLMForMaskedLM, TFLayoutLMForTokenClassification, TFLayoutLMForSequenceClassification) | 1 |
Javascript | Javascript | improve test coverage for `os` package | 5e3055931822837840ba257768e7bd1350547d69 | <ide><path>test/parallel/test-os-process-priority.js
<ide> for (let i = PRIORITY_HIGHEST; i <= PRIORITY_LOW; i++) {
<ide> checkPriority(process.pid, i);
<ide> }
<ide>
<add>{
<add> assert.throws(() => { os.getPriority(-1); }, {
<add> code: 'ERR_SYSTEM_ERROR',
<add> message: /A system error occurred: uv_os_getpriority returned /,
<add> name: 'SystemError'
<add> });
<add>}
<add>
<ide>
<ide> function checkPriority(pid, expected) {
<ide> const priority = os.getPriority(pid); | 1 |
Ruby | Ruby | fix calculation tests to work on sqlite | df8669d4b5691646ca8bb4ba01f6e5348ae8dd69 | <ide><path>activerecord/test/cases/calculations_test.rb
<ide> def test_should_count_selected_field_with_include
<ide> end
<ide>
<ide> def test_should_count_scoped_select
<del> Account.update_all("credit_limit = 50")
<del> assert_equal 1, Account.scoped(:select => "DISTINCT credit_limit").count
<add> Account.update_all("credit_limit = NULL")
<add> assert_equal 0, Account.scoped(:select => "credit_limit").count
<ide> end
<ide>
<ide> def test_should_count_scoped_select_with_options
<del> Account.update_all("credit_limit = 50")
<del> Account.first.update_attribute('credit_limit', 49)
<del> assert_equal 1, Account.scoped(:select => "DISTINCT credit_limit").count(:conditions => [ 'credit_limit >= 50'] )
<add> Account.update_all("credit_limit = NULL")
<add> Account.last.update_attribute('credit_limit', 49)
<add> Account.first.update_attribute('credit_limit', 51)
<add>
<add> assert_equal 1, Account.scoped(:select => "credit_limit").count(:conditions => ['credit_limit >= 50'])
<ide> end
<ide>
<ide> def test_should_count_manual_select_with_include | 1 |
Javascript | Javascript | fix windows path incompatibilities | 86f3e41dfe78e20d48cd78ddbac0da343ce164b4 | <ide><path>docs/src/writer.js
<ide> * All writing related code here. This is so that we can separate the async code from sync code
<ide> * for testability
<ide> */
<add>var pathUtils = require('path');
<ide> var qfs = require('q-fs');
<ide> var Q = require('qq');
<del>var OUTPUT_DIR = 'build/docs/';
<add>var OUTPUT_DIR = pathUtils.join('build','docs');
<add>var TEMPLATES_DIR = pathUtils.join('docs','src','templates');
<ide> var fs = require('fs');
<ide>
<ide> exports.output = output;
<ide> function output(file, content) {
<del> var fullPath = OUTPUT_DIR + file;
<del> var dir = parent(fullPath);
<add> var fullPath = pathUtils.join(OUTPUT_DIR,file);
<add> var dir = pathUtils.dirname(fullPath);
<ide> return Q.when(exports.makeDir(dir), function(error) {
<ide> qfs.write(fullPath, exports.toString(content));
<ide> });
<del>};
<add>}
<ide>
<ide> //recursively create directory
<ide> exports.makeDir = function(p) {
<del> var parts = p.split(/\//);
<add> p = pathUtils.normalize(p);
<add> var parts = p.split(pathUtils.sep);
<ide> var path = ".";
<ide>
<ide> // Recursively rebuild directory structure
<ide> return qfs.exists(p).
<ide> then(function createPart(exists) {
<ide> if(!exists && parts.length) {
<del> path += "/" + parts.shift();
<add> path = pathUtils.join(path, parts.shift());
<ide> return qfs.exists(path).then(function(exists) {
<ide> if (!exists) {
<ide> return qfs.makeDirectory(path).then(createPart, createPart);
<ide> exports.makeDir = function(p) {
<ide> };
<ide>
<ide> exports.copyTemplate = function(filename) {
<del> return exports.copy('docs/src/templates/' + filename, filename);
<add> // Don't need to normalize here as `exports.copy` will do it for us
<add> return exports.copy(pathUtils.join(TEMPLATES_DIR,filename), filename);
<ide> };
<ide>
<ide> /* Copy files from one place to another.
<ide> exports.copyTemplate = function(filename) {
<ide> * @param transform{function=} transfromation function to be applied before return
<ide> */
<ide> exports.copy = function(from, to, transform) {
<del> var args = Array.prototype.slice.call(arguments, 3);
<add> from = pathUtils.normalize(from);
<add> to = pathUtils.normalize(to);
<ide>
<ide> // We have to use binary reading, Since some characters are unicode.
<ide> return qfs.read(from, 'b').then(function(content) {
<ide> if (transform) {
<del> args.unshift(content.toString());
<del> content = transform.apply(null, args);
<add> content = transform.call(null, content.toString(), from, to, transform);
<ide> }
<ide> return output(to, content);
<ide> });
<ide> exports.copy = function(from, to, transform) {
<ide>
<ide> exports.symlink = symlink;
<ide> function symlink(from, to, type) {
<add> // qfs will normalize the path arguments for us here
<ide> return qfs.exists(to).then(function(exists) {
<ide> if (!exists) {
<ide> return qfs.symbolicLink(to, from, type);
<ide> function symlink(from, to, type) {
<ide>
<ide> exports.symlinkTemplate = symlinkTemplate;
<ide> function symlinkTemplate(filename, type) {
<del> var dest = OUTPUT_DIR + filename,
<del> dirDepth = dest.split('/').length,
<del> src = Array(dirDepth).join('../') + 'docs/src/templates/' + filename;
<add> // pathUtils.join will normalize the filename for us
<add> var dest = pathUtils.join(OUTPUT_DIR, filename),
<add> dirDepth = dest.split(pathUtils.sep).length,
<add> src = pathUtils.join(Array(dirDepth).join('..' + pathUtils.sep), TEMPLATES_DIR, filename);
<ide> return symlink(src, dest, type);
<ide> }
<ide>
<ide> function symlinkTemplate(filename, type) {
<ide> * @param replacements{obj} key and value pairs in which key will be replaced with value in content
<ide> */
<ide> exports.replace = function(content, replacements) {
<del> for(key in replacements) {
<add> for(var key in replacements) {
<ide> content = content.replace(key, replacements[key]);
<ide> }
<ide> return content;
<del>}
<add>};
<ide>
<ide> exports.copyDir = function copyDir(from, to) {
<add> from = pathUtils.normalize(from);
<add> to = pathUtils.normalize(to);
<ide> return qfs.listTree(from).then(function(files) {
<ide> files.forEach(function(file) {
<ide> var path = to ? file.replace(from, to) : from;
<add> // Not sure why this next line is here...
<ide> path = path.replace('/docs/build', '');
<ide> exports.copy(file, path);
<ide> });
<ide> });
<ide> };
<ide>
<ide> exports.merge = function(srcs, to) {
<del> return merge(srcs.map(function(src) { return 'docs/src/templates/' + src; }), to);
<add> // pathUtils.join will normalize each of the srcs inside the mapping
<add> to = pathUtils.normalize(to);
<add> return merge(srcs.map(function(src) { return pathUtils.join(TEMPLATES_DIR, src); }), to);
<ide> };
<ide>
<ide> function merge(srcs, to) {
<ide> function merge(srcs, to) {
<ide>
<ide> //----------------------- Synchronous Methods ----------------------------------
<ide>
<del>function parent(file) {
<del> var parts = file.split('/');
<del> parts.pop();
<del> return parts.join('/');
<del>}
<del>
<del>
<ide> exports.toString = function toString(obj) {
<ide> switch (typeof obj) {
<ide> case 'string':
<ide> exports.toString = function toString(obj) {
<ide> };
<ide>
<ide>
<del>function noop() {};
<add>function noop() {}
<ide> | 1 |
Ruby | Ruby | add missing require | 5f60735194290172533521e417f81bb3075dc867 | <ide><path>actionpack/lib/action_view/helpers/number_helper.rb
<ide> require 'active_support/core_ext/big_decimal/conversions'
<ide> require 'active_support/core_ext/float/rounding'
<ide> require 'active_support/core_ext/object/blank'
<add>require 'active_support/core_ext/string/output_safety'
<ide>
<ide> module ActionView
<ide> # = Action View Number Helpers | 1 |
Javascript | Javascript | enable eslint strict key-spacing | 684c1bb42d916fed12945ba1678934e8983082dd | <ide><path>.eslintrc.js
<ide> module.exports = {
<ide> ObjectExpression: 'first',
<ide> SwitchCase: 1,
<ide> }],
<del> 'key-spacing': ['error', { mode: 'minimum' }],
<add> 'key-spacing': ['error', { mode: 'strict' }],
<ide> 'keyword-spacing': 'error',
<ide> 'linebreak-style': ['error', 'unix'],
<ide> 'max-len': ['error', {
<ide><path>benchmark/http/_chunky_http_client.js
<ide> const common = require('../common.js');
<ide> const net = require('net');
<ide>
<ide> const bench = common.createBenchmark(main, {
<del> len: [1, 4, 8, 16, 32, 64, 128],
<del> n: [5, 50, 500, 2000],
<add> len: [1, 4, 8, 16, 32, 64, 128],
<add> n: [5, 50, 500, 2000],
<ide> type: ['send'],
<ide> });
<ide>
<ide><path>test/parallel/test-eslint-require-buffer.js
<ide> ruleTester.run('require-buffer', rule, {
<ide> output: useStrict + bufferModule + useBuffer,
<ide> },
<ide> {
<del> code: mockComment + useBuffer,
<add> code: mockComment + useBuffer,
<ide> errors: [{ message }],
<del> output: mockComment + bufferModule + useBuffer,
<add> output: mockComment + bufferModule + useBuffer,
<ide> },
<ide> {
<del> code: mockComment + useStrict + useBuffer,
<add> code: mockComment + useStrict + useBuffer,
<ide> errors: [{ message }],
<del> output: mockComment + useStrict + bufferModule + useBuffer,
<add> output: mockComment + useStrict + bufferModule + useBuffer,
<ide> },
<ide> ]
<ide> });
<ide><path>test/parallel/test-https-agent-servername.js
<ide> const fixtures = require('../common/fixtures');
<ide> const options = {
<ide> key: fixtures.readKey('agent1-key.pem'),
<ide> cert: fixtures.readKey('agent1-cert.pem'),
<del> ca: fixtures.readKey('ca1-cert.pem')
<add> ca: fixtures.readKey('ca1-cert.pem')
<ide> };
<ide>
<ide> | 4 |
Ruby | Ruby | keep rubocop happy with the new selenium runner | f50aeba01ee14f8fcd9fd98ec75b26cd5ef7aea8 | <ide><path>ci/qunit-selenium-runner.rb
<del>require 'qunit/selenium/test_runner'
<del>require 'chromedriver/helper'
<add># frozen_string_literal: true
<add>
<add>require "qunit/selenium/test_runner"
<add>require "chromedriver/helper"
<ide>
<ide> driver_options = Selenium::WebDriver::Chrome::Options.new
<del>driver_options.add_argument('--headless')
<del>driver_options.add_argument('--disable-gpu')
<add>driver_options.add_argument("--headless")
<add>driver_options.add_argument("--disable-gpu")
<ide>
<ide> driver = ::Selenium::WebDriver.for(:chrome, options: driver_options)
<ide> result = QUnit::Selenium::TestRunner.new(driver).open(ARGV[0], timeout: 60) | 1 |
Javascript | Javascript | add some tests for bind | 44a9cdaeb3a3b28cdb95b1c6c65f9051ea62db85 | <ide><path>packages/ember-handlebars/tests/helpers/bind_test.js
<add>import EmberView from "ember-views/views/view";
<add>import EmberObject from "ember-runtime/system/object";
<add>import run from "ember-metal/run_loop";
<add>
<add>function appendView(view) {
<add> run(function() { view.appendTo('#qunit-fixture'); });
<add>}
<add>
<add>var view;
<add>
<add>QUnit.module("Handlebars {{#bind}} helper", {
<add> teardown: function() {
<add> if (view) {
<add> run(view, view.destroy);
<add> view = null;
<add> }
<add> }
<add>});
<add>
<add>test("it should render the current value of a property on the context", function() {
<add> view = EmberView.create({
<add> template: Ember.Handlebars.compile('{{bind "foo"}}'),
<add> context: EmberObject.create({
<add> foo: "BORK"
<add> })
<add> });
<add>
<add> appendView(view);
<add>
<add> equal(view.$().text(), "BORK", "initial value is rendered");
<add>
<add> run(view, view.set, 'context.foo', 'MWEEER');
<add>
<add> equal(view.$().text(), "MWEEER", "value can be updated");
<add>});
<add>
<add>test("it should render the current value of a path on the context", function() {
<add> view = EmberView.create({
<add> template: Ember.Handlebars.compile('{{bind "foo.bar"}}'),
<add> context: EmberObject.create({
<add> foo: {
<add> bar: "BORK"
<add> }
<add> })
<add> });
<add>
<add> appendView(view);
<add>
<add> equal(view.$().text(), "BORK", "initial value is rendered");
<add>
<add> run(view, view.set, 'context.foo.bar', 'MWEEER');
<add>
<add> equal(view.$().text(), "MWEEER", "value can be updated");
<add>});
<add> | 1 |
Ruby | Ruby | fix typo in comment | 2488998a0fa0bdeb384961d826d2e0f4abe1b968 | <ide><path>Library/Homebrew/exceptions.rb
<ide> class CurlDownloadStrategyError < RuntimeError
<ide> class ErrorDuringExecution < RuntimeError
<ide> end
<ide>
<del># raised by Pathname#verify_checksum when cksum is nil or empty
<add># raised by Pathname#verify_checksum when "expected" is nil or empty
<ide> class ChecksumMissingError < ArgumentError
<ide> end
<ide> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.