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
PHP
PHP
fix issue with postgres and virtualfields
fe9e59591319302760be9c470bb6f6c905b4d43d
<ide><path>lib/Cake/Model/Datasource/Database/Postgres.php <ide> public function fields($model, $alias = null, $fields = array(), $quote = true) <ide> <ide> /** <ide> * Auxiliary function to quote matched `(Model.fields)` from a preg_replace_callback call <add> * Quotes the fields in a function call. <ide> * <ide> * @param string $match matched string <ide> * @return string quoted strig <ide> protected function _quoteFunctionField($match) { <ide> $prepend = 'DISTINCT '; <ide> $match[1] = trim(str_replace('DISTINCT', '', $match[1])); <ide> } <del> if (strpos($match[1], '.') === false) { <add> $constant = preg_match('/^\d+|NULL|FALSE|TRUE$/i', $match[1]); <add> <add> if (!$constant && strpos($match[1], '.') === false) { <ide> $match[1] = $this->name($match[1]); <del> } else { <add> } elseif (!$constant){ <ide> $parts = explode('.', $match[1]); <ide> if (!Set::numeric($parts)) { <ide> $match[1] = $this->name($match[1]); <ide><path>lib/Cake/Test/Case/Model/Datasource/Database/PostgresTest.php <ide> public function testVirtualFields() { <ide> $this->assertEqual($result['Article']['subquery'], 6); <ide> } <ide> <add>/** <add> * Test that virtual fields work with SQL constants <add> * <add> * @return void <add> */ <add> function testVirtualFieldAsAConstant() { <add> $this->loadFixtures('Article', 'Comment'); <add> $Article =& ClassRegistry::init('Article'); <add> $Article->virtualFields = array( <add> 'empty' => "NULL", <add> 'number' => 43, <add> 'truth' => 'TRUE' <add> ); <add> $result = $Article->find('first'); <add> $this->assertNull($result['Article']['empty']); <add> $this->assertTrue($result['Article']['truth']); <add> $this->assertEquals(43, $result['Article']['number']); <add> } <add> <ide> /** <ide> * Tests additional order options for postgres <ide> *
2
Text
Text
add note regarding multiple authentications
b0331a0c5bb2e81bb2daa0ae56b4fd30620f0da4
<ide><path>README.md <ide> need to go through each provider to generate new credentials. <ide> <ide> Obtaining API Keys <ide> ------------------ <add> <add>:pushpin: You could support all 5 authentication methods by setting up OAuth keys, but you don't have to. If you would only like to have **Facebook sign-in** and **Local sign-in** with email and password, in **secrets.js** set `googleAuth: false`, `twitterOauth: false`, `githubAuth: false`. By doing so, *Google, Twitter and Github* buttons will not show up on the *Login* page. If you set `localAuth: false`, users will not be able to login/create an account with email and password or change password in the *Account Management* page. <add> <ide> <img src="http://images.google.com/intl/en_ALL/images/srpr/logo6w.png" width="200"> <ide> - Visit [Google Cloud Console](https://cloud.google.com/console/project) <ide> - Click **CREATE PROJECT** button
1
Python
Python
use absl app
5a1b5af396c2ef257e6134da754ae59d351516ba
<ide><path>official/nlp/transformer/data_download.py <ide> import tarfile <ide> <ide> # pylint: disable=g-bad-import-order <del>from absl import app as absl_app <add>from absl import app <ide> from absl import flags <ide> from absl import logging <ide> import six <ide> def define_data_download_flags(): <ide> logging.set_verbosity(logging.INFO) <ide> define_data_download_flags() <ide> FLAGS = flags.FLAGS <del> tf.app.run(main) <add> app.run(main)
1
PHP
PHP
add partialmock shorthand
850dffca81baafdbab209f0ce961cf07f8172a19
<ide><path>src/Illuminate/Foundation/Testing/Concerns/InteractsWithContainer.php <ide> protected function mock($abstract, Closure $mock = null) <ide> return $this->instance($abstract, Mockery::mock(...array_filter(func_get_args()))); <ide> } <ide> <add> /** <add> * Mock a partial instance of an object in the container. <add> * <add> * @param string $abstract <add> * @param \Closure|null $mock <add> * @return \Mockery\MockInterface <add> */ <add> protected function partialMock($abstract, Closure $mock = null) <add> { <add> return $this->instance($abstract, Mockery::mock(...array_filter(func_get_args()))->makePartial()); <add> } <add> <ide> /** <ide> * Spy an instance of an object in the container. <ide> *
1
Go
Go
remove lcow code
190b6f64e3143e160e79d733fd4abfec1c89b7fd
<ide><path>builder/dockerfile/copy.go <ide> func (o *copier) Cleanup() { <ide> // TODO: allowWildcards can probably be removed by refactoring this function further. <ide> func (o *copier) calcCopyInfo(origPath string, allowWildcards bool) ([]copyInfo, error) { <ide> imageSource := o.imageSource <add> if err := validateCopySourcePath(imageSource, origPath); err != nil { <add> return nil, err <add> } <ide> <ide> // TODO: do this when creating copier. Requires validateCopySourcePath <ide> // (and other below) to be aware of the difference sources. Why is it only <ide> func (o *copier) calcCopyInfo(origPath string, allowWildcards bool) ([]copyInfo, <ide> return nil, errors.Errorf("missing build context") <ide> } <ide> <del> root := o.source.Root() <del> <del> if err := validateCopySourcePath(imageSource, origPath, root.OS()); err != nil { <del> return nil, err <del> } <del> <del> // Work in source OS specific filepath semantics <del> // For LCOW, this is NOT the daemon OS. <del> origPath = root.FromSlash(origPath) <del> origPath = strings.TrimPrefix(origPath, string(root.Separator())) <del> origPath = strings.TrimPrefix(origPath, "."+string(root.Separator())) <add> // Work in daemon-specific OS filepath semantics <add> origPath = filepath.FromSlash(origPath) <add> origPath = strings.TrimPrefix(origPath, string(os.PathSeparator)) <add> origPath = strings.TrimPrefix(origPath, "."+string(os.PathSeparator)) <ide> <ide> // Deal with wildcards <del> if allowWildcards && containsWildcards(origPath, root.OS()) { <add> if allowWildcards && containsWildcards(origPath) { <ide> return o.copyWithWildcards(origPath) <ide> } <ide> <ide> func (o *copier) calcCopyInfo(origPath string, allowWildcards bool) ([]copyInfo, <ide> return newCopyInfos(newCopyInfoFromSource(o.source, origPath, hash)), nil <ide> } <ide> <del>func containsWildcards(name, platform string) bool { <del> isWindows := platform == "windows" <add>func containsWildcards(name string) bool { <add> isWindows := runtime.GOOS == "windows" <ide> for i := 0; i < len(name); i++ { <ide> ch := name[i] <ide> if ch == '\\' && !isWindows { <ide> func copyDirectory(archiver Archiver, source, dest *copyEndpoint, identity *idto <ide> return errors.Wrapf(err, "failed to copy directory") <ide> } <ide> if identity != nil { <del> // TODO: @gupta-ak. Investigate how LCOW permission mappings will work. <ide> return fixPermissions(source.path, dest.path, *identity, !destExists) <ide> } <ide> return nil <ide> } <ide> <ide> func copyFile(archiver Archiver, source, dest *copyEndpoint, identity *idtools.Identity) error { <del> if runtime.GOOS == "windows" && dest.driver.OS() == "linux" { <del> // LCOW <del> if err := dest.driver.MkdirAll(dest.driver.Dir(dest.path), 0755); err != nil { <del> return errors.Wrapf(err, "failed to create new directory") <add> if identity == nil { <add> // Use system.MkdirAll here, which is a custom version of os.MkdirAll <add> // modified for use on Windows to handle volume GUID paths. These paths <add> // are of the form \\?\Volume{<GUID>}\<path>. An example would be: <add> // \\?\Volume{dae8d3ac-b9a1-11e9-88eb-e8554b2ba1db}\bin\busybox.exe <add> if err := system.MkdirAll(filepath.Dir(dest.path), 0755); err != nil { <add> return err <ide> } <ide> } else { <del> // Normal containers <del> if identity == nil { <del> // Use system.MkdirAll here, which is a custom version of os.MkdirAll <del> // modified for use on Windows to handle volume GUID paths. These paths <del> // are of the form \\?\Volume{<GUID>}\<path>. An example would be: <del> // \\?\Volume{dae8d3ac-b9a1-11e9-88eb-e8554b2ba1db}\bin\busybox.exe <del> <del> if err := system.MkdirAll(filepath.Dir(dest.path), 0755); err != nil { <del> return err <del> } <del> } else { <del> if err := idtools.MkdirAllAndChownNew(filepath.Dir(dest.path), 0755, *identity); err != nil { <del> return errors.Wrapf(err, "failed to create new directory") <del> } <add> if err := idtools.MkdirAllAndChownNew(filepath.Dir(dest.path), 0755, *identity); err != nil { <add> return errors.Wrapf(err, "failed to create new directory") <ide> } <ide> } <ide> <ide> if err := archiver.CopyFileWithTar(source.path, dest.path); err != nil { <ide> return errors.Wrapf(err, "failed to copy file") <ide> } <ide> if identity != nil { <del> // TODO: @gupta-ak. Investigate how LCOW permission mappings will work. <ide> return fixPermissions(source.path, dest.path, *identity, false) <ide> } <ide> return nil <ide><path>builder/dockerfile/copy_unix.go <ide> func fixPermissions(source, destination string, identity idtools.Identity, overr <ide> }) <ide> } <ide> <del>func validateCopySourcePath(imageSource *imageMount, origPath, platform string) error { <add>func validateCopySourcePath(imageSource *imageMount, origPath string) error { <ide> return nil <ide> } <ide><path>builder/dockerfile/copy_windows.go <ide> func fixPermissionsWindows(source, destination, SID string) error { <ide> return windows.SetNamedSecurityInfo(destination, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION, sid, nil, dacl, nil) <ide> } <ide> <del>func validateCopySourcePath(imageSource *imageMount, origPath, platform string) error { <del> // validate windows paths from other images + LCOW <del> if imageSource == nil || platform != "windows" { <add>func validateCopySourcePath(imageSource *imageMount, origPath string) error { <add> if imageSource == nil { <ide> return nil <ide> } <del> <ide> origPath = filepath.FromSlash(origPath) <ide> p := strings.ToLower(filepath.Clean(origPath)) <ide> if !filepath.IsAbs(p) { <ide> if filepath.VolumeName(p) != "" { <ide> if p[len(p)-2:] == ":." { // case where clean returns weird c:. paths <ide> p = p[:len(p)-1] <ide> } <del> p += "\\" <add> p += `\` <ide> } else { <del> p = filepath.Join("c:\\", p) <add> p = filepath.Join(`c:\`, p) <ide> } <ide> } <ide> if _, ok := pathDenyList[p]; ok { <del> return errors.New("copy from c:\\ or c:\\windows is not allowed on windows") <add> return errors.New(`copy from c:\ or c:\windows is not allowed on windows`) <ide> } <ide> return nil <ide> }
3
Text
Text
fix translation in contributing.md
66631812fa92e1dda9553366d264097301f12115
<ide><path>docs/i18n-languages/russian/CONTRIBUTING.md <ide> freeCodeCamp.org возможен благодаря тысячам добров <ide> <ide> **Как я могу сообщить о проблеме безопасности?** <ide> <del>Пожалуйста, не создавайте проблемы на GitHub для проблем безопасности. Вместо этого отправьте электронное письмо по адресу `security@freecodecamp.org` и мы рассмотрим его немедленно. <add>Пожалуйста, не создавайте проблемы на GitHub для проблем безопасности. Вместо этого отправьте электронное письмо по адресу `security@freecodecamp.org` и мы незамедлительно рассмотрим его. <ide> <ide> **Я застрял в том, чего нет в этой документации. Как получить помощь?** <ide> <ide> freeCodeCamp.org возможен благодаря тысячам добров <ide> <ide> Читайте наше [Руководство о внесении вклада в проекты с открытым исходным кодом](https://github.com/freeCodeCamp/how-to-contribute-to-open-source). <ide> <del>**Что означают эти разные ярлыки, которые отмечены проблемы?** <add>**Что означают разные виды ярлыков, которыми отмечены проблемы?** <ide> <del>Наши модераторы сообщества [сортируют](https://en.wikipedia.org/wiki/Software_bug#Bug_management) проблемы и вытягивать запросы на основе их приоритета, серьезности и других факторов. Вы можете [найти полный глоссарий их значений здесь](https://github.com/freecodecamp/freecodecamp/labels). <add>Наши модераторы сообщества [сортируют](https://en.wikipedia.org/wiki/Software_bug#Bug_management) проблемы и выбирают запросы в соответствии с их приоритетом, серьезности или других факторов. Вы можете [найти полный глоссарий значений здесь](https://github.com/freecodecamp/freecodecamp/labels). <ide> <del>Вы должны искать Нужна Помощь **`Help Wanted`** или Новички приветствуются **`first timers welcome`** для быстрого поиска того, что доступно для вас. Они готовы к работе, и вам не нужно ничего делать прежде чем начать работать над ними. <add>Лучше всего искать ярлыки с названиями "Нужна помощь" (**`Help Wanted`**) или "Новички приветствуются" (**`first timers welcome`**) для быстрого поиска тех проблем, которым вы можете помочь. Они уже готовы к работе, и никакой дополнительной подготовки не требуется. <ide> <del>Если в этих вопросах не хватает ясности в отношении того, что нужно сделать, не стесняйтесь задавать вопросы в комментариях. <add>Если в этих вопросах не хватает ясности в понимании того, что нужно сделать, не стесняйтесь задавать вопросы в комментариях. <ide> <del>**Я нашел опечатку, должен ли я сообщить о проблеме, прежде чем я смогу сделать запрос на дополнение, 'pull request'?** <add>**Я нашел опечатку, должен ли я сообщить о проблеме, прежде чем я смогу сделать запрос на дополнение ('pull request')?** <ide> <del>Вы можете сразу создать pull request, не сообщая о каких-либо проблемах, для опечаток или небольших изменений в [пустословие](https://en.oxforddictionaries.com/definition/verbiage). Трекер Проблем - это инструмент для поиска подтверждения изменений, которые вы хотели бы предложить посредством pull request. <add>Вы можете сразу создать pull request с исправлениями опечаток или небольшими изменениями в [пустословие](https://en.oxforddictionaries.com/definition/verbiage), не сообщая о каких-либо проблемах дополнительно. Трекер Проблем ('issue tracker') - это инструмент для поиска существующих проблем, исправление которых вы можете предложить посредством pull request.
1
PHP
PHP
fix failing tests and inconsistent types
436135598f3994a0c2aee1f7a002b1978c3a02ff
<ide><path>src/Console/ConsoleErrorHandler.php <ide> use Cake\Error\FatalErrorException; <ide> use Cake\Error\PHP7ErrorException; <ide> use Exception; <add>use Throwable; <ide> <ide> /** <ide> * Error Handler for Cake console. Does simple printing of the <ide> public function __construct($options = []) <ide> * Handle errors in the console environment. Writes errors to stderr, <ide> * and logs messages if Configure::read('debug') is false. <ide> * <del> * @param \Exception $exception Exception instance. <add> * @param \Throwable $exception Exception instance. <ide> * @return void <ide> * @throws \Exception When renderer class not found <ide> * @see https://secure.php.net/manual/en/function.set-exception-handler.php <ide> */ <del> public function handleException(Exception $exception): void <add> public function handleException(Throwable $exception): void <ide> { <ide> $this->_displayException($exception); <ide> $this->_logException($exception); <ide> public function handleException(Exception $exception): void <ide> /** <ide> * Prints an exception to stderr. <ide> * <del> * @param \Exception $exception The exception to handle <add> * @param \Throwable $exception The exception to handle <ide> * @return void <ide> */ <del> protected function _displayException($exception): void <add> protected function _displayException(Throwable $exception): void <ide> { <ide> $errorName = 'Exception:'; <ide> if ($exception instanceof FatalErrorException) { <ide> $errorName = 'Fatal Error:'; <ide> } <ide> <del> if ($exception instanceof PHP7ErrorException) { <del> $exception = $exception->getError(); <del> } <del> <ide> $message = sprintf( <ide> '<error>%s</error> %s in [%s, line %s]', <ide> $errorName, <ide> protected function _displayException($exception): void <ide> * @param bool $debug Whether or not the app is in debug mode. <ide> * @return void <ide> */ <del> protected function _displayError($error, $debug) <add> protected function _displayError(array $error, bool $debug): void <ide> { <ide> $message = sprintf( <ide> '%s in [%s, line %s]', <ide><path>src/Core/ObjectRegistry.php <ide> public function load($objectName, array $config = []) <ide> * @return void <ide> * @throws \RuntimeException When a duplicate is found. <ide> */ <del> protected function _checkDuplicate(string $name, config $config): void <add> protected function _checkDuplicate(string $name, array $config): void <ide> { <ide> /** @var \Cake\Core\InstanceConfigTrait $existing */ <ide> $existing = $this->_loaded[$name]; <ide><path>src/Core/StaticConfigTrait.php <ide> trait StaticConfigTrait <ide> * ``` <ide> * <ide> * @param string|array $key The name of the configuration, or an array of multiple configs. <del> * @param array $config An array of name => configuration data for adapter. <add> * @param array|object $config An array of name => configuration data for adapter. <ide> * @throws \BadMethodCallException When trying to modify an existing config. <ide> * @throws \LogicException When trying to store an invalid structured config array. <ide> * @return void <ide> */ <del> public static function setConfig($key, ?array $config = null): void <add> public static function setConfig($key, $config = null): void <ide> { <ide> if ($config === null) { <ide> if (!is_array($key)) { <ide><path>src/Http/BaseApplication.php <ide> public function pluginMiddleware($middleware) <ide> /** <ide> * {@inheritDoc} <ide> */ <del> public function addPlugin(string $name, array $config = []): PluginApplicationInterface <add> public function addPlugin($name, array $config = []): PluginApplicationInterface <ide> { <ide> if (is_string($name)) { <ide> $plugin = $this->makePlugin($name, $config); <ide><path>tests/TestCase/Controller/Component/AuthComponentTest.php <ide> public function testLoginRedirectDifferentBaseUrl(): void <ide> $appConfig = Configure::read('App'); <ide> <ide> Configure::write('App', [ <add> 'namespace' => 'TestApp', <ide> 'dir' => APP_DIR, <ide> 'webroot' => 'webroot', <ide> 'base' => false, <ide><path>tests/TestCase/ExceptionsTest.php <ide> namespace Cake\Test\TestCase; <ide> <ide> use Cake\Error\FatalErrorException; <del>use Cake\Error\PHP7ErrorException; <ide> use Cake\ORM\Entity; <ide> use Cake\ORM\Exception\PersistenceFailedException; <ide> use Cake\TestSuite\TestCase; <ide> public function testFatalErrorException() <ide> $this->assertSame($previous, $exception->getPrevious()); <ide> } <ide> <del> /** <del> * Tests PHP7ErrorException works. <del> * <del> * @return void <del> */ <del> public function testPHP7ErrorException() <del> { <del> $this->skipIf(version_compare(PHP_VERSION, '7.0.0', '<')); <del> <del> $previous = new Exception(); <del> $error = new Error('message', 100, $previous); <del> $line = __LINE__ - 1; <del> <del> $exception = new PHP7ErrorException($error); <del> $this->assertSame(100, $exception->getCode()); <del> $this->assertSame(__FILE__, $exception->getFile()); <del> $this->assertSame($line, $exception->getLine()); <del> $this->assertSame($previous, $exception->getPrevious()); <del> } <del> <ide> /** <ide> * Tests PersistenceFailedException works. <ide> * <ide><path>tests/test_app/TestApp/Http/BadResponseApplication.php <ide> public function middleware($middleware) <ide> * @param callable $next The next middleware <ide> * @return \Psr\Http\Message\ResponseInterface <ide> */ <del> public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next) <add> public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next): ResponseInterface <ide> { <ide> return $res; <ide> } <ide><path>tests/test_app/TestApp/Http/MiddlewareApplication.php <ide> public function middleware($middleware) <ide> * @param callable $next The next middleware <ide> * @return \Psr\Http\Message\ResponseInterface <ide> */ <del> public function __invoke(ServerRequestInterface $req, ResponseInterface $res, $next) <add> public function __invoke(ServerRequestInterface $req, ResponseInterface $res, $next): ResponseInterface <ide> { <ide> return $res; <ide> }
8
Text
Text
fix typos and grammar in docs
3b80af727a18e318076cfafa10f0670c822f5fe9
<ide><path>TESTING.md <ide> Most code changes will fall into one of the following categories. <ide> ### Writing tests for new features <ide> <ide> New code should be covered by unit tests. If the code is difficult to test with <del>a unit tests then that is a good sign that it should be refactored to make it <add>unit tests, then that is a good sign that it should be refactored to make it <ide> easier to reuse and maintain. Consider accepting unexported interfaces instead <ide> of structs so that fakes can be provided for dependencies. <ide> <ide> case. Error cases should be handled by unit tests. <ide> <ide> Bugs fixes should include a unit test case which exercises the bug. <ide> <del>A bug fix may also include new assertions in an existing integration tests for the <add>A bug fix may also include new assertions in existing integration tests for the <ide> API endpoint. <ide> <ide> ### Integration tests environment considerations <ide> <del>When adding new tests or modifying existing test under `integration/`, testing <add>When adding new tests or modifying existing tests under `integration/`, testing <ide> environment should be properly considered. `skip.If` from <ide> [gotest.tools/skip](https://godoc.org/gotest.tools/skip) can be used to make the <ide> test run conditionally. Full testing environment conditions can be found at <ide> TEST_SKIP_INTEGRATION and/or TEST_SKIP_INTEGRATION_CLI environment variables. <ide> Flags specific to each suite can be set in the TESTFLAGS_INTEGRATION and <ide> TESTFLAGS_INTEGRATION_CLI environment variables. <ide> <del>If all you want is to specity a test filter to run, you can set the <add>If all you want is to specify a test filter to run, you can set the <ide> `TEST_FILTER` environment variable. This ends up getting passed directly to `go <del>test -run` (or `go test -check-f`, dpenending on the test suite). It will also <add>test -run` (or `go test -check-f`, depending on the test suite). It will also <ide> automatically set the other above mentioned environment variables accordingly. <ide> <ide> ### Go Version <ide><path>docs/contributing/test.md <ide> hour. To run the test suite, do the following: <ide> * cross-compiles all the binaries for the various operating systems <ide> * runs all the tests in the system <ide> <del> It can take approximate one hour to run all the tests. The time depends <add> It can take approximately one hour to run all the tests. The time depends <ide> on your host performance. The default timeout is 60 minutes, which is <ide> defined in `hack/make.sh` (`${TIMEOUT:=60m}`). You can modify the timeout <ide> value on the basis of your host performance. When they complete <ide> run a Bash terminal on Windows. <ide> ``` <ide> <ide> 4. Set `DOCKER_TEST_HOST` to the `tcp://IP_ADDRESS:2376` value; substitute your <del> Linux machines actual IP address. For example: <add> Linux machine's actual IP address. For example: <ide> <ide> ```bash <ide> $ export DOCKER_TEST_HOST=tcp://213.124.23.200:2376
2
Javascript
Javascript
avoid empty fixture in module test
c903a9e0c0926921b660c542f921057acd7b3587
<ide><path>test/sequential/test-module-loading.js <ide> <ide> 'use strict'; <ide> const common = require('../common'); <add>const tmpdir = require('../common/tmpdir'); <add> <ide> const assert = require('assert'); <del>const path = require('path'); <ide> const fs = require('fs'); <add>const path = require('path'); <ide> <ide> const backslash = /\\/g; <ide> <ide> assert.strictEqual(require('../fixtures/foo').foo, 'ok', <ide> <ide> // Should not attempt to load a directory <ide> try { <del> require('../fixtures/empty'); <add> tmpdir.refresh(); <add> require(tmpdir.path); <ide> } catch (err) { <del> assert.strictEqual(err.message, 'Cannot find module \'../fixtures/empty\''); <add> assert.strictEqual(err.message, `Cannot find module '${tmpdir.path}'`); <ide> } <ide> <ide> { <ide> try { <ide> 'fixtures/registerExt.test': {}, <ide> 'fixtures/registerExt.hello.world': {}, <ide> 'fixtures/registerExt2.test': {}, <del> 'fixtures/empty.js': {}, <ide> 'fixtures/module-load-order/file1': {}, <ide> 'fixtures/module-load-order/file2.js': {}, <ide> 'fixtures/module-load-order/file3.node': {},
1
Python
Python
add sorts for python3
744dd712386f1d9e86c0305a46dcf81061b769f4
<ide><path>sorts/pancake_sort.py <add># Pancake sort algorithm <add># Only can reverse array from 0 to i <add> <add>def pancakesort(arr): <add> cur = len(arr) <add> while cur > 1: <add> # Find the maximum number in arr <add> mi = arr.index(max(arr[0:cur])) <add> # Reverse from 0 to mi <add> arr = arr[mi::-1] + arr[mi+1:len(arr)] <add> # Reverse whole list <add> arr = arr[cur-1::-1] + arr[cur:len(arr)] <add> cur -= 1 <add> return arr <add> <add>print(pancakesort([0,10,15,3,2,9,14,13])) <ide><path>sorts/tree_sort.py <add># Tree_sort algorithm <add># Build a BST and in order traverse. <add> <add>class node(): <add> # BST data structure <add> def __init__(self, val): <add> self.val = val <add> self.left = None <add> self.right = None <add> <add> def insert(self,val): <add> if self.val: <add> if val < self.val: <add> if self.left == None: <add> self.left = node(val) <add> else: <add> self.left.insert(val) <add> elif val > self.val: <add> if self.right == None: <add> self.right = node(val) <add> else: <add> self.right.insert(val) <add> else: <add> self.val = val <add> <add>def inorder(root, res): <add> # Recursive travesal <add> if root: <add> inorder(root.left,res) <add> res.append(root.val) <add> inorder(root.right,res) <add> <add>def treesort(arr): <add> # Build BST <add> if len(arr) == 0: <add> return arr <add> root = node(arr[0]) <add> for i in range(1,len(arr)): <add> root.insert(arr[i]) <add> # Traverse BST in order. <add> res = [] <add> inorder(root,res) <add> return res <add> <add>print(treesort([10,1,3,2,9,14,13])) <ide>\ No newline at end of file
2
Go
Go
ignore certain tests on lxc driver
0a5b8c40c088c90abb8e3410b92758ed603836d9
<ide><path>integration-cli/docker_cli_run_test.go <ide> func (s *DockerSuite) TestRunCapAddALLDropNetAdminCanDownInterface(c *check.C) { <ide> } <ide> <ide> func (s *DockerSuite) TestRunGroupAdd(c *check.C) { <add> testRequires(c, NativeExecDriver) <ide> out, _ := dockerCmd(c, "run", "--group-add=audio", "--group-add=dbus", "--group-add=777", "busybox", "sh", "-c", "id") <ide> <ide> groupsList := "uid=0(root) gid=0(root) groups=10(wheel),29(audio),81(dbus),777" <ide> func (s *DockerSuite) TestRunDnsOptionsBasedOnHostResolvConf(c *check.C) { <ide> // Test to see if a non-root user can resolve a DNS name and reach out to it. Also <ide> // check if the container resolv.conf file has atleast 0644 perm. <ide> func (s *DockerSuite) TestRunNonRootUserResolvName(c *check.C) { <del> testRequires(c, SameHostDaemon) <add> testRequires(c, SameHostDaemon, NativeExecDriver) <ide> testRequires(c, Network) <ide> <ide> dockerCmd(c, "run", "--name=testperm", "--user=default", "busybox", "ping", "-c", "1", "www.docker.io") <ide> func (s *DockerSuite) TestVolumeFromMixedRWOptions(c *check.C) { <ide> } <ide> <ide> func (s *DockerSuite) TestRunWriteFilteredProc(c *check.C) { <del> testRequires(c, Apparmor) <add> testRequires(c, Apparmor, NativeExecDriver) <ide> <ide> testWritePaths := []string{ <ide> /* modprobe and core_pattern should both be denied by generic
1
Python
Python
add unitary test for history restfull api
a790a3b7f0e10027fdc3c17a82e25d9225456d2e
<ide><path>unitest-restful.py <ide> def test_009_plugins_views(self): <ide> self.assertTrue(req.ok) <ide> self.assertIsInstance(req.json(), dict) <ide> <add> def test_010_history(self): <add> """History.""" <add> method = "history" <add> print('INFO: [TEST_010] History') <add> print("HTTP RESTful request: %s/cpu/%s" % (URL, method)) <add> req = requests.get("%s/cpu/%s" % (URL, method)) <add> self.assertIsInstance(req.json(), dict) <add> self.assertIsInstance(req.json()['user'], list) <add> self.assertTrue(len(req.json()['user']) > 0) <add> print("HTTP RESTful request: %s/cpu/%s/3" % (URL, method)) <add> req = requests.get("%s/cpu/%s/3" % (URL, method)) <add> self.assertIsInstance(req.json(), dict) <add> self.assertIsInstance(req.json()['user'], list) <add> self.assertTrue(len(req.json()['user']) == 3) <add> print("HTTP RESTful request: %s/cpu/system/%s" % (URL, method)) <add> req = requests.get("%s/cpu/system/%s" % (URL, method)) <add> self.assertIsInstance(req.json(), dict) <add> self.assertIsInstance(req.json()['system'], list) <add> self.assertTrue(len(req.json()['system']) > 0) <add> print("HTTP RESTful request: %s/cpu/system/%s/3" % (URL, method)) <add> req = requests.get("%s/cpu/system/%s/3" % (URL, method)) <add> self.assertIsInstance(req.json(), dict) <add> self.assertIsInstance(req.json()['system'], list) <add> self.assertTrue(len(req.json()['system']) == 3) <add> <ide> def test_999_stop_server(self): <ide> """Stop the Glances Web Server.""" <ide> print('INFO: [TEST_999] Stop the Glances Web Server')
1
Text
Text
fix typos in locker example
6d3bc28289c265a65879a7f28264e6bacb95fbe1
<ide><path>pkg/locker/README.md <ide> type important struct { <ide> func (i *important) Get(name string) interface{} { <ide> i.locks.Lock(name) <ide> defer i.locks.Unlock(name) <del> return data[name] <add> return i.data[name] <ide> } <ide> <ide> func (i *important) Create(name string, data interface{}) { <ide> func (i *important) Create(name string, data interface{}) { <ide> <ide> i.createImportant(data) <ide> <del> s.mu.Lock() <add> i.mu.Lock() <ide> i.data[name] = data <del> s.mu.Unlock() <add> i.mu.Unlock() <ide> } <ide> <ide> func (i *important) createImportant(data interface{}) {
1
Text
Text
add openslate to inthewild.md
b81bdaaf86df115a295610f9958061af0aeb9872
<ide><path>INTHEWILD.md <ide> Currently **officially** using Airflow: <ide> 1. [OfferUp](https://offerupnow.com) <ide> 1. [OneFineStay](https://www.onefinestay.com) [[@slangwald](https://github.com/slangwald)] <ide> 1. [Open Knowledge International](https://okfn.org) [@vitorbaptista](https://github.com/vitorbaptista) <add>1. [OpenSlate](https://openslate.com) [@marcusianlevine](https://github.com/marcusianlevine) <ide> 1. [Optum](https://www.optum.com/) - [UnitedHealthGroup](https://www.unitedhealthgroup.com/) [[@fhoda](https://github.com/fhoda), [@ianstanton](https://github.com/ianstanton), [@nilaybhatt](https://github.com/NilayBhatt),[@hiteshrd](https://github.com/hiteshrd)] <ide> 1. [OrangeBank](https://www.orangebank.fr/) [[@HamzaBoukraa](https://github.com/HamzaBoukraa)] <ide> 1. [Outcome Health](https://www.outcomehealth.com/) [[@mikethoun](https://github.com/mikethoun), [@rolandotribo](https://github.com/rolandotribo)]
1
Mixed
Ruby
fix validation on uniqueness of empty association
c449a74e8944eed75453963288ea7a8652f5ba93
<ide><path>activerecord/CHANGELOG.md <add>* Fix validation on uniqueness of empty association. <add> <add> *Evgeny Li* <add> <ide> * Make `ActiveRecord::Relation#unscope` affect relations it is merged in to. <ide> <ide> *Jon Leighton* <ide><path>activerecord/lib/active_record/validations/uniqueness.rb <ide> def find_finder_class_for(record) #:nodoc: <ide> def build_relation(klass, table, attribute, value) #:nodoc: <ide> if reflection = klass.reflect_on_association(attribute) <ide> attribute = reflection.foreign_key <del> value = value.attributes[reflection.primary_key_column.name] <add> value = value.attributes[reflection.primary_key_column.name] unless value.nil? <ide> end <ide> <ide> column = klass.columns_hash[attribute.to_s] <ide><path>activerecord/test/cases/validations/uniqueness_validation_test.rb <ide> class Employee < ActiveRecord::Base <ide> validates_uniqueness_of :nicknames <ide> end <ide> <add>class TopicWithUniqEvent < Topic <add> belongs_to :event, foreign_key: :parent_id <add> validates :event, uniqueness: true <add>end <add> <ide> class UniquenessValidationTest < ActiveRecord::TestCase <ide> fixtures :topics, 'warehouse-things', :developers <ide> <ide> def test_validate_uniqueness_with_array_column <ide> assert_equal ["has already been taken"], e2.errors[:nicknames], "Should have uniqueness message for nicknames" <ide> end <ide> end <add> <add> def test_validate_uniqueness_on_existing_relation <add> event = Event.create <add> assert TopicWithUniqEvent.create(event: event).valid? <add> <add> topic = TopicWithUniqEvent.new(event: event) <add> assert_not topic.valid? <add> assert_equal ['has already been taken'], topic.errors[:event] <add> end <add> <add> def test_validate_uniqueness_on_empty_relation <add> topic = TopicWithUniqEvent.new <add> assert topic.valid? <add> end <ide> end
3
Ruby
Ruby
add support for openjdk formula
bbb269674270b145614780dbaa2258f6c770ff65
<ide><path>Library/Homebrew/extend/os/mac/language/java.rb <ide> module Language <ide> module Java <ide> def self.system_java_home_cmd(version = nil) <ide> version_flag = " --version #{version}" if version <del> "/usr/libexec/java_home#{version_flag}" <add> "/usr/libexec/java_home#{version_flag} --failfast 2>/dev/null" <ide> end <ide> private_class_method :system_java_home_cmd <ide> <ide> def self.java_home(version = nil) <add> f = find_openjdk_formula(version) <add> return f.opt_libexec/"openjdk.jdk/Contents/Home" if f <add> <ide> cmd = system_java_home_cmd(version) <del> Pathname.new Utils.popen_read(cmd).chomp <add> path = Utils.popen_read(cmd).chomp <add> <add> Pathname.new path if path.present? <ide> end <ide> <ide> # @private <ide> def self.java_home_shell(version = nil) <add> f = find_openjdk_formula(version) <add> return (f.opt_libexec/"openjdk.jdk/Contents/Home").to_s if f <add> <ide> "$(#{system_java_home_cmd(version)})" <ide> end <ide> end <ide><path>Library/Homebrew/language/java.rb <ide> <ide> module Language <ide> module Java <add> def self.find_openjdk_formula(version = nil) <add> can_be_newer = version&.end_with?("+") <add> version = version.to_i <add> <add> openjdk = Formula["openjdk"] <add> [openjdk, *openjdk.versioned_formulae].find do |f| <add> next false unless f.any_version_installed? <add> <add> unless version.zero? <add> major = f.version.to_s[/\d+/].to_i <add> next false if major < version <add> next false if major > version && !can_be_newer <add> end <add> <add> true <add> end <add> rescue FormulaUnavailableError <add> nil <add> end <add> private_class_method :find_openjdk_formula <add> <ide> def self.java_home(version = nil) <add> f = find_openjdk_formula(version) <add> return f.opt_libexec if f <add> <ide> req = JavaRequirement.new [*version] <ide> raise UnsatisfiedRequirements, req.message unless req.satisfied? <ide>
2
Text
Text
remove dead link from immutability reading list
dd2844fd21bbbfc051e36bdf3a12256f9828a202
<ide><path>docs/recipes/reducers/PrerequisiteConcepts.md <ide> Because of these rules, it's important that the following core concepts are full <ide> **Reading List**: <ide> <ide> - [Pros and Cons of Using Immutability With React](http://reactkungfu.com/2015/08/pros-and-cons-of-using-immutability-with-react-js/) <del>- [Javascript and Immutability](http://www.t4d.io/javascript-and-immutability/) <ide> - [Immutable Data using ES6 and Beyond](http://wecodetheweb.com/2016/02/12/immutable-javascript-using-es6-and-beyond/) <ide> - [Immutable Data from Scratch](https://ryanfunduk.com/articles/immutable-data-from-scratch/) <ide> - [Redux Docs: Using the Object Spread Operator](../UsingObjectSpreadOperator.md)
1
Text
Text
update the subtitle for stack ps
98fb1644c2b9bf7d808a3d75de5997f87b9c60e6
<ide><path>docs/reference/commandline/stack_ps.md <ide> Multiple filter flags are combined as an `OR` filter. For example, <ide> <ide> The currently supported filters are: <ide> <del>* [id](#id) <del>* [name](#name) <del>* [desired-state](#desired-state) <add>* id <add>* name <add>* desired-state <ide> <ide> ## Related information <ide>
1
Javascript
Javascript
upgrade removeparentmodulesplugin to es6
61251de9c01a0f6729d5bc7f0267f23e75f68940
<ide><path>lib/optimize/RemoveParentModulesPlugin.js <ide> MIT License http://www.opensource.org/licenses/mit-license.php <ide> Author Tobias Koppers @sokra <ide> */ <add>"use strict"; <add> <ide> function chunkContainsModule(chunk, module) { <del> var chunks = module.chunks; <del> var modules = chunk.modules; <add> const chunks = module.chunks; <add> const modules = chunk.modules; <ide> if(chunks.length < modules.length) { <ide> return chunks.indexOf(chunk) >= 0; <ide> } else { <ide> function chunkContainsModule(chunk, module) { <ide> function hasModule(chunk, module, checkedChunks) { <ide> if(chunkContainsModule(chunk, module)) return [chunk]; <ide> if(chunk.parents.length === 0) return false; <del> return allHaveModule(chunk.parents.filter(function(c) { <add> return allHaveModule(chunk.parents.filter((c) => { <ide> return checkedChunks.indexOf(c) < 0; <ide> }), module, checkedChunks); <ide> } <ide> <ide> function allHaveModule(someChunks, module, checkedChunks) { <ide> if(!checkedChunks) checkedChunks = []; <del> var chunks = []; <add> let chunks = []; <ide> for(var i = 0; i < someChunks.length; i++) { <ide> checkedChunks.push(someChunks[i]); <del> var subChunks = hasModule(someChunks[i], module, checkedChunks); <add> const subChunks = hasModule(someChunks[i], module, checkedChunks); <ide> if(!subChunks) return false; <ide> addToSet(chunks, subChunks); <ide> } <ide> return chunks; <ide> } <ide> <ide> function addToSet(set, items) { <del> items.forEach(function(item) { <add> items.forEach((item) => { <ide> if(set.indexOf(item) < 0) <ide> set.push(item); <ide> }); <ide> } <ide> <ide> function debugIds(chunks) { <del> var list = chunks.map(function(chunk) { <add> const list = chunks.map((chunk) => { <ide> return chunk.debugId; <ide> }); <del> var debugIdMissing = list.some(function(dId) { <add> const debugIdMissing = list.some((dId) => { <ide> return typeof dId !== "number"; <ide> }); <ide> if(debugIdMissing) <ide> function debugIds(chunks) { <ide> return list.join(","); <ide> } <ide> <del>function RemoveParentModulesPlugin() {} <del>module.exports = RemoveParentModulesPlugin; <del> <del>RemoveParentModulesPlugin.prototype.apply = function(compiler) { <del> compiler.plugin("compilation", function(compilation) { <del> compilation.plugin(["optimize-chunks-basic", "optimize-extracted-chunks-basic"], function(chunks) { <del> chunks.forEach(function(chunk) { <del> var cache = {}; <del> chunk.modules.slice().forEach(function(module) { <del> if(chunk.parents.length === 0) return; <del> var dId = "$" + debugIds(module.chunks); <del> var parentChunksWithModule; <del> if((dId in cache) && dId !== "$no") { <del> parentChunksWithModule = cache[dId]; <del> } else { <del> parentChunksWithModule = cache[dId] = allHaveModule(chunk.parents, module); <del> } <del> if(parentChunksWithModule) { <del> module.rewriteChunkInReasons(chunk, parentChunksWithModule); <del> chunk.removeModule(module); <del> } <add>class RemoveParentModulesPlugin { <add> apply(compiler) { <add> compiler.plugin("compilation", (compilation) => { <add> compilation.plugin(["optimize-chunks-basic", "optimize-extracted-chunks-basic"], (chunks) => { <add> chunks.forEach((chunk) => { <add> const cache = {}; <add> chunk.modules.slice().forEach((module) => { <add> if(chunk.parents.length === 0) return; <add> const dId = "$" + debugIds(module.chunks); <add> let parentChunksWithModule; <add> if((dId in cache) && dId !== "$no") { <add> parentChunksWithModule = cache[dId]; <add> } else { <add> parentChunksWithModule = cache[dId] = allHaveModule(chunk.parents, module); <add> } <add> if(parentChunksWithModule) { <add> module.rewriteChunkInReasons(chunk, parentChunksWithModule); <add> chunk.removeModule(module); <add> } <add> }); <ide> }); <ide> }); <ide> }); <del> }); <del>}; <add> } <add>} <add>module.exports = RemoveParentModulesPlugin;
1
Javascript
Javascript
move styled-jsx to external modules
409cf71a4d8296251c07b118e9da43bab98424c0
<ide><path>packages/next/build/webpack.js <ide> function externalsConfig (dir, isServer) { <ide> return externals <ide> } <ide> <del> const notExternalModules = ['next/app', 'next/document', 'next/error', 'http-status'] <add> const notExternalModules = ['next/app', 'next/document', 'next/error', 'http-status', 'styled-jsx'] <ide> <ide> externals.push((context, request, callback) => { <ide> if (notExternalModules.indexOf(request) !== -1) {
1
Python
Python
add siamese example
652f2eb56dfd8b5f8549d06d66bae86bf98454f3
<ide><path>examples/mnist_siamese_graph.py <add>'''Train a Siamese MLP on pairs of digits from the MNIST dataset. <add> <add>It follows Hadsell-et-al.'06 [1] by computing the Euclidean distance on the <add>output of the shared network and by optimizing the contrastive loss (see paper <add>for mode details). <add> <add>[1] "Dimensionality Reduction by Learning an Invariant Mapping" <add> http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf <add> <add>Run on GPU: THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python mnist_siamese_graph.py <add> <add>Get to 99.5% test accuracy after 20 epochs. <add>3 seconds per epoch on a Titan X GPU <add>''' <add>from __future__ import absolute_import <add>from __future__ import print_function <add>import numpy as np <add>np.random.seed(1337) # for reproducibility <add> <add>import random <add>from keras.datasets import mnist <add>from keras.models import Sequential, Graph <add>from keras.layers.core import * <add>from keras.optimizers import SGD, RMSprop <add>from keras import backend as K <add> <add> <add>def euclidean_distance(inputs): <add> assert len(inputs) == 2, \ <add> 'Euclidean distance needs 2 inputs, %d given' % len(inputs) <add> u, v = inputs.values() <add> return K.sqrt((K.square(u - v)).sum(axis=1, keepdims=True)) <add> <add> <add>def contrastive_loss(y, d): <add> """ Contrastive loss from Hadsell-et-al.'06 <add> http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf <add> """ <add> margin = 1 <add> return K.mean(y * K.square(d) + (1 - y) * K.square(K.maximum(margin - d, 0))) <add> <add> <add>def create_pairs(x, digit_indices): <add> """ Positive and negative pair creation. <add> Alternates between positive and negative pairs. <add> """ <add> pairs = [] <add> labels = [] <add> n = min([len(digit_indices[d]) for d in range(10)]) - 1 <add> for d in range(10): <add> for i in range(n): <add> z1, z2 = digit_indices[d][i], digit_indices[d][i+1] <add> pairs += [[x[z1], x[z2]]] <add> inc = random.randrange(1, 10) <add> dn = (d + inc) % 10 <add> z1, z2 = digit_indices[d][i], digit_indices[dn][i] <add> pairs += [[x[z1], x[z2]]] <add> labels += [1, 0] <add> return np.array(pairs), np.array(labels) <add> <add> <add>def create_base_network(in_dim): <add> """ Base network to be shared (eq. to feature extraction). <add> """ <add> seq = Sequential() <add> seq.add(Dense(128, input_shape=(in_dim,), activation='relu')) <add> seq.add(Dropout(0.1)) <add> seq.add(Dense(128, activation='relu')) <add> seq.add(Dropout(0.1)) <add> seq.add(Dense(128, activation='relu')) <add> return seq <add> <add> <add>def compute_accuracy(predictions, labels): <add> """ Compute classification accuracy with a fixed threshold on distances. <add> """ <add> return labels[predictions.ravel() < 0.5].mean() <add> <add> <add># the data, shuffled and split between tran and test sets <add>(X_train, y_train), (X_test, y_test) = mnist.load_data() <add>X_train = X_train.reshape(60000, 784) <add>X_test = X_test.reshape(10000, 784) <add>X_train = X_train.astype('float32') <add>X_test = X_test.astype('float32') <add>X_train /= 255 <add>X_test /= 255 <add>in_dim = 784 <add>nb_epoch = 20 <add> <add># create training+test positive and negative pairs <add>digit_indices = [np.where(y_train == i)[0] for i in range(10)] <add>tr_pairs, tr_y = create_pairs(X_train, digit_indices) <add> <add>digit_indices = [np.where(y_test == i)[0] for i in range(10)] <add>te_pairs, te_y = create_pairs(X_test, digit_indices) <add> <add># network definition <add>base_network = create_base_network(in_dim) <add> <add>g = Graph() <add>g.add_input(name='input_a', input_shape=(in_dim,)) <add>g.add_input(name='input_b', input_shape=(in_dim,)) <add>g.add_shared_node(base_network, name='shared', inputs=['input_a', 'input_b'], <add> merge_mode='join') <add>g.add_node(Lambda(euclidean_distance), name='d', input='shared') <add>g.add_output(name='output', input='d') <add> <add># train <add>rms = RMSprop() <add>g.compile(loss={'output': contrastive_loss}, optimizer=rms) <add>g.fit({'input_a': tr_pairs[:, 0], 'input_b': tr_pairs[:, 1], 'output': tr_y}, <add> validation_data={'input_a': te_pairs[:, 0], 'input_b': te_pairs[:, 1], 'output': te_y}, <add> batch_size=128, nb_epoch=nb_epoch) <add> <add># compute final accuracy on training and test sets <add>pred = g.predict({'input_a': tr_pairs[:, 0], 'input_b': tr_pairs[:, 1]})['output'] <add>tr_acc = compute_accuracy(pred, tr_y) <add>pred = g.predict({'input_a': te_pairs[:, 0], 'input_b': te_pairs[:, 1]})['output'] <add>te_acc = compute_accuracy(pred, te_y) <add> <add>print('* Accuracy on training set: %0.2f%%' % (100 * tr_acc)) <add>print('* Accuracy on test set: %0.2f%%' % (100 * te_acc))
1
Java
Java
require rsocket 1.0+
5bdbbdfcfb1e0200664e8a2ddcec644928a6d26d
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/ClientRSocketFactoryConfigurer.java <del>/* <del> * Copyright 2002-2020 the original author or authors. <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> * https://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 org.springframework.messaging.rsocket; <del> <del>/** <del> * Strategy to apply configuration to a client side {@code RSocketFactory}. <del> * that's being prepared by {@link RSocketRequester.Builder} to connect <del> * to a server. <del> * <del> * @author Rossen Stoyanchev <del> * @since 5.2 <del> * @deprecated as of 5.2.6 following the deprecation of <del> * {@link io.rsocket.RSocketFactory.ClientRSocketFactory RSocketFactory.ClientRSocketFactory} <del> * in RSocket 1.0 RC7. Please, use {@link RSocketConnectorConfigurer}. <del> */ <del>@FunctionalInterface <del>@Deprecated <del>public interface ClientRSocketFactoryConfigurer { <del> <del> /** <del> * Apply configuration to the given {@code ClientRSocketFactory}. <del> */ <del> void configure(io.rsocket.RSocketFactory.ClientRSocketFactory rsocketFactory); <del> <del>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/DefaultRSocketRequesterBuilder.java <ide> final class DefaultRSocketRequesterBuilder implements RSocketRequester.Builder { <ide> <ide> private List<RSocketConnectorConfigurer> rsocketConnectorConfigurers = new ArrayList<>(); <ide> <del> @SuppressWarnings("deprecation") <del> private List<ClientRSocketFactoryConfigurer> rsocketFactoryConfigurers = new ArrayList<>(); <del> <ide> <ide> @Override <ide> public RSocketRequester.Builder dataMimeType(@Nullable MimeType mimeType) { <ide> public RSocketRequester.Builder rsocketConnector(RSocketConnectorConfigurer conf <ide> return this; <ide> } <ide> <del> @Override <del> @Deprecated <del> public RSocketRequester.Builder rsocketFactory(ClientRSocketFactoryConfigurer configurer) { <del> this.rsocketFactoryConfigurers.add(configurer); <del> return this; <del> } <del> <ide> @Override <ide> public RSocketRequester.Builder apply(Consumer<RSocketRequester.Builder> configurer) { <ide> configurer.accept(this); <ide> public RSocketRequester transport(ClientTransport transport) { <ide> Mono<Payload> setupPayload = getSetupPayload(dataMimeType, metaMimeType, strategies); <ide> <ide> RSocketConnector connector = initConnector( <del> this.rsocketConnectorConfigurers, this.rsocketFactoryConfigurers, <add> this.rsocketConnectorConfigurers, <ide> metaMimeType, dataMimeType, setupPayload, strategies); <ide> <ide> return new DefaultRSocketRequester( <ide> public Mono<RSocketRequester> connect(ClientTransport transport) { <ide> Mono<Payload> setupPayload = getSetupPayload(dataMimeType, metaMimeType, rsocketStrategies); <ide> <ide> RSocketConnector connector = initConnector( <del> this.rsocketConnectorConfigurers, this.rsocketFactoryConfigurers, <add> this.rsocketConnectorConfigurers, <ide> metaMimeType, dataMimeType, setupPayload, rsocketStrategies); <ide> <ide> return connector.connect(transport).map(rsocket -> <ide> private Mono<Payload> getSetupPayload( <ide> <ide> @SuppressWarnings("deprecation") <ide> private RSocketConnector initConnector(List<RSocketConnectorConfigurer> connectorConfigurers, <del> List<ClientRSocketFactoryConfigurer> factoryConfigurers, <ide> MimeType metaMimeType, MimeType dataMimeType, Mono<Payload> setupPayloadMono, <ide> RSocketStrategies rsocketStrategies) { <ide> <ide> RSocketConnector connector = RSocketConnector.create(); <ide> connectorConfigurers.forEach(c -> c.configure(connector)); <ide> <del> if (!factoryConfigurers.isEmpty()) { <del> io.rsocket.RSocketFactory.ClientRSocketFactory factory = <del> new io.rsocket.RSocketFactory.ClientRSocketFactory(connector); <del> factoryConfigurers.forEach(c -> c.configure(factory)); <del> } <del> <ide> if (rsocketStrategies.dataBufferFactory() instanceof NettyDataBufferFactory) { <ide> connector.payloadDecoder(PayloadDecoder.ZERO_COPY); <ide> } <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/MetadataEncoder.java <ide> private DataBuffer encodeEntries(List<MetadataEntry> entries) { <ide> CompositeByteBuf composite = this.allocator.compositeBuffer(); <ide> try { <ide> if (this.route != null) { <del> io.rsocket.metadata.CompositeMetadataFlyweight.encodeAndAddMetadata(composite, this.allocator, <add> io.rsocket.metadata.CompositeMetadataCodec.encodeAndAddMetadata(composite, this.allocator, <ide> WellKnownMimeType.MESSAGE_RSOCKET_ROUTING, encodeRoute()); <ide> } <ide> entries.forEach(entry -> { <ide> Object value = entry.value(); <del> io.rsocket.metadata.CompositeMetadataFlyweight.encodeAndAddMetadata( <add> io.rsocket.metadata.CompositeMetadataCodec.encodeAndAddMetadata( <ide> composite, this.allocator, entry.mimeType().toString(), <ide> value instanceof ByteBuf ? (ByteBuf) value : PayloadUtils.asByteBuf(encodeEntry(entry))); <ide> }); <ide> else if (this.route != null) { <ide> } <ide> } <ide> <del> @SuppressWarnings("deprecation") <ide> private ByteBuf encodeRoute() { <del> return io.rsocket.metadata.TaggingMetadataFlyweight.createRoutingMetadata( <add> return io.rsocket.metadata.TaggingMetadataCodec.createRoutingMetadata( <ide> this.allocator, Collections.singletonList(this.route)).getContent(); <ide> } <ide> <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/RSocketRequester.java <ide> interface Builder { <ide> */ <ide> RSocketRequester.Builder rsocketConnector(RSocketConnectorConfigurer configurer); <ide> <del> /** <del> * Callback to configure the {@code ClientRSocketFactory} directly. <del> * <ul> <del> * <li>The data and metadata mime types cannot be set directly <del> * on the {@code ClientRSocketFactory} and will be overridden. Use the <del> * shortcuts {@link #dataMimeType(MimeType)} and <del> * {@link #metadataMimeType(MimeType)} on this builder instead. <del> * <li>The frame decoder also cannot be set directly and instead is set <del> * to match the configured {@code DataBufferFactory}. <del> * <li>For the <del> * {@link io.rsocket.RSocketFactory.ClientRSocketFactory#setupPayload(Payload) <del> * setupPayload}, consider using methods on this builder to specify the <del> * route, other metadata, and data as Object values to be encoded. <del> * <li>To configure client side responding, see <del> * {@link RSocketMessageHandler#clientResponder(RSocketStrategies, Object...)}. <del> * </ul> <del> * @deprecated as of 5.2.6 following the deprecation of <del> * {@link io.rsocket.RSocketFactory.ClientRSocketFactory RSocketFactory.ClientRSocketFactory} <del> * in RSocket 1.0 RC7. Please, use {@link #rsocketConnector(RSocketConnectorConfigurer)}. <del> */ <del> @Deprecated <del> RSocketRequester.Builder rsocketFactory(ClientRSocketFactoryConfigurer configurer); <del> <ide> /** <ide> * Configure this builder through a {@code Consumer}. This enables <ide> * libraries such as Spring Security to provide shortcuts for applying <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/annotation/support/RSocketMessageHandler.java <ide> protected CompositeMessageCondition extendMapping(CompositeMessageCondition comp <ide> <ide> List<MessageCondition<?>> conditions = composite.getMessageConditions(); <ide> Assert.isTrue(conditions.size() == 2 && <del> conditions.get(0) instanceof RSocketFrameTypeMessageCondition && <del> conditions.get(1) instanceof DestinationPatternsMessageCondition, <add> conditions.get(0) instanceof RSocketFrameTypeMessageCondition && <add> conditions.get(1) instanceof DestinationPatternsMessageCondition, <ide> "Unexpected message condition types"); <ide> <ide> if (conditions.get(0) != RSocketFrameTypeMessageCondition.EMPTY_CONDITION) { <ide> protected void handleNoMatch(@Nullable RouteMatcher.Route destination, Message<? <ide> * Return an RSocket {@link SocketAcceptor} backed by this <ide> * {@code RSocketMessageHandler} instance that can be plugged in as a <ide> * {@link io.rsocket.core.RSocketConnector#acceptor(SocketAcceptor) client} or <del> * {@link io.rsocket.core.RSocketServer#acceptor(SocketAcceptor) server} <add> * {@link io.rsocket.core.RSocketServer#acceptor(SocketAcceptor) server} <ide> * RSocket responder. <ide> * <p>The initial {@link ConnectionSetupPayload} is handled through <ide> * {@link ConnectMapping @ConnectionMapping} methods that can be asynchronous <ide> public static SocketAcceptor responder(RSocketStrategies strategies, Object... c <ide> return handler.responder(); <ide> } <ide> <del> /** <del> * Static factory method for a configurer of a client side responder with <del> * annotated handler methods. This is intended to be passed into <del> * {@link org.springframework.messaging.rsocket.RSocketRequester.Builder#rsocketFactory}. <del> * <p>In effect a shortcut to create and initialize <del> * {@code RSocketMessageHandler} with the given strategies and handlers. <del> * Use {@link #responder()} to obtain the responder and plug that into <del> * {@link io.rsocket.RSocketFactory.ClientRSocketFactory ClientRSocketFactory}. <del> * For more advanced scenarios, e.g. discovering handlers through a custom <del> * stereotype annotation, consider declaring {@code RSocketMessageHandler} <del> * as a bean, and then obtain the responder from it. <del> * @param strategies the strategies to set on the created <del> * {@code RSocketMessageHandler} <del> * @param candidateHandlers a list of Objects and/or Classes with annotated <del> * handler methods; used to call {@link #setHandlers(List)} on the created <del> * {@code RSocketMessageHandler} <del> * @return a configurer that may be passed into <del> * {@link org.springframework.messaging.rsocket.RSocketRequester.Builder#rsocketFactory} <del> * @deprecated as of 5.2.6 following the deprecation of <del> * {@link io.rsocket.RSocketFactory.ClientRSocketFactory RSocketFactory.ClientRSocketFactory} <del> * in RSocket 1.0 RC7 <del> */ <del> @Deprecated <del> @SuppressWarnings("deprecation") <del> public static org.springframework.messaging.rsocket.ClientRSocketFactoryConfigurer clientResponder( <del> RSocketStrategies strategies, Object... candidateHandlers) { <del> <del> Assert.notEmpty(candidateHandlers, "No handlers"); <del> List<Object> handlers = new ArrayList<>(candidateHandlers.length); <del> for (Object obj : candidateHandlers) { <del> handlers.add(obj instanceof Class ? BeanUtils.instantiateClass((Class<?>) obj) : obj); <del> } <del> <del> return factory -> { <del> RSocketMessageHandler handler = new RSocketMessageHandler(); <del> handler.setHandlers(handlers); <del> handler.setRSocketStrategies(strategies); <del> handler.afterPropertiesSet(); <del> factory.acceptor(handler.responder()); <del> }; <del> } <ide> } <ide><path>spring-messaging/src/test/java/org/springframework/messaging/rsocket/DefaultRSocketRequesterBuilderTests.java <ide> public void setup() { <ide> <ide> <ide> @Test <del> @SuppressWarnings({"unchecked", "deprecation"}) <add> @SuppressWarnings("unchecked") <ide> public void rsocketConnectorConfigurer() { <del> ClientRSocketFactoryConfigurer factoryConfigurer = mock(ClientRSocketFactoryConfigurer.class); <ide> Consumer<RSocketStrategies.Builder> strategiesConfigurer = mock(Consumer.class); <ide> RSocketRequester.builder() <ide> .rsocketConnector(this.connectorConfigurer) <del> .rsocketFactory(factoryConfigurer) <ide> .rsocketStrategies(strategiesConfigurer) <ide> .transport(this.transport); <ide> <ide> // RSocketStrategies and RSocketConnector configurers should have been called <ide> <ide> verify(strategiesConfigurer).accept(any(RSocketStrategies.Builder.class)); <del> verify(factoryConfigurer).configure(any(io.rsocket.RSocketFactory.ClientRSocketFactory.class)); <ide> assertThat(this.connectorConfigurer.connector()).isNotNull(); <ide> } <ide>
6
PHP
PHP
fix mail notification for mailgun
14d3818f339f1ca928feb19a3a67cd53c8454ba7
<ide><path>src/Illuminate/Notifications/Channels/MailChannel.php <ide> protected function addressMessage($mailMessage, $notifiable, $message) <ide> { <ide> $this->addSender($mailMessage, $message); <ide> <del> $mailMessage->bcc($this->getRecipients($notifiable, $message)); <add> $mailMessage->to($this->getRecipients($notifiable, $message)); <ide> } <ide> <ide> /** <ide><path>tests/Notifications/NotificationMailChannelTest.php <ide> public function testMessageWithSubject() <ide> <ide> $mock->shouldReceive('subject')->once()->with('test subject'); <ide> <del> $mock->shouldReceive('bcc')->once()->with(['taylor@laravel.com']); <add> $mock->shouldReceive('to')->once()->with(['taylor@laravel.com']); <ide> <ide> $mock->shouldReceive('from')->never(); <ide> <ide> public function testMessageWithoutSubjectAutogeneratesSubjectFromClassName() <ide> <ide> $mock->shouldReceive('subject')->once()->with('Notification Mail Channel Test Notification No Subject'); <ide> <del> $mock->shouldReceive('bcc')->once()->with(['taylor@laravel.com']); <add> $mock->shouldReceive('to')->once()->with(['taylor@laravel.com']); <ide> <ide> $closure($mock); <ide> <ide> public function testMessageWithMultipleSenders() <ide> <ide> $mock->shouldReceive('to')->never(); <ide> <del> $mock->shouldReceive('bcc')->with(['taylor@laravel.com', 'jeffrey@laracasts.com']); <add> $mock->shouldReceive('to')->with(['taylor@laravel.com', 'jeffrey@laracasts.com']); <ide> <ide> $closure($mock); <ide> <ide> public function testMessageWithFromAddress() <ide> <ide> $mock->shouldReceive('subject')->once(); <ide> <del> $mock->shouldReceive('bcc')->once(); <add> $mock->shouldReceive('to')->once(); <ide> <ide> $mock->shouldReceive('from')->with('test@mail.com', 'Test Man'); <ide> <ide> public function testMessageWithFromAddressAndNoName() <ide> <ide> $mock->shouldReceive('subject')->once(); <ide> <del> $mock->shouldReceive('bcc')->once(); <add> $mock->shouldReceive('to')->once(); <ide> <ide> $mock->shouldReceive('from')->with('test@mail.com', null); <ide> <ide> public function testMessageWithReplyToAddress() <ide> <ide> $mock->shouldReceive('subject')->once(); <ide> <del> $mock->shouldReceive('bcc')->once(); <add> $mock->shouldReceive('to')->once(); <ide> <ide> $mock->shouldReceive('replyTo')->with('test@mail.com', 'Test Man'); <ide> <ide> public function testMessageWithReplyToAddressAndNoName() <ide> <ide> $mock->shouldReceive('subject')->once(); <ide> <del> $mock->shouldReceive('bcc')->once(); <add> $mock->shouldReceive('to')->once(); <ide> <ide> $mock->shouldReceive('replyTo')->with('test@mail.com', null); <ide> <ide> public function testMessageWithPriority() <ide> <ide> $mock->shouldReceive('subject')->once(); <ide> <del> $mock->shouldReceive('bcc')->once()->with(['taylor@laravel.com']); <add> $mock->shouldReceive('to')->once()->with(['taylor@laravel.com']); <ide> <ide> $mock->shouldReceive('setPriority')->once()->with(1); <ide>
2
Javascript
Javascript
ignore undefined parameters
10e1c759f4602d993a76b0eacf6a2d04c8880017
<ide><path>src/ngResource/resource.js <ide> angular.module('ngResource', ['ng']). <ide> url: function(params) { <ide> var self = this, <ide> url = this.template, <add> val, <ide> encodedVal; <ide> <ide> params = params || {}; <ide> forEach(this.urlParams, function(_, urlParam){ <del> encodedVal = encodeUriSegment(params[urlParam] || self.defaults[urlParam] || ""); <del> url = url.replace(new RegExp(":" + urlParam + "(\\W)"), encodedVal + "$1"); <add> if (val = (params[urlParam] || self.defaults[urlParam])) { <add> encodedVal = encodeUriSegment(val); <add> url = url.replace(new RegExp(":" + urlParam + "(\\W)", "g"), encodedVal + "$1"); <add> } else { <add> url = url.replace(new RegExp("/?:" + urlParam + "(\\W)", "g"), '$1'); <add> } <ide> }); <ide> url = url.replace(/\/?#$/, ''); <ide> var query = []; <ide> angular.module('ngResource', ['ng']). <ide> <ide> actions = extend({}, DEFAULT_ACTIONS, actions); <ide> <del> function extractParams(data){ <add> function extractParams(data, actionParams){ <ide> var ids = {}; <add> paramDefaults = extend(paramDefaults, actionParams); <ide> forEach(paramDefaults || {}, function(value, key){ <ide> ids[key] = value.charAt && value.charAt(0) == '@' ? getter(data, value.substr(1)) : value; <ide> }); <ide> angular.module('ngResource', ['ng']). <ide> var value = this instanceof Resource ? this : (action.isArray ? [] : new Resource(data)); <ide> $http({ <ide> method: action.method, <del> url: route.url(extend({}, extractParams(data), action.params || {}, params)), <add> url: route.url(extend({}, extractParams(data, action.params || {}), params)), <ide> data: data, <ide> headers: extend({}, action.headers || {}) <ide> }).then(function(response) { <ide><path>test/ngResource/resourceSpec.js <ide> describe("resource", function() { <ide> $httpBackend.expect('GET', '/Path'); <ide> $httpBackend.expect('GET', '/Path/1'); <ide> $httpBackend.expect('GET', '/Path/2/3'); <del> $httpBackend.expect('GET', '/Path/4/5/6'); <add> $httpBackend.expect('GET', '/Path/4/5'); <add> $httpBackend.expect('GET', '/Path/6/7/8'); <ide> <ide> R.get({}); <ide> R.get({a:1}); <ide> R.get({a:2, b:3}); <del> R.get({a:4, b:5, c:6}); <add> R.get({a:4, c:5}); <add> R.get({a:6, b:7, c:8}); <ide> }); <ide> <ide> <ide> describe("resource", function() { <ide> }); <ide> <ide> <add> it('should build resource with action default param reading the value from instance', function() { <add> $httpBackend.expect('POST', '/Customer/123').respond(); <add> var R = $resource('/Customer/:id', {}, {post: {method: 'POST', params: {id: '@id'}}}); <add> <add> var inst = new R({id:123}); <add> expect(inst.id).toBe(123); <add> <add> inst.$post(); <add> }); <add> <add> <add> it('should handle multiple params with same name', function() { <add> var R = $resource('/:id/:id'); <add> <add> $httpBackend.when('GET').respond('{}'); <add> $httpBackend.expect('GET', '/1/1'); <add> <add> R.get({id:1}); <add> }); <add> <add> <ide> it("should create resource", function() { <ide> $httpBackend.expect('POST', '/CreditCard', '{"name":"misko"}').respond({id: 123, name: 'misko'}); <ide>
2
Text
Text
add an information about games built
7a2ae44353f9d8a0c89b721bd2475de6d6e3a6d7
<ide><path>guide/english/game-development/pygame/index.md <ide> title: Pygame <ide> <ide> Pygame is an open source, cross platform Python library used for game development, written by Pete Shinners. The Pygame documentation and more information can be found on their website at https://pygame.org. <ide> <add> <ide> ### Overview <ide> <ide> The project started in the year 2000 as a result of the death of PySDL. The Pygame library version 1.0 was <ide> released after six months development in April of 2001. <ide> <add>### Games Built with Pygame <add> <add>- Too Many Troopers <add>- Vectorpods 2 <add>- QANAT <add> <add> <ide> * [Pygame Official Website](https://www.pygame.org) <ide> <ide> ### Tutorials
1
Text
Text
add release notes for 1.4.9
dc3013e848889431fcff6be57ce828cb309b2077
<ide><path>CHANGELOG.md <add><a name="1.4.9"></a> <add># 1.4.9 implicit-superannuation (2016-01-21) <add> <add> <add>## Bug Fixes <add> <add>### Core `ng` Module <add>- **$animate:** <add> - correctly handle `$animate.pin()` host elements <add> ([a985adfd](https://github.com/angular/angular.js/commit/a985adfdabd871f3f3f3ee59f371da50cd9611d9), <add> [#13783](https://github.com/angular/angular.js/issues/13783)) <add> - allow animations when pinned element is parent element <add> ([4cb8ac61](https://github.com/angular/angular.js/commit/4cb8ac61c7574ab4039852c358dd5946268b69fb), <add> [#13466](https://github.com/angular/angular.js/issues/13466)) <add> - allow enabled children to animate on disabled parents <add> ([6d85f24e](https://github.com/angular/angular.js/commit/6d85f24e2081d2a69c80697d90ebd45f228d9682), <add> [#13179](https://github.com/angular/angular.js/issues/13179), [#13695](https://github.com/angular/angular.js/issues/13695)) <add> - correctly access `minErr` <add> ([0c1b54f0](https://github.com/angular/angular.js/commit/0c1b54f04cf5bd7c1fe42ac49b4fbfdf35c60979)) <add> - ensure animate runner is the same with and without animations <add> ([937942f5](https://github.com/angular/angular.js/commit/937942f5ada6de1bdacdf0ba465f6f118c270119), <add> [#13205](https://github.com/angular/angular.js/issues/13205), [#13347](https://github.com/angular/angular.js/issues/13347)) <add>- **$animateCss:** <add> - remove animation end event listeners on close <add> ([d9157849](https://github.com/angular/angular.js/commit/d9157849df224a3a8d2e0bf03099d137f51499f6), <add> [#13672](https://github.com/angular/angular.js/issues/13672)) <add> - consider options.delay value for closing timeout <add> ([592bf516](https://github.com/angular/angular.js/commit/592bf516e50b9729e446d9aa01f4d9ebdd72d187), <add> [#13355](https://github.com/angular/angular.js/issues/13355), [#13363](https://github.com/angular/angular.js/issues/13363)) <add>- **$controller:** allow identifiers containing `$` <add> ([2563ff7b](https://github.com/angular/angular.js/commit/2563ff7ba92d84af978e7e4131253190d4d00c20), <add> [#13736](https://github.com/angular/angular.js/issues/13736)) <add>- **$http:** throw if url passed is not a string <add> ([c5bf9dae](https://github.com/angular/angular.js/commit/c5bf9daef6dfdb3e4a2942c21155a9f67d92e237), <add> [#12925](https://github.com/angular/angular.js/issues/12925), [#13444](https://github.com/angular/angular.js/issues/13444)) <add>- **$parse:** handle interceptors with `undefined` expressions <add> ([7bb2414b](https://github.com/angular/angular.js/commit/7bb2414bf6461aa45a983fd322ae875f81814cc4)) <add>- **$resource:** don't allow using promises as `timeout` and log a warning <add> ([47486524](https://github.com/angular/angular.js/commit/474865242c89ba3e8143f0cd52f8c292979ea730)) <add>- **formatNumber:** cope with large and small number corner cases <add> ([9c49eb13](https://github.com/angular/angular.js/commit/9c49eb131a6100d58c965d01fb08bcd319032229), <add> [#13394](https://github.com/angular/angular.js/issues/13394), [#8674](https://github.com/angular/angular.js/issues/8674), [#12709](https://github.com/angular/angular.js/issues/12709), [#8705](https://github.com/angular/angular.js/issues/8705), [#12707](https://github.com/angular/angular.js/issues/12707), [#10246](https://github.com/angular/angular.js/issues/10246), [#10252](https://github.com/angular/angular.js/issues/10252)) <add>- **input:** <add> - fix URL validation being too strict <add> ([6610ae81](https://github.com/angular/angular.js/commit/6610ae816f78ee8fc1080b93a55bf19e4ce48d3e), <add> [#13528](https://github.com/angular/angular.js/issues/13528), [#13544](https://github.com/angular/angular.js/issues/13544)) <add> - add missing chars to URL validation regex <add> ([2995b54a](https://github.com/angular/angular.js/commit/2995b54afdb9a3a2a81b0076a6ac0a9001041163), <add> [#13379](https://github.com/angular/angular.js/issues/13379), [#13460](https://github.com/angular/angular.js/issues/13460)) <add>- **isArrayLike:** recognize empty instances of an Array subclass <add> ([323f9ab7](https://github.com/angular/angular.js/commit/323f9ab73696f223c245ddefd62a769fe102615e), <add> [#13560](https://github.com/angular/angular.js/issues/13560), [#13708](https://github.com/angular/angular.js/issues/13708)) <add>- **ngInclude:** do not compile template if original scope is destroyed <add> ([9590bcf0](https://github.com/angular/angular.js/commit/9590bcf0620cd507a7795c55f9a6f4a48bfedbc1)) <add>- **ngOptions:** <add> - don't skip `optgroup` elements with `value === ''` <add> ([85e392f3](https://github.com/angular/angular.js/commit/85e392f3543ef5285c7e90e843af0ab522cb0531), <add> [#13487](https://github.com/angular/angular.js/issues/13487), [#13489](https://github.com/angular/angular.js/issues/13489)) <add> - don't `$dirty` multiple select after compilation <add> ([f163c905](https://github.com/angular/angular.js/commit/f163c90555774426ccb14752d089fc707cb4029c), <add> [#13211](https://github.com/angular/angular.js/issues/13211), [#13326](https://github.com/angular/angular.js/issues/13326)) <add>- **select:** re-define `ngModelCtrl.$render` in the `select` directive's postLink function <add> ([529b2507](https://github.com/angular/angular.js/commit/529b2507bdb4fcc22dfa0f7ab462c79fc78d1413), <add> [#13583](https://github.com/angular/angular.js/issues/13583), [#13583](https://github.com/angular/angular.js/issues/13583), [#13663](https://github.com/angular/angular.js/issues/13663)) <add> <add>### `ngAnimate` Module <add> <add>- **ngAnimate:** <add> - ensure that animate promises resolve when the document is hidden <add> ([9a60408c](https://github.com/angular/angular.js/commit/9a60408c804a62a9517857bdb9a42182ab6769e3)) <add> - do not trigger animations if the document is hidden <add> ([09f6061a](https://github.com/angular/angular.js/commit/09f6061a8ee41cae4268e8d44d727d3bf52e22a9), <add> [#12842](https://github.com/angular/angular.js/issues/12842), [#13776](https://github.com/angular/angular.js/issues/13776)) <add> - only copy over the animation options once <add> ([2fc954d3](https://github.com/angular/angular.js/commit/2fc954d33a3a4c5d4f355be1e15a381664e02f1b), <add> [#13722](https://github.com/angular/angular.js/issues/13722), [#13578](https://github.com/angular/angular.js/issues/13578)) <add> - allow event listeners on document in IE <add> ([5ba4419e](https://github.com/angular/angular.js/commit/5ba4419e265ff34c6c23bf3533a3332c99c5f014), <add> [#13548](https://github.com/angular/angular.js/issues/13548), [#13696](https://github.com/angular/angular.js/issues/13696)) <add> - allow removing classes that are added by a running animation <add> ([6c4581fc](https://github.com/angular/angular.js/commit/6c4581fcb692b17295a41b8918c6038333e7bc3d), <add> [#13339](https://github.com/angular/angular.js/issues/13339), [#13380](https://github.com/angular/angular.js/issues/13380), [#13414](https://github.com/angular/angular.js/issues/13414), [#13472](https://github.com/angular/angular.js/issues/13472), [#13678](https://github.com/angular/angular.js/issues/13678)) <add> - do not use `event.timeStamp` anymore for time tracking <add> ([620a20d1](https://github.com/angular/angular.js/commit/620a20d1b3376d95f85004ffa494e36bb19a2e4d), <add> [#13494](https://github.com/angular/angular.js/issues/13494), [#13495](https://github.com/angular/angular.js/issues/13495)) <add> - ignore children without animation data when closing them <add> ([be01cebf](https://github.com/angular/angular.js/commit/be01cebfae9ca2383105e535820442b39a96b240), <add> [#11992](https://github.com/angular/angular.js/issues/11992), [#13424](https://github.com/angular/angular.js/issues/13424)) <add> - do not alter the provided options data <add> ([7a81e6fe](https://github.com/angular/angular.js/commit/7a81e6fe2db084172e34d509f0baad2b33a8722c), <add> [#13040](https://github.com/angular/angular.js/issues/13040), [#13175](https://github.com/angular/angular.js/issues/13175)) <add> <add>## Minor Features <add> <add>- **ngLocale:** add support for standalone months <add> ([54c4041e](https://github.com/angular/angular.js/commit/54c4041ebc0cc4df70cf6996f43a6aaaf56d46bd), <add> [#3744](https://github.com/angular/angular.js/issues/3744), [#10247](https://github.com/angular/angular.js/issues/10247), [#12642](https://github.com/angular/angular.js/issues/12642), [#12844](https://github.com/angular/angular.js/issues/12844)) <add>- **ngMock:** add support for `$animate.closeAndFlush()` <add> ([512c0811](https://github.com/angular/angular.js/commit/512c08118786a419fabbd063fa17d224aba125cf)) <add> <add> <add>## Performance Improvements <add> <add>- **ngAnimate:** speed up `areAnimationsAllowed` check <add> ([2d3303dd](https://github.com/angular/angular.js/commit/2d3303ddda6330c4f45b381b6b17346f6cfe2d97)) <add> <add> <add>## Breaking Changes <add> <add>While we do not deem the following to be a real breaking change we are highlighting it here in the <add>changelog to ensure that it does not surprise anyone. <add> <add>- **$resource:** due to [47486524](https://github.com/angular/angular.js/commit/474865242c89ba3e8143f0cd52f8c292979ea730), <add> <add>**Possible breaking change** for users who updated their code to provide a `timeout` <add>promise for a `$resource` request in version 1.4.8. <add> <add>Up to v1.4.7 (included), using a promise as a timeout in `$resource`, would silently <add>fail (i.e. have no effect). <add> <add>In v1.4.8, using a promise as timeout would have the (buggy) behaviour described <add>in https://github.com/angular/angular.js/pull/12657#issuecomment-152108887 <add>(i.e. it will work as expected for the first time you resolve the promise and will <add>cancel all subsequent requests after that - one has to re-create the resource <add>class. This is feature was not documented.) <add> <add>With this change, using a promise as timeout in 1.4.9 onwsards is not allowed. <add>It will log a warning and ignore the timeout value. <add> <add>If you need support for cancellable `$resource` actions, you should upgrade to <add>version 1.5 or higher. <add> <add> <ide> <a name="1.5.0-rc.1"></a> <ide> # 1.5.0-rc.1 quantum-fermentation (2016-01-15) <ide>
1
Text
Text
correct ndim in docs
dece775279955e4aa84f718675a72ff34174a7ee
<ide><path>website/docs/api/vectors.md <ide> modified later. <ide> | _keyword-only_ | | <ide> | `strings` | The string store. A new string store is created if one is not provided. Defaults to `None`. ~~Optional[StringStore]~~ | <ide> | `shape` | Size of the table as `(n_entries, n_columns)`, the number of entries and number of columns. Not required if you're initializing the object with `data` and `keys`. ~~Tuple[int, int]~~ | <del>| `data` | The vector data. ~~numpy.ndarray[ndim=1, dtype=float32]~~ | <add>| `data` | The vector data. ~~numpy.ndarray[ndim=2, dtype=float32]~~ | <ide> | `keys` | A sequence of keys aligned with the data. ~~Iterable[Union[str, int]]~~ | <ide> | `name` | A name to identify the vectors table. ~~str~~ | <ide> | `mode` <Tag variant="new">3.2</Tag> | Vectors mode: `"default"` or [`"floret"`](https://github.com/explosion/floret) (default: `"default"`). ~~str~~ |
1
Ruby
Ruby
fix logger reference
34b809ce6d6a73296bfbc9f9677f7fb04c218c49
<ide><path>app/controllers/action_mailbox/ingresses/mandrill/inbound_emails_controller.rb <ide> def create <ide> raw_emails.each { |raw_email| ActionMailbox::InboundEmail.create_and_extract_message_id! raw_email } <ide> head :ok <ide> rescue JSON::ParserError => error <del> log.error error.message <add> logger.error error.message <ide> head :unprocessable_entity <ide> end <ide>
1
Python
Python
wrap long lines
391737f8568890f9dcd89bd83f7616ce2081e563
<ide><path>numpy/core/tests/test_scalarmath.py <ide> def _test_abs_func(self, absfunc, test_dtype): <ide> def test_builtin_abs(self, dtype): <ide> if ( <ide> sys.platform == "cygwin" and dtype == np.clongdouble and <del> _LooseVersion(platform.release().split("-")[0]) < _LooseVersion("3.3.0") <add> ( <add> _LooseVersion(platform.release().split("-")[0]) <add> < _LooseVersion("3.3.0") <add> ) <ide> ): <ide> pytest.xfail( <ide> reason="absl is computed in double precision on cygwin < 3.3" <ide> def test_builtin_abs(self, dtype): <ide> def test_numpy_abs(self, dtype): <ide> if ( <ide> sys.platform == "cygwin" and dtype == np.clongdouble and <del> _LooseVersion(platform.release().split("-")[0]) < _LooseVersion("3.3.0") <add> ( <add> _LooseVersion(platform.release().split("-")[0]) <add> < _LooseVersion("3.3.0") <add> ) <ide> ): <ide> pytest.xfail( <ide> reason="absl is computed in double precision on cygwin < 3.3"
1
Text
Text
remove wrong spaces and make quotes consistent
5589c378048e29f6238fe9161e34324558efb222
<ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/letter-frequency.md <ide> assert(typeof letterFrequency == 'function'); <ide> assert(Array.isArray(letterFrequency('Not all that Mrs. Bennet, however'))); <ide> ``` <ide> <del>`letterFrequency("Not all that Mrs. Bennet, however")` should return `[[" ", 5], [", ", 1], [".", 1], ["B", 1], ["M", 1], ["N", 1], ["a", 2], ["e", 4], ["h", 2], ["l", 2], ["n", 2], ["o", 2], ["r", 2], ["s", 1], ["t", 4], ["v", 1], ["w", 1]]`. <add>`letterFrequency("Not all that Mrs. Bennet, however")` should return `[[" ", 5], [",", 1], [".", 1], ["B", 1], ["M", 1], ["N", 1], ["a", 2], ["e", 4], ["h", 2], ["l", 2], ["n", 2], ["o", 2], ["r", 2], ["s", 1], ["t", 4], ["v", 1], ["w", 1]]`. <ide> <ide> ```js <ide> assert.deepEqual(letterFrequency('Not all that Mrs. Bennet, however'), [ <ide> assert.deepEqual(letterFrequency('Not all that Mrs. Bennet, however'), [ <ide> ]); <ide> ``` <ide> <del>`letterFrequency("daughters, could ask on the ")` should return `[[' ',5],[',',1],['a',2],['c',1],['d',2],['e',2],['g',1],['h',2],['k',1],['l',1],['n',1],['o',2],['r',1],['s',2],['t',2],['u',2]]`. <add>`letterFrequency("daughters, could ask on the ")` should return `[[" ", 5],[",", 1],["a", 2],["c", 1],["d", 2],["e", 2],["g", 1],["h", 2],["k", 1],["l", 1],["n", 1],["o", 2],["r", 1],["s", 2],["t", 2],["u", 2]]`. <ide> <ide> ```js <ide> assert.deepEqual(letterFrequency('daughters, could ask on the '), [ <ide> assert.deepEqual(letterFrequency('in various ways--with barefaced'), [ <ide> ]); <ide> ``` <ide> <del>`letterFrequency("distant surmises; but he eluded")` should return `[[" ", 4], ["; ", 1], ["a", 1], ["b", 1], ["d", 3], ["e", 4], ["h", 1], ["i", 2], ["l", 1], ["m", 1], ["n", 1], ["r", 1], ["s", 4], ["t", 3], ["u", 3]]`. <add>`letterFrequency("distant surmises; but he eluded")` should return `[[" ", 4], [";", 1], ["a", 1], ["b", 1], ["d", 3], ["e", 4], ["h", 1], ["i", 2], ["l", 1], ["m", 1], ["n", 1], ["r", 1], ["s", 4], ["t", 3], ["u", 3]]`. <ide> <ide> ```js <ide> assert.deepEqual(letterFrequency('distant surmises; but he eluded'), [ <ide> assert.deepEqual(letterFrequency('distant surmises; but he eluded'), [ <ide> ]); <ide> ``` <ide> <del>`letterFrequency("last obliged to accept the second-hand,")` should return `[[" ", 5], [", ", 1], ["-", 1], ["a", 3], ["b", 1], ["c", 3], ["d", 3], ["e", 4], ["g", 1], ["h", 2], ["i", 1], ["l", 2], ["n", 2], ["o", 3], ["p", 1], ["s", 2], ["t", 4]]`. <add>`letterFrequency("last obliged to accept the second-hand,")` should return `[[" ", 5], [",", 1], ["-", 1], ["a", 3], ["b", 1], ["c", 3], ["d", 3], ["e", 4], ["g", 1], ["h", 2], ["i", 1], ["l", 2], ["n", 2], ["o", 3], ["p", 1], ["s", 2], ["t", 4]]`. <ide> <ide> ```js <ide> assert.deepEqual(letterFrequency('last obliged to accept the second-hand,'), [
1
Text
Text
fix modelserializer useage
9aa37260098b5ec2750090fb035945780b35ad1d
<ide><path>docs/tutorial/1-serialization.md <ide> Open the file `snippets/serializers.py` again, and edit the `SnippetSerializer` <ide> <ide> class SnippetSerializer(serializers.ModelSerializer): <ide> class Meta: <del> model = models.Snippet <add> model = Snippet <ide> fields = ('pk', 'title', 'code', 'linenos', 'language', 'style') <ide> <ide>
1
Javascript
Javascript
stabilize raf logic & align timeout logic with it
6d43dc42337089f5fb52b715981c12993f490920
<ide><path>src/effects.js <ide> define( [ <ide> "use strict"; <ide> <ide> var <del> fxNow, timerId, <add> fxNow, inProgress, <ide> rfxtypes = /^(?:toggle|show|hide)$/, <ide> rrun = /queueHooks$/; <ide> <del>function raf() { <del> if ( timerId ) { <del> window.requestAnimationFrame( raf ); <add>function schedule() { <add> if ( inProgress ) { <add> if ( document.hidden === false && window.requestAnimationFrame ) { <add> window.requestAnimationFrame( schedule ); <add> } else { <add> window.setTimeout( schedule, jQuery.fx.interval ); <add> } <add> <ide> jQuery.fx.tick(); <ide> } <ide> } <ide> jQuery.speed = function( speed, easing, fn ) { <ide> easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing <ide> }; <ide> <del> // Go to the end state if fx are off or if document is hidden <del> if ( jQuery.fx.off || document.hidden ) { <add> // Go to the end state if fx are off <add> if ( jQuery.fx.off ) { <ide> opt.duration = 0; <ide> <ide> } else { <ide> jQuery.fx.tick = function() { <ide> }; <ide> <ide> jQuery.fx.timer = function( timer ) { <del> var i = jQuery.timers.push( timer ) - 1, <del> timers = jQuery.timers; <del> <del> if ( timer() ) { <del> jQuery.fx.start(); <del> <del> // If the timer finished immediately, safely remove it (allowing for external removal) <del> // Use a superfluous post-decrement for better compressibility w.r.t. jQuery.fx.tick above <del> } else if ( timers[ i ] === timer ) { <del> timers.splice( i--, 1 ); <del> } <add> jQuery.timers.push( timer ); <add> jQuery.fx.start(); <ide> }; <ide> <ide> jQuery.fx.interval = 13; <ide> jQuery.fx.start = function() { <del> if ( !timerId ) { <del> timerId = window.requestAnimationFrame ? <del> window.requestAnimationFrame( raf ) : <del> window.setInterval( jQuery.fx.tick, jQuery.fx.interval ); <add> if ( inProgress ) { <add> return; <ide> } <add> <add> inProgress = true; <add> schedule(); <ide> }; <ide> <ide> jQuery.fx.stop = function() { <del> if ( window.cancelAnimationFrame ) { <del> window.cancelAnimationFrame( timerId ); <del> } else { <del> window.clearInterval( timerId ); <del> } <del> <del> timerId = null; <add> inProgress = null; <ide> }; <ide> <ide> jQuery.fx.speeds = { <ide><path>test/unit/effects.js <ide> QUnit.test( "non-px animation handles non-numeric start (#11971)", function( ass <ide> } ); <ide> <ide> QUnit.test( "Animation callbacks (#11797)", function( assert ) { <del> assert.expect( 16 ); <add> assert.expect( 15 ); <ide> <ide> var prog = 0, <ide> targets = jQuery( "#foo" ).children(), <ide> done = false, <del> expectedProgress = 0; <add> expectedProgress = 1; <ide> <ide> targets.eq( 0 ).animate( {}, { <ide> duration: 1, <ide> QUnit.test( "Animation callbacks (#11797)", function( assert ) { <ide> assert.ok( true, "async: start" ); <ide> }, <ide> progress: function( anim, percent ) { <del> <del> // occasionally the progress handler is called twice in first frame.... *shrug* <del> if ( percent === 0 && expectedProgress === 1 ) { <del> return; <del> } <ide> assert.equal( percent, expectedProgress, "async: progress " + expectedProgress ); <del> <del> // once at 0, once at 1 <ide> expectedProgress++; <ide> }, <ide> done: function() {
2
Mixed
Go
add support for exclusion rules in dockerignore
6fd8e485c85c4f8ca62578d0840bdeddc4cba151
<ide><path>docs/sources/articles/dockerfile_best-practices.md <ide> ephemeral as possible. By “ephemeral,” we mean that it can be stopped and <ide> destroyed and a new one built and put in place with an absolute minimum of <ide> set-up and configuration. <ide> <del>### Use [a .dockerignore file](https://docs.docker.com/reference/builder/#the-dockerignore-file) <del> <del>For faster uploading and efficiency during `docker build`, you should use <del>a `.dockerignore` file to exclude files or directories from the build <del>context and final image. For example, unless`.git` is needed by your build <del>process or scripts, you should add it to `.dockerignore`, which can save many <del>megabytes worth of upload time. <add>### Use a .dockerignore file <add> <add>In most cases, it's best to put each Dockerfile in an empty directory. Then, <add>add to that directory only the files needed for building the Dockerfile. To <add>increase the build's performance, you can exclude files and directories by <add>adding a `.dockerignore` file to that directory as well. This file supports <add>exclusion patterns similar to `.gitignore` files. For information on creating one, <add>see the [.dockerignore file](../../reference/builder/#dockerignore-file). <ide> <ide> ### Avoid installing unnecessary packages <ide> <ide><path>docs/sources/reference/builder.md <ide> whole context must be transferred to the daemon. The Docker CLI reports <ide> > repository, the entire contents of your hard drive will get sent to the daemon (and <ide> > thus to the machine running the daemon). You probably don't want that. <ide> <del>In most cases, it's best to put each Dockerfile in an empty directory, and then add only <del>the files needed for building that Dockerfile to that directory. To further speed up the <del>build, you can exclude files and directories by adding a `.dockerignore` file to the same <del>directory. <add>In most cases, it's best to put each Dockerfile in an empty directory. Then, <add>only add the files needed for building the Dockerfile to the directory. To <add>increase the build's performance, you can exclude files and directories by <add>adding a `.dockerignore` file to the directory. For information about how to <add>[create a `.dockerignore` file](#the-dockerignore-file) on this page. <ide> <ide> You can specify a repository and tag at which to save the new image if <ide> the build succeeds: <ide> will result in `def` having a value of `hello`, not `bye`. However, <ide> `ghi` will have a value of `bye` because it is not part of the same command <ide> that set `abc` to `bye`. <ide> <del>## The `.dockerignore` file <add>### .dockerignore file <ide> <del>If a file named `.dockerignore` exists in the source repository, then it <del>is interpreted as a newline-separated list of exclusion patterns. <del>Exclusion patterns match files or directories relative to the source repository <del>that will be excluded from the context. Globbing is done using Go's <add>If a file named `.dockerignore` exists in the root of `PATH`, then Docker <add>interprets it as a newline-separated list of exclusion patterns. Docker excludes <add>files or directories relative to `PATH` that match these exclusion patterns. If <add>there are any `.dockerignore` files in `PATH` subdirectories, Docker treats <add>them as normal files. <add> <add>Filepaths in `.dockerignore` are absolute with the current directory as the <add>root. Wildcards are allowed but the search is not recursive. Globbing (file name <add>expansion) is done using Go's <ide> [filepath.Match](http://golang.org/pkg/path/filepath#Match) rules. <ide> <del>> **Note**: <del>> The `.dockerignore` file can even be used to ignore the `Dockerfile` and <del>> `.dockerignore` files. This might be useful if you are copying files from <del>> the root of the build context into your new container but do not want to <del>> include the `Dockerfile` or `.dockerignore` files (e.g. `ADD . /someDir/`). <add>You can specify exceptions to exclusion rules. To do this, simply prefix a <add>pattern with an `!` (exclamation mark) in the same way you would in a <add>`.gitignore` file. Currently there is no support for regular expressions. <add>Formats like `[^temp*]` are ignored. <ide> <del>The following example shows the use of the `.dockerignore` file to exclude the <del>`.git` directory from the context. Its effect can be seen in the changed size of <del>the uploaded context. <add>The following is an example `.dockerignore` file: <add> <add>``` <add> */temp* <add> */*/temp* <add> temp? <add> *.md <add> !LICENCSE.md <add>``` <add> <add>This file causes the following build behavior: <add> <add>| Rule | Behavior | <add>|----------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| <add>| `*/temp*` | Exclude all files with names starting with`temp` in any subdirectory below the root directory. For example, a file named`/somedir/temporary.txt` is ignored. | <add>| `*/*/temp*` | Exclude files starting with name `temp` from any subdirectory that is two levels below the root directory. For example, the file `/somedir/subdir/temporary.txt` is ignored. | <add>| `temp?` | Exclude the files that match the pattern in the root directory. For example, the files `tempa`, `tempb` in the root directory are ignored. | <add>| `*.md ` | Exclude all markdown files. | <add>| `!LICENSE.md` | Exception to the exclude all Markdown files is this file, `LICENSE.md`, include this file in the build. | <add> <add>The placement of `!` exception rules influences the matching algorithm; the <add>last line of the `.dockerignore` that matches a particular file determines <add>whether it is included or excluded. In the above example, the `LICENSE.md` file <add>matches both the `*.md` and `!LICENSE.md` rule. If you reverse the lines in the <add>example: <add> <add>``` <add> */temp* <add> */*/temp* <add> temp? <add> !LICENCSE.md <add> *.md <add>``` <add> <add>The build would exclude `LICENSE.md` because the last `*.md` rule adds all <add>Markdown files back onto the ignore list. The `!LICENSE.md` rule has no effect <add>because the subsequent `*.md` rule overrides it. <add> <add>You can even use the `.dockerignore` file to ignore the `Dockerfile` and <add>`.dockerignore` files. This is useful if you are copying files from the root of <add>the build context into your new container but do not want to include the <add>`Dockerfile` or `.dockerignore` files (e.g. `ADD . /someDir/`). <ide> <del> $ docker build . <del> Uploading context 18.829 MB <del> Uploading context <del> Step 0 : FROM busybox <del> ---> 769b9341d937 <del> Step 1 : CMD echo Hello World <del> ---> Using cache <del> ---> 99cc1ad10469 <del> Successfully built 99cc1ad10469 <del> $ echo ".git" > .dockerignore <del> $ docker build . <del> Uploading context 6.76 MB <del> Uploading context <del> Step 0 : FROM busybox <del> ---> 769b9341d937 <del> Step 1 : CMD echo Hello World <del> ---> Using cache <del> ---> 99cc1ad10469 <del> Successfully built 99cc1ad10469 <ide> <ide> ## FROM <ide> <ide><path>docs/sources/reference/commandline/cli.md <ide> If you use STDIN or specify a `URL`, the system places the contents into a <ide> file called `Dockerfile`, and any `-f`, `--file` option is ignored. In this <ide> scenario, there is no context. <ide> <add>By default the `docker build` command will look for a `Dockerfile` at the <add>root of the build context. The `-f`, `--file`, option lets you specify <add>the path to an alternative file to use instead. This is useful <add>in cases where the same set of files are used for multiple builds. The path <add>must be to a file within the build context. If a relative path is specified <add>then it must to be relative to the current directory. <add> <add>In most cases, it's best to put each Dockerfile in an empty directory. Then, add <add>to that directory only the files needed for building the Dockerfile. To increase <add>the build's performance, you can exclude files and directories by adding a <add>`.dockerignore` file to that directory as well. For information on creating one, <add>see the [.dockerignore file](../../reference/builder/#dockerignore-file). <add> <add>If the Docker client loses connection to the daemon, the build is canceled. <add>This happens if you interrupt the Docker client with `ctrl-c` or if the Docker <add>client is killed for any reason. <add> <add>> **Note:** Currently only the "run" phase of the build can be canceled until <add>> pull cancelation is implemented). <add> <ide> ### Return code <ide> <ide> On a successful build, a return code of success `0` will be returned. <ide> INFO[0000] The command [/bin/sh -c exit 13] returned a non-zero code: 13 <ide> $ echo $? <ide> 1 <ide> ``` <del> <del>### .dockerignore file <del> <del>If a file named `.dockerignore` exists in the root of `PATH` then it <del>is interpreted as a newline-separated list of exclusion patterns. <del>Exclusion patterns match files or directories relative to `PATH` that <del>will be excluded from the context. Globbing is done using Go's <del>[filepath.Match](http://golang.org/pkg/path/filepath#Match) rules. <del> <del>Please note that `.dockerignore` files in other subdirectories are <del>considered as normal files. Filepaths in `.dockerignore` are absolute with <del>the current directory as the root. Wildcards are allowed but the search <del>is not recursive. <del> <del>#### Example .dockerignore file <del> */temp* <del> */*/temp* <del> temp? <del> <del>The first line above `*/temp*`, would ignore all files with names starting with <del>`temp` from any subdirectory below the root directory. For example, a file named <del>`/somedir/temporary.txt` would be ignored. The second line `*/*/temp*`, will <del>ignore files starting with name `temp` from any subdirectory that is two levels <del>below the root directory. For example, the file `/somedir/subdir/temporary.txt` <del>would get ignored in this case. The last line in the above example `temp?` <del>will ignore the files that match the pattern from the root directory. <del>For example, the files `tempa`, `tempb` are ignored from the root directory. <del>Currently there is no support for regular expressions. Formats <del>like `[^temp*]` are ignored. <del> <del>By default the `docker build` command will look for a `Dockerfile` at the <del>root of the build context. The `-f`, `--file`, option lets you specify <del>the path to an alternative file to use instead. This is useful <del>in cases where the same set of files are used for multiple builds. The path <del>must be to a file within the build context. If a relative path is specified <del>then it must to be relative to the current directory. <del> <del>If the Docker client loses connection to the daemon, the build is canceled. <del>This happens if you interrupt the Docker client with `ctrl-c` or if the Docker <del>client is killed for any reason. <del> <del>> **Note:** Currently only the "run" phase of the build can be canceled until <del>> pull cancelation is implemented). <del> <ide> See also: <ide> <ide> [*Dockerfile Reference*](/reference/builder). <ide> <del>#### Examples <add>### Examples <ide> <ide> $ docker build . <ide> Uploading context 10240 bytes <ide> affect the build cache. <ide> <ide> This example shows the use of the `.dockerignore` file to exclude the `.git` <ide> directory from the context. Its effect can be seen in the changed size of the <del>uploaded context. <add>uploaded context. The builder reference contains detailed information on <add>[creating a .dockerignore file](../../builder/#dockerignore-file) <ide> <ide> $ docker build -t vieux/apache:2.0 . <ide> <ide><path>integration-cli/docker_cli_build_test.go <ide> func (s *DockerSuite) TestBuildDockerignore(c *check.C) { <ide> RUN [[ ! -e /bla/src/_vendor ]] <ide> RUN [[ ! -e /bla/.gitignore ]] <ide> RUN [[ ! -e /bla/README.md ]] <add> RUN [[ ! -e /bla/dir/foo ]] <add> RUN [[ ! -e /bla/foo ]] <ide> RUN [[ ! -e /bla/.git ]]` <ide> ctx, err := fakeContext(dockerfile, map[string]string{ <ide> "Makefile": "all:", <ide> ".git/HEAD": "ref: foo", <ide> "src/x.go": "package main", <ide> "src/_vendor/v.go": "package main", <add> "dir/foo": "", <ide> ".gitignore": "", <ide> "README.md": "readme", <del> ".dockerignore": ".git\npkg\n.gitignore\nsrc/_vendor\n*.md", <add> ".dockerignore": ` <add>.git <add>pkg <add>.gitignore <add>src/_vendor <add>*.md <add>dir`, <ide> }) <del> defer ctx.Close() <ide> if err != nil { <ide> c.Fatal(err) <ide> } <add> defer ctx.Close() <ide> if _, err := buildImageFromContext(name, ctx, true); err != nil { <ide> c.Fatal(err) <ide> } <ide> func (s *DockerSuite) TestBuildDockerignoreCleanPaths(c *check.C) { <ide> } <ide> } <ide> <add>func (s *DockerSuite) TestBuildDockerignoreExceptions(c *check.C) { <add> name := "testbuilddockerignoreexceptions" <add> defer deleteImages(name) <add> dockerfile := ` <add> FROM busybox <add> ADD . /bla <add> RUN [[ -f /bla/src/x.go ]] <add> RUN [[ -f /bla/Makefile ]] <add> RUN [[ ! -e /bla/src/_vendor ]] <add> RUN [[ ! -e /bla/.gitignore ]] <add> RUN [[ ! -e /bla/README.md ]] <add> RUN [[ -e /bla/dir/dir/foo ]] <add> RUN [[ ! -e /bla/dir/foo1 ]] <add> RUN [[ -f /bla/dir/e ]] <add> RUN [[ -f /bla/dir/e-dir/foo ]] <add> RUN [[ ! -e /bla/foo ]] <add> RUN [[ ! -e /bla/.git ]]` <add> ctx, err := fakeContext(dockerfile, map[string]string{ <add> "Makefile": "all:", <add> ".git/HEAD": "ref: foo", <add> "src/x.go": "package main", <add> "src/_vendor/v.go": "package main", <add> "dir/foo": "", <add> "dir/foo1": "", <add> "dir/dir/f1": "", <add> "dir/dir/foo": "", <add> "dir/e": "", <add> "dir/e-dir/foo": "", <add> ".gitignore": "", <add> "README.md": "readme", <add> ".dockerignore": ` <add>.git <add>pkg <add>.gitignore <add>src/_vendor <add>*.md <add>dir <add>!dir/e* <add>!dir/dir/foo`, <add> }) <add> if err != nil { <add> c.Fatal(err) <add> } <add> defer ctx.Close() <add> if _, err := buildImageFromContext(name, ctx, true); err != nil { <add> c.Fatal(err) <add> } <add>} <add> <ide> func (s *DockerSuite) TestBuildDockerignoringDockerfile(c *check.C) { <ide> name := "testbuilddockerignoredockerfile" <ide> dockerfile := ` <ide> func (s *DockerSuite) TestBuildDockerignoringWholeDir(c *check.C) { <ide> ctx, err := fakeContext(dockerfile, map[string]string{ <ide> "Dockerfile": "FROM scratch", <ide> "Makefile": "all:", <add> ".gitignore": "", <ide> ".dockerignore": ".*\n", <ide> }) <ide> defer ctx.Close() <ide><path>pkg/archive/archive.go <ide> func Tar(path string, compression Compression) (io.ReadCloser, error) { <ide> // TarWithOptions creates an archive from the directory at `path`, only including files whose relative <ide> // paths are included in `options.IncludeFiles` (if non-nil) or not in `options.ExcludePatterns`. <ide> func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) { <add> <add> patterns, patDirs, exceptions, err := fileutils.CleanPatterns(options.ExcludePatterns) <add> <add> if err != nil { <add> return nil, err <add> } <add> <ide> pipeReader, pipeWriter := io.Pipe() <ide> <ide> compressWriter, err := CompressStream(pipeWriter, options.Compression) <ide> func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) <ide> // is asking for that file no matter what - which is true <ide> // for some files, like .dockerignore and Dockerfile (sometimes) <ide> if include != relFilePath { <del> skip, err = fileutils.Matches(relFilePath, options.ExcludePatterns) <add> skip, err = fileutils.OptimizedMatches(relFilePath, patterns, patDirs) <ide> if err != nil { <ide> logrus.Debugf("Error matching %s", relFilePath, err) <ide> return err <ide> } <ide> } <ide> <ide> if skip { <del> if f.IsDir() { <add> if !exceptions && f.IsDir() { <ide> return filepath.SkipDir <ide> } <ide> return nil <ide><path>pkg/fileutils/fileutils.go <ide> package fileutils <ide> <ide> import ( <add> "errors" <ide> "fmt" <ide> "io" <ide> "io/ioutil" <ide> "os" <ide> "path/filepath" <add> "strings" <ide> <ide> "github.com/Sirupsen/logrus" <ide> ) <ide> <del>// Matches returns true if relFilePath matches any of the patterns <del>func Matches(relFilePath string, patterns []string) (bool, error) { <del> for _, exclude := range patterns { <del> matched, err := filepath.Match(exclude, relFilePath) <add>func Exclusion(pattern string) bool { <add> return pattern[0] == '!' <add>} <add> <add>func Empty(pattern string) bool { <add> return pattern == "" <add>} <add> <add>// Cleanpatterns takes a slice of patterns returns a new <add>// slice of patterns cleaned with filepath.Clean, stripped <add>// of any empty patterns and lets the caller know whether the <add>// slice contains any exception patterns (prefixed with !). <add>func CleanPatterns(patterns []string) ([]string, [][]string, bool, error) { <add> // Loop over exclusion patterns and: <add> // 1. Clean them up. <add> // 2. Indicate whether we are dealing with any exception rules. <add> // 3. Error if we see a single exclusion marker on it's own (!). <add> cleanedPatterns := []string{} <add> patternDirs := [][]string{} <add> exceptions := false <add> for _, pattern := range patterns { <add> // Eliminate leading and trailing whitespace. <add> pattern = strings.TrimSpace(pattern) <add> if Empty(pattern) { <add> continue <add> } <add> if Exclusion(pattern) { <add> if len(pattern) == 1 { <add> logrus.Errorf("Illegal exclusion pattern: %s", pattern) <add> return nil, nil, false, errors.New("Illegal exclusion pattern: !") <add> } <add> exceptions = true <add> } <add> pattern = filepath.Clean(pattern) <add> cleanedPatterns = append(cleanedPatterns, pattern) <add> if Exclusion(pattern) { <add> pattern = pattern[1:] <add> } <add> patternDirs = append(patternDirs, strings.Split(pattern, "/")) <add> } <add> <add> return cleanedPatterns, patternDirs, exceptions, nil <add>} <add> <add>// Matches returns true if file matches any of the patterns <add>// and isn't excluded by any of the subsequent patterns. <add>func Matches(file string, patterns []string) (bool, error) { <add> file = filepath.Clean(file) <add> <add> if file == "." { <add> // Don't let them exclude everything, kind of silly. <add> return false, nil <add> } <add> <add> patterns, patDirs, _, err := CleanPatterns(patterns) <add> if err != nil { <add> return false, err <add> } <add> <add> return OptimizedMatches(file, patterns, patDirs) <add>} <add> <add>// Matches is basically the same as fileutils.Matches() but optimized for archive.go. <add>// It will assume that the inputs have been preprocessed and therefore the function <add>// doen't need to do as much error checking and clean-up. This was done to avoid <add>// repeating these steps on each file being checked during the archive process. <add>// The more generic fileutils.Matches() can't make these assumptions. <add>func OptimizedMatches(file string, patterns []string, patDirs [][]string) (bool, error) { <add> matched := false <add> parentPath := filepath.Dir(file) <add> parentPathDirs := strings.Split(parentPath, "/") <add> <add> for i, pattern := range patterns { <add> negative := false <add> <add> if Exclusion(pattern) { <add> negative = true <add> pattern = pattern[1:] <add> } <add> <add> match, err := filepath.Match(pattern, file) <ide> if err != nil { <del> logrus.Errorf("Error matching: %s (pattern: %s)", relFilePath, exclude) <add> logrus.Errorf("Error matching: %s (pattern: %s)", file, pattern) <ide> return false, err <ide> } <del> if matched { <del> if filepath.Clean(relFilePath) == "." { <del> logrus.Errorf("Can't exclude whole path, excluding pattern: %s", exclude) <del> continue <add> <add> if !match && parentPath != "." { <add> // Check to see if the pattern matches one of our parent dirs. <add> if len(patDirs[i]) <= len(parentPathDirs) { <add> match, _ = filepath.Match(strings.Join(patDirs[i], "/"), <add> strings.Join(parentPathDirs[:len(patDirs[i])], "/")) <ide> } <del> logrus.Debugf("Skipping excluded path: %s", relFilePath) <del> return true, nil <ide> } <add> <add> if match { <add> matched = !negative <add> } <add> } <add> <add> if matched { <add> logrus.Debugf("Skipping excluded path: %s", file) <ide> } <del> return false, nil <add> return matched, nil <ide> } <ide> <ide> func CopyFile(src, dst string) (int64, error) { <ide><path>pkg/fileutils/fileutils_test.go <ide> func TestReadSymlinkedDirectoryToFile(t *testing.T) { <ide> t.Errorf("failed to remove symlink: %s", err) <ide> } <ide> } <add> <add>func TestWildcardMatches(t *testing.T) { <add> match, _ := Matches("fileutils.go", []string{"*"}) <add> if match != true { <add> t.Errorf("failed to get a wildcard match, got %v", match) <add> } <add>} <add> <add>// A simple pattern match should return true. <add>func TestPatternMatches(t *testing.T) { <add> match, _ := Matches("fileutils.go", []string{"*.go"}) <add> if match != true { <add> t.Errorf("failed to get a match, got %v", match) <add> } <add>} <add> <add>// An exclusion followed by an inclusion should return true. <add>func TestExclusionPatternMatchesPatternBefore(t *testing.T) { <add> match, _ := Matches("fileutils.go", []string{"!fileutils.go", "*.go"}) <add> if match != true { <add> t.Errorf("failed to get true match on exclusion pattern, got %v", match) <add> } <add>} <add> <add>// A folder pattern followed by an exception should return false. <add>func TestPatternMatchesFolderExclusions(t *testing.T) { <add> match, _ := Matches("docs/README.md", []string{"docs", "!docs/README.md"}) <add> if match != false { <add> t.Errorf("failed to get a false match on exclusion pattern, got %v", match) <add> } <add>} <add> <add>// A folder pattern followed by an exception should return false. <add>func TestPatternMatchesFolderWithSlashExclusions(t *testing.T) { <add> match, _ := Matches("docs/README.md", []string{"docs/", "!docs/README.md"}) <add> if match != false { <add> t.Errorf("failed to get a false match on exclusion pattern, got %v", match) <add> } <add>} <add> <add>// A folder pattern followed by an exception should return false. <add>func TestPatternMatchesFolderWildcardExclusions(t *testing.T) { <add> match, _ := Matches("docs/README.md", []string{"docs/*", "!docs/README.md"}) <add> if match != false { <add> t.Errorf("failed to get a false match on exclusion pattern, got %v", match) <add> } <add>} <add> <add>// A pattern followed by an exclusion should return false. <add>func TestExclusionPatternMatchesPatternAfter(t *testing.T) { <add> match, _ := Matches("fileutils.go", []string{"*.go", "!fileutils.go"}) <add> if match != false { <add> t.Errorf("failed to get false match on exclusion pattern, got %v", match) <add> } <add>} <add> <add>// A filename evaluating to . should return false. <add>func TestExclusionPatternMatchesWholeDirectory(t *testing.T) { <add> match, _ := Matches(".", []string{"*.go"}) <add> if match != false { <add> t.Errorf("failed to get false match on ., got %v", match) <add> } <add>} <add> <add>// A single ! pattern should return an error. <add>func TestSingleExclamationError(t *testing.T) { <add> _, err := Matches("fileutils.go", []string{"!"}) <add> if err == nil { <add> t.Errorf("failed to get an error for a single exclamation point, got %v", err) <add> } <add>} <add> <add>// A string preceded with a ! should return true from Exclusion. <add>func TestExclusion(t *testing.T) { <add> exclusion := Exclusion("!") <add> if !exclusion { <add> t.Errorf("failed to get true for a single !, got %v", exclusion) <add> } <add>} <add> <add>// An empty string should return true from Empty. <add>func TestEmpty(t *testing.T) { <add> empty := Empty("") <add> if !empty { <add> t.Errorf("failed to get true for an empty string, got %v", empty) <add> } <add>} <add> <add>func TestCleanPatterns(t *testing.T) { <add> cleaned, _, _, _ := CleanPatterns([]string{"docs", "config"}) <add> if len(cleaned) != 2 { <add> t.Errorf("expected 2 element slice, got %v", len(cleaned)) <add> } <add>} <add> <add>func TestCleanPatternsStripEmptyPatterns(t *testing.T) { <add> cleaned, _, _, _ := CleanPatterns([]string{"docs", "config", ""}) <add> if len(cleaned) != 2 { <add> t.Errorf("expected 2 element slice, got %v", len(cleaned)) <add> } <add>} <add> <add>func TestCleanPatternsExceptionFlag(t *testing.T) { <add> _, _, exceptions, _ := CleanPatterns([]string{"docs", "!docs/README.md"}) <add> if !exceptions { <add> t.Errorf("expected exceptions to be true, got %v", exceptions) <add> } <add>} <add> <add>func TestCleanPatternsLeadingSpaceTrimmed(t *testing.T) { <add> _, _, exceptions, _ := CleanPatterns([]string{"docs", " !docs/README.md"}) <add> if !exceptions { <add> t.Errorf("expected exceptions to be true, got %v", exceptions) <add> } <add>} <add> <add>func TestCleanPatternsTrailingSpaceTrimmed(t *testing.T) { <add> _, _, exceptions, _ := CleanPatterns([]string{"docs", "!docs/README.md "}) <add> if !exceptions { <add> t.Errorf("expected exceptions to be true, got %v", exceptions) <add> } <add>} <add> <add>func TestCleanPatternsErrorSingleException(t *testing.T) { <add> _, _, _, err := CleanPatterns([]string{"!"}) <add> if err == nil { <add> t.Errorf("expected error on single exclamation point, got %v", err) <add> } <add>} <add> <add>func TestCleanPatternsFolderSplit(t *testing.T) { <add> _, dirs, _, _ := CleanPatterns([]string{"docs/config/CONFIG.md"}) <add> if dirs[0][0] != "docs" { <add> t.Errorf("expected first element in dirs slice to be docs, got %v", dirs[0][1]) <add> } <add> if dirs[0][1] != "config" { <add> t.Errorf("expected first element in dirs slice to be config, got %v", dirs[0][1]) <add> } <add>}
7
PHP
PHP
add a from helper method
382f8d6d754cc19828948796821376495397285e
<ide><path>src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php <ide> public function followingRedirects() <ide> return $this; <ide> } <ide> <add> /** <add> * Set the referer header to simulate a previous request. <add> * <add> * @param string $url <add> * @return $this <add> */ <add> public function from(string $url) <add> { <add> return $this->withHeader('referer', $url); <add> } <add> <ide> /** <ide> * Visit the given URI with a GET request. <ide> *
1
Text
Text
fix a broken link in fs.md
e588ed7391fb2a92b3936e0011d6fbe0df903fc2
<ide><path>doc/api/fs.md <ide> the file contents. <ide> [chcp]: https://ss64.com/nt/chcp.html <ide> [inode]: https://en.wikipedia.org/wiki/Inode <ide> [support of file system `flags`]: #fs_file_system_flags <del>[Writable Stream]: #stream_class_stream_writable <add>[Writable Stream]: stream.html#stream_class_stream_writable
1
Java
Java
fix compilation error in eclipse
44c5705b45af3733d8180cd47cdc16146ad9dda2
<ide><path>src/test/java/io/reactivex/internal/operators/completable/CompletableDelayTest.java <ide> public void testOnErrorCalledOnScheduler() throws Exception { <ide> final CountDownLatch latch = new CountDownLatch(1); <ide> final AtomicReference<Thread> thread = new AtomicReference<Thread>(); <ide> <del> Completable.<String>error(new Exception()) <add> Completable.error(new Exception()) <ide> .delay(0, TimeUnit.MILLISECONDS, Schedulers.newThread()) <ide> .doOnError(new Consumer<Throwable>() { <ide> @Override
1
Python
Python
continue keras conversion to dual-backend version
8f2b5f0458cce4e5588238b86e3e2738952ea849
<ide><path>keras/backend/common.py <ide> import numpy as np <ide> <ide> # the type of float to use throughout the session. <del>_FLOATX = 'float32' <add>_FLOATX = 'float64' <ide> _EPSILON = 10e-8 <ide> <ide> <add>def epsilon(): <add> return _EPSILON <add> <add> <add>def set_epsilon(e): <add> global _EPSILON <add> _EPSILON = e <add> <add> <ide> def floatx(): <ide> return _FLOATX <ide> <ide> <ide> def set_floatx(floatx): <del> ''' <del> ''' <ide> global _FLOATX <ide> if floatx not in {'float32', 'float64'}: <ide> raise Exception('Unknown floatx type: ' + str(floatx)) <ide><path>keras/backend/tensorflow_backend.py <ide> def variable(value, dtype=_FLOATX, name=None): <ide> <ide> <ide> def placeholder(shape=None, ndim=None, dtype=_FLOATX, name=None): <add> if not shape: <add> if ndim: <add> shape = [None for _ in range(ndim)] <ide> return tf.placeholder(dtype, shape=shape, name=name) <ide> <ide> <ide> def shape(x): <ide> return x.get_shape() <ide> <ide> <add>def ndim(x): <add> return len(x.get_shape()) <add> <add> <ide> def eval(x): <ide> '''Run a graph. <ide> ''' <ide> def count_params(x): <ide> return np.prod([shape[i]._value for i in range(len(shape))]) <ide> <ide> <add>def cast(x, dtype): <add> return tf.cast(x, dtype) <add> <add> <ide> # LINEAR ALGEBRA <ide> <ide> def dot(x, y): <ide> def transpose(x): <ide> return tf.transpose(x) <ide> <ide> <del>def embedding(reference, indices): <add>def gather(reference, indices): <ide> '''reference: a tensor. <ide> indices: an int tensor of indices. <ide> <ide> def embedding(reference, indices): <ide> # ELEMENT-WISE OPERATIONS <ide> <ide> def max(x, axis=None, keepdims=False): <del> if axis is not None: <add> if axis is not None and axis < 0: <ide> axis = axis % len(x.get_shape()) <ide> return tf.reduce_max(x, reduction_indices=axis, keep_dims=keepdims) <ide> <ide> <ide> def min(x, axis=None, keepdims=False): <del> if axis is not None: <add> if axis is not None and axis < 0: <ide> axis = axis % len(x.get_shape()) <ide> return tf.reduce_min(x, reduction_indices=axis, keep_dims=keepdims) <ide> <ide> <ide> def sum(x, axis=None, keepdims=False): <ide> '''Sum of the values in a tensor, alongside the specified axis. <ide> ''' <del> if axis is not None: <add> if axis is not None and axis < 0: <ide> axis = axis % len(x.get_shape()) <ide> return tf.reduce_sum(x, reduction_indices=axis, keep_dims=keepdims) <ide> <ide> def prod(x, axis=None, keepdims=False): <ide> <ide> <ide> def std(x, axis=None, keepdims=False): <add> if axis is not None and axis < 0: <add> axis = axis % len(x.get_shape()) <add> if x.dtype.base_dtype == tf.bool: <add> x = tf.cast(x, _FLOATX) <ide> m = tf.reduce_mean(x, reduction_indices=axis, keep_dims=keepdims) <ide> devs_squared = tf.square(x - m) <ide> return tf.sqrt(tf.reduce_mean(devs_squared, <ide> def std(x, axis=None, keepdims=False): <ide> <ide> <ide> def mean(x, axis=None, keepdims=False): <del> if axis is not None: <add> if axis is not None and axis < 0: <ide> axis = axis % len(x.get_shape()) <add> if x.dtype.base_dtype == tf.bool: <add> x = tf.cast(x, _FLOATX) <ide> return tf.reduce_mean(x, reduction_indices=axis, keep_dims=keepdims) <ide> <ide> <ide> def any(x, axis=None, keepdims=False): <ide> <ide> Return array of int8 (0s and 1s). <ide> ''' <del> if axis is not None: <add> if axis is not None and axis < 0: <ide> axis = axis % len(x.get_shape()) <ide> x = tf.cast(x, tf.bool) <ide> x = tf.reduce_any(x, reduction_indices=axis, keep_dims=keepdims) <ide> return tf.cast(x, tf.int8) <ide> <ide> <ide> def argmax(x, axis=-1): <del> axis = axis % len(x.get_shape()) <add> if axis < 0: <add> axis = axis % len(x.get_shape()) <ide> return tf.argmax(x, axis) <ide> <ide> <ide> def argmin(x, axis=-1): <del> axis = axis % len(x.get_shape()) <add> if axis < 0: <add> axis = axis % len(x.get_shape()) <ide> return tf.argmin(x, axis) <ide> <ide> <ide> def round(x): <ide> return tf.round(x) <ide> <ide> <add>def pow(x, a): <add> return tf.pow(x, a) <add> <add> <ide> def clip(x, min_value, max_value): <ide> if max_value < min_value: <ide> max_value = min_value <ide> def minimum(x, y): <ide> # SHAPE OPERATIONS <ide> <ide> def concatenate(tensors, axis=-1): <del> axis = axis % len(tensors[0].get_shape()) <add> if axis < 0: <add> axis = axis % len(tensors[0].get_shape()) <ide> return tf.concat(axis, tensors) <ide> <ide> <ide> def tile(x, n): <ide> <ide> <ide> def flatten(x): <add> '''Turn a n-D tensor into a 2D tensor where <add> the first dimension is conserved. <add> ''' <ide> x = tf.reshape(x, [-1, np.prod(x.get_shape()[1:].as_list())]) <ide> return x <ide> <ide> def squeeze(x, axis): <ide> return tf.squeeze(x, [axis]) <ide> <ide> <add>def temporal_padding(x, padding=1): <add> '''Pad the middle dimension of a 3D tensor <add> with "padding" zeros left and right. <add> <add> Appologies for the inane API, but Theano makes this <add> really hard. <add> ''' <add> pattern = [[0, 0], [padding, padding], [0, 0]] <add> return tf.pad(x, pattern) <add> <add> <add>def spatial_2d_padding(x, padding=(1, 1)): <add> '''Pad the 2nd and 3rd dimensions of a 4D tensor <add> with "padding[0]" and "padding[1]" (resp.) zeros left and right. <add> ''' <add> pattern = [[0, 0], [0, 0], <add> [padding[0], padding[0]], [padding[1], padding[1]]] <add> return tf.pad(x, pattern) <add> <add> <ide> # VALUE MANIPULATION <ide> <ide> def get_value(x): <ide> def get_value(x): <ide> <ide> <ide> def set_value(x, value): <del> tf.assign(x, value).op.run(session=_get_session()) <add> tf.assign(x, np.asarray(value)).op.run(session=_get_session()) <ide> <ide> <ide> # GRAPH MANIPULATION <ide> def relu(x, alpha=0., max_value=None): <ide> if max_value is not None: <ide> x = tf.clip_by_value(x, tf.cast(0., dtype=_FLOATX), <ide> tf.cast(max_value, dtype=_FLOATX)) <del> x -= alpha * negative_part <add> x -= tf.constant(alpha, dtype=_FLOATX) * negative_part <ide> return x <ide> <ide> <ide><path>keras/backend/theano_backend.py <ide> <ide> <ide> # INTERNAL UTILS <add>theano.config.floatX = _FLOATX <add> <ide> <ide> def _on_gpu(): <ide> '''Returns whether the session is set to <ide> def shape(x): <ide> return x.shape <ide> <ide> <add>def ndim(x): <add> return x.ndim <add> <add> <ide> def eval(x): <ide> '''Run a graph. <ide> ''' <ide> def count_params(x): <ide> return np.prod(x.shape.eval()) <ide> <ide> <add>def cast(x, dtype): <add> return T.cast(x, dtype) <add> <add> <ide> # LINEAR ALGEBRA <ide> <ide> ''' <ide> def transpose(x): <ide> return T.transpose(x) <ide> <ide> <del>def embedding(reference, indices): <add>def gather(reference, indices): <ide> '''reference: a tensor. <ide> indices: an int tensor of indices. <ide> <ide> def embedding(reference, indices): <ide> <ide> # ELEMENT-WISE OPERATIONS <ide> <add> <ide> def max(x, axis=None, keepdims=False): <ide> return T.max(x, axis=axis, keepdims=keepdims) <ide> <ide> def round(x): <ide> return T.round(x) <ide> <ide> <add>def pow(x, a): <add> return T.pow(x, a) <add> <add> <ide> def clip(x, min_value, max_value): <ide> if max_value < min_value: <ide> max_value = min_value <ide> def tile(x, n): <ide> <ide> <ide> def flatten(x): <add> '''Turn a n-D tensor into a 2D tensor where <add> the first dimension is conserved. <add> ''' <ide> x = T.reshape(x, (x.shape[0], T.prod(x.shape) // x.shape[0])) <ide> return x <ide> <ide> def expand_dims(x, dim=-1): <ide> ''' <ide> pattern = [i for i in range(x.type.ndim)] <ide> if dim < 0: <del> dim = dim % x.type.ndim + 1 <add> if x.type.ndim == 0: <add> dim = 0 <add> else: <add> dim = dim % x.type.ndim + 1 <ide> pattern.insert(dim, 'x') <ide> return x.dimshuffle(pattern) <ide> <ide> def squeeze(x, axis): <ide> return T.squeeze(x) <ide> <ide> <add>def temporal_padding(x, padding=1): <add> '''Pad the middle dimension of a 3D tensor <add> with "padding" zeros left and right. <add> <add> Appologies for the inane API, but Theano makes this <add> really hard. <add> ''' <add> input_shape = x.shape <add> output_shape = (input_shape[0], <add> input_shape[1] + 2 * padding, <add> input_shape[2]) <add> output = T.zeros(output_shape) <add> return T.set_subtensor(output[:, padding:x.shape[1] + padding, :], x) <add> <add> <add>def spatial_2d_padding(x, padding=(1, 1)): <add> '''Pad the 2nd and 3rd dimensions of a 4D tensor <add> with "padding[0]" and "padding[1]" (resp.) zeros left and right. <add> ''' <add> input_shape = x.shape <add> output_shape = (input_shape[0], <add> input_shape[1], <add> input_shape[2] + 2 * padding[0], <add> input_shape[3] + 2 * padding[1]) <add> output = T.zeros(output_shape) <add> indices = (slice(None), <add> slice(None), <add> slice(padding[0], input_shape[2] + padding[0]), <add> slice(padding[1], input_shape[3] + padding[1])) <add> return T.set_subtensor(output[indices], x) <add> <ide> # VALUE MANIPULATION <ide> <add> <ide> def get_value(x): <ide> if not hasattr(x, 'get_value'): <ide> raise Exception("'get_value() can only be called on a variable. " + <ide> def __init__(self, inputs, outputs, updates=[], **kwargs): <ide> allow_input_downcast=True, **kwargs) <ide> <ide> def __call__(self, inputs): <del> if len(inputs) == 1: <del> inputs = inputs[0] # Theano is pretty dumb there tbh <del> return self.function(inputs) <add> return self.function(*inputs) <ide> <ide> <ide> def function(inputs, outputs, updates=[]): <ide><path>keras/constraints.py <ide> def get_config(self): <ide> <ide> class NonNeg(Constraint): <ide> def __call__(self, p): <del> p = K.variable(p) <del> p *= (p >= 0.) <add> p *= K.cast(p >= 0., K.floatx()) <ide> return p <ide> <ide> <ide> class UnitNorm(Constraint): <ide> def __call__(self, p): <del> return p / K.sqrt(K.sum(p**2, axis=-1, keepdims=True)) <add> return p / K.sqrt(K.sum(K.square(p), axis=-1, keepdims=True)) <ide> <ide> identity = Constraint <ide> maxnorm = MaxNorm <ide><path>keras/layers/containers.py <ide> def add_input(self, name, input_shape, dtype='float'): <ide> layer.set_input_shape(input_shape) <ide> ndim = len(input_shape) + 1 <ide> if dtype == 'float': <del> layer.input = K.placeholder(ndim=ndim) <add> layer.input = K.placeholder(ndim=ndim, name=name) <ide> else: <ide> if ndim == 2: <del> layer.input = K.placeholder(ndim=2, dtype='int32') <add> layer.input = K.placeholder(ndim=2, dtype='int32', name=name) <ide> else: <ide> raise Exception('Type "int" can only be used with ndim==2 (Embedding).') <del> layer.input.name = name <ide> self.inputs[name] = layer <ide> self.input_config.append({'name': name, <ide> 'input_shape': input_shape, <ide><path>keras/layers/convolutional.py <ide> # -*- coding: utf-8 -*- <ide> from __future__ import absolute_import <ide> <del>import theano <del>import theano.tensor as T <del>from theano.tensor.signal import downsample <del> <add>from .. import backend as K <ide> from .. import activations, initializations, regularizers, constraints <del>from ..utils.theano_utils import shared_zeros, on_gpu <ide> from ..layers.core import Layer <ide> <del>if on_gpu(): <del> from theano.sandbox.cuda import dnn <del> <ide> <ide> def conv_output_length(input_length, filter_size, border_mode, stride): <ide> if input_length is None: <ide> return None <del> assert border_mode in {'same', 'full', 'valid'} <add> assert border_mode in {'same', 'valid'} <ide> if border_mode == 'same': <ide> output_length = input_length <del> elif border_mode == 'full': <del> output_length = input_length + filter_size - 1 <ide> elif border_mode == 'valid': <ide> output_length = input_length - filter_size + 1 <ide> return (output_length + stride - 1) // stride <ide> <ide> <del>def pool_output_length(input_length, pool_size, ignore_border, stride): <del> if input_length is None: <del> return None <del> if ignore_border: <del> output_length = input_length - pool_size + 1 <del> output_length = (output_length + stride - 1) // stride <del> else: <del> if pool_size == input_length: <del> output_length = min(input_length, stride - stride % 2) <del> if output_length <= 0: <del> output_length = 1 <del> elif stride >= pool_size: <del> output_length = (input_length + stride - 1) // stride <del> else: <del> output_length = (input_length - pool_size + stride - 1) // stride <del> if output_length <= 0: <del> output_length = 1 <del> else: <del> output_length += 1 <del> return output_length <del> <del> <ide> class Convolution1D(Layer): <ide> input_ndim = 3 <ide> <ide> def __init__(self, nb_filter, filter_length, <ide> W_regularizer=None, b_regularizer=None, activity_regularizer=None, <ide> W_constraint=None, b_constraint=None, input_dim=None, input_length=None, **kwargs): <ide> <del> if border_mode not in {'valid', 'full', 'same'}: <add> if border_mode not in {'valid', 'same'}: <ide> raise Exception('Invalid border mode for Convolution1D:', border_mode) <ide> self.nb_filter = nb_filter <ide> self.filter_length = filter_length <ide> def __init__(self, nb_filter, filter_length, <ide> self.input_length = input_length <ide> if self.input_dim: <ide> kwargs['input_shape'] = (self.input_length, self.input_dim) <add> self.input = K.placeholder(ndim=3) <ide> super(Convolution1D, self).__init__(**kwargs) <ide> <ide> def build(self): <ide> input_dim = self.input_shape[2] <del> self.input = T.tensor3() <ide> self.W_shape = (self.nb_filter, input_dim, self.filter_length, 1) <ide> self.W = self.init(self.W_shape) <del> self.b = shared_zeros((self.nb_filter,)) <add> self.b = K.zeros((self.nb_filter,)) <ide> self.params = [self.W, self.b] <ide> self.regularizers = [] <ide> <ide> def output_shape(self): <ide> <ide> def get_output(self, train=False): <ide> X = self.get_input(train) <del> X = T.reshape(X, (X.shape[0], X.shape[1], X.shape[2], 1)).dimshuffle(0, 2, 1, 3) <del> <del> border_mode = self.border_mode <del> if on_gpu() and dnn.dnn_available(): <del> if border_mode == 'same': <del> assert(self.subsample_length == 1) <del> pad_x = (self.filter_length - self.subsample_length) // 2 <del> conv_out = dnn.dnn_conv(img=X, <del> kerns=self.W, <del> border_mode=(pad_x, 0)) <del> else: <del> conv_out = dnn.dnn_conv(img=X, <del> kerns=self.W, <del> border_mode=border_mode, <del> subsample=self.subsample) <del> else: <del> if border_mode == 'same': <del> assert(self.subsample_length == 1) <del> border_mode = 'full' <del> <del> input_shape = self.input_shape <del> image_shape = (input_shape[0], input_shape[2], input_shape[1], 1) <del> conv_out = T.nnet.conv.conv2d(X, self.W, <del> border_mode=border_mode, <del> subsample=self.subsample, <del> image_shape=image_shape, <del> filter_shape=self.W_shape) <del> if self.border_mode == 'same': <del> shift_x = (self.filter_length - 1) // 2 <del> conv_out = conv_out[:, :, shift_x:X.shape[2] + shift_x, :] <del> <del> output = self.activation(conv_out + self.b.dimshuffle('x', 0, 'x', 'x')) <del> output = T.reshape(output, (output.shape[0], output.shape[1], output.shape[2])).dimshuffle(0, 2, 1) <add> X = K.expand_dims(X, -1) # add a dimension of the right <add> X = K.permute_dimensions(X, (0, 2, 1, 3)) <add> conv_out = K.conv2d(X, self.W, strides=self.subsample, <add> border_mode=self.border_mode, dim_ordering='th') <add> <add> output = conv_out + K.reshape(self.b, (1, self.nb_filter, 1, 1)) <add> output = self.activation(output) <add> output = K.squeeze(output, 3) # remove the dummy 3rd dimension <add> output = K.permute_dimensions(output, (0, 2, 1)) <ide> return output <ide> <ide> def get_config(self): <ide> class Convolution2D(Layer): <ide> <ide> def __init__(self, nb_filter, nb_row, nb_col, <ide> init='glorot_uniform', activation='linear', weights=None, <del> border_mode='valid', subsample=(1, 1), <add> border_mode='valid', subsample=(1, 1), dim_ordering='th', <ide> W_regularizer=None, b_regularizer=None, activity_regularizer=None, <ide> W_constraint=None, b_constraint=None, **kwargs): <ide> <del> if border_mode not in {'valid', 'full', 'same'}: <add> if border_mode not in {'valid', 'same'}: <ide> raise Exception('Invalid border mode for Convolution2D:', border_mode) <ide> self.nb_filter = nb_filter <ide> self.nb_row = nb_row <ide> def __init__(self, nb_filter, nb_row, nb_col, <ide> self.activation = activations.get(activation) <ide> self.border_mode = border_mode <ide> self.subsample = tuple(subsample) <add> self.dim_ordering = dim_ordering <ide> <ide> self.W_regularizer = regularizers.get(W_regularizer) <ide> self.b_regularizer = regularizers.get(b_regularizer) <ide> def __init__(self, nb_filter, nb_row, nb_col, <ide> self.constraints = [self.W_constraint, self.b_constraint] <ide> <ide> self.initial_weights = weights <add> self.input = K.placeholder(ndim=4) <ide> super(Convolution2D, self).__init__(**kwargs) <ide> <ide> def build(self): <ide> stack_size = self.input_shape[1] <del> self.input = T.tensor4() <ide> self.W_shape = (self.nb_filter, stack_size, self.nb_row, self.nb_col) <ide> self.W = self.init(self.W_shape) <del> self.b = shared_zeros((self.nb_filter,)) <add> self.b = K.zeros((self.nb_filter,)) <ide> self.params = [self.W, self.b] <ide> self.regularizers = [] <ide> <ide> def output_shape(self): <ide> <ide> def get_output(self, train=False): <ide> X = self.get_input(train) <del> border_mode = self.border_mode <del> if on_gpu() and dnn.dnn_available(): <del> if border_mode == 'same': <del> assert(self.subsample == (1, 1)) <del> pad_x = (self.nb_row - self.subsample[0]) // 2 <del> pad_y = (self.nb_col - self.subsample[1]) // 2 <del> conv_out = dnn.dnn_conv(img=X, <del> kerns=self.W, <del> border_mode=(pad_x, pad_y)) <del> else: <del> conv_out = dnn.dnn_conv(img=X, <del> kerns=self.W, <del> border_mode=border_mode, <del> subsample=self.subsample) <del> else: <del> if border_mode == 'same': <del> border_mode = 'full' <del> assert(self.subsample == (1, 1)) <del> <del> conv_out = T.nnet.conv.conv2d(X, self.W, <del> border_mode=border_mode, <del> subsample=self.subsample, <del> image_shape=self.input_shape, <del> filter_shape=self.W_shape) <del> if self.border_mode == 'same': <del> shift_x = (self.nb_row - 1) // 2 <del> shift_y = (self.nb_col - 1) // 2 <del> conv_out = conv_out[:, :, shift_x:X.shape[2] + shift_x, shift_y:X.shape[3] + shift_y] <del> <del> return self.activation(conv_out + self.b.dimshuffle('x', 0, 'x', 'x')) <add> conv_out = K.conv2d(X, self.W, strides=self.subsample, <add> border_mode=self.border_mode, <add> dim_ordering=self.dim_ordering) <add> <add> output = conv_out + K.reshape(self.b, (1, self.nb_filter, 1, 1)) <add> output = self.activation(output) <add> return output <ide> <ide> def get_config(self): <ide> config = {"name": self.__class__.__name__, <ide> def get_config(self): <ide> "activation": self.activation.__name__, <ide> "border_mode": self.border_mode, <ide> "subsample": self.subsample, <add> "dim_ordering": self.dim_ordering, <ide> "W_regularizer": self.W_regularizer.get_config() if self.W_regularizer else None, <ide> "b_regularizer": self.b_regularizer.get_config() if self.b_regularizer else None, <ide> "activity_regularizer": self.activity_regularizer.get_config() if self.activity_regularizer else None, <ide> def get_config(self): <ide> class MaxPooling1D(Layer): <ide> input_ndim = 3 <ide> <del> def __init__(self, pool_length=2, stride=None, ignore_border=True, **kwargs): <add> def __init__(self, pool_length=2, stride=None, <add> border_mode='valid', **kwargs): <ide> super(MaxPooling1D, self).__init__(**kwargs) <ide> if stride is None: <ide> stride = pool_length <ide> self.pool_length = pool_length <ide> self.stride = stride <ide> self.st = (self.stride, 1) <ide> <del> self.input = T.tensor3() <add> self.input = K.placeholder(ndim=3) <ide> self.pool_size = (pool_length, 1) <del> self.ignore_border = ignore_border <add> self.border_mode = border_mode <ide> <ide> @property <ide> def output_shape(self): <ide> input_shape = self.input_shape <del> length = pool_output_length(input_shape[1], self.pool_length, self.ignore_border, self.stride) <add> length = conv_output_length(input_shape[1], self.pool_length, <add> self.border_mode, self.stride) <ide> return (input_shape[0], length, input_shape[2]) <ide> <ide> def get_output(self, train=False): <ide> X = self.get_input(train) <del> X = T.reshape(X, (X.shape[0], X.shape[1], X.shape[2], 1)).dimshuffle(0, 2, 1, 3) <del> output = downsample.max_pool_2d(X, ds=self.pool_size, st=self.st, ignore_border=self.ignore_border) <del> output = output.dimshuffle(0, 2, 1, 3) <del> return T.reshape(output, (output.shape[0], output.shape[1], output.shape[2])) <add> X = K.expand_dims(X, -1) # add dummy last dimension <add> X = K.permute_dimensions(X, (0, 2, 1, 3)) <add> output = K.maxpool2d(X, pool_size=self.pool_size, strides=self.st, <add> border_mode=self.border_mode, <add> dim_ordering='th') <add> output = K.permute_dimensions(output, (0, 2, 1, 3)) <add> return K.squeeze(output, 3) # remove dummy last dimension <ide> <ide> def get_config(self): <ide> config = {"name": self.__class__.__name__, <ide> "stride": self.stride, <ide> "pool_length": self.pool_length, <del> "ignore_border": self.ignore_border} <add> "border_mode": self.border_mode} <ide> base_config = super(MaxPooling1D, self).get_config() <ide> return dict(list(base_config.items()) + list(config.items())) <ide> <ide> <ide> class MaxPooling2D(Layer): <ide> input_ndim = 4 <ide> <del> def __init__(self, pool_size=(2, 2), stride=None, ignore_border=True, **kwargs): <add> def __init__(self, pool_size=(2, 2), strides=None, border_mode='valid', <add> dim_ordering='th', **kwargs): <ide> super(MaxPooling2D, self).__init__(**kwargs) <del> self.input = T.tensor4() <add> self.input = K.placeholder(ndim=4) <ide> self.pool_size = tuple(pool_size) <del> if stride is None: <del> stride = self.pool_size <del> self.stride = tuple(stride) <del> self.ignore_border = ignore_border <add> if strides is None: <add> strides = self.pool_size <add> self.strides = tuple(strides) <add> self.border_mode = border_mode <add> self.dim_ordering = dim_ordering <ide> <ide> @property <ide> def output_shape(self): <ide> input_shape = self.input_shape <del> rows = pool_output_length(input_shape[2], self.pool_size[0], self.ignore_border, self.stride[0]) <del> cols = pool_output_length(input_shape[3], self.pool_size[1], self.ignore_border, self.stride[1]) <add> rows = conv_output_length(input_shape[2], self.pool_size[0], <add> self.border_mode, self.strides[0]) <add> cols = conv_output_length(input_shape[3], self.pool_size[1], <add> self.border_mode, self.strides[1]) <ide> return (input_shape[0], input_shape[1], rows, cols) <ide> <ide> def get_output(self, train=False): <ide> X = self.get_input(train) <del> output = downsample.max_pool_2d(X, ds=self.pool_size, st=self.stride, ignore_border=self.ignore_border) <add> output = K.maxpool2d(X, pool_size=self.pool_size, <add> strides=self.strides, <add> border_mode=self.border_mode, <add> dim_ordering=self.dim_ordering) <ide> return output <ide> <ide> def get_config(self): <ide> config = {"name": self.__class__.__name__, <ide> "pool_size": self.pool_size, <del> "ignore_border": self.ignore_border, <del> "stride": self.stride} <add> "border_mode": self.border_mode, <add> "strides": self.strides, <add> "dim_ordering": self.dim_ordering} <ide> base_config = super(MaxPooling2D, self).get_config() <ide> return dict(list(base_config.items()) + list(config.items())) <ide> <ide> class UpSample1D(Layer): <ide> def __init__(self, length=2, **kwargs): <ide> super(UpSample1D, self).__init__(**kwargs) <ide> self.length = length <del> self.input = T.tensor3() <add> self.input = K.placeholder(ndim=3) <ide> <ide> @property <ide> def output_shape(self): <ide> def output_shape(self): <ide> <ide> def get_output(self, train=False): <ide> X = self.get_input(train) <del> output = T.extra_ops.repeat(X, self.length, axis=1) <add> output = K.concatenate([X] * self.length, axis=1) <ide> return output <ide> <ide> def get_config(self): <ide> class UpSample2D(Layer): <ide> <ide> def __init__(self, size=(2, 2), **kwargs): <ide> super(UpSample2D, self).__init__(**kwargs) <del> self.input = T.tensor4() <add> self.input = K.placeholder(ndim=4) <ide> self.size = tuple(size) <ide> <ide> @property <ide> def output_shape(self): <ide> input_shape = self.input_shape <del> return (input_shape[0], input_shape[1], self.size[0] * input_shape[2], self.size[1] * input_shape[3]) <add> return (input_shape[0], input_shape[1], <add> self.size[0] * input_shape[2], <add> self.size[1] * input_shape[3]) <ide> <ide> def get_output(self, train=False): <ide> X = self.get_input(train) <del> Y = T.extra_ops.repeat(X, self.size[0], axis=2) <del> output = T.extra_ops.repeat(Y, self.size[1], axis=3) <add> output = K.concatenate([X] * self.size[0], axis=2) <add> output = K.concatenate([output] * self.size[1], axis=3) <ide> return output <ide> <ide> def get_config(self): <ide> class ZeroPadding1D(Layer): <ide> def __init__(self, padding=1, **kwargs): <ide> super(ZeroPadding1D, self).__init__(**kwargs) <ide> self.padding = padding <del> self.input = T.tensor3() <add> self.input = K.placeholder(ndim=3) <ide> <ide> @property <ide> def output_shape(self): <ide> input_shape = self.input_shape <del> return (input_shape[0], input_shape[1] + self.padding * 2, input_shape[2]) <add> return (input_shape[0], <add> input_shape[1] + self.padding * 2, <add> input_shape[2]) <ide> <ide> def get_output(self, train=False): <ide> X = self.get_input(train) <del> input_shape = X.shape <del> output_shape = (input_shape[0], <del> input_shape[1] + 2 * self.padding, <del> input_shape[2]) <del> output = T.zeros(output_shape) <del> # TODO: use concatenation instead <del> return T.set_subtensor(output[:, self.padding:X.shape[1] + self.padding, :], X) <add> return K.temporal_padding(X, padding=self.padding) <ide> <ide> def get_config(self): <ide> config = {"name": self.__class__.__name__, <ide> def get_config(self): <ide> <ide> <ide> class ZeroPadding2D(Layer): <del> """Zero-padding layer for 1D input (e.g. temporal sequence). <add> """Zero-padding layer for 2D input (e.g. picture). <ide> <ide> Input shape <ide> ----------- <del> 4D tensor with shape (samples, depth, first_axis_to_pad, second_axis_to_pad) <add> 4D tensor with shape: <add> (samples, depth, first_axis_to_pad, second_axis_to_pad) <ide> <ide> Output shape <ide> ------------ <del> 4D tensor with shape (samples, depth, first_padded_axis, second_padded_axis) <add> 4D tensor with shape: <add> (samples, depth, first_padded_axis, second_padded_axis) <ide> <ide> Arguments <ide> --------- <ide> class ZeroPadding2D(Layer): <ide> def __init__(self, padding=(1, 1), **kwargs): <ide> super(ZeroPadding2D, self).__init__(**kwargs) <ide> self.padding = tuple(padding) <del> self.input = T.tensor4() <add> self.input = K.placeholder(ndim=4) <ide> <ide> @property <ide> def output_shape(self): <ide> def output_shape(self): <ide> <ide> def get_output(self, train=False): <ide> X = self.get_input(train) <del> input_shape = X.shape <del> output_shape = (input_shape[0], <del> input_shape[1], <del> input_shape[2] + 2 * self.padding[0], <del> input_shape[3] + 2 * self.padding[1]) <del> output = T.zeros(output_shape) <del> indices = (slice(None), <del> slice(None), <del> slice(self.padding[0], input_shape[2] + self.padding[0]), <del> slice(self.padding[1], input_shape[3] + self.padding[1])) <del> # TODO: use concatenation instead <del> return T.set_subtensor(output[indices], X) <add> return K.spatial_2d_padding(X, padding=self.padding) <ide> <ide> def get_config(self): <ide> config = {"name": self.__class__.__name__, <ide><path>keras/layers/core.py <ide> def set_input_shape(self, input_shape): <ide> raise Exception('Invalid input shape - Layer expects input ndim=' + <ide> str(self.input_ndim) + ', was provided with input shape ' + str(input_shape)) <ide> self._input_shape = input_shape <del> self.input = K.placeholder(ndim=len(self._input_shape)) <add> self.input = K.placeholder(shape=self._input_shape) <ide> self.build() <ide> <ide> @property <ide> def output_shape(self): <ide> <ide> def get_output(self, train=False): <ide> X = self.get_input(train) <del> new_shape = (X.shape[0],) + self.dims <del> return K.reshape(X, new_shape) <add> return K.reshape(X, (-1,) + self.dims) <ide> <ide> def get_config(self): <ide> config = {"name": self.__class__.__name__, <ide> def __init__(self, output_dim, init='glorot_uniform', activation='linear', weigh <ide> self.input_dim = input_dim <ide> if self.input_dim: <ide> kwargs['input_shape'] = (self.input_dim,) <add> self.input = K.placeholder(ndim=2) <ide> super(Dense, self).__init__(**kwargs) <ide> <ide> def build(self): <ide> input_dim = self.input_shape[1] <ide> <del> self.input = K.placeholder(ndim=2) <ide> self.W = self.init((input_dim, self.output_dim)) <ide> self.b = K.zeros((self.output_dim,)) <ide> <ide> def __init__(self, output_dim, init='glorot_uniform', activation='linear', weigh <ide> self.input_length = input_length <ide> if self.input_dim: <ide> kwargs['input_shape'] = (self.input_length, self.input_dim) <add> self.input = K.placeholder(ndim=3) <ide> super(TimeDistributedDense, self).__init__(**kwargs) <ide> <ide> def build(self): <ide> input_dim = self.input_shape[2] <ide> <del> self.input = K.placeholder(ndim=3) <ide> self.W = self.init((input_dim, self.output_dim)) <ide> self.b = K.zeros((self.output_dim)) <ide> <ide> def __init__(self, output_dim, nb_feature=4, init='glorot_uniform', weights=None <ide> self.input_dim = input_dim <ide> if self.input_dim: <ide> kwargs['input_shape'] = (self.input_dim,) <add> self.input = K.placeholder(ndim=2) <ide> super(MaxoutDense, self).__init__(**kwargs) <ide> <ide> def build(self): <ide> input_dim = self.input_shape[1] <ide> <del> self.input = K.placeholder(ndim=2) <ide> self.W = self.init((self.nb_feature, input_dim, self.output_dim)) <ide> self.b = K.zeros((self.nb_feature, self.output_dim)) <ide> <ide><path>keras/layers/embeddings.py <ide> def __init__(self, input_dim, output_dim, init='uniform', input_length=None, <ide> super(Embedding, self).__init__(**kwargs) <ide> <ide> def build(self): <del> self.input = K.placeholder(ndim=2, dtype='int32') <add> self.input = K.placeholder(shape=(None, self.input_length), <add> dtype='int32') <ide> self.W = self.init((self.input_dim, self.output_dim)) <ide> self.params = [self.W] <ide> self.regularizers = [] <ide> def output_shape(self): <ide> <ide> def get_output(self, train=False): <ide> X = self.get_input(train) <del> out = K.embedding(self.W, X) <add> out = K.gather(self.W, X) <ide> return out <ide> <ide> def get_config(self): <ide><path>keras/layers/normalization.py <ide> def __init__(self, epsilon=1e-6, mode=0, momentum=0.9, <ide> def build(self): <ide> input_shape = self.input_shape # starts with samples axis <ide> input_shape = input_shape[1:] <del> self.input = K.placeholder(ndim=len(input_shape) + 1) <ide> <ide> self.gamma = self.init((input_shape)) <ide> self.beta = K.zeros(input_shape) <ide> def build(self): <ide> # initialize self.updates: batch mean/std computation <ide> X = self.get_input(train=True) <ide> m = K.mean(X, axis=0) <del> std = K.mean((X - m) ** 2 + self.epsilon, axis=0) ** 0.5 <add> std = K.mean(K.square(X - m) + self.epsilon, axis=0) <add> std = K.sqrt(std) <ide> mean_update = self.momentum * self.running_mean + (1-self.momentum) * m <ide> std_update = self.momentum * self.running_std + (1-self.momentum) * std <ide> self.updates = [(self.running_mean, mean_update), <ide> def get_output(self, train): <ide> b, ch, r, c = K.shape(X) <ide> half_n = self.n // 2 <ide> input_sqr = K.square(X) <del> extra_channels = K.zeros((b, ch + 2*half_n, r, c)) <add> extra_channels = K.zeros((b, ch + 2 * half_n, r, c)) <ide> input_sqr = K.concatenate([extra_channels[:, :half_n, :, :], <ide> input_sqr, <del> extra_channels[:, half_n+ch:, :, :]], <add> extra_channels[:, half_n + ch:, :, :]], <ide> axis=1) <ide> scale = self.k <ide> for i in range(self.n): <del> scale += self.alpha * input_sqr[:, i:i+ch, :, :] <add> scale += self.alpha * input_sqr[:, i:i + ch, :, :] <ide> scale = scale ** self.beta <ide> return X / scale <ide> <ide><path>keras/layers/recurrent.py <ide> def get_padded_shuffled_mask(self, train, X, pad=0): <ide> if mask is None: <ide> mask = T.ones_like(X.sum(axis=-1)) # is there a better way to do this without a sum? <ide> <add> # TODO: reimplement <ide> # mask is (nb_samples, time) <ide> mask = T.shape_padright(mask) # (nb_samples, time, 1) <ide> mask = T.addbroadcast(mask, -1) # the new dimension (the '1') is made broadcastable <ide><path>keras/models.py <ide> from __future__ import absolute_import <ide> from __future__ import print_function <del>import theano <del>import theano.tensor as T <ide> import numpy as np <del>import warnings, time, copy, pprint <add>import warnings <add>import time <add>import copy <add>import pprint <ide> from six.moves import range <ide> import six <ide> <add>from . import backend as K <ide> from . import optimizers <ide> from . import objectives <ide> from . import regularizers <ide> def standardize_y(y): <ide> <ide> <ide> def batch_shuffle(index_array, batch_size): <del> batch_count = int(len(index_array)/batch_size) <add> batch_count = int(len(index_array) / batch_size) <ide> # to reshape we need to be cleanly divisible by batch size <ide> # we stash extra items and reappend them after shuffling <del> last_batch = index_array[batch_count*batch_size:] <del> index_array = index_array[:batch_count*batch_size] <add> last_batch = index_array[batch_count * batch_size:] <add> index_array = index_array[:batch_count * batch_size] <ide> index_array = index_array.reshape((batch_count, batch_size)) <ide> np.random.shuffle(index_array) <ide> index_array = index_array.flatten() <ide> return np.append(index_array, last_batch) <ide> <ide> <ide> def make_batches(size, batch_size): <del> nb_batch = int(np.ceil(size/float(batch_size))) <del> return [(i*batch_size, min(size, (i+1)*batch_size)) for i in range(0, nb_batch)] <add> nb_batch = int(np.ceil(size / float(batch_size))) <add> return [(i * batch_size, min(size, (i + 1) * batch_size)) for i in range(0, nb_batch)] <ide> <ide> <ide> def standardize_X(X): <ide> def slice_X(X, start=None, stop=None): <ide> if hasattr(start, '__len__'): <ide> # hdf5 dataset only support list object as indices <ide> if hasattr(start, 'shape'): <del> start = start.tolist() <add> start = start.tolist() <ide> return [x[start] for x in X] <ide> else: <ide> return [x[start:stop] for x in X] <ide> else: <ide> if hasattr(start, '__len__'): <ide> if hasattr(start, 'shape'): <del> start = start.tolist() <add> start = start.tolist() <ide> return X[start] <ide> else: <ide> return X[start:stop] <ide> <ide> <ide> def weighted_objective(fn): <ide> def weighted(y_true, y_pred, weights, mask=None): <del> # it's important that 0 * Inf == 0, not NaN, so we need to filter <del> # those out first <del> filtered_y_true = y_true[weights.nonzero()[:-1]] <del> filtered_y_pred = y_pred[weights.nonzero()[:-1]] <del> filtered_weights = weights[weights.nonzero()] <del> obj_output = fn(filtered_y_true, filtered_y_pred) <del> weighted = filtered_weights * obj_output <del> if mask is None: <del> # Instead of calling mean() here, we divide by the sum of filtered_weights. <del> return weighted.sum() / filtered_weights.sum() <del> else: <del> filtered_mask = mask[weights.nonzero()[:-1]] <del> return weighted.sum() / (filtered_mask * filtered_weights).sum() <add> '''To be called only with non-zero weights. <add> <add> mask: binary <add> ''' <add> score_array = fn(y_true, y_pred) <add> if mask is not None: <add> score_array *= mask <add> # the loss per batch should be proportional <add> # to the number of unmasked sampled. <add> score_array /= K.mean(mask) <add> <add> # reduce score_array to 1D <add> ndim = K.ndim(score_array) <add> for d in range(ndim-1): <add> score_array = K.mean(score_array, axis=-1) <add> <add> if weights is not None: <add> score_array *= weights <add> return K.mean(score_array) <ide> return weighted <ide> <ide> <ide> def standardize_weights(y, sample_weight=None, class_weight=None): <ide> if sample_weight is not None: <del> return standardize_y(sample_weight) <add> assert len(sample_weight) == len(y) <add> return sample_weight.flatten() <ide> elif isinstance(class_weight, dict): <del> if len(y.shape) > 3: <del> raise Exception('class_weight not supported for 4+ dimensional targets.') <del> yshape = y.shape <del> y = np.reshape(y, (-1, yshape[-1])) # for time-distributed data, collapse time and sample <add> if len(y.shape) > 2: <add> raise Exception('class_weight not supported for 3+ dimensional targets.') <ide> if y.shape[1] > 1: <ide> y_classes = y.argmax(axis=1) <ide> elif y.shape[1] == 1: <ide> y_classes = np.reshape(y, y.shape[0]) <ide> else: <ide> y_classes = y <del> class_weights = np.asarray([class_weight[cls] for cls in y_classes]) <del> return np.reshape(class_weights, yshape[:-1] + (1,)) # uncollapse initial dimensions <add> weights = np.asarray([class_weight[cls] for cls in y_classes]) <add> return weights <ide> else: <del> return np.ones(y.shape[:-1] + (1,)) <add> return np.ones((y.shape[0],)) <ide> <ide> <ide> def model_from_yaml(yaml_string, custom_objects={}): <ide> ''' <ide> Returns a model generated from a local yaml file, <del> which is either created by hand or from to_yaml method of Sequential or Graph <add> which is either created by hand or from to_yaml method <add> of Sequential or Graph <ide> ''' <ide> import yaml <ide> config = yaml.load(yaml_string) <ide> def model_from_config(config, custom_objects={}): <ide> optimizer = optimizers.get(optimizer_name, optimizer_params) <ide> <ide> if model_name == 'Sequential': <del> model.compile(loss=loss, optimizer=optimizer, class_mode=class_mode, theano_mode=theano_mode) <add> model.compile(loss=loss, optimizer=optimizer, <add> class_mode=class_mode, theano_mode=theano_mode) <ide> elif model_name == 'Graph': <del> model.compile(loss=loss, optimizer=optimizer, theano_mode=theano_mode) <del> <add> model.compile(loss=loss, optimizer=optimizer, <add> theano_mode=theano_mode) <ide> return model <ide> <ide> <ide> def get_function_name(o): <ide> <ide> <ide> class Model(object): <del> def _fit(self, f, ins, out_labels=[], batch_size=128, nb_epoch=100, verbose=1, callbacks=[], <add> def _fit(self, f, ins, out_labels=[], batch_size=128, <add> nb_epoch=100, verbose=1, callbacks=[], <ide> val_f=None, val_ins=None, shuffle=True, metrics=[]): <ide> ''' <del> Abstract fit function for f(*ins). Assume that f returns a list, labelled by out_labels. <add> Abstract fit function for f(ins). <add> Assume that f returns a list, labelled by out_labels. <ide> ''' <ide> do_validation = False <ide> if val_f and val_ins: <ide> def _fit(self, f, ins, out_labels=[], batch_size=128, nb_epoch=100, verbose=1, c <ide> batch_ids = index_array[batch_start:batch_end] <ide> try: <ide> ins_batch = slice_X(ins, batch_ids) <del> except TypeError as err: <add> except TypeError: <ide> raise Exception('TypeError while preparing batch. \ <ide> If using HDF5 input data, pass shuffle="batch".\n') <ide> <ide> batch_logs = {} <ide> batch_logs['batch'] = batch_index <ide> batch_logs['size'] = len(batch_ids) <ide> callbacks.on_batch_begin(batch_index, batch_logs) <del> outs = f(*ins_batch) <add> outs = f(ins_batch) <ide> if type(outs) != list: <ide> outs = [outs] <ide> for l, o in zip(out_labels, outs): <ide> def _fit(self, f, ins, out_labels=[], batch_size=128, nb_epoch=100, verbose=1, c <ide> # validation <ide> if do_validation: <ide> # replace with self._evaluate <del> val_outs = self._test_loop(val_f, val_ins, batch_size=batch_size, verbose=0) <add> val_outs = self._test_loop(val_f, val_ins, <add> batch_size=batch_size, <add> verbose=0) <ide> if type(val_outs) != list: <ide> val_outs = [val_outs] <ide> # same labels assumed <ide> def _predict_loop(self, f, ins, batch_size=128, verbose=0): <ide> batch_ids = index_array[batch_start:batch_end] <ide> ins_batch = slice_X(ins, batch_ids) <ide> <del> batch_outs = f(*ins_batch) <add> batch_outs = f(ins_batch) <ide> if type(batch_outs) != list: <ide> batch_outs = [batch_outs] <ide> if batch_index == 0: <ide> def _test_loop(self, f, ins, batch_size=128, verbose=0): <ide> batch_ids = index_array[batch_start:batch_end] <ide> ins_batch = slice_X(ins, batch_ids) <ide> <del> batch_outs = f(*ins_batch) <add> batch_outs = f(ins_batch) <ide> if type(batch_outs) == list: <ide> if batch_index == 0: <ide> for batch_out in enumerate(batch_outs): <ide> class Sequential(Model, containers.Sequential): <ide> - set_weights <ide> ''' <ide> <del> def compile(self, optimizer, loss, class_mode="categorical", theano_mode=None): <add> def compile(self, optimizer, loss, <add> class_mode="categorical", theano_mode=None): <ide> self.optimizer = optimizers.get(optimizer) <ide> <ide> self.loss = objectives.get(loss) <ide> def compile(self, optimizer, loss, class_mode="categorical", theano_mode=None): <ide> self.y_test = self.get_output(train=False) <ide> <ide> # target of model <del> self.y = T.zeros_like(self.y_train) <del> <del> self.weights = T.ones_like(self.y_train) <add> self.y = K.placeholder(ndim=K.ndim(self.y_train)) <add> # weights: one scalar per sample <add> self.weights = K.placeholder(ndim=1) <ide> <ide> if hasattr(self.layers[-1], "get_output_mask"): <ide> mask = self.layers[-1].get_output_mask() <ide> def compile(self, optimizer, loss, class_mode="categorical", theano_mode=None): <ide> train_loss = weighted_loss(self.y, self.y_train, self.weights, mask) <ide> test_loss = weighted_loss(self.y, self.y_test, self.weights, mask) <ide> <del> train_loss.name = 'train_loss' <del> test_loss.name = 'test_loss' <del> self.y.name = 'y' <del> <ide> if class_mode == "categorical": <del> train_accuracy = T.mean(T.eq(T.argmax(self.y, axis=-1), T.argmax(self.y_train, axis=-1))) <del> test_accuracy = T.mean(T.eq(T.argmax(self.y, axis=-1), T.argmax(self.y_test, axis=-1))) <add> train_accuracy = K.mean(K.equal(K.argmax(self.y, axis=-1), <add> K.argmax(self.y_train, axis=-1))) <add> test_accuracy = K.mean(K.equal(K.argmax(self.y, axis=-1), <add> K.argmax(self.y_test, axis=-1))) <ide> <ide> elif class_mode == "binary": <del> train_accuracy = T.mean(T.eq(self.y, T.round(self.y_train))) <del> test_accuracy = T.mean(T.eq(self.y, T.round(self.y_test))) <add> train_accuracy = K.mean(K.equal(self.y, K.round(self.y_train))) <add> test_accuracy = K.mean(K.equal(self.y, K.round(self.y_test))) <ide> else: <ide> raise Exception("Invalid class mode:" + str(class_mode)) <ide> self.class_mode = class_mode <ide> self.theano_mode = theano_mode <ide> <ide> for r in self.regularizers: <ide> train_loss = r(train_loss) <del> updates = self.optimizer.get_updates(self.params, self.constraints, train_loss) <add> updates = self.optimizer.get_updates(self.params, <add> self.constraints, <add> train_loss) <ide> updates += self.updates <ide> <ide> if type(self.X_train) == list: <ide> train_ins = self.X_train + [self.y, self.weights] <ide> test_ins = self.X_test + [self.y, self.weights] <add> assert type(self.X_test) == list <ide> predict_ins = self.X_test <ide> else: <ide> train_ins = [self.X_train, self.y, self.weights] <ide> test_ins = [self.X_test, self.y, self.weights] <ide> predict_ins = [self.X_test] <ide> <del> self._train = theano.function(train_ins, train_loss, updates=updates, <del> allow_input_downcast=True, mode=theano_mode) <del> self._train_with_acc = theano.function(train_ins, [train_loss, train_accuracy], updates=updates, <del> allow_input_downcast=True, mode=theano_mode) <del> self._predict = theano.function(predict_ins, self.y_test, <del> allow_input_downcast=True, mode=theano_mode) <del> self._test = theano.function(test_ins, test_loss, <del> allow_input_downcast=True, mode=theano_mode) <del> self._test_with_acc = theano.function(test_ins, [test_loss, test_accuracy], <del> allow_input_downcast=True, mode=theano_mode) <del> <del> def train_on_batch(self, X, y, accuracy=False, class_weight=None, sample_weight=None): <add> self._train = K.function(train_ins, [train_loss], updates=updates) <add> self._train_with_acc = K.function(train_ins, [train_loss, train_accuracy], updates=updates) <add> self._predict = K.function(predict_ins, [self.y_test]) <add> self._test = K.function(test_ins, [test_loss]) <add> self._test_with_acc = K.function(test_ins, [test_loss, test_accuracy]) <add> <add> def train_on_batch(self, X, y, accuracy=False, <add> class_weight=None, sample_weight=None): <ide> X = standardize_X(X) <ide> y = standardize_y(y) <del> sample_weight = standardize_weights(y, class_weight=class_weight, sample_weight=sample_weight) <del> <add> sample_weight = standardize_weights(y, class_weight=class_weight, <add> sample_weight=sample_weight) <ide> ins = X + [y, sample_weight] <ide> if accuracy: <del> return self._train_with_acc(*ins) <add> return self._train_with_acc(ins) <ide> else: <del> return self._train(*ins) <add> return self._train(ins) <ide> <ide> def test_on_batch(self, X, y, accuracy=False, sample_weight=None): <ide> X = standardize_X(X) <ide> def test_on_batch(self, X, y, accuracy=False, sample_weight=None): <ide> <ide> ins = X + [y, sample_weight] <ide> if accuracy: <del> return self._test_with_acc(*ins) <add> return self._test_with_acc(ins) <ide> else: <del> return self._test(*ins) <add> return self._test(ins) <ide> <ide> def predict_on_batch(self, X): <ide> ins = standardize_X(X) <del> return self._predict(*ins) <add> return self._predict(ins) <ide> <ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1, callbacks=[], <del> validation_split=0., validation_data=None, shuffle=True, show_accuracy=False, <del> class_weight=None, sample_weight=None): <add> validation_split=0., validation_data=None, shuffle=True, <add> show_accuracy=False, class_weight=None, sample_weight=None): <ide> <ide> X = standardize_X(X) <ide> y = standardize_y(y) <ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1, callbacks=[], <ide> X_val, y_val = validation_data <ide> X_val = standardize_X(X_val) <ide> y_val = standardize_y(y_val) <del> sample_weight_val = np.ones(y_val.shape[:-1] + (1,)) <add> sample_weight_val = standardize_weights(y_val) <ide> elif len(validation_data) == 3: <ide> X_val, y_val, sample_weight_val = validation_data <ide> X_val = standardize_X(X_val) <ide> y_val = standardize_y(y_val) <del> sample_weight_val = standardize_weights(y_val, sample_weight=sample_weight_val) <add> sample_weight_val = standardize_weights(y_val, <add> sample_weight=sample_weight_val) <ide> else: <ide> raise Exception("Invalid format for validation data; provide a tuple (X_val, y_val) or (X_val, y_val, sample_weight). \ <ide> X_val may be a numpy array or a list of numpy arrays depending on your model input.") <ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1, callbacks=[], <ide> sample_weight, sample_weight_val = (slice_X(sample_weight, 0, split_at), slice_X(sample_weight, split_at)) <ide> sample_weight_val = standardize_weights(y_val, sample_weight=sample_weight_val) <ide> else: <del> sample_weight_val = np.ones(y_val.shape[:-1] + (1,)) <add> sample_weight_val = standardize_weights(y_val) <ide> val_ins = X_val + [y_val, sample_weight_val] <ide> <ide> if show_accuracy: <ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1, callbacks=[], <ide> sample_weight = standardize_weights(y, class_weight=class_weight, sample_weight=sample_weight) <ide> ins = X + [y, sample_weight] <ide> metrics = ['loss', 'acc', 'val_loss', 'val_acc'] <del> return self._fit(f, ins, out_labels=out_labels, batch_size=batch_size, nb_epoch=nb_epoch, <add> return self._fit(f, ins, out_labels=out_labels, <add> batch_size=batch_size, nb_epoch=nb_epoch, <ide> verbose=verbose, callbacks=callbacks, <ide> val_f=val_f, val_ins=val_ins, <ide> shuffle=shuffle, metrics=metrics) <ide> def predict_classes(self, X, batch_size=128, verbose=1): <ide> else: <ide> return (proba > 0.5).astype('int32') <ide> <del> def evaluate(self, X, y, batch_size=128, show_accuracy=False, verbose=1, sample_weight=None): <add> def evaluate(self, X, y, batch_size=128, show_accuracy=False, <add> verbose=1, sample_weight=None): <ide> X = standardize_X(X) <ide> y = standardize_y(y) <ide> sample_weight = standardize_weights(y, sample_weight=sample_weight) <ide> def compile(self, optimizer, loss, theano_mode=None): <ide> output = self.outputs[output_name] <ide> y_train = output.get_output(True) <ide> y_test = output.get_output(False) <del> y = T.zeros_like(y_test) <add> y = K.placeholder(ndim=K.ndim(y_train)) <ide> ys.append(y) <ide> ys_train.append(y_train) <ide> ys_test.append(y_test) <ide> def compile(self, optimizer, loss, theano_mode=None): <ide> else: <ide> mask = None <ide> <del> weight = T.ones_like(y_test) <add> weight = K.placeholder(ndim=1) <ide> weights.append(weight) <ide> weighted_loss = weighted_objective(objectives.get(loss_fn)) <ide> train_loss += weighted_loss(y, y_train, weight, mask) <ide> test_loss += weighted_loss(y, y_test, weight, mask) <ide> <del> train_loss.name = 'train_loss' <del> test_loss.name = 'test_loss' <del> <ide> ins = [self.inputs[name].input for name in self.input_order] <ide> train_ins = ins + ys + weights <ide> test_ins = ins + ys + weights <ide> def compile(self, optimizer, loss, theano_mode=None): <ide> self.theano_mode = theano_mode <ide> self.loss = loss <ide> <del> self._train = theano.function(train_ins, train_loss, updates=updates, <del> allow_input_downcast=True, mode=theano_mode) <del> self._test = theano.function(test_ins, test_loss, <del> allow_input_downcast=True, mode=theano_mode) <del> self._predict = theano.function(inputs=ins, outputs=ys_test, <del> allow_input_downcast=True, mode=theano_mode) <add> self._train = K.function(train_ins, [train_loss], updates=updates) <add> self._test = K.function(test_ins, [test_loss]) <add> self._predict = K.function(inputs=ins, outputs=ys_test) <ide> <ide> def train_on_batch(self, data, class_weight={}, sample_weight={}): <ide> # data is a dictionary mapping output and input names to arrays <ide> sample_weight = [standardize_weights(data[name], <ide> sample_weight=sample_weight.get(name), <ide> class_weight=class_weight.get(name)) for name in self.output_order] <ide> ins = [data[name] for name in self.input_order] + [standardize_y(data[name]) for name in self.output_order] + sample_weight <del> return self._train(*ins) <add> return self._train(ins) <ide> <ide> def test_on_batch(self, data, sample_weight={}): <ide> # data is a dictionary mapping input names to arrays <ide> sample_weight = [standardize_weights(data[name], <ide> sample_weight=sample_weight.get(name)) for name in self.output_order] <ide> ins = [data[name] for name in self.input_order] + [standardize_y(data[name]) for name in self.output_order] + sample_weight <del> return self._test(*ins) <add> return self._test(ins) <ide> <ide> def predict_on_batch(self, data): <ide> # data is a dictionary mapping input names to arrays <ide> ins = [data[name] for name in self.input_order] <del> return self._predict(*ins) <add> return self._predict(ins) <ide> <ide> def fit(self, data, batch_size=128, nb_epoch=100, verbose=1, callbacks=[], <del> validation_split=0., validation_data=None, shuffle=True, class_weight={}, sample_weight={}): <add> validation_split=0., validation_data=None, shuffle=True, <add> class_weight={}, sample_weight={}): <ide> X = [data[name] for name in self.input_order] <ide> y = [standardize_y(data[name]) for name in self.output_order] <ide> <ide><path>keras/objectives.py <ide> def mean_squared_error(y_true, y_pred): <ide> <ide> <ide> def root_mean_squared_error(y_true, y_pred): <del> return K.mean(K.square(K.square(y_pred - y_true), axis=-1)) <add> return K.sqrt(K.mean(K.square(y_pred - y_true), axis=-1)) <ide> <ide> <ide> def mean_absolute_error(y_true, y_pred): <ide><path>keras/optimizers.py <ide> def get_updates(self, params, constraints, loss): <ide> def get_gradients(self, loss, params): <ide> grads = K.gradients(loss, params) <ide> if hasattr(self, 'clipnorm') and self.clipnorm > 0: <del> norm = K.sqrt(sum([K.sum(g ** 2) for g in grads])) <add> norm = K.sqrt(sum([K.sum(K.square(g)) for g in grads])) <ide> grads = [clip_norm(g, self.clipnorm, norm) for g in grads] <ide> if hasattr(self, 'clipvalue') and self.clipvalue > 0: <ide> grads = [K.clip(g, -self.clipvalue, self.clipvalue) for g in grads] <ide> def get_updates(self, params, constraints, loss): <ide> <ide> for p, g, a, c in zip(params, grads, accumulators, constraints): <ide> # update accumulator <del> new_a = self.rho * a + (1 - self.rho) * g ** 2 <add> new_a = self.rho * a + (1 - self.rho) * K.square(g) <ide> self.updates.append((a, new_a)) <ide> <ide> new_p = p - self.lr * g / K.sqrt(new_a + self.epsilon) <ide> def get_updates(self, params, constraints, loss): <ide> self.updates = [] <ide> <ide> for p, g, a, c in zip(params, grads, accumulators, constraints): <del> new_a = a + g ** 2 # update accumulator <add> new_a = a + K.square(g) # update accumulator <ide> self.updates.append((a, new_a)) <ide> new_p = p - self.lr * g / K.sqrt(new_a + self.epsilon) <ide> self.updates.append((p, c(new_p))) # apply constraints <ide> def get_updates(self, params, constraints, loss): <ide> for p, g, a, d_a, c in zip(params, grads, accumulators, <ide> delta_accumulators, constraints): <ide> # update accumulator <del> new_a = self.rho * a + (1 - self.rho) * g ** 2 <add> new_a = self.rho * a + (1 - self.rho) * K.square(g) <ide> self.updates.append((a, new_a)) <ide> <ide> # use the new accumulator and the *old* delta_accumulator <ide> def get_updates(self, params, constraints, loss): <ide> self.updates.append((p, c(new_p))) # apply constraints <ide> <ide> # update delta_accumulator <del> new_d_a = self.rho * d_a + (1 - self.rho) * update ** 2 <add> new_d_a = self.rho * d_a + (1 - self.rho) * K.square(update) <ide> self.updates.append((d_a, new_d_a)) <ide> return self.updates <ide> <ide> def __init__(self, lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-8, <ide> self.__dict__.update(locals()) <ide> self.iterations = K.variable(0) <ide> self.lr = K.variable(lr) <add> self.beta_1 = K.variable(beta_1) <add> self.beta_2 = K.variable(beta_2) <ide> <ide> def get_updates(self, params, constraints, loss): <ide> grads = self.get_gradients(loss, params) <ide> self.updates = [(self.iterations, self.iterations+1.)] <ide> <ide> t = self.iterations + 1 <del> lr_t = self.lr * K.sqrt(1 - self.beta_2 ** t) / (1 - self.beta_1 ** t) <add> lr_t = self.lr * K.sqrt(1 - K.pow(self.beta_2, t)) / (1 - K.pow(self.beta_1, t)) <ide> <ide> for p, g, c in zip(params, grads, constraints): <ide> # zero init of moment <ide> def get_updates(self, params, constraints, loss): <ide> v = K.variable(np.zeros(K.get_value(p).shape)) <ide> <ide> m_t = (self.beta_1 * m) + (1 - self.beta_1) * g <del> v_t = (self.beta_2 * v) + (1 - self.beta_2) * (g ** 2) <add> v_t = (self.beta_2 * v) + (1 - self.beta_2) * K.square(g) <ide> p_t = p - lr_t * m_t / (K.sqrt(v_t) + self.epsilon) <ide> <ide> self.updates.append((m, m_t)) <ide> def get_updates(self, params, constraints, loss): <ide> def get_config(self): <ide> return {"name": self.__class__.__name__, <ide> "lr": float(K.get_value(self.lr)), <del> "beta_1": self.beta_1, <del> "beta_2": self.beta_2, <add> "beta_1": float(K.get_value(self.beta_1)), <add> "beta_2": float(K.get_value(self.beta_2)), <ide> "epsilon": self.epsilon} <ide> <ide> # aliases <ide><path>keras/regularizers.py <ide> def set_param(self, p): <ide> <ide> def __call__(self, loss): <ide> loss += K.sum(K.abs(self.p)) * self.l1 <del> loss += K.sum(self.p ** 2) * self.l2 <add> loss += K.sum(K.square(self.p)) * self.l2 <ide> return loss <ide> <ide> def get_config(self): <ide> def set_layer(self, layer): <ide> def __call__(self, loss): <ide> output = self.layer.get_output(True) <ide> loss += self.l1 * K.sum(K.mean(K.abs(output), axis=0)) <del> loss += self.l2 * K.sum(K.mean(output ** 2, axis=0)) <add> loss += self.l2 * K.sum(K.mean(K.square(output), axis=0)) <ide> return loss <ide> <ide> def get_config(self):
14
Javascript
Javascript
add regression test for
eb091458c0f264f6bf8246b7f5626b8e8500148e
<ide><path>test/simple/test-regress-GH-6235.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add>var common = require('../common'); <add>var assert = require('assert'); <add> <add>assert.doesNotThrow(function() { <add> require('vm').runInNewContext('"use strict"; var v = 1; v = 2'); <add>});
1
Text
Text
add documentation tip about overriding variables
d524f6415f4d20e7549d8a5a81be4fdb4f71c3f0
<ide><path>website/docs/usage/projects.md <ide> pipelines. <ide> ```yaml <ide> %%GITHUB_PROJECTS/pipelines/tagger_parser_ud/project.yml <ide> ``` <add>> #### Tip: Overriding variables on the CLI <add>> <add>> If you want to override one or more variables on the CLI and are not already specifying a <add>> project directory, you need to add `.` as a placeholder: <add>> <add>> ``` <add>> python -m spacy project run test . --vars.foo bar <add>> ``` <ide> <ide> | Section | Description | <ide> | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | <ide> | `title` | An optional project title used in `--help` message and [auto-generated docs](#custom-docs). | <ide> | `description` | An optional project description used in [auto-generated docs](#custom-docs). | <del>| `vars` | A dictionary of variables that can be referenced in paths, URLs and scripts, just like [`config.cfg` variables](/usage/training#config-interpolation). For example, `${vars.name}` will use the value of the variable `name`. Variables need to be defined in the section `vars`, but can be a nested dict, so you're able to reference `${vars.model.name}`. | <add>| `vars` | A dictionary of variables that can be referenced in paths, URLs and scripts and overriden on the CLI, just like [`config.cfg` variables](/usage/training#config-interpolation). For example, `${vars.name}` will use the value of the variable `name`. Variables need to be defined in the section `vars`, but can be a nested dict, so you're able to reference `${vars.model.name}`. | <ide> | `env` | A dictionary of variables, mapped to the names of environment variables that will be read in when running the project. For example, `${env.name}` will use the value of the environment variable defined as `name`. | <ide> | `directories` | An optional list of [directories](#project-files) that should be created in the project for assets, training outputs, metrics etc. spaCy will make sure that these directories always exist. | <ide> | `assets` | A list of assets that can be fetched with the [`project assets`](/api/cli#project-assets) command. `url` defines a URL or local path, `dest` is the destination file relative to the project directory, and an optional `checksum` ensures that an error is raised if the file's checksum doesn't match. Instead of `url`, you can also provide a `git` block with the keys `repo`, `branch` and `path`, to download from a Git repo. |
1
Javascript
Javascript
remove ballshooter_multiview from examples list
5d319675f8d99b44f5e59abe44ba74eb273110d8
<ide><path>examples/files.js <ide> var files = { <ide> ], <ide> "webvr": [ <ide> "webvr_ballshooter", <del> "webvr_ballshooter_multiview", <ide> "webvr_cubes", <ide> "webvr_dragging", <ide> "webvr_lorenzattractor",
1
Text
Text
fix broken link in testing documentation
e82958ca781990f22033052b7530c0c030a14cfb
<ide><path>docs/testing.md <ide> The Next.js community has created packages and articles you may find helpful: <ide> For more information on what to read next, we recommend: <ide> <ide> <div class="card"> <del> <a href="/docs/basic-features/environment-variables#test-environment-variable.md"> <add> <a href="/docs/basic-features/environment-variables#test-environment-variables.md"> <ide> <b>Test Environment Variables</b> <ide> <small>Learn more about the test environment variables.</small> <ide> </a>
1
Text
Text
use subscribe to persist to localstorage
b8f36625e9377cec298659634e2655af563dfdf6
<ide><path>README.md <ide> function counter(state = 0, action) { <ide> // Its API is { subscribe, dispatch, getState }. <ide> let store = createStore(counter) <ide> <del>// You can subscribe to the updates manually, or use bindings to your view layer. <add>// You can use subscribe() to update the UI in response to state changes. <add>// Normally you’d use a view binding library (e.g. React Redux) rather than subscribe() directly. <add>// However it can also be handy to persist the current state in the localStorage. <add> <ide> store.subscribe(() => <ide> console.log(store.getState()) <ide> )
1
PHP
PHP
remove uneeded test
3f154f2d8ff4b75fdb7759fb3250f6035cad1823
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testAddContextProviderAdd() <ide> $this->assertSame($stub, $result); <ide> } <ide> <del> /** <del> * Test adding an invalid context class. <del> * <del> * @return void <del> */ <del> public function testAddContextProviderInvalid() <del> { <del> $this->expectException(\TypeError::class); <del> $this->expectExceptionMessage('Return value of Cake\View\Form\ContextFactory::get() must implement interface Cake\View\Form\ContextInterface, instance of stdClass returned'); <del> $context = 'My data'; <del> $this->Form->addContextProvider('test', function ($request, $data) use ($context) { <del> return new \stdClass(); <del> }); <del> $this->Form->create($context); <del> } <del> <ide> /** <ide> * Provides context options for create(). <ide> *
1
Go
Go
remove api codepaths < 1.12
7284b08204fb85838170bdf82e2c379e1a4713c9
<ide><path>api/server/server.go <ide> func (s *Server) getImagesJSON(version version.Version, w http.ResponseWriter, r <ide> return err <ide> } <ide> <del> if version.GreaterThanOrEqualTo("1.7") { <del> return writeJSON(w, http.StatusOK, images) <del> } <del> <del> legacyImages := []types.LegacyImage{} <del> <del> for _, image := range images { <del> for _, repoTag := range image.RepoTags { <del> repo, tag := parsers.ParseRepositoryTag(repoTag) <del> legacyImage := types.LegacyImage{ <del> Repository: repo, <del> Tag: tag, <del> ID: image.ID, <del> Created: image.Created, <del> Size: image.Size, <del> VirtualSize: image.VirtualSize, <del> } <del> legacyImages = append(legacyImages, legacyImage) <del> } <del> } <del> <del> return writeJSON(w, http.StatusOK, legacyImages) <add> return writeJSON(w, http.StatusOK, images) <ide> } <ide> <ide> func (s *Server) getInfo(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> func (s *Server) getContainersChanges(version version.Version, w http.ResponseWr <ide> } <ide> <ide> func (s *Server) getContainersTop(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> if version.LessThan("1.4") { <del> return fmt.Errorf("top was improved a lot since 1.3, Please upgrade your docker client.") <del> } <del> <ide> if vars == nil { <ide> return fmt.Errorf("Missing parameter") <ide> } <ide> func (s *Server) postImagesCreate(version version.Version, w http.ResponseWriter <ide> } <ide> <ide> var ( <del> err error <del> useJSON = version.GreaterThan("1.0") <del> output = ioutils.NewWriteFlusher(w) <add> err error <add> output = ioutils.NewWriteFlusher(w) <ide> ) <ide> <del> if useJSON { <del> w.Header().Set("Content-Type", "application/json") <del> } <add> w.Header().Set("Content-Type", "application/json") <ide> <ide> if image != "" { //pull <ide> if tag == "" { <ide> func (s *Server) postImagesCreate(version version.Version, w http.ResponseWriter <ide> } <ide> <ide> imagePullConfig := &graph.ImagePullConfig{ <del> Parallel: version.GreaterThan("1.3"), <ide> MetaHeaders: metaHeaders, <ide> AuthConfig: authConfig, <ide> OutStream: output, <del> Json: useJSON, <ide> } <ide> <ide> err = s.daemon.Repositories().Pull(image, tag, imagePullConfig) <del> <ide> } else { //import <ide> if tag == "" { <ide> repo, tag = parsers.ParseRepositoryTag(repo) <ide> func (s *Server) postImagesCreate(version version.Version, w http.ResponseWriter <ide> Changes: r.Form["changes"], <ide> InConfig: r.Body, <ide> OutStream: output, <del> Json: useJSON, <ide> } <ide> <ide> newConfig, err := builder.BuildFromConfig(s.daemon, &runconfig.Config{}, imageImportConfig.Changes) <ide> func (s *Server) postImagesCreate(version version.Version, w http.ResponseWriter <ide> if !output.Flushed() { <ide> return err <ide> } <del> sf := streamformatter.NewStreamFormatter(useJSON) <add> sf := streamformatter.NewStreamFormatter(true) <ide> output.Write(sf.FormatError(err)) <ide> } <ide> <ide> func (s *Server) postImagesPush(version version.Version, w http.ResponseWriter, <ide> } <ide> } <ide> <del> useJSON := version.GreaterThan("1.0") <ide> name := vars["name"] <del> <ide> output := ioutils.NewWriteFlusher(w) <ide> imagePushConfig := &graph.ImagePushConfig{ <ide> MetaHeaders: metaHeaders, <ide> AuthConfig: authConfig, <ide> Tag: r.Form.Get("tag"), <ide> OutStream: output, <del> Json: useJSON, <del> } <del> if useJSON { <del> w.Header().Set("Content-Type", "application/json") <ide> } <ide> <add> w.Header().Set("Content-Type", "application/json") <add> <ide> if err := s.daemon.Repositories().Push(name, imagePushConfig); err != nil { <ide> if !output.Flushed() { <ide> return err <ide> } <del> sf := streamformatter.NewStreamFormatter(useJSON) <add> sf := streamformatter.NewStreamFormatter(true) <ide> output.Write(sf.FormatError(err)) <ide> } <ide> return nil <ide> func (s *Server) getImagesGet(version version.Version, w http.ResponseWriter, r <ide> return err <ide> } <ide> <del> useJSON := version.GreaterThan("1.0") <del> if useJSON { <del> w.Header().Set("Content-Type", "application/x-tar") <del> } <add> w.Header().Set("Content-Type", "application/x-tar") <ide> <ide> output := ioutils.NewWriteFlusher(w) <ide> imageExportConfig := &graph.ImageExportConfig{Outstream: output} <ide> func (s *Server) getImagesGet(version version.Version, w http.ResponseWriter, r <ide> if !output.Flushed() { <ide> return err <ide> } <del> sf := streamformatter.NewStreamFormatter(useJSON) <add> sf := streamformatter.NewStreamFormatter(true) <ide> output.Write(sf.FormatError(err)) <ide> } <ide> return nil <ide> func (s *Server) getContainersByName(version version.Version, w http.ResponseWri <ide> return fmt.Errorf("Missing parameter") <ide> } <ide> <del> name := vars["name"] <del> <del> if version.LessThan("1.12") { <del> containerJSONRaw, err := s.daemon.ContainerInspectRaw(name) <del> if err != nil { <del> return err <del> } <del> return writeJSON(w, http.StatusOK, containerJSONRaw) <del> } <del> containerJSON, err := s.daemon.ContainerInspect(name) <add> containerJSON, err := s.daemon.ContainerInspect(vars["name"]) <ide> if err != nil { <ide> return err <ide> } <ide> func (s *Server) getImagesByName(version version.Version, w http.ResponseWriter, <ide> return fmt.Errorf("Missing parameter") <ide> } <ide> <del> name := vars["name"] <del> if version.LessThan("1.12") { <del> imageInspectRaw, err := s.daemon.Repositories().LookupRaw(name) <del> if err != nil { <del> return err <del> } <del> <del> return writeJSON(w, http.StatusOK, imageInspectRaw) <del> } <del> <del> imageInspect, err := s.daemon.Repositories().Lookup(name) <add> imageInspect, err := s.daemon.Repositories().Lookup(vars["name"]) <ide> if err != nil { <ide> return err <ide> } <ide> func (s *Server) getImagesByName(version version.Version, w http.ResponseWriter, <ide> } <ide> <ide> func (s *Server) postBuild(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> if version.LessThan("1.3") { <del> return fmt.Errorf("Multipart upload for build is no longer supported. Please upgrade your docker client.") <del> } <ide> var ( <del> authEncoded = r.Header.Get("X-Registry-Auth") <ide> authConfig = &cliconfig.AuthConfig{} <ide> configFileEncoded = r.Header.Get("X-Registry-Config") <ide> configFile = &cliconfig.ConfigFile{} <ide> buildConfig = builder.NewBuildConfig() <ide> ) <ide> <del> // This block can be removed when API versions prior to 1.9 are deprecated. <del> // Both headers will be parsed and sent along to the daemon, but if a non-empty <del> // ConfigFile is present, any value provided as an AuthConfig directly will <del> // be overridden. See BuildFile::CmdFrom for details. <del> if version.LessThan("1.9") && authEncoded != "" { <del> authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded)) <del> if err := json.NewDecoder(authJson).Decode(authConfig); err != nil { <del> // for a pull it is not an error if no auth was given <del> // to increase compatibility with the existing api it is defaulting to be empty <del> authConfig = &cliconfig.AuthConfig{} <del> } <del> } <del> <ide> if configFileEncoded != "" { <ide> configFileJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(configFileEncoded)) <ide> if err := json.NewDecoder(configFileJson).Decode(configFile); err != nil { <ide> func (s *Server) postBuild(version version.Version, w http.ResponseWriter, r *ht <ide> } <ide> } <ide> <del> if version.GreaterThanOrEqualTo("1.8") { <del> w.Header().Set("Content-Type", "application/json") <del> buildConfig.JSONFormat = true <del> } <add> w.Header().Set("Content-Type", "application/json") <ide> <ide> if boolValue(r, "forcerm") && version.GreaterThanOrEqualTo("1.12") { <ide> buildConfig.Remove = true <ide> func (s *Server) postBuild(version version.Version, w http.ResponseWriter, r *ht <ide> if !output.Flushed() { <ide> return err <ide> } <del> sf := streamformatter.NewStreamFormatter(version.GreaterThanOrEqualTo("1.8")) <add> sf := streamformatter.NewStreamFormatter(true) <ide> w.Write(sf.FormatError(err)) <ide> } <ide> return nil <ide> func (s *Server) postContainerExecStart(version version.Version, w http.Response <ide> fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n") <ide> } <ide> <del> if !execStartCheck.Tty && version.GreaterThanOrEqualTo("1.6") { <add> if !execStartCheck.Tty { <ide> errStream = stdcopy.NewStdWriter(outStream, stdcopy.Stderr) <ide> outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout) <del> } else { <del> errStream = outStream <ide> } <add> <ide> stdin = inStream <ide> stdout = outStream <ide> stderr = errStream <ide><path>api/types/types.go <ide> type ImageInspect struct { <ide> VirtualSize int64 <ide> } <ide> <del>type LegacyImage struct { <del> ID string `json:"Id"` <del> Repository string <del> Tag string <del> Created int <del> Size int <del> VirtualSize int <del>} <del> <ide> // GET "/containers/json" <ide> type Port struct { <ide> IP string <ide><path>builder/internals.go <ide> func (b *Builder) pullImage(name string) (*imagepkg.Image, error) { <ide> } <ide> <ide> imagePullConfig := &graph.ImagePullConfig{ <del> Parallel: true, <ide> AuthConfig: pullRegistryAuth, <ide> OutStream: ioutils.NopWriteCloser(b.OutOld), <del> Json: b.StreamFormatter.Json(), <ide> } <ide> <ide> if err := b.Daemon.Repositories().Pull(remote, tag, imagePullConfig); err != nil { <ide><path>builder/job.go <ide> type Config struct { <ide> Remove bool <ide> ForceRemove bool <ide> Pull bool <del> JSONFormat bool <ide> Memory int64 <ide> MemorySwap int64 <ide> CpuShares int64 <ide> func Build(d *daemon.Daemon, buildConfig *Config) error { <ide> } <ide> defer context.Close() <ide> <del> sf := streamformatter.NewStreamFormatter(buildConfig.JSONFormat) <add> sf := streamformatter.NewStreamFormatter(true) <ide> <ide> builder := &Builder{ <ide> Daemon: d, <ide><path>daemon/inspect.go <ide> type ContainerJSONRaw struct { <ide> HostConfig *runconfig.HostConfig <ide> } <ide> <del>func (daemon *Daemon) ContainerInspectRaw(name string) (*ContainerJSONRaw, error) { <del> container, err := daemon.Get(name) <del> if err != nil { <del> return nil, err <del> } <del> <del> container.Lock() <del> defer container.Unlock() <del> <del> return &ContainerJSONRaw{container, container.hostConfig}, nil <del>} <del> <ide> func (daemon *Daemon) ContainerInspect(name string) (*types.ContainerJSON, error) { <ide> container, err := daemon.Get(name) <ide> if err != nil { <ide><path>graph/import.go <ide> import ( <ide> type ImageImportConfig struct { <ide> Changes []string <ide> InConfig io.ReadCloser <del> Json bool <ide> OutStream io.Writer <ide> ContainerConfig *runconfig.Config <ide> } <ide> <ide> func (s *TagStore) Import(src string, repo string, tag string, imageImportConfig *ImageImportConfig) error { <ide> var ( <del> sf = streamformatter.NewStreamFormatter(imageImportConfig.Json) <add> sf = streamformatter.NewStreamFormatter(true) <ide> archive archive.ArchiveReader <ide> resp *http.Response <ide> ) <ide><path>graph/pull.go <ide> import ( <ide> ) <ide> <ide> type ImagePullConfig struct { <del> Parallel bool <ide> MetaHeaders map[string][]string <ide> AuthConfig *cliconfig.AuthConfig <del> Json bool <ide> OutStream io.Writer <ide> } <ide> <ide> func (s *TagStore) Pull(image string, tag string, imagePullConfig *ImagePullConfig) error { <ide> var ( <del> sf = streamformatter.NewStreamFormatter(imagePullConfig.Json) <add> sf = streamformatter.NewStreamFormatter(true) <ide> ) <ide> <ide> // Resolve the Repository name from fqn to RepositoryInfo <ide> func (s *TagStore) Pull(image string, tag string, imagePullConfig *ImagePullConf <ide> } <ide> <ide> logrus.Debugf("pulling v2 repository with local name %q", repoInfo.LocalName) <del> if err := s.pullV2Repository(r, imagePullConfig.OutStream, repoInfo, tag, sf, imagePullConfig.Parallel); err == nil { <add> if err := s.pullV2Repository(r, imagePullConfig.OutStream, repoInfo, tag, sf); err == nil { <ide> s.eventsService.Log("pull", logName, "") <ide> return nil <ide> } else if err != registry.ErrDoesNotExist && err != ErrV2RegistryUnavailable { <ide> func (s *TagStore) Pull(image string, tag string, imagePullConfig *ImagePullConf <ide> } <ide> <ide> logrus.Debugf("pulling v1 repository with local name %q", repoInfo.LocalName) <del> if err = s.pullRepository(r, imagePullConfig.OutStream, repoInfo, tag, sf, imagePullConfig.Parallel); err != nil { <add> if err = s.pullRepository(r, imagePullConfig.OutStream, repoInfo, tag, sf); err != nil { <ide> return err <ide> } <ide> <ide> func (s *TagStore) Pull(image string, tag string, imagePullConfig *ImagePullConf <ide> return nil <ide> } <ide> <del>func (s *TagStore) pullRepository(r *registry.Session, out io.Writer, repoInfo *registry.RepositoryInfo, askedTag string, sf *streamformatter.StreamFormatter, parallel bool) error { <add>func (s *TagStore) pullRepository(r *registry.Session, out io.Writer, repoInfo *registry.RepositoryInfo, askedTag string, sf *streamformatter.StreamFormatter) error { <ide> out.Write(sf.FormatStatus("", "Pulling repository %s", repoInfo.CanonicalName)) <ide> <ide> repoData, err := r.GetRepositoryData(repoInfo.RemoteName) <ide> func (s *TagStore) pullRepository(r *registry.Session, out io.Writer, repoInfo * <ide> for _, image := range repoData.ImgList { <ide> downloadImage := func(img *registry.ImgData) { <ide> if askedTag != "" && img.Tag != askedTag { <del> if parallel { <del> errors <- nil <del> } <add> errors <- nil <ide> return <ide> } <ide> <ide> if img.Tag == "" { <ide> logrus.Debugf("Image (id: %s) present in this repository but untagged, skipping", img.ID) <del> if parallel { <del> errors <- nil <del> } <add> errors <- nil <ide> return <ide> } <ide> <ide> func (s *TagStore) pullRepository(r *registry.Session, out io.Writer, repoInfo * <ide> } else { <ide> logrus.Debugf("Image (id: %s) pull is already running, skipping: %v", img.ID, err) <ide> } <del> if parallel { <del> errors <- nil <del> } <add> errors <- nil <ide> return <ide> } <ide> defer s.poolRemove("pull", "img:"+img.ID) <ide> func (s *TagStore) pullRepository(r *registry.Session, out io.Writer, repoInfo * <ide> if !success { <ide> err := fmt.Errorf("Error pulling image (%s) from %s, %v", img.Tag, repoInfo.CanonicalName, lastErr) <ide> out.Write(sf.FormatProgress(stringid.TruncateID(img.ID), err.Error(), nil)) <del> if parallel { <del> errors <- err <del> return <del> } <add> errors <- err <add> return <ide> } <ide> out.Write(sf.FormatProgress(stringid.TruncateID(img.ID), "Download complete", nil)) <ide> <del> if parallel { <del> errors <- nil <del> } <add> errors <- nil <ide> } <ide> <del> if parallel { <del> go downloadImage(image) <del> } else { <del> downloadImage(image) <del> } <add> go downloadImage(image) <ide> } <del> if parallel { <del> var lastError error <del> for i := 0; i < len(repoData.ImgList); i++ { <del> if err := <-errors; err != nil { <del> lastError = err <del> } <del> } <del> if lastError != nil { <del> return lastError <del> } <ide> <add> var lastError error <add> for i := 0; i < len(repoData.ImgList); i++ { <add> if err := <-errors; err != nil { <add> lastError = err <add> } <add> } <add> if lastError != nil { <add> return lastError <ide> } <add> <ide> for tag, id := range tagsList { <ide> if askedTag != "" && tag != askedTag { <ide> continue <ide> type downloadInfo struct { <ide> err chan error <ide> } <ide> <del>func (s *TagStore) pullV2Repository(r *registry.Session, out io.Writer, repoInfo *registry.RepositoryInfo, tag string, sf *streamformatter.StreamFormatter, parallel bool) error { <add>func (s *TagStore) pullV2Repository(r *registry.Session, out io.Writer, repoInfo *registry.RepositoryInfo, tag string, sf *streamformatter.StreamFormatter) error { <ide> endpoint, err := r.V2RegistryEndpoint(repoInfo.Index) <ide> if err != nil { <ide> if repoInfo.Index.Official { <ide> func (s *TagStore) pullV2Repository(r *registry.Session, out io.Writer, repoInfo <ide> return registry.ErrDoesNotExist <ide> } <ide> for _, t := range tags { <del> if downloaded, err := s.pullV2Tag(r, out, endpoint, repoInfo, t, sf, parallel, auth); err != nil { <add> if downloaded, err := s.pullV2Tag(r, out, endpoint, repoInfo, t, sf, auth); err != nil { <ide> return err <ide> } else if downloaded { <ide> layersDownloaded = true <ide> } <ide> } <ide> } else { <del> if downloaded, err := s.pullV2Tag(r, out, endpoint, repoInfo, tag, sf, parallel, auth); err != nil { <add> if downloaded, err := s.pullV2Tag(r, out, endpoint, repoInfo, tag, sf, auth); err != nil { <ide> return err <ide> } else if downloaded { <ide> layersDownloaded = true <ide> func (s *TagStore) pullV2Repository(r *registry.Session, out io.Writer, repoInfo <ide> return nil <ide> } <ide> <del>func (s *TagStore) pullV2Tag(r *registry.Session, out io.Writer, endpoint *registry.Endpoint, repoInfo *registry.RepositoryInfo, tag string, sf *streamformatter.StreamFormatter, parallel bool, auth *registry.RequestAuthorization) (bool, error) { <add>func (s *TagStore) pullV2Tag(r *registry.Session, out io.Writer, endpoint *registry.Endpoint, repoInfo *registry.RepositoryInfo, tag string, sf *streamformatter.StreamFormatter, auth *registry.RequestAuthorization) (bool, error) { <ide> logrus.Debugf("Pulling tag from V2 registry: %q", tag) <ide> <ide> manifestBytes, manifestDigest, err := r.GetV2ImageManifest(endpoint, repoInfo.RemoteName, tag, auth) <ide> func (s *TagStore) pullV2Tag(r *registry.Session, out io.Writer, endpoint *regis <ide> return nil <ide> } <ide> <del> if parallel { <del> downloads[i].err = make(chan error) <del> go func(di *downloadInfo) { <del> di.err <- downloadFunc(di) <del> }(&downloads[i]) <del> } else { <del> if err := downloadFunc(&downloads[i]); err != nil { <del> return false, err <del> } <del> } <add> downloads[i].err = make(chan error) <add> go func(di *downloadInfo) { <add> di.err <- downloadFunc(di) <add> }(&downloads[i]) <ide> } <ide> <ide> var tagUpdated bool <ide><path>graph/push.go <ide> type ImagePushConfig struct { <ide> MetaHeaders map[string][]string <ide> AuthConfig *cliconfig.AuthConfig <ide> Tag string <del> Json bool <ide> OutStream io.Writer <ide> } <ide> <ide> func (s *TagStore) pushV2Image(r *registry.Session, img *image.Image, endpoint * <ide> // FIXME: Allow to interrupt current push when new push of same image is done. <ide> func (s *TagStore) Push(localName string, imagePushConfig *ImagePushConfig) error { <ide> var ( <del> sf = streamformatter.NewStreamFormatter(imagePushConfig.Json) <add> sf = streamformatter.NewStreamFormatter(true) <ide> ) <ide> <ide> // Resolve the Repository name from fqn to RepositoryInfo <ide><path>integration-cli/docker_api_images_test.go <ide> import ( <ide> "github.com/go-check/check" <ide> ) <ide> <del>func (s *DockerSuite) TestLegacyImages(c *check.C) { <del> status, body, err := sockRequest("GET", "/v1.6/images/json", nil) <del> c.Assert(status, check.Equals, http.StatusOK) <del> c.Assert(err, check.IsNil) <del> <del> images := []types.LegacyImage{} <del> if err = json.Unmarshal(body, &images); err != nil { <del> c.Fatalf("Error on unmarshal: %s", err) <del> } <del> <del> if len(images) == 0 || images[0].Tag == "" || images[0].Repository == "" { <del> c.Fatalf("Bad data: %q", images) <del> } <del>} <del> <ide> func (s *DockerSuite) TestApiImagesFilter(c *check.C) { <ide> name := "utest:tag1" <ide> name2 := "utest/docker:tag2" <ide><path>integration-cli/docker_api_inspect_test.go <ide> func (s *DockerSuite) TestInspectApiContainerResponse(c *check.C) { <ide> <ide> cleanedContainerID := strings.TrimSpace(out) <ide> <del> // test on json marshal version <del> // and latest version <del> testVersions := []string{"v1.11", "latest"} <del> <del> for _, testVersion := range testVersions { <del> endpoint := "/containers/" + cleanedContainerID + "/json" <del> if testVersion != "latest" { <del> endpoint = "/" + testVersion + endpoint <del> } <del> status, body, err := sockRequest("GET", endpoint, nil) <del> c.Assert(status, check.Equals, http.StatusOK) <del> c.Assert(err, check.IsNil) <add> endpoint := "/containers/" + cleanedContainerID + "/json" <add> status, body, err := sockRequest("GET", endpoint, nil) <add> c.Assert(status, check.Equals, http.StatusOK) <add> c.Assert(err, check.IsNil) <add> <add> var inspectJSON map[string]interface{} <add> if err = json.Unmarshal(body, &inspectJSON); err != nil { <add> c.Fatalf("unable to unmarshal body for latest version: %v", err) <add> } <ide> <del> var inspectJSON map[string]interface{} <del> if err = json.Unmarshal(body, &inspectJSON); err != nil { <del> c.Fatalf("unable to unmarshal body for %s version: %v", testVersion, err) <del> } <add> keys := []string{"State", "Created", "Path", "Args", "Config", "Image", "NetworkSettings", "ResolvConfPath", "HostnamePath", "HostsPath", "LogPath", "Name", "Driver", "ExecDriver", "MountLabel", "ProcessLabel", "Volumes", "VolumesRW"} <ide> <del> keys := []string{"State", "Created", "Path", "Args", "Config", "Image", "NetworkSettings", "ResolvConfPath", "HostnamePath", "HostsPath", "LogPath", "Name", "Driver", "ExecDriver", "MountLabel", "ProcessLabel", "Volumes", "VolumesRW"} <add> keys = append(keys, "Id") <ide> <del> if testVersion == "v1.11" { <del> keys = append(keys, "ID") <del> } else { <del> keys = append(keys, "Id") <del> } <del> <del> for _, key := range keys { <del> if _, ok := inspectJSON[key]; !ok { <del> c.Fatalf("%s does not exist in response for %s version", key, testVersion) <del> } <del> } <del> //Issue #6830: type not properly converted to JSON/back <del> if _, ok := inspectJSON["Path"].(bool); ok { <del> c.Fatalf("Path of `true` should not be converted to boolean `true` via JSON marshalling") <add> for _, key := range keys { <add> if _, ok := inspectJSON[key]; !ok { <add> c.Fatalf("%s does not exist in response for latest version", key) <ide> } <ide> } <add> //Issue #6830: type not properly converted to JSON/back <add> if _, ok := inspectJSON["Path"].(bool); ok { <add> c.Fatalf("Path of `true` should not be converted to boolean `true` via JSON marshalling") <add> } <ide> }
10
Java
Java
add files changed count to reload metrics
6ceb4fa53feaaedeb2466ff4c349695715c11239
<ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/BundleDownloader.java <ide> <ide> package com.facebook.react.devsupport; <ide> <add>import android.util.Log; <ide> import javax.annotation.Nullable; <ide> <ide> import java.io.File; <ide> import okio.Sink; <ide> <ide> public class BundleDownloader { <add> private static final String TAG = "BundleDownloader"; <add> <add> // Should be kept in sync with constants in RCTJavaScriptLoader.h <add> private static final int FILES_CHANGED_COUNT_NOT_BUILT_BY_BUNDLER = -2; <add> <ide> private final OkHttpClient mClient; <ide> <ide> private @Nullable Call mDownloadBundleFromURLCall; <ide> <add> public static class BundleInfo { <add> private @Nullable String mUrl; <add> private int mFilesChangedCount; <add> <add> public static @Nullable BundleInfo fromJSONString(String jsonStr) { <add> if (jsonStr == null) { <add> return null; <add> } <add> <add> BundleInfo info = new BundleInfo(); <add> <add> try { <add> JSONObject obj = new JSONObject(jsonStr); <add> info.mUrl = obj.getString("url"); <add> info.mFilesChangedCount = obj.getInt("filesChangedCount"); <add> } catch (JSONException e) { <add> Log.e(TAG, "Invalid bundle info: ", e); <add> return null; <add> } <add> <add> return info; <add> } <add> <add> public @Nullable String toJSONString() { <add> JSONObject obj = new JSONObject(); <add> <add> try { <add> obj.put("url", mUrl); <add> obj.put("filesChangedCount", mFilesChangedCount); <add> } catch (JSONException e) { <add> Log.e(TAG, "Can't serialize bundle info: ", e); <add> return null; <add> } <add> <add> return obj.toString(); <add> } <add> <add> public String getUrl() { <add> return mUrl != null ? mUrl : "unknown"; <add> } <add> <add> public int getFilesChangedCount() { <add> return mFilesChangedCount; <add> } <add> } <add> <ide> public BundleDownloader(OkHttpClient client) { <ide> mClient = client; <ide> } <ide> <ide> public void downloadBundleFromURL( <ide> final DevBundleDownloadListener callback, <ide> final File outputFile, <del> final String bundleURL) { <add> final String bundleURL, <add> final @Nullable BundleInfo bundleInfo) { <ide> final Request request = new Request.Builder() <ide> .url(bundleURL) <ide> // FIXME: there is a bug that makes MultipartStreamReader to never find the end of the <ide> public void execute(Map<String, String> headers, Buffer body, boolean finished) <ide> if (headers.containsKey("X-Http-Status")) { <ide> status = Integer.parseInt(headers.get("X-Http-Status")); <ide> } <del> processBundleResult(url, status, body, outputFile, callback); <add> processBundleResult(url, status, okhttp3.Headers.of(headers), body, outputFile, bundleInfo, callback); <ide> } else { <ide> if (!headers.containsKey("Content-Type") || !headers.get("Content-Type").equals("application/json")) { <ide> return; <ide> public void execute(Map<String, String> headers, Buffer body, boolean finished) <ide> } <ide> } else { <ide> // In case the server doesn't support multipart/mixed responses, fallback to normal download. <del> processBundleResult(url, response.code(), Okio.buffer(response.body().source()), outputFile, callback); <add> processBundleResult(url, response.code(), response.headers(), Okio.buffer(response.body().source()), outputFile, bundleInfo, callback); <ide> } <ide> } <ide> }); <ide> public void cancelDownloadBundleFromURL() { <ide> } <ide> } <ide> <del> private void processBundleResult( <add> private static void processBundleResult( <ide> String url, <ide> int statusCode, <add> okhttp3.Headers headers, <ide> BufferedSource body, <ide> File outputFile, <add> BundleInfo bundleInfo, <ide> DevBundleDownloadListener callback) throws IOException { <ide> // Check for server errors. If the server error has the expected form, fail with more info. <ide> if (statusCode != 200) { <ide> private void processBundleResult( <ide> return; <ide> } <ide> <add> if (bundleInfo != null) { <add> populateBundleInfo(url, headers, bundleInfo); <add> } <add> <ide> File tmpFile = new File(outputFile.getPath() + ".tmp"); <ide> Sink output = null; <ide> try { <ide> private void processBundleResult( <ide> throw new IOException("Couldn't rename " + tmpFile + " to " + outputFile); <ide> } <ide> } <add> <add> private static void populateBundleInfo(String url, okhttp3.Headers headers, BundleInfo bundleInfo) { <add> bundleInfo.mUrl = url; <add> <add> String filesChangedCountStr = headers.get("X-Metro-Files-Changed-Count"); <add> if (filesChangedCountStr != null) { <add> try { <add> bundleInfo.mFilesChangedCount = Integer.parseInt(filesChangedCountStr); <add> } catch (NumberFormatException e) { <add> bundleInfo.mFilesChangedCount = FILES_CHANGED_COUNT_NOT_BUILT_BY_BUNDLER; <add> } <add> } <add> } <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManagerImpl.java <ide> public void reloadJSFromServer(final String bundleURL) { <ide> mDevLoadingViewController.showForUrl(bundleURL); <ide> mDevLoadingViewVisible = true; <ide> <add> final BundleDownloader.BundleInfo bundleInfo = new BundleDownloader.BundleInfo(); <add> <ide> mDevServerHelper.getBundleDownloader().downloadBundleFromURL( <ide> new DevBundleDownloadListener() { <ide> @Override <ide> public void onSuccess() { <ide> new Runnable() { <ide> @Override <ide> public void run() { <del> ReactMarker.logMarker(ReactMarkerConstants.DOWNLOAD_END); <add> ReactMarker.logMarker(ReactMarkerConstants.DOWNLOAD_END, bundleInfo.toJSONString()); <ide> mReactInstanceCommandsHandler.onJSBundleLoadedFromServer(); <ide> } <ide> }); <ide> public void run() { <ide> } <ide> }, <ide> mJSBundleTempFile, <del> bundleURL); <add> bundleURL, <add> bundleInfo); <ide> } <ide> <ide> @Override
2
PHP
PHP
remove duplicated assertions
e132a7c85655ef1bba3ca9e9b3cce58d2d7b1692
<ide><path>lib/Cake/Test/Case/View/Helper/FormHelperTest.php <ide> public function testRadio() { <ide> ); <ide> $this->assertTags($result, $expected); <ide> <del> $result = $this->Form->input('Newsletter.subscribe', array('legend' => 'Legend title', 'type' => 'radio', 'options' => array('0' => 'Unsubscribe', '1' => 'Subscribe'))); <del> $expected = array( <del> 'div' => array('class' => 'input radio'), <del> 'fieldset' => array(), <del> 'legend' => array(), <del> 'Legend title', <del> '/legend', <del> 'input' => array('type' => 'hidden', 'name' => 'data[Newsletter][subscribe]', 'value' => '', 'id' => 'NewsletterSubscribe_'), <del> array('input' => array('type' => 'radio', 'name' => 'data[Newsletter][subscribe]', 'value' => '0', 'id' => 'NewsletterSubscribe0')), <del> array('label' => array('for' => 'NewsletterSubscribe0')), <del> 'Unsubscribe', <del> '/label', <del> array('input' => array('type' => 'radio', 'name' => 'data[Newsletter][subscribe]', 'value' => '1', 'id' => 'NewsletterSubscribe1')), <del> array('label' => array('for' => 'NewsletterSubscribe1')), <del> 'Subscribe', <del> '/label', <del> '/fieldset', <del> '/div' <del> ); <del> $this->assertTags($result, $expected); <del> <del> $result = $this->Form->input('Newsletter.subscribe', array('legend' => false, 'type' => 'radio', 'options' => array('0' => 'Unsubscribe', '1' => 'Subscribe'))); <del> $expected = array( <del> 'div' => array('class' => 'input radio'), <del> 'input' => array('type' => 'hidden', 'name' => 'data[Newsletter][subscribe]', 'value' => '', 'id' => 'NewsletterSubscribe_'), <del> array('input' => array('type' => 'radio', 'name' => 'data[Newsletter][subscribe]', 'value' => '0', 'id' => 'NewsletterSubscribe0')), <del> array('label' => array('for' => 'NewsletterSubscribe0')), <del> 'Unsubscribe', <del> '/label', <del> array('input' => array('type' => 'radio', 'name' => 'data[Newsletter][subscribe]', 'value' => '1', 'id' => 'NewsletterSubscribe1')), <del> array('label' => array('for' => 'NewsletterSubscribe1')), <del> 'Subscribe', <del> '/label', <del> '/div' <del> ); <del> $this->assertTags($result, $expected); <del> <del> $result = $this->Form->input('Newsletter.subscribe', array('legend' => 'Legend title', 'label' => false, 'type' => 'radio', 'options' => array('0' => 'Unsubscribe', '1' => 'Subscribe'))); <del> $expected = array( <del> 'div' => array('class' => 'input radio'), <del> 'fieldset' => array(), <del> 'legend' => array(), <del> 'Legend title', <del> '/legend', <del> 'input' => array('type' => 'hidden', 'name' => 'data[Newsletter][subscribe]', 'value' => '', 'id' => 'NewsletterSubscribe_'), <del> array('input' => array('type' => 'radio', 'name' => 'data[Newsletter][subscribe]', 'value' => '0', 'id' => 'NewsletterSubscribe0')), <del> 'Unsubscribe', <del> array('input' => array('type' => 'radio', 'name' => 'data[Newsletter][subscribe]', 'value' => '1', 'id' => 'NewsletterSubscribe1')), <del> 'Subscribe', <del> '/fieldset', <del> '/div' <del> ); <del> $this->assertTags($result, $expected); <del> <del> $result = $this->Form->input('Newsletter.subscribe', array('legend' => false, 'label' => false, 'type' => 'radio', 'options' => array('0' => 'Unsubscribe', '1' => 'Subscribe'))); <del> $expected = array( <del> 'div' => array('class' => 'input radio'), <del> 'input' => array('type' => 'hidden', 'name' => 'data[Newsletter][subscribe]', 'value' => '', 'id' => 'NewsletterSubscribe_'), <del> array('input' => array('type' => 'radio', 'name' => 'data[Newsletter][subscribe]', 'value' => '0', 'id' => 'NewsletterSubscribe0')), <del> 'Unsubscribe', <del> array('input' => array('type' => 'radio', 'name' => 'data[Newsletter][subscribe]', 'value' => '1', 'id' => 'NewsletterSubscribe1')), <del> 'Subscribe', <del> '/div' <del> ); <del> $this->assertTags($result, $expected); <del> <del> $result = $this->Form->input('Newsletter.subscribe', array('legend' => false, 'label' => false, 'type' => 'radio', 'value' => '1', 'options' => array('0' => 'Unsubscribe', '1' => 'Subscribe'))); <del> $expected = array( <del> 'div' => array('class' => 'input radio'), <del> array('input' => array('type' => 'radio', 'name' => 'data[Newsletter][subscribe]', 'value' => '0', 'id' => 'NewsletterSubscribe0')), <del> 'Unsubscribe', <del> array('input' => array('type' => 'radio', 'name' => 'data[Newsletter][subscribe]', 'value' => '1', 'id' => 'NewsletterSubscribe1', 'checked' => 'checked')), <del> 'Subscribe', <del> '/div' <del> ); <del> $this->assertTags($result, $expected); <del> <ide> $result = $this->Form->radio('Employee.gender', array('male' => 'Male', 'female' => 'Female')); <ide> $expected = array( <ide> 'fieldset' => array(),
1
Java
Java
use reflection for jdkflowadapter
0078f4677957a3d0c582cf19a145a390cd33ea9a
<ide><path>spring-core/src/main/java/org/springframework/core/ReactiveAdapterRegistry.java <ide> void registerAdapters(ReactiveAdapterRegistry registry) { <ide> private static class ReactorJdkFlowAdapterRegistrar { <ide> <ide> void registerAdapter(ReactiveAdapterRegistry registry) throws Exception { <add> <ide> // TODO: remove reflection when build requires JDK 9+ <del> Class<?> type = ClassUtils.forName("java.util.concurrent.Flow.Publisher", getClass().getClassLoader()); <del> Method toFluxMethod = getMethod("flowPublisherToFlux", type); <del> Method toFlowMethod = getMethod("publisherToFlowPublisher", Publisher.class); <add> <add> String publisherName = "java.util.concurrent.Flow.Publisher"; <add> Class<?> publisherClass = ClassUtils.forName(publisherName, getClass().getClassLoader()); <add> <add> String adapterName = "reactor.adapter.JdkFlowAdapter"; <add> Class<?> flowAdapterClass = ClassUtils.forName(adapterName, getClass().getClassLoader()); <add> <add> Method toFluxMethod = flowAdapterClass.getMethod("flowPublisherToFlux", publisherClass); <add> Method toFlowMethod = flowAdapterClass.getMethod("publisherToFlowPublisher", Publisher.class); <ide> Object emptyFlow = ReflectionUtils.invokeMethod(toFlowMethod, null, Flux.empty()); <ide> <ide> registry.registerReactiveType( <del> ReactiveTypeDescriptor.multiValue(type, () -> emptyFlow), <add> ReactiveTypeDescriptor.multiValue(publisherClass, () -> emptyFlow), <ide> source -> (Publisher<?>) ReflectionUtils.invokeMethod(toFluxMethod, null, source), <ide> publisher -> ReflectionUtils.invokeMethod(toFlowMethod, null, publisher) <ide> ); <ide> } <del> <del> private static Method getMethod(String name, Class<?> argumentType) throws NoSuchMethodException { <del> return reactor.adapter.JdkFlowAdapter.class.getMethod(name, argumentType); <del> } <ide> } <ide> <ide>
1
Go
Go
use direct filesystem access for tar-split on aufs
0641429ad8a474c25eb99ee3c5a969b28baaad21
<ide><path>daemon/graphdriver/aufs/aufs.go <ide> func (a *Driver) Diff(id, parent string) (archive.Archive, error) { <ide> }) <ide> } <ide> <add>// DiffPath returns path to the directory that contains files for the layer <add>// differences. Used for direct access for tar-split. <add>func (a *Driver) DiffPath(id string) (string, func() error, error) { <add> return path.Join(a.rootPath(), "diff", id), func() error { return nil }, nil <add>} <add> <ide> func (a *Driver) applyDiff(id string, diff archive.Reader) error { <ide> dir := path.Join(a.rootPath(), "diff", id) <ide> if err := chrootarchive.UntarUncompressed(diff, dir, &archive.TarOptions{
1
Python
Python
use existing functionality for
f4f4e6b2d3f8ff6a5d418c3cb617caebf37e3893
<ide><path>src/transformers/models/auto/tokenization_auto.py <ide> CONFIG_MAPPING_NAMES, <ide> AutoConfig, <ide> config_class_to_model_type, <add> model_type_to_module_name, <ide> replace_list_option_in_docstrings, <ide> ) <ide> <ide> def tokenizer_class_from_name(class_name: str): <ide> if class_name in tokenizers: <ide> break <ide> <del> if module_name == "openai-gpt": <del> module_name = "openai" <add> module_name = model_type_to_module_name(module_name) <ide> <del> module = importlib.import_module(f".{module_name.replace('-', '_')}", "transformers.models") <add> module = importlib.import_module(f".{module_name}", "transformers.models") <ide> return getattr(module, class_name) <ide> <ide>
1
Ruby
Ruby
allow hiding from man page
1bdcd2001c53556a3cdc472b0b3797d3822a800b
<ide><path>Library/Homebrew/cli_parser.rb <ide> module Homebrew <ide> module CLI <ide> class Parser <del> attr_reader :processed_options <add> attr_reader :processed_options, :hide_from_man_page <ide> <ide> def self.parse(args = ARGV, &block) <ide> new(&block).parse(args) <ide> def initialize(&block) <ide> @conflicts = [] <ide> @processed_options = [] <ide> @desc_line_length = 43 <add> @hide_from_man_page = false <ide> instance_eval(&block) <ide> post_initialize <ide> end <ide> def formula_options <ide> end <ide> end <ide> <add> def hide_from_man_page! <add> @hide_from_man_page = true <add> end <add> <ide> private <ide> <ide> def enable_switch(*names)
1
Go
Go
remove unused errnodefaultroute
888e75dfc93d6f3ecb535729a55f9c4673cf5fd0
<ide><path>libnetwork/netutils/utils.go <ide> var ( <ide> ErrNetworkOverlapsWithNameservers = errors.New("requested network overlaps with nameserver") <ide> // ErrNetworkOverlaps preformatted error <ide> ErrNetworkOverlaps = errors.New("requested network overlaps with existing network") <del> // ErrNoDefaultRoute preformatted error <del> ErrNoDefaultRoute = errors.New("no default route") <ide> ) <ide> <ide> // CheckNameserverOverlaps checks whether the passed network overlaps with any of the nameservers
1
Ruby
Ruby
fix warning in av tests
2f8be7ebafcf7815f9f3ec7983789157525a60fa
<ide><path>actionview/lib/action_view/renderer/partial_renderer.rb <ide> def setup(context, options, block) <ide> partial = options[:partial] <ide> <ide> if String === partial <del> @object = options[:object] if options.has_key?(:object) <add> @has_object = options.key?(:object) <add> @object = options[:object] <ide> @collection = collection_from_options <ide> @path = partial <ide> else <add> @has_object = true <ide> @object = partial <ide> @collection = collection_from_object || collection_from_options <ide> <ide> def merge_prefix_into_object_path(prefix, object_path) <ide> <ide> def retrieve_template_keys <ide> keys = @locals.keys <del> keys << @variable if defined?(@object) || @collection <add> keys << @variable if @has_object || @collection <ide> if @collection <ide> keys << @variable_counter <ide> keys << @variable_iteration
1
Javascript
Javascript
fix cinematic camera example
f069efb0d79b7b9adadc30005d7c832543a68db5
<ide><path>examples/js/cameras/CinematicCamera.js <ide> THREE.CinematicCamera.prototype.initPostProcessing = function () { <ide> fragmentShader: bokeh_shader.fragmentShader, <ide> defines: { <ide> RINGS: this.shaderSettings.rings, <del> SAMPLES: this.shaderSettings.samples <add> SAMPLES: this.shaderSettings.samples, <add> DEPTH_PACKING: this.material_depth.depthPacking <ide> } <ide> } ); <ide>
1
Javascript
Javascript
solve the spaces vs tabs indentation issues
2bfb1f557b7e39bda0656a5a65a4658fcfc7d50f
<ide><path>examples/js/renderers/SoftwareRenderer.js <ide> THREE.SoftwareRenderer = function ( parameters ) { <ide> } <ide> <ide> } else if ( element instanceof THREE.RenderableLine ) { <del> <del> var shader = getMaterialShader( material ); <del> <del> drawLine( <del> element.v1.positionScreen, <del> element.v2.positionScreen, <del> element.vertexColors[0], <del> element.vertexColors[1], <del> shader, <del> material <del> ); <del> } <del> <del> } <add> <add> var shader = getMaterialShader( material ); <add> <add> drawLine( <add> element.v1.positionScreen, <add> element.v2.positionScreen, <add> element.vertexColors[0], <add> element.vertexColors[1], <add> shader, <add> material <add> ); <add> } <add> <add> } <ide> <ide> finishClear(); <ide>
1
Text
Text
revise commandline guide [ci skip]
b8aa3923af388dfbaf7524a83f3ee2f1f59cc36a
<ide><path>guides/source/command_line.md <ide> The `tmp:` namespaced tasks will help you clear the `Rails.root/tmp` directory: <ide> * `rake secret` will give you a pseudo-random key to use for your session secret. <ide> * `rake time:zones:all` lists all the timezones Rails knows about. <ide> <del>### Writing Rake Tasks <add>### Custom Rake Tasks <ide> <del>If you have (or want to write) any automation scripts outside your app (data import, checks, etc), you can make them as rake tasks. It's easy. <del> <del>INFO: [Complete guide about how to write tasks](http://rake.rubyforge.org/files/doc/rakefile_rdoc.html) is available in the official documentation. <del> <del>Tasks should be placed in `Rails.root/lib/tasks` and should have a `.rake` extension. <del> <del>Each task should be defined in next format (dependencies are optional): <add>Custom rake tasks have a `.rake` extension and are placed in `Rails.root/lib/tasks`. <ide> <ide> ```ruby <ide> desc "I am short, but comprehensive description for my cool task" <ide> task :task_name => [:prerequisite_task, :another_task_we_depend_on] do <ide> end <ide> ``` <ide> <del>If you need to pass parameters, you can use next format (both arguments and dependencies are optional): <add>To pass arguments to your custom rake task: <ide> <ide> ```ruby <ide> task :task_name, [:arg_1] => [:pre_1, :pre_2] do |t, args| <ide> end <ide> You can group tasks by placing them in namespaces: <ide> <ide> ```ruby <del>namespace :do <add>namespace :db <ide> desc "This task does nothing" <ide> task :nothing do <ide> # Seriously, nothing <ide> end <ide> end <ide> ``` <ide> <del>You can see your tasks to be listed by `rake -T` command. And, according to the examples above, you can invoke them as follows: <add>Invocation of the tasks will look like: <ide> <ide> ```bash <ide> rake task_name <ide> rake "task_name[value 1]" # entire argument string should be quoted <del>rake do:nothing <add>rake db:nothing <ide> ``` <ide> <ide> NOTE: If your need to interact with your application models, perform database queries and so on, your task should depend on the `environment` task, which will load your application code.
1
Javascript
Javascript
remove unused ensurecomponentisnative mock
d1439e8b854b4e805c94dfbe7444237c4d602b38
<ide><path>Libraries/Components/Touchable/__mocks__/ensureComponentIsNative.js <del>/** <del> * Copyright (c) Facebook, Inc. and its affiliates. <del> * <del> * This source code is licensed under the MIT license found in the <del> * LICENSE file in the root directory of this source tree. <del> * <del> * @format <del> */ <del> <del>'use strict'; <del> <del>module.exports = () => true;
1
Python
Python
use format_html in tags that generate html
21cad8646af7fd91eb3f81097b14b908d6c4c49d
<ide><path>rest_framework/templatetags/rest_framework.py <ide> from django.template import Context, loader <ide> from django.utils import six <ide> from django.utils.encoding import force_text, iri_to_uri <del>from django.utils.html import escape, smart_urlquote <add>from django.utils.html import escape, format_html, smart_urlquote <ide> from django.utils.safestring import SafeData, mark_safe <ide> <ide> from rest_framework.renderers import HTMLFormRenderer <ide> def optional_login(request): <ide> return '' <ide> <ide> snippet = "<li><a href='{href}?next={next}'>Log in</a></li>" <del> snippet = snippet.format(href=login_url, next=escape(request.path)) <add> snippet = format_html(snippet, href=login_url, next=escape(request.path)) <add> <ide> return mark_safe(snippet) <ide> <ide> <ide> def optional_logout(request, user): <ide> <li><a href='{href}?next={next}'>Log out</a></li> <ide> </ul> <ide> </li>""" <del> snippet = snippet.format(user=escape(user), href=logout_url, next=escape(request.path)) <add> snippet = format_html(snippet, user=escape(user), href=logout_url, next=escape(request.path)) <add> <ide> return mark_safe(snippet) <ide> <ide>
1
Mixed
Text
fix typs from go to go
7dad9d5ce45f25750f339642d3b84a81cc2ba98e
<ide><path>cli/command/container/inspect.go <ide> func newInspectCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> } <ide> <ide> flags := cmd.Flags() <del> flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given go template") <add> flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given Go template") <ide> flags.BoolVarP(&opts.size, "size", "s", false, "Display total file sizes") <ide> <ide> return cmd <ide><path>cli/command/image/inspect.go <ide> func newInspectCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> } <ide> <ide> flags := cmd.Flags() <del> flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given go template") <add> flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given Go template") <ide> return cmd <ide> } <ide> <ide><path>cli/command/network/inspect.go <ide> func newInspectCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> }, <ide> } <ide> <del> cmd.Flags().StringVarP(&opts.format, "format", "f", "", "Format the output using the given go template") <add> cmd.Flags().StringVarP(&opts.format, "format", "f", "", "Format the output using the given Go template") <ide> <ide> return cmd <ide> } <ide><path>cli/command/node/inspect.go <ide> func newInspectCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> } <ide> <ide> flags := cmd.Flags() <del> flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given go template") <add> flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given Go template") <ide> flags.BoolVar(&opts.pretty, "pretty", false, "Print the information in a human friendly format.") <ide> return cmd <ide> } <ide><path>cli/command/plugin/inspect.go <ide> func newInspectCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> } <ide> <ide> flags := cmd.Flags() <del> flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given go template") <add> flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given Go template") <ide> return cmd <ide> } <ide> <ide><path>cli/command/service/inspect.go <ide> func newInspectCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> } <ide> <ide> flags := cmd.Flags() <del> flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given go template") <add> flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given Go template") <ide> flags.BoolVar(&opts.pretty, "pretty", false, "Print the information in a human friendly format.") <ide> return cmd <ide> } <ide><path>cli/command/system/events.go <ide> func NewEventsCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> flags.StringVar(&opts.since, "since", "", "Show all events created since timestamp") <ide> flags.StringVar(&opts.until, "until", "", "Stream events until this timestamp") <ide> flags.VarP(&opts.filter, "filter", "f", "Filter output based on conditions provided") <del> flags.StringVar(&opts.format, "format", "", "Format the output using the given go template") <add> flags.StringVar(&opts.format, "format", "", "Format the output using the given Go template") <ide> <ide> return cmd <ide> } <ide><path>cli/command/system/info.go <ide> func NewInfoCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> <ide> flags := cmd.Flags() <ide> <del> flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given go template") <add> flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given Go template") <ide> <ide> return cmd <ide> } <ide><path>cli/command/system/inspect.go <ide> func NewInspectCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> } <ide> <ide> flags := cmd.Flags() <del> flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given go template") <add> flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given Go template") <ide> flags.StringVar(&opts.inspectType, "type", "", "Return JSON for specified type") <ide> flags.BoolVarP(&opts.size, "size", "s", false, "Display total file sizes if the type is container") <ide> <ide><path>cli/command/system/version.go <ide> func NewVersionCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> <ide> flags := cmd.Flags() <ide> <del> flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given go template") <add> flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given Go template") <ide> <ide> return cmd <ide> } <ide><path>cli/command/volume/inspect.go <ide> func newInspectCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> }, <ide> } <ide> <del> cmd.Flags().StringVarP(&opts.format, "format", "f", "", "Format the output using the given go template") <add> cmd.Flags().StringVarP(&opts.format, "format", "f", "", "Format the output using the given Go template") <ide> <ide> return cmd <ide> } <ide><path>docs/reference/commandline/events.md <ide> Get real time events from the server <ide> <ide> Options: <ide> -f, --filter value Filter output based on conditions provided (default []) <del> --format string Format the output using the given go template <add> --format string Format the output using the given Go template <ide> --help Print usage <ide> --since string Show all events created since timestamp <ide> --until string Stream events until this timestamp <ide><path>docs/reference/commandline/info.md <ide> Usage: docker info [OPTIONS] <ide> Display system-wide information <ide> <ide> Options: <del> -f, --format string Format the output using the given go template <add> -f, --format string Format the output using the given Go template <ide> --help Print usage <ide> ``` <ide> <ide><path>docs/reference/commandline/inspect.md <ide> Return low-level information on one or multiple containers, images, volumes, <ide> networks, nodes, services, or tasks identified by name or ID. <ide> <ide> Options: <del> -f, --format Format the output using the given go template <add> -f, --format Format the output using the given Go template <ide> --help Print usage <ide> -s, --size Display total file sizes if the type is container <ide> values are "image" or "container" or "task <ide><path>docs/reference/commandline/network_inspect.md <ide> Usage: docker network inspect [OPTIONS] NETWORK [NETWORK...] <ide> Display detailed information on one or more networks <ide> <ide> Options: <del> -f, --format string Format the output using the given go template <add> -f, --format string Format the output using the given Go template <ide> --help Print usage <ide> ``` <ide> <ide><path>docs/reference/commandline/node_inspect.md <ide> Usage: docker node inspect [OPTIONS] self|NODE [NODE...] <ide> Display detailed information on one or more nodes <ide> <ide> Options: <del> -f, --format string Format the output using the given go template <add> -f, --format string Format the output using the given Go template <ide> --help Print usage <ide> --pretty Print the information in a human friendly format. <ide> ``` <ide><path>docs/reference/commandline/plugin_inspect.md <ide> Usage: docker plugin inspect [OPTIONS] PLUGIN [PLUGIN...] <ide> Display detailed information on one or more plugins <ide> <ide> Options: <del> -f, --format string Format the output using the given go template <add> -f, --format string Format the output using the given Go template <ide> --help Print usage <ide> ``` <ide> <ide><path>docs/reference/commandline/service_inspect.md <ide> Usage: docker service inspect [OPTIONS] SERVICE [SERVICE...] <ide> Display detailed information on one or more services <ide> <ide> Options: <del> -f, --format string Format the output using the given go template <add> -f, --format string Format the output using the given Go template <ide> --help Print usage <ide> --pretty Print the information in a human friendly format. <ide> ``` <ide><path>docs/reference/commandline/system_prune.md <ide> Total reclaimed space: 13.5 MB <ide> * [volume ls](volume_ls.md) <ide> * [volume inspect](volume_inspect.md) <ide> * [volume rm](volume_rm.md) <add>* [volume prune](volume_prune.md) <ide> * [Understand Data Volumes](../../tutorials/dockervolumes.md) <ide> * [system df](system_df.md) <ide> * [container prune](container_prune.md) <ide><path>docs/reference/commandline/version.md <ide> Usage: docker version [OPTIONS] <ide> Show the Docker version information <ide> <ide> Options: <del> -f, --format string Format the output using the given go template <add> -f, --format string Format the output using the given Go template <ide> --help Print usage <ide> ``` <ide> <ide><path>docs/reference/commandline/volume_create.md <ide> $ docker volume create --driver local --opt type=nfs --opt o=addr=192.168.1.1,rw <ide> * [volume inspect](volume_inspect.md) <ide> * [volume ls](volume_ls.md) <ide> * [volume rm](volume_rm.md) <add>* [volume prune](volume_prune.md) <ide> * [Understand Data Volumes](../../tutorials/dockervolumes.md) <ide><path>docs/reference/commandline/volume_inspect.md <ide> Usage: docker volume inspect [OPTIONS] VOLUME [VOLUME...] <ide> Display detailed information on one or more volumes <ide> <ide> Options: <del> -f, --format string Format the output using the given go template <add> -f, --format string Format the output using the given Go template <ide> --help Print usage <ide> ``` <ide> <ide> Example output: <ide> * [volume create](volume_create.md) <ide> * [volume ls](volume_ls.md) <ide> * [volume rm](volume_rm.md) <add>* [volume prune](volume_prune.md) <ide> * [Understand Data Volumes](../../tutorials/dockervolumes.md) <ide><path>docs/reference/commandline/volume_ls.md <ide> Options: <ide> -q, --quiet Only display volume names <ide> ``` <ide> <del>Lists all the volumes Docker knows about. You can filter using the `-f` or `--filter` flag. Refer to the [filtering](#filtering) section for more information about available filter options. <add>List all the volumes Docker knows about. You can filter using the `-f` or `--filter` flag. Refer to the [filtering](#filtering) section for more information about available filter options. <ide> <ide> Example output: <ide> <ide> vol3: local <ide> * [volume create](volume_create.md) <ide> * [volume inspect](volume_inspect.md) <ide> * [volume rm](volume_rm.md) <add>* [volume prune](volume_prune.md) <ide> * [Understand Data Volumes](../../tutorials/dockervolumes.md) <ide><path>docs/reference/commandline/volume_rm.md <ide> Remove one or more volumes. You cannot remove a volume that is in use by a conta <ide> * [volume create](volume_create.md) <ide> * [volume inspect](volume_inspect.md) <ide> * [volume ls](volume_ls.md) <add>* [volume prune](volume_prune.md) <ide> * [Understand Data Volumes](../../tutorials/dockervolumes.md) <ide><path>man/docker-events.1.md <ide> Docker networks report the following events: <ide> Stream events until this timestamp <ide> <ide> **--format**="" <del> Format the output using the given go template <add> Format the output using the given Go template <ide> <ide> The `--since` and `--until` parameters can be Unix timestamps, date formatted <ide> timestamps, or Go duration strings (e.g. `10m`, `1h30m`) computed <ide><path>man/docker-info.1.md <ide> available on the volume where `/var/lib/docker` is mounted. <ide> Print usage statement <ide> <ide> **-f**, **--format**="" <del> Format the output using the given go template <add> Format the output using the given Go template <ide> <ide> # EXAMPLES <ide> <ide><path>man/docker-network-inspect.1.md <ide> $ docker network inspect simple-network <ide> <ide> # OPTIONS <ide> **-f**, **--format**="" <del> Format the output using the given go template. <add> Format the output using the given Go template. <ide> <ide> **--help** <ide> Print usage statement <ide><path>man/docker-version.1.md <ide> daemon. <ide> Print usage statement <ide> <ide> **-f**, **--format**="" <del> Format the output using the given go template. <add> Format the output using the given Go template. <ide> <ide> # EXAMPLES <ide>
28
PHP
PHP
add a comment
10c405725f153670645d5b5657965698149a8f34
<ide><path>src/Illuminate/Foundation/Bootstrap/ConfigureLogging.php <ide> class ConfigureLogging { <ide> */ <ide> public function bootstrap(Application $app) <ide> { <del> $app->instance('log', new Writer(new Monolog($app->environment()), $app['events'])); <add> $app->instance('log', new Writer( <add> new Monolog($app->environment()), $app['events']) <add> ); <ide> <add> // Next we will bind the a Closure to resolve the PSR logger implementation <add> // as this will grant us the ability to be interoperable with many other <add> // libraries which are able to utilize the PSR standardized interface. <ide> $app->bind('Psr\Log\LoggerInterface', function() <ide> { <ide> return $app['log']->getMonolog();
1
Javascript
Javascript
stop caching colorscheme in js
f15309fa15fbbda2feeee2820d3f0d69e3712afd
<ide><path>Libraries/Utilities/Appearance.js <ide> import invariant from 'invariant'; <ide> type AppearanceListener = (preferences: AppearancePreferences) => void; <ide> const eventEmitter = new EventEmitter(); <ide> <del>// TODO: (hramos) T52919652 Use ?ColorSchemeName once codegen supports union <del>const nativeColorScheme: ?string = <del> NativeAppearance == null ? null : NativeAppearance.getColorScheme() || null; <del>invariant( <del> nativeColorScheme === 'dark' || <del> nativeColorScheme === 'light' || <del> nativeColorScheme == null, <del> "Unrecognized color scheme. Did you mean 'dark' or 'light'?", <del>); <del> <del>let currentColorScheme: ?ColorSchemeName = nativeColorScheme; <del> <ide> if (NativeAppearance) { <ide> const nativeEventEmitter = new NativeEventEmitter(NativeAppearance); <ide> nativeEventEmitter.addListener( <ide> if (NativeAppearance) { <ide> colorScheme == null, <ide> "Unrecognized color scheme. Did you mean 'dark' or 'light'?", <ide> ); <del> currentColorScheme = colorScheme; <ide> eventEmitter.emit('change', {colorScheme}); <ide> }, <ide> ); <ide> module.exports = { <ide> * @returns {?ColorSchemeName} Value for the color scheme preference. <ide> */ <ide> getColorScheme(): ?ColorSchemeName { <del> return currentColorScheme; <add> // TODO: (hramos) T52919652 Use ?ColorSchemeName once codegen supports union <add> const nativeColorScheme: ?string = <add> NativeAppearance == null <add> ? null <add> : NativeAppearance.getColorScheme() || null; <add> invariant( <add> nativeColorScheme === 'dark' || <add> nativeColorScheme === 'light' || <add> nativeColorScheme == null, <add> "Unrecognized color scheme. Did you mean 'dark' or 'light'?", <add> ); <add> return nativeColorScheme; <ide> }, <ide> /** <ide> * Add an event handler that is fired when appearance preferences change.
1
Go
Go
fix empty-lines (revive)
cd51c9fafbce704e1246102b3214ff731e0f4c2f
<ide><path>client/events.go <ide> import ( <ide> // be sent over the error channel. If an error is sent all processing will be stopped. It's up <ide> // to the caller to reopen the stream in the event of an error by reinvoking this method. <ide> func (cli *Client) Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error) { <del> <ide> messages := make(chan events.Message) <ide> errs := make(chan error, 1) <ide> <ide><path>client/events_test.go <ide> func TestEventsErrorFromServer(t *testing.T) { <ide> } <ide> <ide> func TestEvents(t *testing.T) { <del> <ide> expectedURL := "/events" <ide> <ide> filters := filters.NewArgs()
2
Java
Java
support custom fonts for flat react rendering
1a2cf776af55d3f8279ee2f14814bd94100f9739
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatUIImplementation.java <ide> <ide> package com.facebook.react.flat; <ide> <add>import javax.annotation.Nullable; <add> <ide> import java.util.ArrayList; <ide> import java.util.List; <ide> <del>import javax.annotation.Nullable; <del> <del>import com.facebook.csslayout.CSSNode; <ide> import com.facebook.react.bridge.ReactApplicationContext; <ide> import com.facebook.react.bridge.ReadableArray; <ide> import com.facebook.react.uimanager.CatalystStylesDiffMap; <del>import com.facebook.react.uimanager.NativeViewHierarchyManager; <ide> import com.facebook.react.uimanager.ReactShadowNode; <del>import com.facebook.react.uimanager.ThemedReactContext; <ide> import com.facebook.react.uimanager.UIImplementation; <del>import com.facebook.react.uimanager.UIViewOperationQueue; <ide> import com.facebook.react.uimanager.ViewManager; <ide> import com.facebook.react.uimanager.ViewManagerRegistry; <ide> import com.facebook.react.uimanager.events.EventDispatcher; <ide> public static FlatUIImplementation createInstance( <ide> viewManagers.add(new RCTTextManager()); <ide> viewManagers.add(new RCTRawTextManager()); <ide> viewManagers.add(new RCTVirtualTextManager()); <add> TypefaceCache.setAssetManager(reactContext.getAssets()); <ide> <ide> ViewManagerRegistry viewManagerRegistry = new ViewManagerRegistry(viewManagers); <ide> FlatNativeViewHierarchyManager nativeViewHierarchyManager = new FlatNativeViewHierarchyManager( <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/TypefaceCache.java <ide> <ide> package com.facebook.react.flat; <ide> <add>import javax.annotation.Nullable; <add> <ide> import java.util.HashMap; <ide> <add>import android.content.res.AssetManager; <ide> import android.graphics.Typeface; <ide> <add>import com.facebook.infer.annotation.Assertions; <add> <ide> /** <ide> * TypefaceCache provides methods to resolve typeface from font family, or existing typeface <ide> * with a different style. <ide> private static final HashMap<String, Typeface[]> FONTFAMILY_CACHE = new HashMap<>(); <ide> private static final HashMap<Typeface, Typeface[]> TYPEFACE_CACHE = new HashMap<>(); <ide> <del> /** <del> * Returns a Typeface for a given a FontFamily and style. <del> */ <add> private static final String[] EXTENSIONS = { <add> "", <add> "_bold", <add> "_italic", <add> "_bold_italic"}; <add> private static final String[] FILE_EXTENSIONS = {".ttf", ".otf"}; <add> private static final String FONTS_ASSET_PATH = "fonts/"; <add> <add> @Nullable private static AssetManager sAssetManager = null; <add> <add> public static void setAssetManager(AssetManager assetManager) { <add> sAssetManager = assetManager; <add> } <add> <ide> public static Typeface getTypeface(String fontFamily, int style) { <ide> Typeface[] cache = FONTFAMILY_CACHE.get(fontFamily); <ide> if (cache == null) { <ide> public static Typeface getTypeface(String fontFamily, int style) { <ide> return cache[style]; <ide> } <ide> <del> Typeface typeface = Typeface.create(fontFamily, style); <add> Typeface typeface = createTypeface(fontFamily, style); <ide> cache[style] = typeface; <ide> TYPEFACE_CACHE.put(typeface, cache); <ide> return typeface; <ide> } <ide> <add> private static Typeface createTypeface(String fontFamilyName, int style) { <add> String extension = EXTENSIONS[style]; <add> StringBuilder fileNameBuffer = new StringBuilder(32) <add> .append(FONTS_ASSET_PATH) <add> .append(fontFamilyName) <add> .append(extension); <add> int length = fileNameBuffer.length(); <add> for (String fileExtension : FILE_EXTENSIONS) { <add> String fileName = fileNameBuffer.append(fileExtension).toString(); <add> try { <add> return Typeface.createFromAsset(sAssetManager, fileName); <add> } catch (RuntimeException e) { <add> // unfortunately Typeface.createFromAsset throws an exception instead of returning null <add> // if the typeface doesn't exist <add> fileNameBuffer.setLength(length); <add> } <add> } <add> return Assertions.assumeNotNull(Typeface.create(fontFamilyName, style)); <add> } <add> <ide> /** <ide> * Returns a derivative of a given Typeface with a different style. <ide> */
2
Javascript
Javascript
remove unnecessary variable from test
323789540a6de11f3777be6a92317d53a905530c
<ide><path>src/browser/server/__tests__/ReactServerRendering-test.js <ide> describe('ReactServerRendering', function() { <ide> <ide> describe('renderToStaticMarkup', function() { <ide> it('should not put checksum and React ID on components', function() { <del> var lifecycle = []; <ide> var NestedComponent = React.createClass({ <ide> render: function() { <ide> return <div>inner text</div>; <ide> describe('ReactServerRendering', function() { <ide> <ide> var TestComponent = React.createClass({ <ide> render: function() { <del> lifecycle.push('render'); <ide> return <span><NestedComponent /></span>; <ide> } <ide> });
1
Python
Python
correct an issue on unicode for python 3
67485845bfc27353491fe04cc085182204d4f525
<ide><path>glances/plugins/glances_fs.py <ide> def update(self): <ide> 'device_name': fs.device, <ide> 'fs_type': fs.fstype, <ide> # Manage non breaking space (see issue #1065) <del> 'mnt_point': unicode(fs.mountpoint, 'utf-8').replace(u'\u00A0', ' '), <add> 'mnt_point': fs.mountpoint.replace(u'\u00A0', ' '), <ide> 'size': fs_usage.total, <ide> 'used': fs_usage.used, <ide> 'free': fs_usage.free,
1
PHP
PHP
check datatype correctly in postgresgrammar
d8e3a500a9bbdbf47a4fd2798da0a85636da56f2
<ide><path>src/Illuminate/Database/Query/Grammars/PostgresGrammar.php <ide> protected function compileUpdateJoinWheres(Builder $query) <ide> public function prepareBindingsForUpdate(array $bindings, array $values) <ide> { <ide> $values = collect($values)->map(function ($value, $column) { <del> return $this->isJsonSelector($column) && ! $this->isExpression($value) <add> return ! $this->isExpression($value) && ($this->isJsonSelector($column) || is_array($value) || is_object($value)) <ide> ? json_encode($value) <ide> : $value; <ide> })->all();
1
Python
Python
change api of reshape layer
7219bb4b964249a515b05b0ee872019bbe9b64ff
<ide><path>keras/layers/core.py <ide> class Reshape(Layer): <ide> Can't be used as first layer in a model (no fixed input!) <ide> First dimension is assumed to be nb_samples. <ide> ''' <del> def __init__(self, *dims): <add> def __init__(self, dims): <ide> super(Reshape, self).__init__() <del> if type(dims[0]) in [list, tuple]: <del> dims = dims[0] <ide> self.dims = tuple(dims) <ide> <ide> @property <ide> def output_shape(self): <del> return make_tuple(self.input_shape[0], *self.dims) <add> return (self.input_shape[0],) + self.dims <ide> <ide> def get_output(self, train=False): <ide> X = self.get_input(train) <del> nshape = make_tuple(X.shape[0], *self.dims) <del> return theano.tensor.reshape(X, nshape) <add> new_shape = (X.shape[0],) + self.dims <add> return theano.tensor.reshape(X, new_shape) <ide> <ide> def get_config(self): <ide> return {"name": self.__class__.__name__,
1
Javascript
Javascript
update error name
1ed3c54ecbd72a33693e5954f86bcc9fd9b1cc09
<ide><path>lib/internal/assert/assertion_error.js <ide> class AssertionError extends Error { <ide> } <ide> <ide> this.generatedMessage = !message; <del> this.name = 'AssertionError [ERR_ASSERTION]'; <add> Object.defineProperty(this, 'name', { <add> value: 'AssertionError [ERR_ASSERTION]', <add> enumerable: false, <add> writable: true, <add> configurable: true <add> }); <ide> this.code = 'ERR_ASSERTION'; <ide> this.actual = actual; <ide> this.expected = expected; <ide> this.operator = operator; <ide> Error.captureStackTrace(this, stackStartFn); <add> // Create error message including the error code in the name. <add> this.stack; <add> // Reset the name. <add> this.name = 'AssertionError'; <add> } <add> <add> toString() { <add> return `${this.name} [${this.code}]: ${this.message}`; <ide> } <ide> <ide> [inspect.custom](recurseTimes, ctx) { <ide><path>lib/internal/errors.js <ide> const codes = {}; <ide> const { kMaxLength } = internalBinding('buffer'); <ide> const { defineProperty } = Object; <ide> <add>let useOriginalName = false; <add> <ide> // Lazily loaded <ide> let util; <ide> let assert; <ide> class SystemError extends Error { <ide> value: key, <ide> writable: true <ide> }); <del> } <del> <del> get name() { <del> return `SystemError [${this[kCode]}]`; <del> } <del> <del> set name(value) { <del> defineProperty(this, 'name', { <del> configurable: true, <del> enumerable: true, <del> value, <del> writable: true <del> }); <add> addCodeToName(this, 'SystemError', key); <ide> } <ide> <ide> get code() { <ide> class SystemError extends Error { <ide> this[kInfo].dest = val ? <ide> lazyBuffer().from(val.toString()) : undefined; <ide> } <add> <add> toString() { <add> return `${this.name} [${this.code}]: ${this.message}`; <add> } <ide> } <ide> <ide> function makeSystemErrorWithCode(key) { <ide> function makeSystemErrorWithCode(key) { <ide> }; <ide> } <ide> <del>let useOriginalName = false; <del> <ide> function makeNodeErrorWithCode(Base, key) { <ide> return class NodeError extends Base { <ide> constructor(...args) { <ide> function makeNodeErrorWithCode(Base, key) { <ide> writable: true, <ide> configurable: true <ide> }); <del> } <del> <del> get name() { <del> if (useOriginalName) { <del> return super.name; <del> } <del> return `${super.name} [${key}]`; <del> } <del> <del> set name(value) { <del> defineProperty(this, 'name', { <del> configurable: true, <del> enumerable: true, <del> value, <del> writable: true <del> }); <add> addCodeToName(this, super.name, key); <ide> } <ide> <ide> get code() { <ide> function makeNodeErrorWithCode(Base, key) { <ide> writable: true <ide> }); <ide> } <add> <add> toString() { <add> return `${this.name} [${key}]: ${this.message}`; <add> } <ide> }; <ide> } <ide> <add>function addCodeToName(err, name, code) { <add> if (useOriginalName) { <add> return; <add> } <add> // Add the error code to the name to include it in the stack trace. <add> err.name = `${name} [${code}]`; <add> // Access the stack to generate the error message including the error code <add> // from the name. <add> err.stack; <add> // Reset the name to the actual name. <add> if (name === 'SystemError') { <add> defineProperty(err, 'name', { <add> value: name, <add> enumerable: false, <add> writable: true, <add> configurable: true <add> }); <add> } else { <add> delete err.name; <add> } <add>} <add> <ide> // Utility function for registering the error codes. Only used here. Exported <ide> // *only* to allow for testing. <ide> function E(sym, val, def, ...otherClasses) { <ide><path>lib/internal/http2/util.js <ide> class NghttpError extends Error { <ide> this.code = 'ERR_HTTP2_ERROR'; <ide> this.name = 'Error [ERR_HTTP2_ERROR]'; <ide> this.errno = ret; <add> this.stack; <add> delete this.name; <add> } <add> <add> toString() { <add> return `${this.name} [${this.code}]: ${this.message}`; <ide> } <ide> } <ide> <ide><path>test/parallel/test-assert-async.js <ide> const promises = []; <ide> const rejectingFn = async () => assert.fail(); <ide> const errObj = { <ide> code: 'ERR_ASSERTION', <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: 'Failed' <ide> }; <ide> // `assert.rejects` accepts a function or a promise as first argument. <ide> const promises = []; <ide> <ide> promise = assert.rejects(() => {}, common.mustNotCall()); <ide> promises.push(assert.rejects(promise, { <del> name: 'TypeError [ERR_INVALID_RETURN_VALUE]', <add> name: 'TypeError', <ide> code: 'ERR_INVALID_RETURN_VALUE', <ide> message: 'Expected instance of Promise to be returned ' + <ide> 'from the "promiseFn" function but got type undefined.' <ide> promises.push(assert.rejects( <ide> message: 'Expected instance of Promise to be returned ' + <ide> 'from the "promiseFn" function but got instance of Map.', <ide> code: 'ERR_INVALID_RETURN_VALUE', <del> name: 'TypeError [ERR_INVALID_RETURN_VALUE]' <add> name: 'TypeError' <ide> })); <ide> promises.push(assert.doesNotReject(async () => {})); <ide> promises.push(assert.doesNotReject(Promise.resolve())); <ide><path>test/parallel/test-assert-deep.js <ide> assert.throws( <ide> assert.throws( <ide> () => assert.notDeepStrictEqual(new Date(2000, 3, 14), new Date(2000, 3, 14)), <ide> { <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: 'Expected "actual" not to be strictly deep-equal to: ' + <ide> util.inspect(new Date(2000, 3, 14)) <ide> } <ide> assert.throws( <ide> () => assert.deepStrictEqual(/ab/, /a/), <ide> { <ide> code: 'ERR_ASSERTION', <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: `${defaultMsgStartFull}\n\n+ /ab/\n- /a/` <ide> }); <ide> assert.throws( <ide> () => assert.deepStrictEqual(/a/g, /a/), <ide> { <ide> code: 'ERR_ASSERTION', <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: `${defaultMsgStartFull}\n\n+ /a/g\n- /a/` <ide> }); <ide> assert.throws( <ide> () => assert.deepStrictEqual(/a/i, /a/), <ide> { <ide> code: 'ERR_ASSERTION', <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: `${defaultMsgStartFull}\n\n+ /a/i\n- /a/` <ide> }); <ide> assert.throws( <ide> () => assert.deepStrictEqual(/a/m, /a/), <ide> { <ide> code: 'ERR_ASSERTION', <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: `${defaultMsgStartFull}\n\n+ /a/m\n- /a/` <ide> }); <ide> assert.throws( <ide> () => assert.deepStrictEqual(/a/igm, /a/im), <ide> { <ide> code: 'ERR_ASSERTION', <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: `${defaultMsgStartFull}\n\n+ /a/gim\n- /a/im\n ^` <ide> }); <ide> <ide> assert.deepStrictEqual({ a: 4, b: '2' }, { a: 4, b: '2' }); <ide> assert.throws(() => assert.deepStrictEqual([4], ['4']), <ide> { <ide> code: 'ERR_ASSERTION', <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: `${defaultMsgStartFull}\n\n [\n+ 4\n- '4'\n ]` <ide> }); <ide> assert.throws( <ide> () => assert.deepStrictEqual({ a: 4 }, { a: 4, b: true }), <ide> { <ide> code: 'ERR_ASSERTION', <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: `${defaultMsgStartFull}\n\n ` + <ide> '{\n a: 4,\n- b: true\n }' <ide> }); <ide> assert.throws( <ide> () => assert.deepStrictEqual(['a'], { 0: 'a' }), <ide> { <ide> code: 'ERR_ASSERTION', <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: `${defaultMsgStartFull}\n\n` + <ide> "+ [\n+ 'a'\n+ ]\n- {\n- '0': 'a'\n- }" <ide> }); <ide> assert.deepStrictEqual(obj1, obj2); <ide> () => assert.deepStrictEqual(a, b), <ide> { <ide> code: 'ERR_ASSERTION', <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: /\.\.\./g <ide> } <ide> ); <ide> assert.throws( <ide> () => assert.deepStrictEqual([1, 2, 3], [1, 2]), <ide> { <ide> code: 'ERR_ASSERTION', <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: `${defaultMsgStartFull}\n\n` + <ide> ' [\n' + <ide> ' 1,\n' + <ide> assert.throws( <ide> () => assert.deepStrictEqual(a, b), <ide> { <ide> code: 'ERR_ASSERTION', <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: /a: \[Getter: 5]\n- a: \[Getter: 6]\n / <ide> } <ide> ); <ide><path>test/parallel/test-assert-fail-deprecation.js <ide> assert.throws(() => { <ide> assert.fail('first', 'second'); <ide> }, { <ide> code: 'ERR_ASSERTION', <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: '\'first\' != \'second\'', <ide> operator: '!=', <ide> actual: 'first', <ide> assert.throws(() => { <ide> assert.fail('ignored', 'ignored', 'another custom message'); <ide> }, { <ide> code: 'ERR_ASSERTION', <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: 'another custom message', <ide> operator: 'fail', <ide> actual: 'ignored', <ide> assert.throws(() => { <ide> assert.fail('first', 'second', undefined, 'operator'); <ide> }, { <ide> code: 'ERR_ASSERTION', <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: '\'first\' operator \'second\'', <ide> operator: 'operator', <ide> actual: 'first', <ide><path>test/parallel/test-assert-fail.js <ide> assert.throws( <ide> () => { assert.fail(); }, <ide> { <ide> code: 'ERR_ASSERTION', <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: 'Failed', <ide> operator: 'fail', <ide> actual: undefined, <ide> assert.throws(() => { <ide> assert.fail('custom message'); <ide> }, { <ide> code: 'ERR_ASSERTION', <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: 'custom message', <ide> operator: 'fail', <ide> actual: undefined, <ide><path>test/parallel/test-assert-first-line.js <ide> const { path } = require('../common/fixtures'); <ide> assert.throws( <ide> () => require(path('assert-first-line')), <ide> { <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: "The expression evaluated to a falsy value:\n\n ässört.ok('')\n" <ide> } <ide> ); <ide> <ide> assert.throws( <ide> () => require(path('assert-long-line')), <ide> { <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: "The expression evaluated to a falsy value:\n\n assert.ok('')\n" <ide> } <ide> ); <ide><path>test/parallel/test-assert.js <ide> assert.throws( <ide> () => a.notStrictEqual(2, 2), <ide> { <ide> message: 'Expected "actual" to be strictly unequal to: 2', <del> name: 'AssertionError [ERR_ASSERTION]' <add> name: 'AssertionError' <ide> } <ide> ); <ide> <ide> assert.throws( <ide> { <ide> message: 'Expected "actual" to be strictly unequal to: ' + <ide> `'${'a '.repeat(30)}'`, <del> name: 'AssertionError [ERR_ASSERTION]' <add> name: 'AssertionError' <ide> } <ide> ); <ide> <ide> assert.throws(() => thrower(TypeError)); <ide> assert.throws( <ide> () => a.doesNotThrow(() => thrower(Error), 'user message'), <ide> { <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> code: 'ERR_ASSERTION', <ide> operator: 'doesNotThrow', <ide> message: 'Got unwanted exception: user message\n' + <ide> assert.throws(() => { <ide> () => new assert.AssertionError(input), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "options" argument must be of type Object. ' + <ide> `Received type ${typeof input}` <ide> }); <ide> assert.throws( <ide> () => assert.strictEqual(new Error('foo'), new Error('foobar')), <ide> { <ide> code: 'ERR_ASSERTION', <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: 'Expected "actual" to be reference-equal to "expected":\n' + <ide> '+ actual - expected\n\n' + <ide> '+ [Error: foo]\n- [Error: foobar]' <ide> assert.throws( <ide> () => assert(...[]), <ide> { <ide> message: 'No value argument passed to `assert.ok()`', <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> generatedMessage: true <ide> } <ide> ); <ide> assert.throws( <ide> () => a(), <ide> { <ide> message: 'No value argument passed to `assert.ok()`', <del> name: 'AssertionError [ERR_ASSERTION]' <add> name: 'AssertionError' <ide> } <ide> ); <ide> <ide> common.expectsError( <ide> () => assert.throws(errFn, errObj), <ide> { <ide> code: 'ERR_ASSERTION', <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: `${start}\n${actExp}\n\n` + <ide> ' Comparison {\n' + <ide> ' code: 404,\n' + <ide> common.expectsError( <ide> () => assert.throws(errFn, errObj), <ide> { <ide> code: 'ERR_ASSERTION', <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: `${start}\n${actExp}\n\n` + <ide> ' Comparison {\n' + <ide> '+ code: 404,\n' + <ide> common.expectsError( <ide> assert.throws( <ide> () => assert.throws(() => { throw new TypeError('e'); }, new Error('e')), <ide> { <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> code: 'ERR_ASSERTION', <ide> message: `${start}\n${actExp}\n\n` + <ide> ' Comparison {\n' + <ide> common.expectsError( <ide> assert.throws( <ide> () => assert.throws(() => { throw new Error('foo'); }, new Error('')), <ide> { <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> code: 'ERR_ASSERTION', <ide> generatedMessage: true, <ide> message: `${start}\n${actExp}\n\n` + <ide> common.expectsError( <ide> // eslint-disable-next-line no-throw-literal <ide> () => a.doesNotThrow(() => { throw undefined; }), <ide> { <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> code: 'ERR_ASSERTION', <ide> message: 'Got unwanted exception.\nActual message: "undefined"' <ide> } <ide> assert.throws( <ide> () => assert.strictEqual('test test', 'test foobar'), <ide> { <ide> code: 'ERR_ASSERTION', <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: strictEqualMessageStart + <ide> '+ actual - expected\n\n' + <ide> "+ 'test test'\n" + <ide> assert.throws( <ide> }, <ide> { <ide> code: 'ERR_ASSERTION', <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: 'Expected "actual" not to be reference-equal to "expected": {}' <ide> } <ide> ); <ide> assert.throws( <ide> }, <ide> { <ide> code: 'ERR_ASSERTION', <del> name: 'AssertionError [ERR_ASSERTION]', <add> name: 'AssertionError', <ide> message: 'Expected "actual" not to be reference-equal to "expected":\n\n' + <ide> '{\n a: true\n}\n' <ide> } <ide><path>test/parallel/test-buffer-alloc.js <ide> common.expectsError( <ide> }); <ide> <ide> assert.throws(() => Buffer.from(), { <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The first argument must be one of type string, Buffer, ' + <ide> 'ArrayBuffer, Array, or Array-like Object. Received type undefined' <ide> }); <ide> assert.throws(() => Buffer.from(null), { <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The first argument must be one of type string, Buffer, ' + <ide> 'ArrayBuffer, Array, or Array-like Object. Received type object' <ide> }); <ide><path>test/parallel/test-buffer-arraybuffer.js <ide> assert.throws(function() { <ide> Buffer.from(new AB()); <ide> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The first argument must be one of type string, Buffer,' + <ide> ' ArrayBuffer, Array, or Array-like Object. Received type object' <ide> }); <ide> assert.throws(function() { <ide> <ide> assert.throws(() => Buffer.from(ab.buffer, 6), { <ide> code: 'ERR_BUFFER_OUT_OF_BOUNDS', <del> name: 'RangeError [ERR_BUFFER_OUT_OF_BOUNDS]', <add> name: 'RangeError', <ide> message: '"offset" is outside of buffer bounds' <ide> }); <ide> assert.throws(() => Buffer.from(ab.buffer, 3, 6), { <ide> code: 'ERR_BUFFER_OUT_OF_BOUNDS', <del> name: 'RangeError [ERR_BUFFER_OUT_OF_BOUNDS]', <add> name: 'RangeError', <ide> message: '"length" is outside of buffer bounds' <ide> }); <ide> } <ide> assert.throws(function() { <ide> <ide> assert.throws(() => Buffer(ab.buffer, 6), { <ide> code: 'ERR_BUFFER_OUT_OF_BOUNDS', <del> name: 'RangeError [ERR_BUFFER_OUT_OF_BOUNDS]', <add> name: 'RangeError', <ide> message: '"offset" is outside of buffer bounds' <ide> }); <ide> assert.throws(() => Buffer(ab.buffer, 3, 6), { <ide> code: 'ERR_BUFFER_OUT_OF_BOUNDS', <del> name: 'RangeError [ERR_BUFFER_OUT_OF_BOUNDS]', <add> name: 'RangeError', <ide> message: '"length" is outside of buffer bounds' <ide> }); <ide> } <ide> assert.throws(function() { <ide> Buffer.from(ab, Infinity); <ide> }, { <ide> code: 'ERR_BUFFER_OUT_OF_BOUNDS', <del> name: 'RangeError [ERR_BUFFER_OUT_OF_BOUNDS]', <add> name: 'RangeError', <ide> message: '"offset" is outside of buffer bounds' <ide> }); <ide> } <ide> assert.throws(function() { <ide> Buffer.from(ab, 0, Infinity); <ide> }, { <ide> code: 'ERR_BUFFER_OUT_OF_BOUNDS', <del> name: 'RangeError [ERR_BUFFER_OUT_OF_BOUNDS]', <add> name: 'RangeError', <ide> message: '"length" is outside of buffer bounds' <ide> }); <ide> } <ide><path>test/parallel/test-buffer-read.js <ide> read(buf, 'readUIntLE', [2, 2], 0xea48); <ide> // Error name and message <ide> const OOR_ERROR = <ide> { <del> name: 'RangeError [ERR_OUT_OF_RANGE]' <add> name: 'RangeError' <ide> }; <ide> <ide> const OOB_ERROR = <ide> { <del> name: 'RangeError [ERR_BUFFER_OUT_OF_BOUNDS]', <add> name: 'RangeError', <ide> message: 'Attempt to write outside buffer bounds' <ide> }; <ide> <ide><path>test/parallel/test-buffer-readdouble.js <ide> assert.strictEqual(buffer.readDoubleLE(0), -Infinity); <ide> () => buffer[fn](offset), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "offset" is out of range. ' + <ide> `It must be >= 0 and <= 0. Received ${offset}` <ide> }); <ide> assert.strictEqual(buffer.readDoubleLE(0), -Infinity); <ide> () => Buffer.alloc(1)[fn](1), <ide> { <ide> code: 'ERR_BUFFER_OUT_OF_BOUNDS', <del> name: 'RangeError [ERR_BUFFER_OUT_OF_BOUNDS]', <add> name: 'RangeError', <ide> message: 'Attempt to write outside buffer bounds' <ide> }); <ide> <ide> assert.strictEqual(buffer.readDoubleLE(0), -Infinity); <ide> () => buffer[fn](offset), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "offset" is out of range. ' + <ide> `It must be an integer. Received ${offset}` <ide> }); <ide><path>test/parallel/test-buffer-readfloat.js <ide> assert.strictEqual(buffer.readFloatLE(0), -Infinity); <ide> () => buffer[fn](offset), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "offset" is out of range. ' + <ide> `It must be >= 0 and <= 0. Received ${offset}` <ide> }); <ide> assert.strictEqual(buffer.readFloatLE(0), -Infinity); <ide> () => Buffer.alloc(1)[fn](1), <ide> { <ide> code: 'ERR_BUFFER_OUT_OF_BOUNDS', <del> name: 'RangeError [ERR_BUFFER_OUT_OF_BOUNDS]', <add> name: 'RangeError', <ide> message: 'Attempt to write outside buffer bounds' <ide> }); <ide> <ide> assert.strictEqual(buffer.readFloatLE(0), -Infinity); <ide> () => buffer[fn](offset), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "offset" is out of range. ' + <ide> `It must be an integer. Received ${offset}` <ide> }); <ide><path>test/parallel/test-buffer-readint.js <ide> const assert = require('assert'); <ide> () => buffer[`read${fn}`](o), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]' <add> name: 'TypeError' <ide> }); <ide> }); <ide> <ide> const assert = require('assert'); <ide> () => buffer[`read${fn}`](offset), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]' <add> name: 'RangeError' <ide> }); <ide> }); <ide> <ide> const assert = require('assert'); <ide> () => buffer[`read${fn}`](offset), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "offset" is out of range. ' + <ide> `It must be an integer. Received ${offset}` <ide> }); <ide> const assert = require('assert'); <ide> () => buffer[fn](0, byteLength), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "byteLength" is out of range. ' + <ide> `It must be an integer. Received ${byteLength}` <ide> }); <ide> const assert = require('assert'); <ide> () => buffer[fn](o, i), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]' <add> name: 'TypeError' <ide> }); <ide> }); <ide> <ide> const assert = require('assert'); <ide> () => buffer[fn](offset, i), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "offset" is out of range. ' + <ide> `It must be >= 0 and <= ${8 - i}. Received ${offset}` <ide> }); <ide> const assert = require('assert'); <ide> () => buffer[fn](offset, i), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "offset" is out of range. ' + <ide> `It must be an integer. Received ${offset}` <ide> }); <ide><path>test/parallel/test-buffer-readuint.js <ide> const assert = require('assert'); <ide> () => buffer[`read${fn}`](o), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]' <add> name: 'TypeError' <ide> }); <ide> }); <ide> <ide> const assert = require('assert'); <ide> () => buffer[`read${fn}`](offset), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]' <add> name: 'RangeError' <ide> }); <ide> }); <ide> <ide> const assert = require('assert'); <ide> () => buffer[`read${fn}`](offset), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "offset" is out of range. ' + <ide> `It must be an integer. Received ${offset}` <ide> }); <ide> const assert = require('assert'); <ide> () => buffer[fn](0, byteLength), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "byteLength" is out of range. ' + <ide> `It must be an integer. Received ${byteLength}` <ide> }); <ide> const assert = require('assert'); <ide> () => buffer[fn](o, i), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]' <add> name: 'TypeError' <ide> }); <ide> }); <ide> <ide> const assert = require('assert'); <ide> () => buffer[fn](offset, i), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "offset" is out of range. ' + <ide> `It must be >= 0 and <= ${8 - i}. Received ${offset}` <ide> }); <ide> const assert = require('assert'); <ide> () => buffer[fn](offset, i), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "offset" is out of range. ' + <ide> `It must be an integer. Received ${offset}` <ide> }); <ide><path>test/parallel/test-buffer-slow.js <ide> try { <ide> // Should throw with invalid length type <ide> const bufferInvalidTypeMsg = { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: /^The "size" argument must be of type number/, <ide> }; <ide> assert.throws(() => SlowBuffer(), bufferInvalidTypeMsg); <ide> assert.throws(() => SlowBuffer(true), bufferInvalidTypeMsg); <ide> // Should throw with invalid length value <ide> const bufferMaxSizeMsg = { <ide> code: 'ERR_INVALID_OPT_VALUE', <del> name: 'RangeError [ERR_INVALID_OPT_VALUE]', <add> name: 'RangeError', <ide> message: /^The value "[^"]*" is invalid for option "size"$/ <ide> }; <ide> assert.throws(() => SlowBuffer(NaN), bufferMaxSizeMsg); <ide><path>test/parallel/test-buffer-writedouble.js <ide> assert.ok(Number.isNaN(buffer.readDoubleLE(8))); <ide> () => small[fn](11.11, 0), <ide> { <ide> code: 'ERR_BUFFER_OUT_OF_BOUNDS', <del> name: 'RangeError [ERR_BUFFER_OUT_OF_BOUNDS]', <add> name: 'RangeError', <ide> message: 'Attempt to write outside buffer bounds' <ide> }); <ide> <ide> assert.ok(Number.isNaN(buffer.readDoubleLE(8))); <ide> () => buffer[fn](23, offset), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "offset" is out of range. ' + <ide> `It must be >= 0 and <= 8. Received ${offset}` <ide> }); <ide> assert.ok(Number.isNaN(buffer.readDoubleLE(8))); <ide> () => buffer[fn](42, offset), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "offset" is out of range. ' + <ide> `It must be an integer. Received ${offset}` <ide> }); <ide><path>test/parallel/test-buffer-writefloat.js <ide> assert.ok(Number.isNaN(buffer.readFloatLE(4))); <ide> () => small[fn](11.11, 0), <ide> { <ide> code: 'ERR_BUFFER_OUT_OF_BOUNDS', <del> name: 'RangeError [ERR_BUFFER_OUT_OF_BOUNDS]', <add> name: 'RangeError', <ide> message: 'Attempt to write outside buffer bounds' <ide> }); <ide> <ide> assert.ok(Number.isNaN(buffer.readFloatLE(4))); <ide> () => buffer[fn](23, offset), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "offset" is out of range. ' + <ide> `It must be >= 0 and <= 4. Received ${offset}` <ide> } <ide> assert.ok(Number.isNaN(buffer.readFloatLE(4))); <ide> () => buffer[fn](42, offset), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "offset" is out of range. ' + <ide> `It must be an integer. Received ${offset}` <ide> }); <ide><path>test/parallel/test-buffer-writeint.js <ide> const errorOutOfBounds = common.expectsError({ <ide> () => data[fn](42, 0, byteLength), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "byteLength" is out of range. ' + <ide> `It must be an integer. Received ${byteLength}` <ide> }); <ide> const errorOutOfBounds = common.expectsError({ <ide> data[fn](val, 0, i); <ide> }, { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "value" is out of range. ' + <ide> `It must be >= ${min} and <= ${max}. Received ${val}` <ide> }); <ide> const errorOutOfBounds = common.expectsError({ <ide> () => data[fn](min, o, i), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]' <add> name: 'TypeError' <ide> }); <ide> }); <ide> <ide> const errorOutOfBounds = common.expectsError({ <ide> () => data[fn](min, offset, i), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "offset" is out of range. ' + <ide> `It must be >= 0 and <= ${8 - i}. Received ${offset}` <ide> }); <ide> const errorOutOfBounds = common.expectsError({ <ide> () => data[fn](max, offset, i), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "offset" is out of range. ' + <ide> `It must be an integer. Received ${offset}` <ide> }); <ide><path>test/parallel/test-buffer-writeuint.js <ide> const assert = require('assert'); <ide> () => data[fn](42, 0, byteLength), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "byteLength" is out of range. ' + <ide> `It must be an integer. Received ${byteLength}` <ide> }); <ide> const assert = require('assert'); <ide> data[fn](val, 0, i); <ide> }, { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "value" is out of range. ' + <ide> `It must be >= 0 and <= ${val - 1}. Received ${val}` <ide> }); <ide> const assert = require('assert'); <ide> () => data[fn](23, o, i), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]' <add> name: 'TypeError' <ide> }); <ide> }); <ide> <ide> const assert = require('assert'); <ide> () => data[fn](val - 1, offset, i), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "offset" is out of range. ' + <ide> `It must be >= 0 and <= ${8 - i}. Received ${offset}` <ide> }); <ide> const assert = require('assert'); <ide> () => data[fn](val - 1, offset, i), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "offset" is out of range. ' + <ide> `It must be an integer. Received ${offset}` <ide> }); <ide><path>test/parallel/test-child-process-fork.js <ide> n.on('message', (m) => { <ide> // https://github.com/joyent/node/issues/2355 - JSON.stringify(undefined) <ide> // returns "undefined" but JSON.parse() cannot parse that... <ide> assert.throws(() => n.send(undefined), { <del> name: 'TypeError [ERR_MISSING_ARGS]', <add> name: 'TypeError', <ide> message: 'The "message" argument must be specified', <ide> code: 'ERR_MISSING_ARGS' <ide> }); <ide> assert.throws(() => n.send(), { <del> name: 'TypeError [ERR_MISSING_ARGS]', <add> name: 'TypeError', <ide> message: 'The "message" argument must be specified', <ide> code: 'ERR_MISSING_ARGS' <ide> }); <ide> <ide> assert.throws(() => n.send(Symbol()), { <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "message" argument must be one of type string,' + <ide> ' object, number, or boolean. Received type symbol', <ide> code: 'ERR_INVALID_ARG_TYPE' <ide><path>test/parallel/test-crypto-pbkdf2.js <ide> assert.throws( <ide> () => crypto.pbkdf2('password', 'salt', 1, 20, null), <ide> { <ide> code: 'ERR_INVALID_CALLBACK', <del> name: 'TypeError [ERR_INVALID_CALLBACK]' <add> name: 'TypeError' <ide> } <ide> ); <ide> <ide> assert.throws( <ide> () => crypto.pbkdf2Sync('password', 'salt', -1, 20, 'sha1'), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "iterations" is out of range. ' + <ide> 'It must be >= 0 && < 4294967296. Received -1' <ide> } <ide> assert.throws( <ide> crypto.pbkdf2Sync('password', 'salt', 1, notNumber, 'sha256'); <ide> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "keylen" argument must be of type number. ' + <ide> `Received type ${typeof notNumber}` <ide> }); <ide> assert.throws( <ide> common.mustNotCall()); <ide> }, { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "keylen" is out of range. It ' + <ide> `must be an integer. Received ${input}` <ide> }); <ide> assert.throws( <ide> common.mustNotCall()); <ide> }, { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "keylen" is out of range. It ' + <ide> `must be >= 0 && < 4294967296. Received ${input}` <ide> }); <ide> assert.throws( <ide> () => crypto.pbkdf2('password', 'salt', 8, 8, common.mustNotCall()), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "digest" argument must be one of type string or null. ' + <ide> 'Received type undefined' <ide> }); <ide> assert.throws( <ide> () => crypto.pbkdf2Sync('password', 'salt', 8, 8), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "digest" argument must be one of type string or null. ' + <ide> 'Received type undefined' <ide> }); <ide> assert.throws( <ide> () => crypto.pbkdf2(input, 'salt', 8, 8, 'sha256', common.mustNotCall()), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: `The "password" argument must be one of type string, ${msgPart2}` <ide> } <ide> ); <ide> assert.throws( <ide> () => crypto.pbkdf2('pass', input, 8, 8, 'sha256', common.mustNotCall()), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: `The "salt" argument must be one of type string, ${msgPart2}` <ide> } <ide> ); <ide> assert.throws( <ide> () => crypto.pbkdf2Sync(input, 'salt', 8, 8, 'sha256'), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: `The "password" argument must be one of type string, ${msgPart2}` <ide> } <ide> ); <ide> assert.throws( <ide> () => crypto.pbkdf2Sync('pass', input, 8, 8, 'sha256'), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: `The "salt" argument must be one of type string, ${msgPart2}` <ide> } <ide> ); <ide> assert.throws( <ide> () => crypto.pbkdf2('pass', 'salt', i, 8, 'sha256', common.mustNotCall()), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: `The "iterations" argument must be of type number. ${received}` <ide> } <ide> ); <ide> assert.throws( <ide> () => crypto.pbkdf2Sync('pass', 'salt', i, 8, 'sha256'), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: `The "iterations" argument must be of type number. ${received}` <ide> } <ide> ); <ide> assert.throws( <ide> () => crypto.pbkdf2('pass', 'salt', 8, 8, 'md55', common.mustNotCall()), <ide> { <ide> code: 'ERR_CRYPTO_INVALID_DIGEST', <del> name: 'TypeError [ERR_CRYPTO_INVALID_DIGEST]', <add> name: 'TypeError', <ide> message: 'Invalid digest: md55' <ide> } <ide> ); <ide> assert.throws( <ide> () => crypto.pbkdf2Sync('pass', 'salt', 8, 8, 'md55'), <ide> { <ide> code: 'ERR_CRYPTO_INVALID_DIGEST', <del> name: 'TypeError [ERR_CRYPTO_INVALID_DIGEST]', <add> name: 'TypeError', <ide> message: 'Invalid digest: md55' <ide> } <ide> ); <ide><path>test/parallel/test-crypto-random.js <ide> common.expectWarning('DeprecationWarning', <ide> [undefined, null, false, true, {}, []].forEach((value) => { <ide> const errObj = { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "size" argument must be of type number. ' + <ide> `Received type ${typeof value}` <ide> }; <ide> common.expectWarning('DeprecationWarning', <ide> [-1, NaN, 2 ** 32].forEach((value) => { <ide> const errObj = { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "size" is out of range. It must be >= 0 && <= ' + <ide> `${kMaxPossibleLength}. Received ${value}` <ide> }; <ide> common.expectWarning('DeprecationWarning', <ide> <ide> const typeErrObj = { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "offset" argument must be of type number. ' + <ide> 'Received type string' <ide> }; <ide> common.expectWarning('DeprecationWarning', <ide> [NaN, kMaxPossibleLength + 1, -10, (-1 >>> 0) + 1].forEach((offsetSize) => { <ide> const errObj = { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "offset" is out of range. ' + <ide> `It must be >= 0 && <= 10. Received ${offsetSize}` <ide> }; <ide> common.expectWarning('DeprecationWarning', <ide> <ide> const rangeErrObj = { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "size + offset" is out of range. ' + <ide> 'It must be <= 10. Received 11' <ide> }; <ide> assert.throws( <ide> () => crypto.randomBytes((-1 >>> 0) + 1), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "size" is out of range. ' + <ide> `It must be >= 0 && <= ${kMaxPossibleLength}. Received 4294967296` <ide> } <ide><path>test/parallel/test-crypto-sign-verify.js <ide> common.expectsError( <ide> const type = typeof input; <ide> const errObj = { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "algorithm" argument must be of type string. ' + <ide> `Received type ${type}` <ide> }; <ide> common.expectsError( <ide> const type = typeof input; <ide> const errObj = { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "key" argument must be one of type string, Buffer, ' + <ide> `TypedArray, DataView, or KeyObject. Received type ${type}` <ide> }; <ide><path>test/parallel/test-dgram-send-address-types.js <ide> const client = dgram.createSocket('udp4').bind(0, () => { <ide> [[], 1, true].forEach((invalidInput) => { <ide> const expectedError = { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "address" argument must be one of type string or falsy. ' + <ide> `Received type ${typeof invalidInput}` <ide> }; <ide><path>test/parallel/test-dgram-sendto.js <ide> const socket = dgram.createSocket('udp4'); <ide> <ide> const errObj = { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "offset" argument must be of type number. Received type ' + <ide> 'undefined' <ide> }; <ide><path>test/parallel/test-dns-setservers-type-check.js <ide> const promiseResolver = new dns.promises.Resolver(); <ide> ].forEach((val) => { <ide> const errObj = { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "servers" argument must be of type Array. Received type ' + <ide> typeof val <ide> }; <ide> const promiseResolver = new dns.promises.Resolver(); <ide> ].forEach((val) => { <ide> const errObj = { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "servers[0]" argument must be of type string. ' + <ide> `Received type ${typeof val[0]}` <ide> }; <ide><path>test/parallel/test-dns.js <ide> assert(existing.length > 0); <ide> dns.setServers([serv]); <ide> }, <ide> { <del> name: 'TypeError [ERR_INVALID_IP_ADDRESS]', <add> name: 'TypeError', <ide> code: 'ERR_INVALID_IP_ADDRESS' <ide> } <ide> ); <ide><path>test/parallel/test-error-serdes.js <ide> assert.strictEqual(cycle(Function), '[Function: Function]'); <ide> { <ide> const err = new ERR_INVALID_ARG_TYPE('object', 'Object', 42); <ide> assert(/^TypeError \[ERR_INVALID_ARG_TYPE\]:/.test(err)); <del> assert.strictEqual(err.name, 'TypeError [ERR_INVALID_ARG_TYPE]'); <add> assert.strictEqual(err.name, 'TypeError'); <ide> assert.strictEqual(err.code, 'ERR_INVALID_ARG_TYPE'); <ide> } <ide><path>test/parallel/test-errors-systemerror.js <ide> const assert = require('assert'); <ide> const { E, SystemError, codes } = require('internal/errors'); <ide> <ide> assert.throws( <del> () => { throw new SystemError(); }, <add> () => { new SystemError(); }, <ide> { <ide> name: 'TypeError', <ide> message: 'Cannot read property \'match\' of undefined' <ide> const { ERR_TEST } = codes; <ide> () => { throw new ERR_TEST(ctx); }, <ide> { <ide> code: 'ERR_TEST', <del> name: 'SystemError [ERR_TEST]', <add> name: 'SystemError', <ide> message: 'custom message: syscall_test returned ETEST (code message)' + <ide> ' /str => /str2', <ide> info: ctx <ide> const { ERR_TEST } = codes; <ide> () => { throw new ERR_TEST(ctx); }, <ide> { <ide> code: 'ERR_TEST', <del> name: 'SystemError [ERR_TEST]', <add> name: 'SystemError', <ide> message: 'custom message: syscall_test returned ETEST (code message)' + <ide> ' /buf => /str2', <ide> info: ctx <ide> const { ERR_TEST } = codes; <ide> () => { throw new ERR_TEST(ctx); }, <ide> { <ide> code: 'ERR_TEST', <del> name: 'SystemError [ERR_TEST]', <add> name: 'SystemError', <ide> message: 'custom message: syscall_test returned ETEST (code message)' + <ide> ' /buf => /buf2', <ide> info: ctx <ide> const { ERR_TEST } = codes; <ide> assert.throws( <ide> () => { <ide> const err = new ERR_TEST(ctx); <del> err.name = 'SystemError [CUSTOM_ERR_TEST]'; <add> err.name = 'Foobar'; <ide> throw err; <ide> }, <ide> { <ide> code: 'ERR_TEST', <del> name: 'SystemError [CUSTOM_ERR_TEST]', <add> name: 'Foobar', <ide> message: 'custom message: syscall_test returned ERR_TEST ' + <ide> '(Error occurred)', <ide> info: ctx <ide><path>test/parallel/test-fs-chmod.js <ide> if (fs.lchmod) { <ide> [false, 1, {}, [], null, undefined].forEach((input) => { <ide> const errObj = { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "path" argument must be one of type string, Buffer, or URL.' + <ide> ` Received type ${typeof input}` <ide> }; <ide><path>test/parallel/test-fs-close-errors.js <ide> const fs = require('fs'); <ide> ['', false, null, undefined, {}, []].forEach((input) => { <ide> const errObj = { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "fd" argument must be of type number. ' + <ide> `Received type ${typeof input}` <ide> }; <ide><path>test/parallel/test-fs-fchmod.js <ide> const fs = require('fs'); <ide> [false, null, undefined, {}, [], ''].forEach((input) => { <ide> const errObj = { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "fd" argument must be of type number. Received type ' + <ide> typeof input <ide> }; <ide> const fs = require('fs'); <ide> [false, null, undefined, {}, [], '', '123x'].forEach((input) => { <ide> const errObj = { <ide> code: 'ERR_INVALID_ARG_VALUE', <del> name: 'TypeError [ERR_INVALID_ARG_VALUE]', <add> name: 'TypeError', <ide> message: 'The argument \'mode\' must be a 32-bit unsigned integer or an ' + <ide> `octal string. Received ${util.inspect(input)}` <ide> }; <ide> const fs = require('fs'); <ide> [-1, 2 ** 32].forEach((input) => { <ide> const errObj = { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "fd" is out of range. It must be >= 0 && <= ' + <ide> `2147483647. Received ${input}` <ide> }; <ide> const fs = require('fs'); <ide> [-1, 2 ** 32].forEach((input) => { <ide> const errObj = { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "mode" is out of range. It must be >= 0 && <= ' + <ide> `4294967295. Received ${input}` <ide> }; <ide> const fs = require('fs'); <ide> [NaN, Infinity].forEach((input) => { <ide> const errObj = { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "fd" is out of range. It must be an integer. ' + <ide> `Received ${input}` <ide> }; <ide> const fs = require('fs'); <ide> [1.5].forEach((input) => { <ide> const errObj = { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "fd" is out of range. It must be an integer. ' + <ide> `Received ${input}` <ide> }; <ide><path>test/parallel/test-fs-fchown.js <ide> function test(input, errObj) { <ide> ['', false, null, undefined, {}, []].forEach((input) => { <ide> const errObj = { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "fd" argument must be of type number. Received type ' + <ide> typeof input <ide> }; <ide> function test(input, errObj) { <ide> [Infinity, NaN].forEach((input) => { <ide> const errObj = { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "fd" is out of range. It must be an integer. ' + <ide> `Received ${input}` <ide> }; <ide> function test(input, errObj) { <ide> [-1, 2 ** 32].forEach((input) => { <ide> const errObj = { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "fd" is out of range. It must be ' + <ide> `>= 0 && < 4294967296. Received ${input}` <ide> }; <ide><path>test/parallel/test-fs-fsync.js <ide> fs.open(fileTemp, 'a', 0o777, common.mustCall(function(err, fd) { <ide> ['', false, null, undefined, {}, []].forEach((input) => { <ide> const errObj = { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "fd" argument must be of type number. Received type ' + <ide> typeof input <ide> }; <ide><path>test/parallel/test-fs-lchmod.js <ide> assert.throws(() => fs.lchmod(f, {}), { code: 'ERR_INVALID_CALLBACK' }); <ide> [false, null, undefined, {}, [], '', '123x'].forEach((input) => { <ide> const errObj = { <ide> code: 'ERR_INVALID_ARG_VALUE', <del> name: 'TypeError [ERR_INVALID_ARG_VALUE]', <add> name: 'TypeError', <ide> message: 'The argument \'mode\' must be a 32-bit unsigned integer or an ' + <ide> `octal string. Received ${util.inspect(input)}` <ide> }; <ide> assert.throws(() => fs.lchmod(f, {}), { code: 'ERR_INVALID_CALLBACK' }); <ide> [-1, 2 ** 32].forEach((input) => { <ide> const errObj = { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "mode" is out of range. It must be >= 0 && <= ' + <ide> `4294967295. Received ${input}` <ide> }; <ide><path>test/parallel/test-fs-open.js <ide> for (const extra of [[], ['r'], ['r', 0], ['r', 0, 'bad callback']]) { <ide> fs.promises.open(i, 'r'), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]' <add> name: 'TypeError' <ide> } <ide> ); <ide> }); <ide><path>test/parallel/test-fs-promises.js <ide> async function getHandle(dest) { <ide> }, <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "gid" is out of range. ' + <ide> 'It must be >= 0 && < 4294967296. Received -1' <ide> }); <ide> async function getHandle(dest) { <ide> }, <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "gid" is out of range. ' + <ide> 'It must be >= 0 && < 4294967296. Received -1' <ide> }); <ide> async function getHandle(dest) { <ide> async () => mkdir(dir, { recursive }), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "recursive" argument must be of type boolean. ' + <ide> `Received type ${typeof recursive}` <ide> } <ide> async function getHandle(dest) { <ide> async () => mkdtemp(1), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]' <add> name: 'TypeError' <ide> } <ide> ); <ide> } <ide><path>test/parallel/test-fs-read-type.js <ide> assert.throws( <ide> () => fs.read(fd, expected.length, 0, 'utf-8', common.mustNotCall()), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "buffer" argument must be one of type Buffer, TypedArray, ' + <ide> 'or DataView. Received type number' <ide> } <ide> assert.throws( <ide> common.mustNotCall()); <ide> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "fd" argument must be of type number. ' + <ide> `Received type ${typeof value}` <ide> }); <ide> assert.throws(() => { <ide> common.mustNotCall()); <ide> }, { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "offset" is out of range. It must be >= 0 && <= 4. ' + <ide> 'Received -1' <ide> }); <ide> assert.throws(() => { <ide> common.mustNotCall()); <ide> }, { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "length" is out of range. ' + <ide> 'It must be >= 0 && <= 4. Received -1' <ide> }); <ide> assert.throws( <ide> () => fs.readSync(fd, expected.length, 0, 'utf-8'), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "buffer" argument must be one of type Buffer, TypedArray, ' + <ide> 'or DataView. Received type number' <ide> } <ide> assert.throws( <ide> 0); <ide> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "fd" argument must be of type number. ' + <ide> `Received type ${typeof value}` <ide> }); <ide> assert.throws(() => { <ide> 0); <ide> }, { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "offset" is out of range. ' + <ide> 'It must be >= 0 && <= 4. Received -1' <ide> }); <ide> assert.throws(() => { <ide> 0); <ide> }, { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "length" is out of range. ' + <ide> 'It must be >= 0 && <= 4. Received -1' <ide> }); <ide><path>test/parallel/test-fs-rename-type-check.js <ide> const fs = require('fs'); <ide> () => fs.rename(input, 'does-not-exist', common.mustNotCall()), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: `The "oldPath" argument must be one ${type}` <ide> } <ide> ); <ide> assert.throws( <ide> () => fs.rename('does-not-exist', input, common.mustNotCall()), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: `The "newPath" argument must be one ${type}` <ide> } <ide> ); <ide> assert.throws( <ide> () => fs.renameSync(input, 'does-not-exist'), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: `The "oldPath" argument must be one ${type}` <ide> } <ide> ); <ide> assert.throws( <ide> () => fs.renameSync('does-not-exist', input), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: `The "newPath" argument must be one ${type}` <ide> } <ide> ); <ide><path>test/parallel/test-fs-stat.js <ide> fs.stat(__filename, common.mustCall(function(err, s) { <ide> () => fs[fnName](input), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "fd" argument must be of type number. ' + <ide> `Received type ${typeof input}` <ide> } <ide> fs.stat(__filename, common.mustCall(function(err, s) { <ide> () => fs.lstat(input, common.mustNotCall()), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]' <add> name: 'TypeError' <ide> } <ide> ); <ide> assert.throws( <ide> () => fs.lstatSync(input), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]' <add> name: 'TypeError' <ide> } <ide> ); <ide> assert.throws( <ide> () => fs.stat(input, common.mustNotCall()), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]' <add> name: 'TypeError' <ide> } <ide> ); <ide> assert.throws( <ide> () => fs.statSync(input), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]' <add> name: 'TypeError' <ide> } <ide> ); <ide> }); <ide><path>test/parallel/test-fs-symlink.js <ide> fs.symlink(linkData, linkPath, common.mustCall(function(err) { <ide> [false, 1, {}, [], null, undefined].forEach((input) => { <ide> const errObj = { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "target" argument must be one of type string, Buffer, or ' + <ide> `URL. Received type ${typeof input}` <ide> }; <ide> fs.symlink(linkData, linkPath, common.mustCall(function(err) { <ide> <ide> const errObj = { <ide> code: 'ERR_FS_INVALID_SYMLINK_TYPE', <del> name: 'Error [ERR_FS_INVALID_SYMLINK_TYPE]', <add> name: 'Error', <ide> message: <ide> 'Symlink type must be one of "dir", "file", or "junction". Received "🍏"' <ide> }; <ide><path>test/parallel/test-fs-truncate.js <ide> function testFtruncate(cb) { <ide> () => fs.truncate(file5, input, common.mustNotCall()), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "len" argument must be of type number. ' + <ide> `Received type ${typeof input}` <ide> } <ide> function testFtruncate(cb) { <ide> () => fs.ftruncate(fd, input), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "len" argument must be of type number. ' + <ide> `Received type ${typeof input}` <ide> } <ide> function testFtruncate(cb) { <ide> () => fs.truncate(file5, input), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "len" is out of range. It must be ' + <ide> `an integer. Received ${input}` <ide> } <ide> function testFtruncate(cb) { <ide> () => fs.ftruncate(fd, input), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "len" is out of range. It must be ' + <ide> `an integer. Received ${input}` <ide> } <ide> function testFtruncate(cb) { <ide> () => fs.truncate('/foo/bar', input), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "len" argument must be of type number. ' + <ide> `Received type ${typeof input}` <ide> } <ide> function testFtruncate(cb) { <ide> () => fs[fnName](input), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "fd" argument must be of type number. ' + <ide> `Received type ${typeof input}` <ide> } <ide><path>test/parallel/test-http-res-write-end-dont-take-array.js <ide> server.once('request', common.mustCall((req, res) => { <ide> <ide> const expectedError = { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> }; <ide> <ide> // Write should not accept an Array <ide><path>test/parallel/test-http2-altsvc.js <ide> server.on('session', common.mustCall((session) => { <ide> () => session.altsvc('h2=":8000"', input), <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "originOrStream" is out of ' + <ide> `range. It must be > 0 && < 4294967296. Received ${input}` <ide> } <ide> server.on('session', common.mustCall((session) => { <ide> () => session.altsvc(input), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]' <add> name: 'TypeError' <ide> } <ide> ); <ide> }); <ide> server.on('session', common.mustCall((session) => { <ide> () => session.altsvc(input), <ide> { <ide> code: 'ERR_INVALID_CHAR', <del> name: 'TypeError [ERR_INVALID_CHAR]', <add> name: 'TypeError', <ide> message: 'Invalid character in alt' <ide> } <ide> ); <ide> server.on('session', common.mustCall((session) => { <ide> () => session.altsvc('clear', input), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]' <add> name: 'TypeError' <ide> } <ide> ); <ide> }); <ide> server.on('session', common.mustCall((session) => { <ide> () => session.altsvc('h2=":8000', input), <ide> { <ide> code: 'ERR_HTTP2_ALTSVC_INVALID_ORIGIN', <del> name: 'TypeError [ERR_HTTP2_ALTSVC_INVALID_ORIGIN]', <add> name: 'TypeError', <ide> message: 'HTTP/2 ALTSVC frames require a valid origin' <ide> } <ide> ); <ide> server.on('session', common.mustCall((session) => { <ide> }, <ide> { <ide> code: 'ERR_HTTP2_ALTSVC_LENGTH', <del> name: 'TypeError [ERR_HTTP2_ALTSVC_LENGTH]', <add> name: 'TypeError', <ide> message: 'HTTP/2 ALTSVC frames are limited to 16382 bytes' <ide> } <ide> ); <ide><path>test/parallel/test-http2-client-http1-server.js <ide> server.listen(0, common.mustCall(() => { <ide> client.on('error', common.expectsError({ <ide> code: 'ERR_HTTP2_ERROR', <ide> type: NghttpError, <del> name: 'Error [ERR_HTTP2_ERROR]', <add> name: 'Error', <ide> message: 'Protocol error' <ide> })); <ide> <ide><path>test/parallel/test-http2-client-onconnect-errors.js <ide> const genericTests = Object.getOwnPropertyNames(constants) <ide> error: { <ide> code: 'ERR_HTTP2_ERROR', <ide> type: NghttpError, <del> name: 'Error [ERR_HTTP2_ERROR]', <add> name: 'Error', <ide> message: nghttp2ErrorString(constants[key]) <ide> }, <ide> type: 'session' <ide><path>test/parallel/test-http2-client-rststream-before-connect.js <ide> server.listen(0, common.mustCall(() => { <ide> assert.throws( <ide> () => req.close(2 ** 32), <ide> { <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> code: 'ERR_OUT_OF_RANGE', <ide> message: 'The value of "code" is out of range. It must be ' + <ide> '>= 0 && <= 4294967295. Received 4294967296' <ide><path>test/parallel/test-http2-compat-serverrequest-headers.js <ide> server.listen(0, common.mustCall(function() { <ide> () => request.method = ' ', <ide> { <ide> code: 'ERR_INVALID_ARG_VALUE', <del> name: 'TypeError [ERR_INVALID_ARG_VALUE]', <add> name: 'TypeError', <ide> message: "The argument 'method' is invalid. Received ' '" <ide> } <ide> ); <ide> assert.throws( <ide> () => request.method = true, <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "method" argument must be of type string. ' + <ide> 'Received type boolean' <ide> } <ide><path>test/parallel/test-http2-compat-serverresponse-headers.js <ide> server.listen(0, common.mustCall(function() { <ide> () => response[fnName](), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "name" argument must be of type string. Received ' + <ide> 'type undefined' <ide> } <ide><path>test/parallel/test-http2-createsecureserver-nooptions.js <ide> invalidOptions.forEach((invalidOption) => { <ide> assert.throws( <ide> () => http2.createSecureServer(invalidOption), <ide> { <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> message: 'The "options" argument must be of type Object. Received ' + <ide> `type ${typeof invalidOption}` <ide><path>test/parallel/test-http2-info-headers-errors.js <ide> const genericTests = Object.getOwnPropertyNames(constants) <ide> error: { <ide> code: 'ERR_HTTP2_ERROR', <ide> type: NghttpError, <del> name: 'Error [ERR_HTTP2_ERROR]', <add> name: 'Error', <ide> message: nghttp2ErrorString(constants[key]) <ide> }, <ide> type: 'stream' <ide><path>test/parallel/test-http2-origin.js <ide> const ca = readKey('fake-startcom-root-cert.pem', 'binary'); <ide> () => session.origin(input), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]' <add> name: 'TypeError' <ide> } <ide> ); <ide> }); <ide> const ca = readKey('fake-startcom-root-cert.pem', 'binary'); <ide> () => session.origin(input), <ide> { <ide> code: 'ERR_HTTP2_INVALID_ORIGIN', <del> name: 'TypeError [ERR_HTTP2_INVALID_ORIGIN]' <add> name: 'TypeError' <ide> } <ide> ); <ide> }); <ide> const ca = readKey('fake-startcom-root-cert.pem', 'binary'); <ide> () => session.origin(input), <ide> { <ide> code: 'ERR_INVALID_URL', <del> name: 'TypeError [ERR_INVALID_URL]' <add> name: 'TypeError' <ide> } <ide> ); <ide> }); <ide> const ca = readKey('fake-startcom-root-cert.pem', 'binary'); <ide> () => session.origin(longInput), <ide> { <ide> code: 'ERR_HTTP2_ORIGIN_LENGTH', <del> name: 'TypeError [ERR_HTTP2_ORIGIN_LENGTH]' <add> name: 'TypeError' <ide> } <ide> ); <ide> })); <ide><path>test/parallel/test-http2-respond-nghttperrors.js <ide> const genericTests = Object.getOwnPropertyNames(constants) <ide> error: { <ide> code: 'ERR_HTTP2_ERROR', <ide> type: NghttpError, <del> name: 'Error [ERR_HTTP2_ERROR]', <add> name: 'Error', <ide> message: nghttp2ErrorString(constants[key]) <ide> }, <ide> type: 'stream' <ide><path>test/parallel/test-http2-respond-with-fd-errors.js <ide> const genericTests = Object.getOwnPropertyNames(constants) <ide> error: { <ide> code: 'ERR_HTTP2_ERROR', <ide> type: NghttpError, <del> name: 'Error [ERR_HTTP2_ERROR]', <add> name: 'Error', <ide> message: nghttp2ErrorString(constants[key]) <ide> }, <ide> type: 'stream' <ide><path>test/parallel/test-http2-server-push-stream-errors-args.js <ide> server.on('stream', common.mustCall((stream, headers) => { <ide> () => stream.pushStream({ 'connection': 'test' }, {}, () => {}), <ide> { <ide> code: 'ERR_HTTP2_INVALID_CONNECTION_HEADERS', <del> name: 'TypeError [ERR_HTTP2_INVALID_CONNECTION_HEADERS]', <add> name: 'TypeError', <ide> message: 'HTTP/1 Connection specific headers are forbidden: "connection"' <ide> } <ide> ); <ide><path>test/parallel/test-http2-server-push-stream-errors.js <ide> const genericTests = Object.getOwnPropertyNames(constants) <ide> error: { <ide> code: 'ERR_HTTP2_ERROR', <ide> type: NghttpError, <del> name: 'Error [ERR_HTTP2_ERROR]', <add> name: 'Error', <ide> message: nghttp2ErrorString(constants[key]) <ide> }, <ide> type: 'stream' <ide><path>test/parallel/test-http2-util-headers-list.js <ide> const { <ide> ].forEach((name) => { <ide> common.expectsError(() => mapToHeaders({ [name]: 'abc' }), { <ide> code: 'ERR_HTTP2_INVALID_CONNECTION_HEADERS', <del> name: 'TypeError [ERR_HTTP2_INVALID_CONNECTION_HEADERS]', <add> name: 'TypeError', <ide> message: 'HTTP/1 Connection specific headers are forbidden: ' + <ide> `"${name.toLowerCase()}"` <ide> }); <ide> }); <ide> <ide> common.expectsError(() => mapToHeaders({ [HTTP2_HEADER_TE]: ['abc'] }), { <ide> code: 'ERR_HTTP2_INVALID_CONNECTION_HEADERS', <del> name: 'TypeError [ERR_HTTP2_INVALID_CONNECTION_HEADERS]', <add> name: 'TypeError', <ide> message: 'HTTP/1 Connection specific headers are forbidden: ' + <ide> `"${HTTP2_HEADER_TE}"` <ide> }); <ide> <ide> common.expectsError( <ide> () => mapToHeaders({ [HTTP2_HEADER_TE]: ['abc', 'trailers'] }), { <ide> code: 'ERR_HTTP2_INVALID_CONNECTION_HEADERS', <del> name: 'TypeError [ERR_HTTP2_INVALID_CONNECTION_HEADERS]', <add> name: 'TypeError', <ide> message: 'HTTP/1 Connection specific headers are forbidden: ' + <ide> `"${HTTP2_HEADER_TE}"` <ide> }); <ide><path>test/parallel/test-https-options-boolean-check.js <ide> const caArrDataView = toDataView(caCert); <ide> https.createServer({ key, cert }); <ide> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "options.key" property must be one of type string, Buffer, ' + <ide> `TypedArray, or DataView. Received type ${type}` <ide> }); <ide> const caArrDataView = toDataView(caCert); <ide> https.createServer({ key, cert }); <ide> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "options.cert" property must be one of type string, Buffer,' + <ide> ` TypedArray, or DataView. Received type ${type}` <ide> }); <ide> const caArrDataView = toDataView(caCert); <ide> https.createServer({ key, cert, ca }); <ide> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "options.ca" property must be one of type string, Buffer, ' + <ide> `TypedArray, or DataView. Received type ${type}` <ide> }); <ide><path>test/parallel/test-internal-error-original-names.js <ide> errors.E('TEST_ERROR_1', 'Error for testing purposes: %s', <ide> { <ide> const err = new errors.codes.TEST_ERROR_1('test'); <ide> assert(err instanceof Error); <del> assert.strictEqual(err.name, 'Error [TEST_ERROR_1]'); <add> assert.strictEqual(err.name, 'Error'); <ide> } <ide> <ide> { <ide> errors.E('TEST_ERROR_1', 'Error for testing purposes: %s', <ide> errors.useOriginalName = false; <ide> const err = new errors.codes.TEST_ERROR_1('test'); <ide> assert(err instanceof Error); <del> assert.strictEqual(err.name, 'Error [TEST_ERROR_1]'); <add> assert.strictEqual(err.name, 'Error'); <ide> } <ide><path>test/parallel/test-internal-errors.js <ide> errors.E('TEST_ERROR_2', (a, b) => `${a} ${b}`, Error); <ide> { <ide> const err = new errors.codes.TEST_ERROR_1('test'); <ide> assert(err instanceof Error); <del> assert.strictEqual(err.name, 'Error [TEST_ERROR_1]'); <add> assert.strictEqual(err.name, 'Error'); <ide> assert.strictEqual(err.message, 'Error for testing purposes: test'); <ide> assert.strictEqual(err.code, 'TEST_ERROR_1'); <ide> } <ide> <ide> { <ide> const err = new errors.codes.TEST_ERROR_1.TypeError('test'); <ide> assert(err instanceof TypeError); <del> assert.strictEqual(err.name, 'TypeError [TEST_ERROR_1]'); <add> assert.strictEqual(err.name, 'TypeError'); <ide> assert.strictEqual(err.message, 'Error for testing purposes: test'); <ide> assert.strictEqual(err.code, 'TEST_ERROR_1'); <ide> } <ide> <ide> { <ide> const err = new errors.codes.TEST_ERROR_1.RangeError('test'); <ide> assert(err instanceof RangeError); <del> assert.strictEqual(err.name, 'RangeError [TEST_ERROR_1]'); <add> assert.strictEqual(err.name, 'RangeError'); <ide> assert.strictEqual(err.message, 'Error for testing purposes: test'); <ide> assert.strictEqual(err.code, 'TEST_ERROR_1'); <ide> } <ide> <ide> { <ide> const err = new errors.codes.TEST_ERROR_2('abc', 'xyz'); <ide> assert(err instanceof Error); <del> assert.strictEqual(err.name, 'Error [TEST_ERROR_2]'); <add> assert.strictEqual(err.name, 'Error'); <ide> assert.strictEqual(err.message, 'abc xyz'); <ide> assert.strictEqual(err.code, 'TEST_ERROR_2'); <ide> } <ide> common.expectsError(() => { <ide> message: 'Error for testing purposes: a' <ide> }); <ide> <del>common.expectsError(() => { <del> common.expectsError(() => { <del> throw new errors.codes.TEST_ERROR_1.TypeError('a'); <del> }, { code: 'TEST_ERROR_1', type: RangeError }); <del>}, { <del> code: 'ERR_ASSERTION', <del> message: /\+ type: \[Function: TypeError]\n- type: \[Function: RangeError]/ <del>}); <del> <del>common.expectsError(() => { <del> common.expectsError(() => { <del> throw new errors.codes.TEST_ERROR_1.TypeError('a'); <del> }, { code: 'TEST_ERROR_1', <del> type: TypeError, <del> message: /^Error for testing 2/ }); <del>}, { <del> code: 'ERR_ASSERTION', <del> type: assert.AssertionError, <del> message: /\+ message: 'Error for testing purposes: a',\n- message: \/\^Error/ <del>}); <del> <ide> // Test that `code` property is mutable and that changing it does not change the <ide> // name. <ide> { <ide> common.expectsError(() => { <ide> assert.strictEqual(myError.code, 'FHQWHGADS'); <ide> assert.strictEqual(myError.name, initialName); <ide> assert.deepStrictEqual(Object.keys(myError), ['code']); <del> assert.ok(myError.name.includes('TEST_ERROR_1')); <add> assert.ok(!myError.name.includes('TEST_ERROR_1')); <ide> assert.ok(!myError.name.includes('FHQWHGADS')); <ide> } <ide> <ide><path>test/parallel/test-next-tick-errors.js <ide> function testNextTickWith(val) { <ide> }, <ide> { <ide> code: 'ERR_INVALID_CALLBACK', <del> name: 'TypeError [ERR_INVALID_CALLBACK]', <add> name: 'TypeError', <ide> type: TypeError <ide> } <ide> ); <ide><path>test/parallel/test-process-cpuUsage.js <ide> assert.throws( <ide> () => process.cpuUsage(1), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "prevValue" argument must be of type object. ' + <ide> 'Received type number' <ide> } <ide> assert.throws( <ide> () => process.cpuUsage(value), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "prevValue.user" property must be of type number. ' + <ide> `Received type ${typeof value.user}` <ide> } <ide> assert.throws( <ide> () => process.cpuUsage(value), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "prevValue.system" property must be of type number. ' + <ide> `Received type ${typeof value.system}` <ide> } <ide> assert.throws( <ide> () => process.cpuUsage(value), <ide> { <ide> code: 'ERR_INVALID_OPT_VALUE', <del> name: 'RangeError [ERR_INVALID_OPT_VALUE]', <add> name: 'RangeError', <ide> message: `The value "${value.user}" is invalid ` + <ide> 'for option "prevValue.user"' <ide> } <ide> assert.throws( <ide> () => process.cpuUsage(value), <ide> { <ide> code: 'ERR_INVALID_OPT_VALUE', <del> name: 'RangeError [ERR_INVALID_OPT_VALUE]', <add> name: 'RangeError', <ide> message: `The value "${value.system}" is invalid ` + <ide> 'for option "prevValue.system"' <ide> } <ide><path>test/parallel/test-process-initgroups.js <ide> if (!common.isMainThread) <ide> }, <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: <ide> 'The "user" argument must be ' + <ide> 'one of type number or string. ' + <ide> if (!common.isMainThread) <ide> }, <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: <ide> 'The "extraGroup" argument must be ' + <ide> 'one of type number or string. ' + <ide><path>test/parallel/test-process-kill-pid.js <ide> const assert = require('assert'); <ide> ['SIGTERM', null, undefined, NaN, Infinity, -Infinity].forEach((val) => { <ide> assert.throws(() => process.kill(val), { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "pid" argument must be of type number. ' + <ide> `Received type ${typeof val}` <ide> }); <ide><path>test/parallel/test-process-setgroups.js <ide> assert.throws( <ide> }, <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "groups" argument must be of type Array. ' + <ide> 'Received type undefined' <ide> } <ide> assert.throws( <ide> }, <ide> { <ide> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> name: 'RangeError', <ide> message: 'The value of "groups[1]" is out of range. ' + <ide> 'It must be >= 0 && < 4294967296. Received -1' <ide> } <ide> assert.throws( <ide> }, <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "groups[0]" argument must be ' + <ide> 'one of type number or string. ' + <ide> `Received type ${typeof val}` <ide><path>test/parallel/test-stream-finished.js <ide> const { promisify } = require('util'); <ide> assert.throws( <ide> () => finished(rs, 'foo'), <ide> { <del> name: /ERR_INVALID_ARG_TYPE/, <add> code: 'ERR_INVALID_ARG_TYPE', <ide> message: /callback/ <ide> } <ide> ); <ide> assert.throws( <ide> () => finished(rs, 'foo', () => {}), <ide> { <del> name: /ERR_INVALID_ARG_TYPE/, <add> code: 'ERR_INVALID_ARG_TYPE', <ide> message: /opts/ <ide> } <ide> ); <ide> assert.throws( <ide> () => finished(rs, {}, 'foo'), <ide> { <del> name: /ERR_INVALID_ARG_TYPE/, <add> code: 'ERR_INVALID_ARG_TYPE', <ide> message: /callback/ <ide> } <ide> ); <ide><path>test/parallel/test-ttywrap-invalid-fd.js <ide> assert.throws( <ide> () => new tty.WriteStream(-1), <ide> { <ide> code: 'ERR_INVALID_FD', <del> name: 'RangeError [ERR_INVALID_FD]', <add> name: 'RangeError', <ide> message: '"fd" must be a positive integer: -1' <ide> } <ide> ); <ide> assert.throws( <ide> }); <ide> }, { <ide> code: 'ERR_TTY_INIT_FAILED', <del> name: 'SystemError [ERR_TTY_INIT_FAILED]', <add> name: 'SystemError', <ide> message, <ide> info <ide> } <ide> assert.throws( <ide> }); <ide> }, { <ide> code: 'ERR_TTY_INIT_FAILED', <del> name: 'SystemError [ERR_TTY_INIT_FAILED]', <add> name: 'SystemError', <ide> message, <ide> info <ide> }); <ide> assert.throws( <ide> () => new tty.ReadStream(-1), <ide> { <ide> code: 'ERR_INVALID_FD', <del> name: 'RangeError [ERR_INVALID_FD]', <add> name: 'RangeError', <ide> message: '"fd" must be a positive integer: -1' <ide> } <ide> ); <ide><path>test/parallel/test-url-format-whatwg.js <ide> assert.strictEqual( <ide> () => url.format(myURL, value), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> name: 'TypeError', <ide> message: 'The "options" argument must be of type Object. ' + <ide> `Received type ${typeof value}` <ide> } <ide><path>test/parallel/test-whatwg-url-custom-parsing.js <ide> for (const test of failureTests) { <ide> assert.throws( <ide> () => new URL(test.input, test.base), <ide> (error) => { <del> if (!expectedError(error)) <del> return false; <add> expectedError(error); <ide> <ide> // The input could be processed, so we don't do strict matching here <del> const match = (`${error}`).match(/Invalid URL: (.*)$/); <del> if (!match) { <del> return false; <del> } <del> return error.input === match[1]; <add> let match; <add> assert(match = (`${error}`).match(/Invalid URL: (.*)$/)); <add> assert.strictEqual(error.input, match[1]); <add> return true; <ide> }); <ide> } <ide>
71
Text
Text
use https url for the api documentation page
4fcbb8aaaf32e57d5ec1c23460c0d2c86da4fe6e
<ide><path>README.md <ide> string which includes their date (in UTC time) and the commit SHA at <ide> the HEAD of the release. <ide> <ide> **API documentation** is available in each release and nightly <del>directory under _docs_. <http://iojs.org/api/> points to the the <add>directory under _docs_. <https://iojs.org/api/> points to the the <ide> latest version. <ide> <ide> ### Verifying Binaries
1
Javascript
Javascript
add quaternion tests
9d324c9601f2fddcb86d1f09262db9a0998338c3
<ide><path>test/unit/src/math/Quaternion.tests.js <ide> export default QUnit.module( 'Maths', () => { <ide> <ide> } ); <ide> <del> QUnit.todo( "x", ( assert ) => { <add> QUnit.test( "x", ( assert ) => { <add> var a = new Quaternion(); <add> assert.ok(a.x === 0, "Passed!"); <ide> <del> assert.ok( false, "everything's gonna be alright" ); <add> a = new Quaternion(1, 2, 3); <add> assert.ok(a.x === 1, "Passed!"); <add> <add> a = new Quaternion(4, 5, 6, 1); <add> assert.ok(a.x === 4, "Passed!"); <add> <add> a = new Quaternion(7, 8, 9); <add> a.x = 10; <add> assert.ok(a.x === 10, "Passed!"); <add> <add> a = new Quaternion(11, 12, 13); <add> var b = false; <add> a._onChange(function () { <add> <add> b = true; <add> <add> }); <add> assert.ok(!b, "Passed!"); <add> a.x = 14; <add> assert.ok(b, "Passed!"); <add> assert.ok(a.x === 14, "Passed!"); <ide> <ide> } ); <ide> <del> QUnit.todo( "y", ( assert ) => { <add> QUnit.test( "y", ( assert ) => { <ide> <del> assert.ok( false, "everything's gonna be alright" ); <add> var a = new Quaternion(); <add> assert.ok(a.y === 0, "Passed!"); <add> <add> a = new Quaternion(1, 2, 3); <add> assert.ok(a.y === 2, "Passed!"); <add> <add> a = new Quaternion(4, 5, 6, 1); <add> assert.ok(a.y === 5, "Passed!"); <add> <add> a = new Quaternion(7, 8, 9); <add> a.y = 10; <add> assert.ok(a.y === 10, "Passed!"); <add> <add> a = new Quaternion(11, 12, 13); <add> var b = false; <add> a._onChange(function () { <add> <add> b = true; <add> <add> }); <add> assert.ok(!b, "Passed!"); <add> a.y = 14; <add> assert.ok(b, "Passed!"); <add> assert.ok(a.y === 14, "Passed!"); <ide> <ide> } ); <ide> <del> QUnit.todo( "z", ( assert ) => { <add> QUnit.test( "z", ( assert ) => { <ide> <del> assert.ok( false, "everything's gonna be alright" ); <add> <add> var a = new Quaternion(); <add> assert.ok(a.z === 0, "Passed!"); <add> <add> a = new Quaternion(1, 2, 3); <add> assert.ok(a.z === 3, "Passed!"); <add> <add> a = new Quaternion(4, 5, 6, 1); <add> assert.ok(a.z === 6, "Passed!"); <add> <add> a = new Quaternion(7, 8, 9); <add> a.z = 10; <add> assert.ok(a.z === 10, "Passed!"); <add> <add> a = new Quaternion(11, 12, 13); <add> var b = false; <add> a._onChange(function () { <add> <add> b = true; <add> <add> }); <add> assert.ok(!b, "Passed!"); <add> a.z = 14; <add> assert.ok(b, "Passed!"); <add> assert.ok(a.z === 14, "Passed!"); <ide> <ide> } ); <ide> <del> QUnit.todo( "w", ( assert ) => { <add> QUnit.test( "w", ( assert ) => { <ide> <del> assert.ok( false, "everything's gonna be alright" ); <add> var a = new Quaternion(); <add> assert.ok(a.w === 1, "Passed!"); <add> <add> a = new Quaternion(1, 2, 3); <add> assert.ok(a.w === 1, "Passed!"); <add> <add> a = new Quaternion(4, 5, 6, 1); <add> assert.ok(a.w === 1, "Passed!"); <add> <add> a = new Quaternion(7, 8, 9); <add> a.w = 10; <add> assert.ok(a.w === 10, "Passed!"); <add> <add> a = new Quaternion(11, 12, 13); <add> var b = false; <add> a._onChange(function () { <add> <add> b = true; <add> <add> }); <add> assert.ok(!b, "Passed!"); <add> a.w = 14; <add> assert.ok(b, "Passed!"); <add> assert.ok(a.w === 14, "Passed!"); <ide> <ide> } ); <ide>
1
Python
Python
add extra col to log model
690c3e6373fa2490f6a8cdec9131e4f9d9f5379f
<ide><path>airflow/models.py <ide> class Log(Base): <ide> event = Column(String(30)) <ide> execution_date = Column(DateTime) <ide> owner = Column(String(500)) <add> extra = Column(Text) <ide> <del> def __init__(self, event, task_instance, owner=None): <add> def __init__(self, event, task_instance, owner=None, extra=None): <ide> self.dttm = datetime.now() <ide> self.event = event <add> self.extra = extra <ide> self.owner = owner or task_instance.task.owner <ide> <ide> if task_instance:
1
PHP
PHP
fix string length for odd lengths
71a715f93a1bb24b2d22a41612c97465b70a9e46
<ide><path>src/Utility/Security.php <ide> public static function randomBytes($length) <ide> */ <ide> public static function randomString($length) <ide> { <del> return bin2hex(Security::randomBytes($length / 2)); <add> return substr( <add> bin2hex(Security::randomBytes(ceil($length / 2))), <add> 0, <add> $length <add> ); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Utility/SecurityTest.php <ide> public function testRandomBytes() <ide> */ <ide> public function testRandomString() <ide> { <del> $value = Security::randomString(16); <del> $this->assertSame(16, strlen($value)); <add> $value = Security::randomString(7); <add> $this->assertSame(7, strlen($value)); <ide> <ide> $value = Security::randomString(64); <ide> $this->assertSame(64, strlen($value));
2
Javascript
Javascript
remove renderwithentry hook and add render hook
b7ad2b368c609070ed212af92e4729980987b233
<ide><path>lib/AmdTemplatePlugin.js <ide> class AmdTemplatePlugin { <ide> <ide> const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation); <ide> <del> hooks.renderWithEntry.tap( <add> hooks.render.tap( <ide> "AmdTemplatePlugin", <ide> (source, { chunk, runtimeTemplate, chunkGraph }) => { <add> if (chunkGraph.getNumberOfEntryModules(chunk) === 0) return source; <ide> const modern = runtimeTemplate.supportsArrowFunction(); <ide> const modules = chunkGraph <ide> .getChunkModules(chunk) <ide> class AmdTemplatePlugin { <ide> } <ide> ); <ide> <del> hooks.chunkHash.tap("AmdTemplatePlugin", (chunk, hash) => { <del> if (!chunk.hasEntryModule()) return; <del> hash.update("exports amd"); <del> if (this.requireAsWrapper) { <del> hash.update("requireAsWrapper"); <del> } else if (this.name) { <del> const name = compilation.getPath(this.name, { <del> chunk <del> }); <del> hash.update(name); <add> hooks.chunkHash.tap( <add> "AmdTemplatePlugin", <add> (chunk, hash, { chunkGraph }) => { <add> if (chunkGraph.getNumberOfEntryModules(chunk) === 0) return; <add> hash.update("exports amd"); <add> if (this.requireAsWrapper) { <add> hash.update("requireAsWrapper"); <add> } else if (this.name) { <add> const name = compilation.getPath(this.name, { <add> chunk <add> }); <add> hash.update(name); <add> } <ide> } <del> }); <add> ); <ide> }); <ide> } <ide> } <ide><path>lib/ChunkTemplate.js <ide> class ChunkTemplate { <ide> (options, fn) => { <ide> getJavascriptModulesPlugin() <ide> .getCompilationHooks(compilation) <del> .renderWithEntry.tap(options, (source, renderContext) => { <del> if (renderContext.chunk.hasRuntime()) return source; <add> .render.tap(options, (source, renderContext) => { <add> if ( <add> renderContext.chunkGraph.getNumberOfEntryModules( <add> renderContext.chunk <add> ) === 0 || <add> renderContext.chunk.hasRuntime() <add> ) { <add> return source; <add> } <ide> return fn(source, renderContext.chunk); <ide> }); <ide> }, <del> "ChunkTemplate.hooks.renderWithEntry is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderWithEntry instead)", <add> "ChunkTemplate.hooks.renderWithEntry is deprecated (use JavascriptModulesPlugin.getCompilationHooks().render instead)", <ide> "DEP_WEBPACK_CHUNK_TEMPLATE_RENDER_WITH_ENTRY" <ide> ) <ide> }, <ide><path>lib/ExportPropertyTemplatePlugin.js <ide> class ExportPropertyTemplatePlugin { <ide> <ide> const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation); <ide> <del> hooks.renderWithEntry.tap( <add> hooks.render.tap( <ide> "ExportPropertyTemplatePlugin", <del> (source, { chunk }) => { <add> (source, { chunk, chunkGraph }) => { <add> if (chunkGraph.getNumberOfEntryModules(chunk) === 0) return source; <ide> const postfix = accessorToObjectAccess([].concat(this.property)); <ide> return new ConcatSource(source, postfix); <ide> } <ide> ); <ide> <del> hooks.chunkHash.tap("ExportPropertyTemplatePlugin", (chunk, hash) => { <del> if (!chunk.hasEntryModule()) return; <del> hash.update("export property"); <del> hash.update(`${this.property}`); <del> }); <add> hooks.chunkHash.tap( <add> "ExportPropertyTemplatePlugin", <add> (chunk, hash, { chunkGraph }) => { <add> if (chunkGraph.getNumberOfEntryModules(chunk) === 0) return; <add> hash.update("export property"); <add> hash.update(`${this.property}`); <add> } <add> ); <ide> } <ide> ); <ide> } <ide><path>lib/JavascriptModulesPlugin.js <ide> const chunkHasJs = (chunk, chunkGraph) => { <ide> * @property {SyncWaterfallHook<[Source, Module, RenderContext]>} renderModulePackage <ide> * @property {SyncWaterfallHook<[Source, RenderContext]>} renderChunk <ide> * @property {SyncWaterfallHook<[Source, RenderContext]>} renderMain <del> * @property {SyncWaterfallHook<[Source, RenderContext]>} renderWithEntry <add> * @property {SyncWaterfallHook<[Source, RenderContext]>} render <ide> * @property {SyncWaterfallHook<[string, RenderBootstrapContext]>} renderRequire <ide> * @property {SyncHook<[Chunk, Hash, ChunkHashContext]>} chunkHash <ide> */ <ide> class JavascriptModulesPlugin { <ide> "module", <ide> "renderContext" <ide> ]), <del> renderWithEntry: new SyncWaterfallHook(["source", "renderContext"]), <add> render: new SyncWaterfallHook(["source", "renderContext"]), <ide> renderChunk: new SyncWaterfallHook(["source", "renderContext"]), <ide> renderMain: new SyncWaterfallHook(["source", "renderContext"]), <ide> renderRequire: new SyncWaterfallHook(["code", "renderContext"]), <ide> class JavascriptModulesPlugin { <ide> () => hooks.renderChunk.call(moduleSources, renderContext), <ide> "JavascriptModulesPlugin.getCompilationHooks().renderChunk" <ide> ); <del> if (renderContext.chunkGraph.getNumberOfEntryModules(chunk) > 0) { <del> source = tryRunOrWebpackError( <del> () => hooks.renderWithEntry.call(source, renderContext), <del> "JavascriptModulesPlugin.getCompilationHooks().renderWithEntry" <del> ); <del> } <add> source = tryRunOrWebpackError( <add> () => hooks.render.call(source, renderContext), <add> "JavascriptModulesPlugin.getCompilationHooks().render" <add> ); <ide> chunk.rendered = true; <ide> return new ConcatSource(source, ";"); <ide> } <ide> class JavascriptModulesPlugin { <ide> "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().renderMain plugins should return something" <ide> ); <ide> } <del> if (chunkGraph.getNumberOfEntryModules(chunk) > 0) { <del> finalSource = tryRunOrWebpackError( <del> () => hooks.renderWithEntry.call(finalSource, renderContext), <del> "JavascriptModulesPlugin.getCompilationHooks().renderWithEntry" <del> ); <del> } <add> finalSource = tryRunOrWebpackError( <add> () => hooks.render.call(finalSource, renderContext), <add> "JavascriptModulesPlugin.getCompilationHooks().render" <add> ); <ide> if (!finalSource) { <ide> throw new Error( <del> "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().renderWithEntry plugins should return something" <add> "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().render plugins should return something" <ide> ); <ide> } <ide> chunk.rendered = true; <ide><path>lib/MainTemplate.js <ide> class MainTemplate { <ide> (options, fn) => { <ide> getJavascriptModulesPlugin() <ide> .getCompilationHooks(compilation) <del> .renderWithEntry.tap(options, (source, renderContext) => { <del> if (!renderContext.chunk.hasRuntime()) return source; <add> .render.tap(options, (source, renderContext) => { <add> if ( <add> renderContext.chunkGraph.getNumberOfEntryModules( <add> renderContext.chunk <add> ) === 0 || <add> !renderContext.chunk.hasRuntime() <add> ) { <add> return source; <add> } <ide> return fn(source, renderContext.chunk, compilation.hash); <ide> }); <ide> }, <del> "MainTemplate.hooks.renderWithEntry is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderWithEntry instead)", <add> "MainTemplate.hooks.renderWithEntry is deprecated (use JavascriptModulesPlugin.getCompilationHooks().render instead)", <ide> "DEP_WEBPACK_MAIN_TEMPLATE_RENDER_WITH_ENTRY" <ide> ) <ide> }, <ide><path>lib/SetVarTemplatePlugin.js <ide> class SetVarTemplatePlugin { <ide> <ide> const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation); <ide> <del> hooks.renderWithEntry.tap("SetVarTemplatePlugin", (source, { chunk }) => { <del> const varExpression = compilation.getPath(this.varExpression, { <del> chunk <del> }); <del> if (this.copyObject) { <del> return new ConcatSource( <del> `(function(e, a) { for(var i in a) e[i] = a[i]; }(${varExpression}, `, <del> source, <del> "))" <del> ); <del> } else { <del> const prefix = `${varExpression} =\n`; <del> return new ConcatSource(prefix, source); <add> hooks.render.tap( <add> "SetVarTemplatePlugin", <add> (source, { chunk, chunkGraph }) => { <add> if (chunkGraph.getNumberOfEntryModules(chunk) === 0) return source; <add> const varExpression = compilation.getPath(this.varExpression, { <add> chunk <add> }); <add> if (this.copyObject) { <add> return new ConcatSource( <add> `(function(e, a) { for(var i in a) e[i] = a[i]; }(${varExpression}, `, <add> source, <add> "))" <add> ); <add> } else { <add> const prefix = `${varExpression} =\n`; <add> return new ConcatSource(prefix, source); <add> } <ide> } <del> }); <add> ); <ide> <del> hooks.chunkHash.tap("SetVarTemplatePlugin", (chunk, hash) => { <del> if (!chunk.hasEntryModule()) return; <del> hash.update("set var"); <del> const varExpression = compilation.getPath(this.varExpression, { <del> chunk <del> }); <del> hash.update(`${varExpression}`); <del> hash.update(`${this.copyObject}`); <del> }); <add> hooks.chunkHash.tap( <add> "SetVarTemplatePlugin", <add> (chunk, hash, { chunkGraph }) => { <add> if (chunkGraph.getNumberOfEntryModules(chunk) === 0) return; <add> hash.update("set var"); <add> const varExpression = compilation.getPath(this.varExpression, { <add> chunk <add> }); <add> hash.update(`${varExpression}`); <add> hash.update(`${this.copyObject}`); <add> } <add> ); <ide> }); <ide> } <ide> } <ide><path>lib/SystemTemplatePlugin.js <ide> class SystemTemplatePlugin { <ide> <ide> const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation); <ide> <del> hooks.renderWithEntry.tap( <add> hooks.render.tap( <ide> "SystemTemplatePlugin", <ide> (source, { chunk, chunkGraph }) => { <add> if (chunkGraph.getNumberOfEntryModules(chunk) === 0) return source; <add> <ide> const modules = chunkGraph <ide> .getChunkModules(chunk) <ide> .filter(m => m instanceof ExternalModule); <ide> class SystemTemplatePlugin { <ide> } <ide> ); <ide> <del> hooks.chunkHash.tap("SystemTemplatePlugin", (chunk, hash) => { <del> hash.update("exports system"); <del> if (this.name) { <del> hash.update(compilation.getPath(this.name, { chunk })); <add> hooks.chunkHash.tap( <add> "SystemTemplatePlugin", <add> (chunk, hash, { chunkGraph }) => { <add> if (chunkGraph.getNumberOfEntryModules(chunk) === 0) return; <add> hash.update("exports system"); <add> if (this.name) { <add> hash.update(compilation.getPath(this.name, { chunk })); <add> } <ide> } <del> }); <add> ); <ide> }); <ide> } <ide> } <ide><path>lib/UmdTemplatePlugin.js <ide> class UmdTemplatePlugin { <ide> <ide> const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation); <ide> <del> hooks.renderWithEntry.tap( <add> hooks.render.tap( <ide> "UmdTemplatePlugin", <ide> (source, { chunk, moduleGraph, chunkGraph, runtimeTemplate }) => { <add> if (chunkGraph.getNumberOfEntryModules(chunk) === 0) return source; <add> <ide> const modules = chunkGraph <ide> .getChunkModules(chunk) <ide> .filter( <ide> class UmdTemplatePlugin { <ide> } <ide> ); <ide> <del> hooks.chunkHash.tap("UmdTemplatePlugin", (chunk, hash) => { <del> if (!chunk.hasEntryModule()) return; <del> hash.update("umd"); <del> hash.update(`${this.names.root}`); <del> hash.update(`${this.names.amd}`); <del> hash.update(`${this.names.commonjs}`); <del> }); <add> hooks.chunkHash.tap( <add> "UmdTemplatePlugin", <add> (chunk, hash, { chunkGraph }) => { <add> if (chunkGraph.getNumberOfEntryModules(chunk) === 0) return; <add> hash.update("umd"); <add> hash.update(`${this.names.root}`); <add> hash.update(`${this.names.amd}`); <add> hash.update(`${this.names.commonjs}`); <add> } <add> ); <ide> }); <ide> } <ide> } <ide><path>lib/web/JsonpExportTemplatePlugin.js <ide> class JsonpExportTemplatePlugin { <ide> <ide> const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation); <ide> <del> hooks.renderWithEntry.tap( <add> hooks.render.tap( <ide> "JsonpExportTemplatePlugin", <del> (source, { chunk }) => { <add> (source, { chunk, chunkGraph }) => { <add> if (chunkGraph.getNumberOfEntryModules(chunk) === 0) return source; <ide> const name = compilation.getPath(this.name || "", { <ide> chunk <ide> }); <ide> return new ConcatSource(`${name}(`, source, ");"); <ide> } <ide> ); <ide> <del> hooks.chunkHash.tap("JsonpExportTemplatePlugin", (chunk, hash) => { <del> hash.update("jsonp export"); <del> const name = compilation.getPath(this.name || "", { <del> chunk <del> }); <del> hash.update(`${name}`); <del> }); <add> hooks.chunkHash.tap( <add> "JsonpExportTemplatePlugin", <add> (chunk, hash, { chunkGraph }) => { <add> if (chunkGraph.getNumberOfEntryModules(chunk) === 0) return; <add> hash.update("jsonp export"); <add> const name = compilation.getPath(this.name || "", { <add> chunk <add> }); <add> hash.update(`${name}`); <add> } <add> ); <ide> } <ide> ); <ide> }
9
Text
Text
remove temporary inline styles
4e6a01023b7422dc3df7f02e248bb06361069fcc
<ide><path>docs/sources/project/find-an-issue.md <ide> page_title: Make a project contribution <ide> page_description: Basic workflow for Docker contributions <ide> page_keywords: contribute, pull request, review, workflow, white-belt, black-belt, squash, commit <ide> <del><!-- TODO (@thaJeztah) remove after docs/base is updated --> <ide> <style type="text/css"> <del>.tg {border-collapse:collapse;border-spacing:0;margin-bottom:15px;} <del>.tg td {background-color: #fff;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top;} <del>.tg th {font-weight:bold;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;text-align:left;} <del>.tg .tg-e3zv{width:150px;} <del></style> <del> <del><style> <ide> <ide> /* GitHub label styles */ <ide> .gh-label { <ide><path>docs/sources/project/get-help.md <ide> page_title: Where to chat or get help <ide> page_description: Describes Docker's communication channels <ide> page_keywords: IRC, Google group, Twitter, blog, Stackoverflow <ide> <del><style> <add><style type="text/css"> <ide> /* @TODO add 'no-zebra' table-style to the docs-base stylesheet */ <ide> /* Table without "zebra" striping */ <ide> .content-body table.no-zebra tr { <ide> page_keywords: IRC, Google group, Twitter, blog, Stackoverflow <ide> There are several communications channels you can use to chat with Docker <ide> community members and developers. <ide> <del><!-- TODO (@thaJeztah) remove after docs/base is updated --> <del><style type="text/css"> <del>.tg {border-collapse:collapse;border-spacing:0;text-align: left;} <del>.tg td{padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top;} <del>.tg th{font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;} <del></style> <del><table class="tg"> <add><table> <ide> <col width="25%"> <ide> <col width="75%"> <ide> <tr> <ide> the easiest way to connect to IRC. <ide> <ide> 2. Fill out the form. <ide> <del> <!-- TODO (@thaJeztah) remove after docs/base is updated --> <del> <style type="text/css"> <del> .tg {border-collapse:collapse;border-spacing:0;} <del> .tg td{padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;} <del> .tg th{font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;} <del> </style> <del> <table class="tg no-zebra" style="width: auto"> <add> <table class="no-zebra" style="width: auto"> <ide> <tr> <ide> <td><b>Nickname</b></td> <ide> <td>The short name you want to be known as in IRC.</td> <ide><path>docs/sources/project/make-a-contribution.md <ide> page_title: Understand how to contribute <ide> page_description: Explains basic workflow for Docker contributions <ide> page_keywords: contribute, maintainers, review, workflow, process <ide> <del><!-- TODO (@thaJeztah) remove after docs/base is updated --> <del><style type="text/css"> <del>.tg {border-collapse:collapse;border-spacing:0;margin-bottom:15px;} <del>.tg td {background-color: #fff;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top;} <del>.tg th {font-weight:bold;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;text-align:left;} <del>.tg .tg-e3zv{width:150px;} <del></style> <del> <del><style> <del> <del>/* GitHub label styles */ <del>.gh-label { <del> display: inline-block; <del> padding: 3px 4px; <del> font-size: 11px; <del> font-weight: bold; <del> line-height: 1; <del> color: #fff; <del> border-radius: 2px; <del> box-shadow: inset 0 -1px 0 rgba(0,0,0,0.12); <del>} <del> <del>.gh-label.black-belt { background-color: #000000; color: #ffffff; } <del>.gh-label.bug { background-color: #fc2929; color: #ffffff; } <del>.gh-label.improvement { background-color: #bfe5bf; color: #2a332a; } <del>.gh-label.project-doc { background-color: #207de5; color: #ffffff; } <del>.gh-label.white-belt { background-color: #ffffff; color: #333333; } <del> <del></style> <del> <ide> # Understand how to contribute <ide> <ide> Contributing is a process where you work with Docker maintainers and the <del>community to improve Docker. The maintainers are experienced contributors who specialize in one or more Docker components. Maintainers play a big role in reviewing contributions. <add>community to improve Docker. The maintainers are experienced contributors <add>who specialize in one or more Docker components. Maintainers play a big role <add>in reviewing contributions. <ide> <ide> There is a formal process for contributing. We try to keep our contribution <ide> process simple so you'll want to contribute frequently. <ide> contributions. When you reach that point in the flow, we make sure to tell you. <ide> <ide> ## Where to go next <ide> <del>Now that you know a little about the contribution process, go to the next section to [find an issue you want to work on](/project/find-an-issue/). <add>Now that you know a little about the contribution process, go to the next section <add>to [find an issue you want to work on](/project/find-an-issue/). <ide><path>docs/sources/project/set-up-dev-env.md <ide> page_title: Work with a development container <ide> page_description: How to use Docker's development environment <ide> page_keywords: development, inception, container, image Dockerfile, dependencies, Go, artifacts <ide> <del> <del><!-- TODO (@thaJeztah) remove after docs/base is updated --> <del><style type="text/css"> <del>.tg {border-collapse:collapse;border-spacing:0;} <del>.tg td{font-family:monospace, serif;font-size:11px;padding:10px 5px;border-style:solid;border-width:0px;overflow:hidden;word-break:normal;} <del>.tg th{font-family:monospace, sans-serif;font-size:11px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:0px;overflow:hidden;word-break:normal;} <del></style> <del> <ide> # Work with a development container <ide> <ide> In this section, you learn to develop like a member of Docker's core team. <ide> To remove unnecessary artifacts. <ide> <ide> You should see something similar to the following: <ide> <del> <table class="tg code"> <add> <table class="code"> <ide> <tr> <ide> <th>CONTAINER ID</th> <ide> <th>IMAGE</th> <ide> To remove unnecessary artifacts. <ide> <ide> You should see something similar to the following: <ide> <del> <table class="tg code"> <add> <table class="code"> <ide> <tr> <ide> <th>REPOSITORY</th> <ide> <th>TAG</th> <ide> environment. <ide> <ide> You should see something similar to this: <ide> <del> <table class="tg code"> <add> <table class="code"> <ide> <tr> <ide> <th>REPOSTITORY</th> <ide> <th>TAG</th> <ide> build and run a `docker` binary in your container. <ide> <ide> $ docker ps <ide> <del> <table class="tg code"> <add> <table class="code"> <ide> <tr> <ide> <th>CONTAINER ID</th> <ide> <th>IMAGE</th> <ide><path>docs/sources/project/test-and-docs.md <ide> page_title: Run tests and test documentation <ide> page_description: Describes Docker's testing infrastructure <ide> page_keywords: make test, make docs, Go tests, gofmt, contributing, running tests <ide> <del><!-- TODO (@thaJeztah) remove after docs/base is updated --> <del><style type="text/css"> <del>.tg {border-collapse:collapse;border-spacing:0;margin-bottom:15px;} <del>.tg td{padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;} <del>.tg th{padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;text-align:left;} <del></style> <del> <ide> # Run tests and test documentation <ide> <ide> Contributing includes testing your changes. If you change the Docker code, you <ide> The `Makefile` contains a target for the entire test suite. The target's name <ide> is simply `test`. The make file contains several targets for testing: <ide> <ide> <style type="text/css"> <del>.make-target {font-family:"Courier New", Courier, monospace !important;} <add>.monospaced {font-family: Monaco, Consolas, "Lucida Console", monospace !important;} <ide> </style> <del><table class="tg"> <add><table> <ide> <tr> <ide> <th>Target</th> <ide> <th>What this target does</th> <ide> </tr> <ide> <tr> <del> <td class="make-target">test</td> <add> <td class="monospaced">test</td> <ide> <td>Run all the tests.</td> <ide> </tr> <ide> <tr> <del> <td class="make-target">test-unit</td> <add> <td class="monospaced">test-unit</td> <ide> <td>Run just the unit tests.</td> <ide> </tr> <ide> <tr> <del> <td class="make-target">test-integration</td> <add> <td class="monospaced">test-integration</td> <ide> <td>Run just integration tests.</td> <ide> </tr> <ide> <tr> <del> <td class="make-target">test-integration-cli</td> <add> <td class="monospaced">test-integration-cli</td> <ide> <td>Run the test for the integration command line interface.</td> <ide> </tr> <ide> <tr> <del> <td class="make-target">test-docker-py</td> <add> <td class="monospaced">test-docker-py</td> <ide> <td>Run the tests for Docker API client.</td> <ide> </tr> <ide> <tr> <del> <td class="make-target">docs-test</td> <add> <td class="monospaced">docs-test</td> <ide> <td>Runs the documentation test build.</td> <ide> </tr> <ide> </table> <ide> You can use the `TESTFLAGS` environment variable to run a single test. The <ide> flag's value is passed as arguments to the `go test` command. For example, from <ide> your local host you can run the `TestBuild` test with this command: <ide> <del> $ TESTFLAGS='-test.run ^TestBuild$' make test <add> $ TESTFLAGS='-test.run ^TestBuild$' make test <ide> <ide> To run the same test inside your Docker development container, you do this: <ide> <del> root@5f8630b873fe:/go/src/github.com/docker/docker# TESTFLAGS='-run ^TestBuild$' hack/make.sh <add> root@5f8630b873fe:/go/src/github.com/docker/docker# TESTFLAGS='-run ^TestBuild$' hack/make.sh <ide> <ide> ## If test under Boot2Docker fail do to space errors <ide> <ide><path>docs/sources/project/work-issue.md <ide> Follow this workflow as you work: <ide> <ide> 5. Format your source files correctly. <ide> <del> <table class="tg"> <add> <table> <ide> <thead> <ide> <tr> <del> <th class="tg-e3zv">File type</th> <add> <th>File type</th> <ide> <th>How to format</th> <ide> </tr> <ide> </thead> <ide> <tbody> <ide> <tr> <del> <td class="tg-e3zv"><code>.go</code></td> <add> <td><code>.go</code></td> <ide> <td> <ide> <p> <ide> Format <code>.go</code> files using the <code>gofmt</code> command. <ide> For example, if you edited the `docker.go` file you would format the file <del> like this: <del> </p> <del> <p><code>$ gofmt -s -w file.go</code></p> <del> <p> <del> Most file editors have a plugin to format for you. Check your editor's <del> documentation. <del> </p> <add> like this: <add> </p> <add> <p><code>$ gofmt -s -w file.go</code></p> <add> <p> <add> Most file editors have a plugin to format for you. Check your editor's <add> documentation. <add> </p> <ide> </td> <ide> </tr> <ide> <tr> <del> <td class="tg-e3zv" style="white-space: nowrap"><code>.md</code> and non-<code>.go</code> files</td> <add> <td style="white-space: nowrap"><code>.md</code> and non-<code>.go</code> files</td> <ide> <td>Wrap lines to 80 characters.</td> <ide> </tr> <ide> </tbody>
6
Text
Text
add arabic translation for bash-mkdir
46d567121ed3439b514e66e9297ad8725fc7408a
<ide><path>guide/arabic/bash/bash-mkdir/index.md <add>--- <add>title: Bash mkdir <add>localeTitle: باش mkdir <add>--- <add> <add>## أمر Bash: mkdir <add> <add>**انشاء مجلد** <add> <add>مثال: <add> <add>`mkdir directory_name` <add> <add>يستخدم هذا الأمر لإنشاء مجلد جديد بالاسم المزود. <add> <add>بعض الخيارات الاكثر استخداما: <add>- `-p` انشاء مجلدات متداخلة، هذا الخيار لا يطبع خطأ عند محاولة انشاء مجلد موجود. <add>- `-v` طبع رسالة عند انشاء مجلد. <add> <add>لنفرض أردنا انشاء مجلد اسمة `dir` داخل المسار `a/b/c/dir`، لكن المجلدين `b` و `c` غير موجودين، في هذه الحالة يمكننا استخدام الأمر بهذه الطريقة `mkdir -p a/b/c/dir` لإنشاء جميع المجلدات بنفس الوقت. <add> <add> <add>### للمزيد من المعلومات: <add>* [ويكيبيديا](https://ar.wikipedia.org/wiki/%D9%85%D8%A7%D9%83_%D8%AF%D9%8A%D8%B1) <add>* [صفحة الويكيبيديا بالإنكليزي](https://en.wikipedia.org/wiki/Mkdir)
1
PHP
PHP
remove numerous calls to in_array()
2789ab09deeb337a2909bd416153470595e959ab
<ide><path>src/View/StringTemplate.php <ide> class StringTemplate { <ide> * @var array <ide> */ <ide> protected $_compactAttributes = array( <del> 'compact', 'checked', 'declare', 'readonly', 'disabled', 'selected', <del> 'defer', 'ismap', 'nohref', 'noshade', 'nowrap', 'multiple', 'noresize', <del> 'autoplay', 'controls', 'loop', 'muted', 'required', 'novalidate', 'formnovalidate' <add> 'compact' => true, <add> 'checked' => true, <add> 'declare' => true, <add> 'readonly' => true, <add> 'disabled' => true, <add> 'selected' => true, <add> 'defer' => true, <add> 'ismap' => true, <add> 'nohref' => true, <add> 'noshade' => true, <add> 'nowrap' => true, <add> 'multiple' => true, <add> 'noresize' => true, <add> 'autoplay' => true, <add> 'controls' => true, <add> 'loop' => true, <add> 'muted' => true, <add> 'required' => true, <add> 'novalidate' => true, <add> 'formnovalidate' => true, <ide> ); <ide> <ide> /** <ide> protected function _formatAttribute($key, $value, $escape = true) { <ide> return "$value=\"$value\""; <ide> } <ide> $truthy = [1, '1', true, 'true', $key]; <del> $isMinimized = in_array($key, $this->_compactAttributes); <add> $isMinimized = isset($this->_compactAttributes[$key]); <ide> if ($isMinimized && in_array($value, $truthy, true)) { <ide> return "$key=\"$key\""; <ide> }
1
Python
Python
add processors to __init__
0b84b9fd8a728ca46e4109aa38a11b25f87a09bf
<ide><path>transformers/__init__.py <ide> glue_output_modes, glue_convert_examples_to_features, <ide> glue_processors, glue_tasks_num_labels, <ide> squad_convert_examples_to_features, SquadFeatures, <del> SquadExample) <add> SquadExample, SquadV1Processor, SquadV2Processor) <ide> <ide> if is_sklearn_available(): <ide> from .data import glue_compute_metrics <ide><path>transformers/data/__init__.py <ide> from .processors import InputExample, InputFeatures, DataProcessor, SquadFeatures <ide> from .processors import glue_output_modes, glue_processors, glue_tasks_num_labels, glue_convert_examples_to_features <del>from .processors import squad_convert_examples_to_features, SquadExample <add>from .processors import squad_convert_examples_to_features, SquadExample, SquadV1Processor, SquadV2Processor <ide> <ide> from .metrics import is_sklearn_available <ide> if is_sklearn_available(): <ide><path>transformers/data/processors/__init__.py <ide> from .utils import InputExample, InputFeatures, DataProcessor <ide> from .glue import glue_output_modes, glue_processors, glue_tasks_num_labels, glue_convert_examples_to_features <del>from .squad import squad_convert_examples_to_features, SquadFeatures, SquadExample <add>from .squad import squad_convert_examples_to_features, SquadFeatures, SquadExample, SquadV1Processor, SquadV2Processor <ide>
3
Go
Go
remove unuse slice in registry
3ed06f96706887e491f8acdb72c5704022504fa9
<ide><path>registry/types.go <ide> import ( <ide> "github.com/docker/docker/reference" <ide> ) <ide> <del>// RepositoryData tracks the image list, list of endpoints, and list of tokens <del>// for a repository <add>// RepositoryData tracks the image list, list of endpoints for a repository <ide> type RepositoryData struct { <ide> // ImgList is a list of images in the repository <ide> ImgList map[string]*ImgData <ide> // Endpoints is a list of endpoints returned in X-Docker-Endpoints <ide> Endpoints []string <del> // Tokens is currently unused (remove it?) <del> Tokens []string <ide> } <ide> <ide> // ImgData is used to transfer image checksums to and from the registry
1
Javascript
Javascript
stabilize azure test
b12389598b20852367074f7cde94b6fce52995e3
<ide><path>test/integration/dynamic-routing/pages/[name]/[comment].js <ide> const $comment = ({ gipQuery }) => { <ide> <ide> return ( <ide> <> <del> <p> <add> <p id="asdf"> <ide> I am {query.comment} on {query.name} <ide> </p> <ide> <span>gip {gipQuery && gipQuery.name}</span> <ide><path>test/integration/dynamic-routing/pages/[name]/comments.js <ide> import { useRouter } from 'next/router' <ide> const Page = () => { <ide> const router = useRouter() <ide> const { query } = router <del> return <p>Show comments for {query.name} here</p> <add> return <p id="asdf">Show comments for {query.name} here</p> <ide> } <ide> <ide> Page.getInitialProps = () => ({}) <ide><path>test/integration/dynamic-routing/pages/[name]/index.js <ide> import { useRouter } from 'next/router' <ide> const Page = () => { <ide> const router = useRouter() <ide> const { query } = router <del> return <p>This is {query.name}</p> <add> return <p id="asdf">This is {query.name}</p> <ide> } <ide> <ide> Page.getInitialProps = () => ({}) <ide><path>test/integration/dynamic-routing/pages/blog/[name]/comment/[id].js <ide> const Page = () => { <ide> <ide> return ( <ide> <> <del> <p> <add> <p id="asdf"> <ide> Blog post {name} comment {id || '(all)'} <ide> </p> <ide> </> <ide><path>test/integration/dynamic-routing/pages/on-mount/[post].js <ide> export default () => { <ide> const { query } = router <ide> return ( <ide> <> <del> <p>onmpost: {query.post || 'pending'}</p> <add> <p id="asdf">onmpost: {query.post || 'pending'}</p> <ide> {Array.from({ length: 500 }, (x, i) => i + 1).map((i) => { <ide> return ( <ide> <div key={`item-${i}`} id={`item-${i}`}> <ide><path>test/integration/dynamic-routing/test/index.test.js <ide> function runTests(dev) { <ide> try { <ide> browser = await webdriver(appPort, '/') <ide> await browser.elementByCss('#view-post-1').click() <del> await browser.waitForElementByCss('p') <add> await browser.waitForElementByCss('#asdf') <ide> <del> const text = await browser.elementByCss('p').text() <add> const text = await browser.elementByCss('#asdf').text() <ide> expect(text).toMatch(/this is.*?post-1/i) <ide> } finally { <ide> if (browser) await browser.close() <ide> function runTests(dev) { <ide> expect(await browser.elementByCss('h3').text()).toBe('My blog') <ide> }) <ide> <del> it.skip('should navigate optional dynamic page', async () => { <add> it('should navigate optional dynamic page', async () => { <ide> let browser <ide> try { <ide> browser = await webdriver(appPort, '/') <del> await browser.elementByCss('#view-blog-post-1-comments').click() <del> await browser.waitForElementByCss('p') <add> await browser.elementByCss('#view-post-1-comments').click() <add> await browser.waitForElementByCss('#asdf') <ide> <del> const text = await browser.elementByCss('p').text() <del> expect(text).toMatch(/blog post.*543.*comment.*\(all\)/i) <add> const text = await browser.elementByCss('#asdf').text() <add> expect(text).toMatch(/comments for post-1 here/i) <ide> } finally { <ide> if (browser) await browser.close() <ide> } <ide> function runTests(dev) { <ide> try { <ide> browser = await webdriver(appPort, '/') <ide> await browser.elementByCss('#view-nested-dynamic-cmnt').click() <del> await browser.waitForElementByCss('p') <add> await browser.waitForElementByCss('#asdf') <ide> <del> const text = await browser.elementByCss('p').text() <add> const text = await browser.elementByCss('#asdf').text() <ide> expect(text).toMatch(/blog post.*321.*comment.*123/i) <ide> } finally { <ide> if (browser) await browser.close() <ide> function runTests(dev) { <ide> try { <ide> browser = await webdriver(appPort, '/') <ide> await browser.elementByCss('#view-post-1-comment-1').click() <del> await browser.waitForElementByCss('p') <add> await browser.waitForElementByCss('#asdf') <ide> <del> const text = await browser.elementByCss('p').text() <add> const text = await browser.elementByCss('#asdf').text() <ide> expect(text).toMatch(/i am.*comment-1.*on.*post-1/i) <ide> } finally { <ide> if (browser) await browser.close() <ide> function runTests(dev) { <ide> it('should scroll to a hash on client-side navigation', async () => { <ide> const browser = await webdriver(appPort, '/') <ide> await browser.elementByCss('#view-dynamic-with-hash').click() <del> await browser.waitForElementByCss('p') <add> await browser.waitForElementByCss('#asdf') <ide> <del> const text = await browser.elementByCss('p').text() <add> const text = await browser.elementByCss('#asdf').text() <ide> expect(text).toMatch(/onmpost:.*test-w-hash/) <ide> <ide> const scrollPosition = await browser.eval('window.pageYOffset') <ide><path>test/integration/invalid-href/pages/[post].js <del>export default () => 'hi from post' <add>export default function Page() { <add> return 'hi from post' <add>} <ide><path>test/integration/invalid-href/pages/dynamic-route-mismatch-manual.js <ide> import Link from 'next/link' <ide> <del>export default () => ( <del> <Link href="/[post]?post=post-1" as="/blog/post-1"> <del> <a>Click me</a> <del> </Link> <del>) <add>export default function Page() { <add> return ( <add> <Link href="/[post]?post=post-1" as="/blog/post-1"> <add> <a id="click-me">Click me</a> <add> </Link> <add> ) <add>} <ide><path>test/integration/invalid-href/pages/dynamic-route-mismatch.js <ide> import Link from 'next/link' <ide> <del>export default () => ( <del> <Link href="/[post]" as="/blog/post-1"> <del> <a>Click me</a> <del> </Link> <del>) <add>export default function Page() { <add> return ( <add> <Link href="/[post]" as="/blog/post-1"> <add> <a id="click-me">Click me</a> <add> </Link> <add> ) <add>} <ide><path>test/integration/invalid-href/pages/first.js <ide> import { useRouter } from 'next/router' <ide> <ide> const invalidLink = 'mailto:idk@idk.com' <ide> <del>export default () => { <add>export default function Page() { <ide> const { query, ...router } = useRouter() <ide> const { method } = query <ide> <ide><path>test/integration/invalid-href/pages/index.js <ide> // page used for loading and installing error catcher <del>export default () => <p>Hi 👋</p> <add>export default function Page() { <add> return <p>Hi 👋</p> <add>} <ide><path>test/integration/invalid-href/pages/second.js <ide> import { useRouter } from 'next/router' <ide> <ide> const invalidLink = 'https://google.com/another' <ide> <del>export default () => { <add>export default function Page() { <ide> const { query, ...router } = useRouter() <ide> const { method } = query <ide> <ide><path>test/integration/invalid-href/test/index.test.js <ide> import { <ide> nextBuild, <ide> nextStart, <ide> waitFor, <add> check, <ide> } from 'next-test-utils' <ide> import webdriver from 'next-webdriver' <ide> import { join } from 'path' <ide> <del>jest.setTimeout(1000 * 60 * 5) <add>jest.setTimeout(1000 * 60 * 2) <add> <ide> let app <ide> let appPort <ide> const appDir = join(__dirname, '..') <ide> <ide> const firstErrorRegex = /Invalid href passed to router: mailto:idk@idk.com.*invalid-href-passed/ <ide> const secondErrorRegex = /Invalid href passed to router: .*google\.com.*invalid-href-passed/ <ide> <del>const showsError = async ( <del> pathname, <del> regex, <del> click = false, <del> isWarn = false, <del> cb <del>) => { <add>const showsError = async (pathname, regex, click = false, isWarn = false) => { <ide> const browser = await webdriver(appPort, pathname) <del> if (isWarn) { <del> await browser.eval(`(function() { <del> window.warnLogs = [] <del> var origWarn = window.console.warn <del> window.console.warn = function() { <del> var warnStr = '' <del> for (var i = 0; i < arguments.length; i++) { <del> if (i > 0) warnStr += ' '; <del> warnStr += arguments[i] <add> try { <add> if (isWarn) { <add> await browser.eval(`(function() { <add> window.warnLogs = [] <add> var origWarn = window.console.warn <add> window.console.warn = function() { <add> var warnStr = '' <add> for (var i = 0; i < arguments.length; i++) { <add> if (i > 0) warnStr += ' '; <add> warnStr += arguments[i] <add> } <add> window.warnLogs.push(warnStr) <add> origWarn.apply(undefined, arguments) <ide> } <del> window.warnLogs.push(warnStr) <del> origWarn.apply(undefined, arguments) <del> } <del> })()`) <del> } <del> <del> if (click) { <del> await browser.elementByCss('a').click() <del> } <del> if (isWarn) { <del> await waitFor(2000) <del> const warnLogs = await browser.eval('window.warnLogs') <del> console.log(warnLogs) <del> expect(warnLogs.some((log) => log.match(regex))).toBe(true) <del> } else { <del> expect(await hasRedbox(browser)).toBe(true) <del> const errorContent = await getRedboxHeader(browser) <del> expect(errorContent).toMatch(regex) <add> })()`) <add> } <add> // wait for page to be built and navigated to <add> await waitFor(3000) <add> await browser.waitForElementByCss('#click-me') <add> if (click) { <add> await browser.elementByCss('#click-me').click() <add> await waitFor(500) <add> } <add> if (isWarn) { <add> await check(async () => { <add> const warnLogs = await browser.eval('window.warnLogs') <add> return warnLogs.join('\n') <add> }, regex) <add> } else { <add> expect(await hasRedbox(browser)).toBe(true) <add> const errorContent = await getRedboxHeader(browser) <add> expect(errorContent).toMatch(regex) <add> } <add> } finally { <add> await browser.close() <ide> } <del> <del> if (cb) await cb(browser) <del> <del> await browser.close() <ide> } <ide> <ide> const noError = async (pathname, click = false) => { <ide> const browser = await webdriver(appPort, '/') <del> await browser.eval(`(function() { <del> window.caughtErrors = [] <del> window.addEventListener('error', function (error) { <del> window.caughtErrors.push(error.message || 1) <del> }) <del> window.addEventListener('unhandledrejection', function (error) { <del> window.caughtErrors.push(error.message || 1) <del> }) <del> window.next.router.replace('${pathname}') <del> })()`) <del> // wait for page to be built and navigated to <del> await waitFor(3000) <del> if (click) { <del> await browser.elementByCss('a').click() <add> try { <add> await browser.eval(`(function() { <add> window.caughtErrors = [] <add> window.addEventListener('error', function (error) { <add> window.caughtErrors.push(error.message || 1) <add> }) <add> window.addEventListener('unhandledrejection', function (error) { <add> window.caughtErrors.push(error.message || 1) <add> }) <add> window.next.router.replace('${pathname}') <add> })()`) <add> // wait for page to be built and navigated to <add> await waitFor(3000) <add> await browser.waitForElementByCss('#click-me') <add> if (click) { <add> await browser.elementByCss('#click-me').click() <add> await waitFor(500) <add> } <add> const caughtErrors = await browser.eval(`window.caughtErrors`) <add> expect(caughtErrors).toHaveLength(0) <add> } finally { <add> await browser.close() <ide> } <del> const numErrors = await browser.eval(`window.caughtErrors.length`) <del> expect(numErrors).toBe(0) <del> await browser.close() <ide> } <ide> <ide> describe('Invalid hrefs', () => { <ide> describe('dev mode', () => { <ide> beforeAll(async () => { <ide> appPort = await findPort() <del> app = await launchApp(appDir, appPort, { <del> env: { __NEXT_TEST_WITH_DEVTOOL: 1 }, <del> }) <add> app = await launchApp(appDir, appPort) <ide> }) <ide> afterAll(() => killApp(app)) <ide> <ide> describe('Invalid hrefs', () => { <ide> <ide> it('shows error when dynamic route mismatch is used on Link', async () => { <ide> const browser = await webdriver(appPort, '/dynamic-route-mismatch') <del> await browser.eval(`(function() { <del> window.caughtErrors = [] <del> window.addEventListener('unhandledrejection', (error) => { <del> window.caughtErrors.push(error.reason.message) <del> }) <del> })()`) <del> await browser.elementByCss('a').click() <del> await waitFor(500) <del> const errors = await browser.eval('window.caughtErrors') <del> expect( <del> errors.find((err) => <del> err.includes( <del> 'The provided `as` value (/blog/post-1) is incompatible with the `href` value (/[post]). Read more: https://err.sh/vercel/next.js/incompatible-href-as' <add> try { <add> await browser.eval(`(function() { <add> window.caughtErrors = [] <add> window.addEventListener('unhandledrejection', (error) => { <add> window.caughtErrors.push(error.reason.message) <add> }) <add> })()`) <add> await browser.elementByCss('a').click() <add> await waitFor(500) <add> const errors = await browser.eval('window.caughtErrors') <add> expect( <add> errors.find((err) => <add> err.includes( <add> 'The provided `as` value (/blog/post-1) is incompatible with the `href` value (/[post]). Read more: https://err.sh/vercel/next.js/incompatible-href-as' <add> ) <ide> ) <del> ) <del> ).toBeTruthy() <add> ).toBeTruthy() <add> } finally { <add> await browser.close() <add> } <ide> }) <ide> <ide> it('makes sure that router push with bad links resolve', async () => {
13
Text
Text
update object_detection docs
c0cf58e635f47145c086b6bf2c39ed73e759557f
<ide><path>object_detection/g3doc/configuring_jobs.md <ide> number of workers, gpu type). <ide> <ide> ## Configuring the Evaluator <ide> <del>Currently evaluation is fixed to generating metrics as defined by the PASCAL <del>VOC challenge. The parameters for `eval_config` are set to reasonable defaults <del>and typically do not need to be configured. <add>Currently evaluation is fixed to generating metrics as defined by the PASCAL VOC <add>challenge. The parameters for `eval_config` are set to reasonable defaults and <add>typically do not need to be configured. <ide><path>object_detection/g3doc/installation.md <ide> to avoid running this manually, you can add it as a new line to the end of your <ide> You can test that you have correctly installed the Tensorflow Object Detection\ <ide> API by running the following command: <ide> <del>``` bash <add>```bash <ide> python object_detection/builders/model_builder_test.py <ide> ``` <ide><path>object_detection/g3doc/preparing_inputs.md <ide> The label map for the PASCAL VOC data set can be found at <ide> <ide> ## Generating the Oxford-IIIT Pet TFRecord files. <ide> <del>The Oxford-IIIT Pet data set is located on <del>[their website](http://www.robots.ox.ac.uk/~vgg/data/pets/). <del>To download, extract and convert it to TFRecrods, run the following commands <del>below: <add>The Oxford-IIIT Pet data set is located <add>[here](http://www.robots.ox.ac.uk/~vgg/data/pets/). To download, extract and <add>convert it to TFRecrods, run the following commands below: <ide> <ide> ```bash <ide> # From tensorflow/models <ide><path>object_detection/g3doc/running_locally.md <ide> tensorboard --logdir=${PATH_TO_MODEL_DIRECTORY} <ide> ``` <ide> <ide> where `${PATH_TO_MODEL_DIRECTORY}` points to the directory that contains the <del>train and eval directories. Please note it may take Tensorboard a couple <del>minutes to populate with data. <add>train and eval directories. Please note it may take Tensorboard a couple minutes <add>to populate with data. <ide><path>object_detection/g3doc/running_notebook.md <ide> jupyter notebook <ide> ``` <ide> <ide> The notebook should open in your favorite web browser. Click the <del>[`object_detection_tutorial.ipynb`](../object_detection_tutorial.ipynb) link <del>to open the demo. <add>[`object_detection_tutorial.ipynb`](../object_detection_tutorial.ipynb) link to <add>open the demo. <ide><path>object_detection/g3doc/running_pets.md <ide> python object_detection/create_pet_tf_record.py \ <ide> Note: It is normal to see some warnings when running this script. You may ignore <ide> them. <ide> <del>Two TFRecord files named `pet_train.record` and `pet_val.record` should be generated <del>in the `tensorflow/models` directory. <add>Two TFRecord files named `pet_train.record` and `pet_val.record` should be <add>generated in the `tensorflow/models` directory. <ide> <ide> Now that the data has been generated, we'll need to upload it to Google Cloud <ide> Storage so the data can be accessed by ML Engine. Run the following command to <ide> Note: It takes roughly 10 minutes for a job to get started on ML Engine, and <ide> roughly an hour for the system to evaluate the validation dataset. It may take <ide> some time to populate the dashboards. If you do not see any entries after half <ide> an hour, check the logs from the [ML Engine <del>Dashboard](https://console.cloud.google.com/mlengine/jobs). <add>Dashboard](https://console.cloud.google.com/mlengine/jobs). Note that by default <add>the training jobs are configured to go for much longer than is necessary for <add>convergence. To save money, we recommend killing your jobs once you've seen <add>that they've converged. <ide> <ide> ## Exporting the Tensorflow Graph <ide>
6
PHP
PHP
fix serials typo
afec6c4becba0ce50d4a58aacb83b3b9b7c1a58b
<ide><path>src/Illuminate/Database/Schema/Grammars/PostgresGrammar.php <ide> class PostgresGrammar extends Grammar { <ide> * <ide> * @var array <ide> */ <del> protected $serial = array('bigInteger', 'integer'); <add> protected $serials = array('bigInteger', 'integer'); <ide> <ide> /** <ide> * Compile the query to determine if a table exists. <ide><path>src/Illuminate/Database/Schema/Grammars/SQLiteGrammar.php <ide> class SQLiteGrammar extends Grammar { <ide> * <ide> * @var array <ide> */ <del> protected $serial = array('bigInteger', 'integer'); <add> protected $serials = array('bigInteger', 'integer'); <ide> <ide> /** <ide> * Compile the query to determine if a table exists. <ide><path>src/Illuminate/Database/Schema/Grammars/SqlServerGrammar.php <ide> class SqlServerGrammar extends Grammar { <ide> * <ide> * @var array <ide> */ <del> protected $serial = array('bigInteger', 'integer'); <add> protected $serials = array('bigInteger', 'integer'); <ide> <ide> /** <ide> * Compile the query to determine if a table exists.
3
Text
Text
remove unrelated trailing characters
067cbb0761e0d8501c5754afe53c6c07e9cd7611
<ide><path>guide/english/laravel/index.md <ide> Ready-to-use bundles provided by Laravel through Composer and Packagist include <ide> - **SSH** - introduced in Laravel 4.1, allows programmatic execution of CLI commands on remote servers using the Secure Shell (SSH) as an encrypted network protocol. <ide> - **Scheduler** - introduced in Laravel 5.0, is an addition to the Artisan command-line utility that allows programmatic scheduling of periodically executed tasks. Internally, Scheduler relies on the cron daemon to run a single Artisan job that, in turn, executes the configured tasks. <ide> - **Flysystem** - introduced in Laravel 5.0, is a file system abstraction layer that allows local file systems and cloud-based storage services provided by Amazon S3 and Rackspace Cloud to be used transparently and in the same way. <del>- **Socialite** - introduced in Laravel 5.0 as an optional package, provides simplified mechanisms for authentication with different OAuth providers, including Facebook, Twitter, Google, GitHub and Bitbucket.:13 <add>- **Socialite** - introduced in Laravel 5.0 as an optional package, provides simplified mechanisms for authentication with different OAuth providers, including Facebook, Twitter, Google, GitHub and Bitbucket. <ide> <ide> ### Top Six Features of Laravel 5.0.1 Framework Most Useful for the Enterprise App Development <ide> 1. Entirely new directory structure
1
PHP
PHP
remove unused import
62fb1e510e97dd0605cdfec76e6a6cadab801bd0
<ide><path>src/Utility/Xml.php <ide> */ <ide> namespace Cake\Utility; <ide> <del>use Cake\Collection\Collection; <ide> use Cake\Core\Configure; <ide> use Cake\Network\Error\SocketException; <ide> use Cake\Network\Http\Client;
1
Python
Python
add support for custom padding value in sequence
9c8e0d43f35c0581f0d2ac8c225d25d57490629e
<ide><path>keras/preprocessing/sequence.py <ide> import random <ide> from six.moves import range <ide> <del>def pad_sequences(sequences, maxlen=None, dtype='int32', padding='pre'): <add>def pad_sequences(sequences, maxlen=None, dtype='int32', padding='pre', value=0.): <ide> """ <ide> Pad each sequence to the same length: <ide> the length of the longuest sequence. <ide> def pad_sequences(sequences, maxlen=None, dtype='int32', padding='pre'): <ide> if maxlen is None: <ide> maxlen = np.max(lengths) <ide> <del> x = np.zeros((nb_samples, maxlen)).astype(dtype) <add> x = (np.ones((nb_samples, maxlen)) * value).astype(dtype) <ide> for idx, s in enumerate(sequences): <ide> if padding == 'post': <ide> x[idx, :lengths[idx]] = s[:maxlen]
1
Javascript
Javascript
fix transpile-row and make linter happy
a1e6947c7987184f9f1872041a894f9d4d67cb86
<ide><path>tasks/transpile.js <ide> module.exports = function (grunt) { <ide> <ide> var headerCache = {}; <ide> function getHeaderByFile(headerFile) { <del> if (headerFile == 'none') { <add> if (headerFile === 'none') { <ide> return ''; <ide> } <ide> if (!(headerFile in headerCache)) { <ide> module.exports = function (grunt) { <ide> // entry, umdName, skipMoment <ide> <ide> var rollupOpts = { <del> entry: opts.entry, <del> plugins: [ <del> babel({}) <del> ] <add> entry: opts.entry, <add> plugins: [ <add> babel({}) <add> ] <ide> }, bundleOpts = { <del> format: 'umd', <del> moduleName: opts.umdName != null ? opts.umdName : 'not_used' <add> format: 'umd', <add> moduleName: opts.umdName != null ? opts.umdName : 'not_used' <ide> }; <ide> <ide> if (opts.skipMoment) { <del> rollupOpts.external = ['./moment', '../moment', '../../moment', path.resolve('build/tmp/moment'), path.resolve('src/moment')]; <del> bundleOpts.globals = {[path.resolve('src/moment')]: 'moment', [path.resolve('build/tmp/moment')]: 'moment'}; <add> // And this is what people call progress? <add> rollupOpts.external = [ <add> './moment', <add> '../moment', <add> '../../moment', <add> path.resolve('src/moment'), <add> path.resolve('build/tmp/moment') <add> ]; <add> bundleOpts.globals = { <add> [path.resolve('src/moment')]: 'moment', <add> [path.resolve('build/tmp/moment')]: 'moment' <add> }; <ide> } <ide> <ide> return rollup(rollupOpts).then(function (bundle) { <ide> module.exports = function (grunt) { <ide> skipLines: 7, <ide> moveComments: true, <ide> targetDir: 'build/umd', <del> skipMoment: true, <add> skipMoment: true <ide> }); <ide> }).then(function () { <ide> grunt.log.ok('build/umd/locale/*.js'); <ide> module.exports = function (grunt) { <ide> } <ide> <ide> return generateLocales( <del> 'build/umd/min/locales.custom.js', localeFiles <add> 'build/umd/min/locales.custom.js', <add> localeFiles, <add> {skipMoment: true} <ide> ).then(function () { <ide> grunt.log.ok('build/umd/min/locales.custom.js'); <ide> }).then(function () { <del> return generateMomentWithLocales('build/umd/min/moment-with-locales.custom.js', <del> localeFiles); <add> return generateLocales( <add> 'build/umd/min/moment-with-locales.custom.js', <add> localeFiles, <add> {skipMoment: false}); <ide> }).then(function () { <ide> grunt.log.ok('build/umd/min/moment-with-locales.custom.js'); <ide> }).then(done, function (e) {
1
Go
Go
correct the flag comments
00bd7b4c414061d71d7f94b5850cbe132da623f0
<ide><path>pkg/mflag/flag.go <ide> For such flags, the default value is just the initial value of the variable. <ide> <ide> You can also add "deprecated" flags, they are still usable, but are not shown <del> in the usage and will display a warning when you try to use them: <del> var ip = flag.Int([]string{"#f", "#flagname", "-flagname2"}, 1234, "help message for flagname") <del> this will display: `Warning: '--flagname' is deprecated, it will be replaced by '--flagname2' soon. See usage.` and <add> in the usage and will display a warning when you try to use them. `#` before <add> an option means this option is deprecated, if there is an following option <add> without `#` ahead, then that's the replacement, if not, it will just be removed: <add> var ip = flag.Int([]string{"#f", "#flagname", "-flagname"}, 1234, "help message for flagname") <add> this will display: `Warning: '-f' is deprecated, it will be replaced by '--flagname' soon. See usage.` or <add> this will display: `Warning: '-flagname' is deprecated, it will be replaced by '--flagname' soon. See usage.` <ide> var ip = flag.Int([]string{"f", "#flagname"}, 1234, "help message for flagname") <del> will display: `Warning: '-f' is deprecated, it will be removed soon. See usage.` <add> will display: `Warning: '-flagname' is deprecated, it will be removed soon. See usage.` <add> so you can only use `-f`. <ide> <ide> You can also group one letter flags, bif you declare <ide> var v = flag.Bool([]string{"v", "-verbose"}, false, "help message for verbose")
1
Javascript
Javascript
update 6 comparions to strict
b869ecaacfdd218e1920f1545a88a4304efd0288
<ide><path>lib/readline.js <ide> Interface.prototype._tabComplete = function(lastKeypressWasTab) { <ide> <ide> // this = Interface instance <ide> function handleGroup(self, group, width, maxColumns) { <del> if (group.length == 0) { <add> if (group.length === 0) { <ide> return; <ide> } <ide> var minRows = Math.ceil(group.length / maxColumns); <ide> function handleGroup(self, group, width, maxColumns) { <ide> } <ide> <ide> function commonPrefix(strings) { <del> if (!strings || strings.length == 0) { <add> if (!strings || strings.length === 0) { <ide> return ''; <ide> } <ide> if (strings.length === 1) return strings[0]; <ide> var sorted = strings.slice().sort(); <ide> var min = sorted[0]; <ide> var max = sorted[sorted.length - 1]; <ide> for (var i = 0, len = min.length; i < len; i++) { <del> if (min[i] != max[i]) { <add> if (min[i] !== max[i]) { <ide> return min.slice(0, i); <ide> } <ide> } <ide> Interface.prototype._ttyWrite = function(s, key) { <ide> this._previousKey = key; <ide> <ide> // Ignore escape key - Fixes #2876 <del> if (key.name == 'escape') return; <add> if (key.name === 'escape') return; <ide> <ide> if (key.ctrl && key.shift) { <ide> /* Control and shift pressed */ <ide> Interface.prototype._ttyWrite = function(s, key) { <ide> break; <ide> <ide> case 'z': <del> if (process.platform == 'win32') break; <add> if (process.platform === 'win32') break; <ide> if (this.listenerCount('SIGTSTP') > 0) { <ide> this.emit('SIGTSTP'); <ide> } else { <ide> function emitKeypressEvents(stream, iface) { <ide> } <ide> <ide> function onNewListener(event) { <del> if (event == 'keypress') { <add> if (event === 'keypress') { <ide> stream.on('data', onData); <ide> stream.removeListener('newListener', onNewListener); <ide> }
1
Ruby
Ruby
use short hash for mercurial
5ddee3502e7c8dd67b1fec4de2f72df6fd16cc94
<ide><path>Library/Homebrew/download_strategy.rb <ide> def source_modified_time <ide> end <ide> <ide> def last_commit <del> Utils.popen_read("hg", "parent", "--template", "{node}", "-R", cached_location.to_s) <add> Utils.popen_read("hg", "parent", "--template", "{node|short}", "-R", cached_location.to_s) <ide> end <ide> <ide> private
1
Ruby
Ruby
remove dead code
46334bac3d0269952e53bb817372cad4d43cb9e1
<ide><path>activerecord/lib/active_record/migration.rb <ide> def any_migrations? <ide> migrations(migrations_paths).any? <ide> end <ide> <del> def last_version <del> last_migration.version <del> end <del> <ide> def last_migration #:nodoc: <ide> migrations(migrations_paths).last || NullMigration.new <ide> end <ide><path>activerecord/test/cases/migration_test.rb <ide> def test_migrator_versions <ide> <ide> ActiveRecord::Migrator.up(migrations_path) <ide> assert_equal 3, ActiveRecord::Migrator.current_version <del> assert_equal 3, ActiveRecord::Migrator.last_version <ide> assert_equal false, ActiveRecord::Migrator.needs_migration? <ide> <ide> ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid") <ide> assert_equal 0, ActiveRecord::Migrator.current_version <del> assert_equal 3, ActiveRecord::Migrator.last_version <ide> assert_equal true, ActiveRecord::Migrator.needs_migration? <ide> <del> ActiveRecord::SchemaMigration.create!(:version => ActiveRecord::Migrator.last_version) <add> ActiveRecord::SchemaMigration.create!(version: 3) <ide> assert_equal true, ActiveRecord::Migrator.needs_migration? <ide> ensure <ide> ActiveRecord::Migrator.migrations_paths = old_path
2
Javascript
Javascript
remove unused variable
5c6985bc82fe984beef2bed3b04e187814b000a9
<ide><path>test/webserver.js <ide> WebServer.prototype = { <ide> res.setHeader('Content-Type', 'text/html'); <ide> res.writeHead(200); <ide> <del> var content = ''; <ide> if (queryPart === 'frame') { <ide> res.end('<html><frameset cols=*,200><frame name=pdf>' + <ide> '<frame src=\"' + encodeURI(pathPart) +
1
Javascript
Javascript
use clamp for clampscalar implementation
8375a6f421c3a761b48fa2c26318d92b7fc8fd49
<ide><path>src/math/Vector2.js <ide> THREE.Vector2.prototype = { <ide> return this; <ide> }, <ide> <del> clampScalar: function ( minVal, maxVal ) { <del> <del> if ( this.x < minVal ) { <del> this.x = minVal; <del> } else if ( this.x > maxVal ) { <del> this.x = maxVal; <del> } <del> <del> if ( this.y < minVal ) { <del> this.y = minVal; <del> } else if ( this.y > maxVal ) { <del> this.y = maxVal; <del> } <del> <del> return this; <del> }, <del> <del> floor: function() { <del> this.x = Math.floor(this.x); <del> this.y = Math.floor(this.y); <del> return this; <del> }, <del> <del> ceil: function() { <del> this.x = Math.ceil(this.x); <del> this.y = Math.ceil(this.y); <del> return this; <del> }, <del> <del> round: function() { <del> this.x = Math.round(this.x); <del> this.y = Math.round(this.y); <del> return this; <del> }, <del> <del> roundToZero: function() { <del> this.x = (this.x < 0) ? Math.ceil(this.x) : Math.floor(this.x); <del> this.y = (this.y < 0) ? Math.ceil(this.y) : Math.floor(this.y); <del> return this; <del> }, <add> clampScalar: ( function () { <add> var min, max; <add> <add> return function ( minVal, maxVal ) { <add> if ( !min || !max ) { <add> min = new THREE.Vector2(); <add> max = new THREE.Vector2(); <add> } <add> <add> min.set(minVal, minVal); <add> max.set(maxVal, maxVal); <add> return this.clamp(min, max); <add> <add> }; <add> } )(), <add> <add> floor: function() { <add> this.x = Math.floor(this.x); <add> this.y = Math.floor(this.y); <add> return this; <add> }, <add> <add> ceil: function() { <add> this.x = Math.ceil(this.x); <add> this.y = Math.ceil(this.y); <add> return this; <add> }, <add> <add> round: function() { <add> this.x = Math.round(this.x); <add> this.y = Math.round(this.y); <add> return this; <add> }, <add> <add> roundToZero: function() { <add> this.x = (this.x < 0) ? Math.ceil(this.x) : Math.floor(this.x); <add> this.y = (this.y < 0) ? Math.ceil(this.y) : Math.floor(this.y); <add> return this; <add> }, <ide> <ide> negate: function() { <ide> <ide><path>src/math/Vector3.js <ide> THREE.Vector3.prototype = { <ide> <ide> }, <ide> <del> clampScalar: function ( minVal, maxVal ) { <del> <del> if ( this.x < minVal ) { <del> this.x = minVal; <del> } else if ( this.x > maxVal ) { <del> this.x = maxVal; <del> } <del> <del> if ( this.y < minVal ) { <del> this.y = minVal; <del> } else if ( this.y > maxVal ) { <del> this.y = maxVal; <del> } <del> <del> if ( this.z < minVal ) { <del> this.z = minVal; <del> } else if ( this.z > maxVal ) { <del> this.z = maxVal; <del> } <del> <del> return this; <del> }, <del> <del> floor: function() { <del> this.x = Math.floor(this.x); <del> this.y = Math.floor(this.y); <del> this.z = Math.floor(this.z); <del> return this; <del> }, <del> <del> ceil: function() { <del> this.x = Math.ceil(this.x); <del> this.y = Math.ceil(this.y); <del> this.z = Math.ceil(this.z); <del> return this; <del> }, <del> <del> round: function() { <del> this.x = Math.round(this.x); <del> this.y = Math.round(this.y); <del> this.z = Math.round(this.z); <del> return this; <del> }, <del> <del> roundToZero: function() { <del> this.x = (this.x < 0) ? Math.ceil(this.x) : Math.floor(this.x); <del> this.y = (this.y < 0) ? Math.ceil(this.y) : Math.floor(this.y); <del> this.z = (this.z < 0) ? Math.ceil(this.z) : Math.floor(this.z); <del> return this; <del> }, <add> clampScalar: ( function () { <add> var min, max; <add> <add> return function ( minVal, maxVal ) { <add> if ( !min || !max ) { <add> min = new THREE.Vector3(); <add> max = new THREE.Vector3(); <add> } <add> <add> min.set(minVal, minVal, minVal); <add> max.set(maxVal, maxVal, maxVal); <add> return this.clamp(min, max); <add> <add> }; <add> } )(), <add> <add> floor: function() { <add> this.x = Math.floor(this.x); <add> this.y = Math.floor(this.y); <add> this.z = Math.floor(this.z); <add> return this; <add> }, <add> <add> ceil: function() { <add> this.x = Math.ceil(this.x); <add> this.y = Math.ceil(this.y); <add> this.z = Math.ceil(this.z); <add> return this; <add> }, <add> <add> round: function() { <add> this.x = Math.round(this.x); <add> this.y = Math.round(this.y); <add> this.z = Math.round(this.z); <add> return this; <add> }, <add> <add> roundToZero: function() { <add> this.x = (this.x < 0) ? Math.ceil(this.x) : Math.floor(this.x); <add> this.y = (this.y < 0) ? Math.ceil(this.y) : Math.floor(this.y); <add> this.z = (this.z < 0) ? Math.ceil(this.z) : Math.floor(this.z); <add> return this; <add> }, <ide> <ide> negate: function () { <ide> <ide><path>src/math/Vector4.js <ide> THREE.Vector4.prototype = { <ide> <ide> }, <ide> <del> clampScalar: function ( minVal, maxVal ) { <del> <del> if ( this.x < minVal ) { <del> this.x = minVal; <del> } else if ( this.x > maxVal ) { <del> this.x = maxVal; <del> } <del> <del> if ( this.y < minVal ) { <del> this.y = minVal; <del> } else if ( this.y > maxVal ) { <del> this.y = maxVal; <del> } <del> <del> if ( this.z < minVal ) { <del> this.z = minVal; <del> } else if ( this.z > maxVal ) { <del> this.z = maxVal; <del> } <del> <del> if ( this.w < minVal ) { <del> this.w = minVal; <del> } else if ( this.w > maxVal ) { <del> this.w = maxVal; <del> } <add> clampScalar: ( function () { <add> var min, max; <ide> <del> return this; <del> }, <add> return function ( minVal, maxVal ) { <add> if ( !min || !max ) { <add> min = new THREE.Vector4(); <add> max = new THREE.Vector4(); <add> } <add> <add> min.set(minVal, minVal, minVal, minVal); <add> max.set(maxVal, maxVal, maxVal, maxVal); <add> return this.clamp(min, max); <add> <add> }; <add> } )(), <ide> <ide> floor: function() { <ide> this.x = Math.floor(this.x); <ide><path>test/unit/math/Vector2.js <ide> test( "min/max/clamp", function() { <ide> c.clamp( b, a ); <ide> ok( c.x == -x, "Passed!" ); <ide> ok( c.y == y, "Passed!" ); <add> <add> c.set(-2*x, 2*x); <add> c.clampScalar( -x, x ); <add> equal( c.x, -x, "scalar clamp x" ); <add> equal( c.y, x, "scalar clamp y" ); <add>}); <add> <add>test( "rounding", function() { <add> deepEqual( new THREE.Vector2( -0.1, 0.1 ).floor(), new THREE.Vector2( -1, 0 ), "floor .1" ); <add> deepEqual( new THREE.Vector2( -0.5, 0.5 ).floor(), new THREE.Vector2( -1, 0 ), "floor .5" ); <add> deepEqual( new THREE.Vector2( -0.9, 0.9 ).floor(), new THREE.Vector2( -1, 0 ), "floor .9" ); <add> <add> deepEqual( new THREE.Vector2( -0.1, 0.1 ).ceil(), new THREE.Vector2( 0, 1 ), "ceil .1" ); <add> deepEqual( new THREE.Vector2( -0.5, 0.5 ).ceil(), new THREE.Vector2( 0, 1 ), "ceil .5" ); <add> deepEqual( new THREE.Vector2( -0.9, 0.9 ).ceil(), new THREE.Vector2( 0, 1 ), "ceil .9" ); <add> <add> deepEqual( new THREE.Vector2( -0.1, 0.1 ).round(), new THREE.Vector2( 0, 0 ), "round .1" ); <add> deepEqual( new THREE.Vector2( -0.5, 0.5 ).round(), new THREE.Vector2( 0, 1 ), "round .5" ); <add> deepEqual( new THREE.Vector2( -0.9, 0.9 ).round(), new THREE.Vector2( -1, 1 ), "round .9" ); <add> <add> deepEqual( new THREE.Vector2( -0.1, 0.1 ).roundToZero(), new THREE.Vector2( 0, 0 ), "roundToZero .1" ); <add> deepEqual( new THREE.Vector2( -0.5, 0.5 ).roundToZero(), new THREE.Vector2( 0, 0 ), "roundToZero .5" ); <add> deepEqual( new THREE.Vector2( -0.9, 0.9 ).roundToZero(), new THREE.Vector2( 0, 0 ), "roundToZero .9" ); <add> deepEqual( new THREE.Vector2( -1.1, 1.1 ).roundToZero(), new THREE.Vector2( -1, 1 ), "roundToZero 1.1" ); <add> deepEqual( new THREE.Vector2( -1.5, 1.5 ).roundToZero(), new THREE.Vector2( -1, 1 ), "roundToZero 1.5" ); <add> deepEqual( new THREE.Vector2( -1.9, 1.9 ).roundToZero(), new THREE.Vector2( -1, 1 ), "roundToZero 1.9" ); <ide> }); <ide> <ide> test( "negate", function() {
4
Javascript
Javascript
fix non-passive event listener warning in chrome
548edc65ea96ac51ab17bde2942fd6f319f63e8c
<ide><path>src/core/core.helpers.js <ide> module.exports = function(Chart) { <ide> }; <ide> <ide> }; <del> helpers.addEvent = function(node, eventType, method) { <del> if (node.addEventListener) { <del> node.addEventListener(eventType, method); <del> } else if (node.attachEvent) { <del> node.attachEvent('on' + eventType, method); <del> } else { <del> node['on' + eventType] = method; <del> } <del> }; <del> helpers.removeEvent = function(node, eventType, handler) { <del> if (node.removeEventListener) { <del> node.removeEventListener(eventType, handler, false); <del> } else if (node.detachEvent) { <del> node.detachEvent('on' + eventType, handler); <del> } else { <del> node['on' + eventType] = helpers.noop; <del> } <del> }; <ide> <ide> // Private helper function to convert max-width/max-height values that may be percentages into a number <ide> function parseMaxStyle(styleValue, node, parentProperty) { <ide><path>src/platforms/platform.dom.js <ide> module.exports = function(Chart) { <ide> return canvas; <ide> } <ide> <add> /** <add> * Detects support for options object argument in addEventListener. <add> * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support <add> * @private <add> */ <add> var supportsEventListenerOptions = (function() { <add> var supports = false; <add> try { <add> var options = Object.defineProperty({}, 'passive', { <add> get: function() { <add> supports = true; <add> } <add> }); <add> window.addEventListener('e', null, options); <add> } catch (e) { <add> // continue regardless of error <add> } <add> return supports; <add> }()); <add> <add> // Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events. <add> // https://github.com/chartjs/Chart.js/issues/4287 <add> var eventListenerOptions = supportsEventListenerOptions? {passive: true} : false; <add> <add> function addEventListener(node, type, listener) { <add> node.addEventListener(type, listener, eventListenerOptions); <add> } <add> <add> function removeEventListener(node, type, listener) { <add> node.removeEventListener(type, listener, eventListenerOptions); <add> } <add> <ide> function createEvent(type, chart, x, y, nativeEvent) { <ide> return { <ide> type: type, <ide> module.exports = function(Chart) { <ide> // If the iframe is re-attached to the DOM, the resize listener is removed because the <ide> // content is reloaded, so make sure to install the handler after the iframe is loaded. <ide> // https://github.com/chartjs/Chart.js/issues/3521 <del> helpers.addEvent(iframe, 'load', function() { <del> helpers.addEvent(iframe.contentWindow || iframe, 'resize', handler); <add> addEventListener(iframe, 'load', function() { <add> addEventListener(iframe.contentWindow || iframe, 'resize', handler); <ide> <ide> // The iframe size might have changed while loading, which can also <ide> // happen if the size has been changed while detached from the DOM. <ide> module.exports = function(Chart) { <ide> delete node._chartjs; <ide> } <ide> <add> /** <add> * Provided for backward compatibility, use EventTarget.addEventListener instead. <add> * EventTarget.addEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+ <add> * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener <add> * @function Chart.helpers.addEvent <add> * @deprecated since version 2.7.0 <add> * @todo remove at version 3 <add> * @private <add> */ <add> helpers.addEvent = addEventListener; <add> <add> /** <add> * Provided for backward compatibility, use EventTarget.removeEventListener instead. <add> * EventTarget.removeEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+ <add> * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener <add> * @function Chart.helpers.removeEvent <add> * @deprecated since version 2.7.0 <add> * @todo remove at version 3 <add> * @private <add> */ <add> helpers.removeEvent = removeEventListener; <add> <ide> return { <ide> acquireContext: function(item, config) { <ide> if (typeof item === 'string') { <ide> module.exports = function(Chart) { <ide> listener(fromNativeEvent(event, chart)); <ide> }; <ide> <del> helpers.addEvent(canvas, type, proxy); <add> addEventListener(canvas, type, proxy); <ide> }, <ide> <ide> removeEventListener: function(chart, type, listener) { <ide> module.exports = function(Chart) { <ide> return; <ide> } <ide> <del> helpers.removeEvent(canvas, type, proxy); <add> removeEventListener(canvas, type, proxy); <ide> } <ide> }; <ide> }; <ide><path>test/specs/global.deprecations.tests.js <ide> describe('Deprecations', function() { <ide> expect(Chart.helpers.canvas.roundedRect).toHaveBeenCalledWith(ctx, 10, 20, 30, 40, 5); <ide> }); <ide> }); <add> <add> describe('Chart.helpers.addEvent', function() { <add> it('should be defined and a function', function() { <add> expect(Chart.helpers.addEvent).toBeDefined(); <add> expect(typeof Chart.helpers.addEvent).toBe('function'); <add> }); <add> it('should correctly add event listener', function() { <add> var listener = jasmine.createSpy('spy'); <add> Chart.helpers.addEvent(window, 'test', listener); <add> window.dispatchEvent(new Event('test')); <add> expect(listener).toHaveBeenCalled(); <add> }); <add> }); <add> <add> describe('Chart.helpers.removeEvent', function() { <add> it('should be defined and a function', function() { <add> expect(Chart.helpers.removeEvent).toBeDefined(); <add> expect(typeof Chart.helpers.removeEvent).toBe('function'); <add> }); <add> it('should correctly remove event listener', function() { <add> var listener = jasmine.createSpy('spy'); <add> Chart.helpers.addEvent(window, 'test', listener); <add> Chart.helpers.removeEvent(window, 'test', listener); <add> window.dispatchEvent(new Event('test')); <add> expect(listener).not.toHaveBeenCalled(); <add> }); <add> }); <ide> }); <ide> <ide> describe('Version 2.6.0', function() {
3
Text
Text
improve translation and formatting consistency
351d19aa75df2b63331261cfd7f77413ce73847f
<ide><path>guide/spanish/css/background/index.md <ide> localeTitle: Fondo <ide> <ide> La propiedad de fondo (background) te permite usar imágenes y colores para crear fondos para tus páginas web. <ide> <del>### Color de fondo <add>### Color de Fondo <ide> <ide> La propiedad de color de fondo te permite elegir el color de tu elemento. Éste puede ser el fondo de toda la página o el fondo de una sección de tu página. <ide> <ide> En CSS el color se puede definir de tres maneras: <ide> * Un valor HEX como `#FFFFF` (Este es el valor hexadecimal para el blanco). <ide> * Un valor RGB como `rgb(76,175,80)` (este es el valor RGB para verde claro). <ide> <del>### Imágenes de fondo <add>### Imágenes de Fondo <ide> <ide> Puedes utilizar la propiedad de imagen de fondo para establecer una imagen como fondo para un elemento. La imagen se repite de forma predeterminada para que cubra todo el elemento. <ide> <ide> body { <ide> <ide> ![imagen](https://user-images.githubusercontent.com/26467304/31036366-eb1fc260-a539-11e7-835d-e3f935a22c86.png) <ide> <del>También puedes vincular imágenes o gifs que encuentres en línea usando su enlace (por ejemplo una búsqueda desde Google Images). <add>También puede vincular imágenes o gifs que encuentre en línea usando un enlace (ej.: desde una búsqueda en Google Imágenes). <ide> <ide> ```css <ide> body { <ide> background-image: url("https://mdn.mozillademos.org/files/11983/starsolid.gif"); <ide> } <ide> ``` <ide> <del>### Imagen de fondo - la propiedad de repetición <add>### Imagen de Fondo - La Propiedad de Repetición <ide> <ide> La imagen de fondo se repite tanto verticalmente (arriba y abajo) como horizontalmente (a través de la página web) de forma predeterminada. Puedes usar la propiedad de repetición de fondo para repetir la imagen vertical u horizontalmente. <ide> <ide> body { <ide> <ide> ![vertical](https://user-images.githubusercontent.com/26467304/31039770-8962c7a6-a54e-11e7-9d25-4fb09760d219.PNG) <ide> <del>Puedes repetir la imagen horizontalmente configurando la propiedad de repetición de fondo en "repetir-x". <add>Puede repetir la imagen horizontalmente configurando la propiedad de repetición de fondo en `repeat-x`. <ide> <ide> ```css <ide> body { <ide> body { <ide> } <ide> ``` <ide> <del>También puedes usar la propiedad de repetición de fondo para configurar una imagen para que no se repita. <add>También puede configurar la propiedad de repetición de fondo para que una imagen no se repita. <ide> <ide> ```css <ide> body { <ide> body { <ide> <ide> ![norepeat](https://user-images.githubusercontent.com/26467304/31039801-c8761efc-a54e-11e7-8bb9-ec5b88885a50.PNG) <ide> <del>### Imagen de fondo - La propiedad de posición <add>### Imagen de Fondo - La Propiedad de Posición <ide> <ide> Puedes usar la propiedad de posición para especificar dónde se ubicará tu imagen en una página web. <ide> <ide> body { <ide> <ide> ![posición](https://user-images.githubusercontent.com/26467304/31039828-077d1038-a54f-11e7-8aa6-092253ca92b8.PNG) <ide> <del>### Imagen de fondo - La posición fija <add>### Imagen de Fondo - La Posición Fija <ide> <del>Puedes utilizar la propiedad de adjuntos de fondo para establecer una imagen en una posición fija. Una posición fija hace que una imagen no se desplace con el resto de la página. <add>Puede utilizar la propiedad `background-attachment` para establecer una imagen en una posición fija. Una posición fija hace que una imagen no se desplace con el resto de la página. <ide> <ide> ```css <ide> body { <ide> body { <ide> <ide> ![fijo](https://user-images.githubusercontent.com/26467304/31039859-39612c92-a54f-11e7-93ca-9d7bcb938225.PNG) <ide> <del>### Gradientes de fondo <add>### Gradientes de Fondo <ide> <del>Un degradado es una transición entre dos o más colores y se puede usar a través de CSS como una imagen de fondo. <add>Un gradiente es una transición entre dos o más colores y se puede usar en CSS de forma similar a una imagen de fondo. <ide> <del>La sintaxis de un fondo degradado puede ser bastante compleja y, a menudo, todavía se usa con prefijos de proveedores debido a las inconsistencias entre los navegadores compatibles. <add>La sintaxis de un fondo con gradiente puede ser bastante compleja, y a menudo se usa con prefijos de proveedores debido a las inconsistencias entre los navegadores compatibles. <ide> <ide> El [Colorzilla Gradient Editor](http://www.colorzilla.com/gradient-editor/) es una excelente herramienta en línea para generar gradientes personalizados y el marcado css asociado. <ide> <del>### Fondo - La propiedad de taquigrafía <add>### Fondo - La Propiedad Abreviada <ide> <del>Puedes escribir las propiedades de fondo en una sola línea. Esto se llama la propiedad taquigrafía. <add>Puede escribir las propiedades de fondo en una sola línea. Esto se conoce como propiedad abreviada. <ide> <ide> ```css <ide> body { <ide> background: url("barn.jpg") no-repeat right top; <ide> } <ide> ``` <ide> <del>Puedes omitir las propiedades que no necesitas al usar la propiedad abreviada, pero las propiedades deben ser utilizadas en un cierto orden. El orden es: <add>Puede omitir las propiedades que no necesita al usar la propiedad abreviada, pero las propiedades deben utilizarse en un cierto orden. El orden es: <ide> <del>* color <del>* imagen <del>* repetir <del>* adjunto archivo <del>* posición <add>* `color` <add>* `image` <add>* `repeat` <add>* `attachment` <add>* `position` <ide> <del>### Múltiples imágenes de fondo <add>### Múltiples Imágenes de Fondo <ide> <ide> Puedes especificar varias imágenes de fondo en una sola propiedad de fondo. <ide> <ide> body { <ide> } <ide> ``` <ide> <del>La primera imagen (o gradiente) especificada es la de más arriba, la segunda viene después, y así sucesivamente. Si uno de los elementos no es correcto debido a su URL o su sintaxis, el navegador ignorará toda la línea. <add>La primera imagen (o gradiente) especificada se situa encima, la segunda viene después, y así sucesivamente. Si uno de los elementos no es correcto debido a su URL o su sintaxis, el navegador ignorará toda la línea. <ide> <del>### Algunas propiedades básicas de fondo de CSS <add>### Algunas Propiedades Básicas de Fondo de CSS <ide> <ide> Las propiedades de fondo de CSS se utilizan para definir los efectos de fondo para los elementos. <ide> <del>Propiedades de fondo CSS: color de fondo, imagen de fondo, repetición de fondo, fondo adjunto, posición de fondo <add>Propiedades de fondo CSS: `background-color` `background-image` `background-repeat` `background-attachment` `background-position` <ide> <del>Puedes consultar el siguiente enlace a las escuelas W3 para obtener más información sobre antecedentes y temas relacionados en CSS. [Referencia de fondo a W3](https://www.w3schools.com/css/css_background.asp) <add>Puede consultar el siguiente enlace a W3 Schools para obtener más información sobre antecedentes y temas relacionados en CSS. [Referencia de fondo a W3](https://www.w3schools.com/css/css_background.asp) <ide> <ide> ### Otros recursos <ide>
1
Javascript
Javascript
remove operatorlist cache from the backend
f701a1427a4473f0e9196edbb5e987a699a0333f
<ide><path>src/core.js <ide> var Page = (function PageClosure() { <ide> }, <ide> <ide> getOperatorList: function Page_getOperatorList(handler, dependency) { <del> if (this.operatorList) { <del> // content was compiled <del> return this.operatorList; <del> } <del> <ide> var xref = this.xref; <ide> var content = this.content; <ide> var resources = this.resources; <ide> var Page = (function PageClosure() { <ide> var pe = this.pe = new PartialEvaluator( <ide> xref, handler, 'p' + this.pageNumber + '_'); <ide> <del> this.operatorList = pe.getOperatorList(content, resources, dependency); <del> return this.operatorList; <add> return pe.getOperatorList(content, resources, dependency); <ide> }, <ide> <ide> getLinks: function Page_getLinks() { <ide><path>web/viewer.js <ide> var Cache = function cacheCache(size) { <ide> data.splice(i); <ide> data.push(view); <ide> if (data.length > size) <del> data.shift().update(); <add> data.shift().destroy(); <ide> }; <ide> }; <ide> <ide> var PageView = function pageView(container, pdfPage, id, scale, <ide> container.appendChild(anchor); <ide> container.appendChild(div); <ide> <add> this.destroy = function pageViewDestroy() { <add> this.update(); <add> this.pdfPage.destroy(); <add> }; <add> <ide> this.update = function pageViewUpdate(scale) { <ide> this.scale = scale || this.scale; <ide> var viewport = this.pdfPage.getViewport(this.scale); <ide> var PageView = function pageView(container, pdfPage, id, scale, <ide> div.removeAttribute('data-loaded'); <ide> <ide> delete this.canvas; <del> this.pdfPage.destroy(); <ide> <ide> this.loadingIconDiv = document.createElement('div'); <ide> this.loadingIconDiv.className = 'loadingIcon';
2
PHP
PHP
take array keys of pattern filters
e350e7397d0518aa2a0cdd152332a31f18ba565e
<ide><path>src/Illuminate/Foundation/Console/RoutesCommand.php <ide> protected function getPatternFilters($route) <ide> // we have already gathered up then return them back out to these consumers. <ide> $inner = $this->getMethodPatterns($route->uri(), $method); <ide> <del> $patterns = array_merge($patterns, $inner); <add> $patterns = array_merge($patterns, array_keys($inner)); <ide> } <ide> <ide> return $patterns;
1
Javascript
Javascript
fix comment typo in sc.inspect
94d0bb71aa1fa8bc82a902aa608ea4b29d043aac
<ide><path>packages/sproutcore-runtime/lib/core.js <ide> SC.copy = function(obj, deep) { <ide> Convenience method to inspect an object. This method will attempt to <ide> convert the object into a useful string description. <ide> <del> @param {Object} obj The object you want to inspec. <add> @param {Object} obj The object you want to inspect. <ide> @returns {String} A description of the object <ide> */ <ide> SC.inspect = function(obj) {
1
Javascript
Javascript
add more logging to debug ci failure
bd05990ccf0ee6c08a9369083ad1c462f8725ce7
<ide><path>src/main-process/start.js <add>console.log('START ATOM!') <add> <ide> const {app} = require('electron') <ide> const nslog = require('nslog') <ide> const path = require('path') <ide> const fs = require('fs') <ide> const CSON = require('season') <ide> const Config = require('../config') <ide> <add>console.log('everything required correctly!') <add> <ide> module.exports = function start (resourcePath, devResourcePath, startTime) { <ide> global.shellStartTime = startTime <ide> <ide> module.exports = function start (resourcePath, devResourcePath, startTime) { <ide> if (handleStartupEventWithSquirrel()) { <ide> return <ide> } else if (args.test && args.mainProcess) { <add> console.log('Running Atom main process tests...') <ide> app.setPath('userData', temp.mkdirSync('atom-user-data-dir-for-main-process-tests')) <ide> console.log = previousConsoleLog <ide> app.on('ready', function () { <add> console.log('App ready!') <ide> const testRunner = require(path.join(args.resourcePath, 'spec/main-process/mocha-test-runner')) <ide> testRunner(args.pathsToOpen) <ide> })
1
Ruby
Ruby
use usageerror, extend timeout
fbb28175d8220ea89556f0275238387f4dfe386a
<ide><path>Library/Homebrew/cmd/info.rb <ide> def info_formula(f) <ide> def formulae_api_json(endpoint) <ide> return if ENV["HOMEBREW_NO_ANALYTICS"] || ENV["HOMEBREW_NO_GITHUB_API"] <ide> <del> output, = curl_output("--max-time", "3", <add> output, = curl_output("--max-time", "5", <ide> "https://formulae.brew.sh/api/#{endpoint}") <ide> return if output.blank? <ide> <ide> def analytics_table(category, days, results, os_version: false) <ide> def output_analytics(filter: nil) <ide> days = args.days || "30" <ide> valid_days = %w[30 90 365] <del> raise ArgumentError("Days must be one of #{valid_days.join(", ")}!") unless valid_days.include?(days) <add> raise UsageError, "days must be one of #{valid_days.join(", ")}" unless valid_days.include?(days) <ide> <ide> category = args.category || "install" <ide> valid_categories = %w[install install-on-request build-error os-version] <ide> unless valid_categories.include?(category) <del> raise ArgumentError("Categories must be one of #{valid_categories.join(", ")}") <add> raise UsageError, "category must be one of #{valid_categories.join(", ")}" <ide> end <ide> <ide> json = formulae_api_json("analytics/#{category}/#{days}d.json")
1
Javascript
Javascript
make use of the block scoping nature of let
79a36a66ff64b3092cfb4c51daf82e38d266b4f8
<ide><path>lib/Stats.js <ide> class Stats { <ide> }; <ide> <ide> const table = (array, align, splitter) => { <del> let row; <ide> const rows = array.length; <del> let col; <ide> const cols = array[0].length; <ide> const colSizes = new Array(cols); <del> let value; <del> for(col = 0; col < cols; col++) <add> for(let col = 0; col < cols; col++) <ide> colSizes[col] = 0; <del> for(row = 0; row < rows; row++) { <del> for(col = 0; col < cols; col++) { <del> value = `${getText(array, row, col)}`; <add> for(let row = 0; row < rows; row++) { <add> for(let col = 0; col < cols; col++) { <add> const value = `${getText(array, row, col)}`; <ide> if(value.length > colSizes[col]) { <ide> colSizes[col] = value.length; <ide> } <ide> } <ide> } <del> for(row = 0; row < rows; row++) { <del> for(col = 0; col < cols; col++) { <add> for(let row = 0; row < rows; row++) { <add> for(let col = 0; col < cols; col++) { <ide> const format = array[row][col].color; <del> value = `${getText(array, row, col)}`; <add> const value = `${getText(array, row, col)}`; <ide> let l = value.length; <ide> if(align[col] === "l") <ide> format(value);
1
Java
Java
fix issue with path matching options
203977972b9c6e0a26cf99e30b620f9ab127bc5b
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/RequestMappingHandlerMapping.java <ide> protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handler <ide> if (this.embeddedValueResolver != null) { <ide> prefix = this.embeddedValueResolver.resolveStringValue(prefix); <ide> } <del> info = RequestMappingInfo.paths(prefix).build().combine(info); <add> info = RequestMappingInfo.paths(prefix).options(this.config).build().combine(info); <ide> break; <ide> } <ide> } <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.java <ide> protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handler <ide> } <ide> String prefix = getPathPrefix(handlerType); <ide> if (prefix != null) { <del> info = RequestMappingInfo.paths(prefix).build().combine(info); <add> info = RequestMappingInfo.paths(prefix).options(this.config).build().combine(info); <ide> } <ide> } <ide> return info; <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMappingTests.java <ide> <ide> import org.springframework.core.annotation.AliasFor; <ide> import org.springframework.http.MediaType; <add>import org.springframework.mock.web.test.MockHttpServletRequest; <ide> import org.springframework.stereotype.Controller; <ide> import org.springframework.util.ClassUtils; <ide> import org.springframework.web.accept.ContentNegotiationManager; <ide> public void useSuffixPatternMatch() { <ide> assertThat(this.handlerMapping.useSuffixPatternMatch()).isFalse(); <ide> <ide> this.handlerMapping.setUseRegisteredSuffixPatternMatch(false); <del> assertThat(this.handlerMapping.useSuffixPatternMatch()).as("'false' registeredSuffixPatternMatch shouldn't impact suffixPatternMatch").isFalse(); <add> assertThat(this.handlerMapping.useSuffixPatternMatch()) <add> .as("'false' registeredSuffixPatternMatch shouldn't impact suffixPatternMatch").isFalse(); <ide> <ide> this.handlerMapping.setUseRegisteredSuffixPatternMatch(true); <del> assertThat(this.handlerMapping.useSuffixPatternMatch()).as("'true' registeredSuffixPatternMatch should enable suffixPatternMatch").isTrue(); <add> assertThat(this.handlerMapping.useSuffixPatternMatch()) <add> .as("'true' registeredSuffixPatternMatch should enable suffixPatternMatch").isTrue(); <ide> } <ide> <ide> @Test <ide> public void pathPrefix() throws NoSuchMethodException { <ide> assertThat(info.getPatternsCondition().getPatterns()).isEqualTo(Collections.singleton("/api/user/{id}")); <ide> } <ide> <add> @Test // gh-23907 <add> public void pathPrefixPreservesPathMatchingSettings() throws NoSuchMethodException { <add> this.handlerMapping.setUseSuffixPatternMatch(false); <add> this.handlerMapping.setPathPrefixes(Collections.singletonMap("/api", HandlerTypePredicate.forAnyHandlerType())); <add> this.handlerMapping.afterPropertiesSet(); <add> <add> Method method = ComposedAnnotationController.class.getMethod("get"); <add> RequestMappingInfo info = this.handlerMapping.getMappingForMethod(method, ComposedAnnotationController.class); <add> <add> assertThat(info).isNotNull(); <add> <add> MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/get"); <add> assertThat(info.getPatternsCondition().getMatchingCondition(request)).isNotNull(); <add> <add> request = new MockHttpServletRequest("GET", "/api/get.pdf"); <add> assertThat(info.getPatternsCondition().getMatchingCondition(request)).isNull(); <add> } <add> <ide> @Test <ide> public void resolveRequestMappingViaComposedAnnotation() throws Exception { <ide> RequestMappingInfo info = assertComposedAnnotationMapping("postJson", "/postJson", RequestMethod.POST); <ide> <del> assertThat(info.getConsumesCondition().getConsumableMediaTypes().iterator().next().toString()).isEqualTo(MediaType.APPLICATION_JSON_VALUE); <del> assertThat(info.getProducesCondition().getProducibleMediaTypes().iterator().next().toString()).isEqualTo(MediaType.APPLICATION_JSON_VALUE); <add> assertThat(info.getConsumesCondition().getConsumableMediaTypes().iterator().next().toString()) <add> .isEqualTo(MediaType.APPLICATION_JSON_VALUE); <add> assertThat(info.getProducesCondition().getProducibleMediaTypes().iterator().next().toString()) <add> .isEqualTo(MediaType.APPLICATION_JSON_VALUE); <ide> } <ide> <ide> @Test // SPR-14988
3
Java
Java
apply extra checks to static resource handling
9cef8e3001ddd61c734281a7556efd84b6cc2755
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/PathResourceResolver.java <ide> package org.springframework.web.servlet.resource; <ide> <ide> import java.io.IOException; <add>import java.net.URLDecoder; <ide> import java.util.List; <add> <ide> import javax.servlet.http.HttpServletRequest; <ide> <add>import org.springframework.core.io.ClassPathResource; <ide> import org.springframework.core.io.Resource; <add>import org.springframework.core.io.UrlResource; <ide> <ide> /** <ide> * A simple {@code ResourceResolver} that tries to find a resource under the given <ide> */ <ide> public class PathResourceResolver extends AbstractResourceResolver { <ide> <add> private Resource[] allowedLocations; <add> <add> <add> /** <add> * By default when a Resource is found, the path of the resolved resource is <add> * compared to ensure it's under the input location where it was found. <add> * However sometimes that may not be the case, e.g. when <add> * {@link org.springframework.web.servlet.resource.CssLinkResourceTransformer} <add> * resolves public URLs of links it contains, the CSS file is the location <add> * and the resources being resolved are css files, images, fonts and others <add> * located in adjacent or parent directories. <add> * <p>This property allows configuring a complete list of locations under <add> * which resources must be so that if a resource is not under the location <add> * relative to which it was found, this list may be checked as well. <add> * <p>By default {@link ResourceHttpRequestHandler} initializes this property <add> * to match its list of locations. <add> * @param locations the list of allowed locations <add> * @since 4.1.2 <add> * @see ResourceHttpRequestHandler#initAllowedLocations() <add> */ <add> public void setAllowedLocations(Resource... locations) { <add> this.allowedLocations = locations; <add> } <add> <add> public Resource[] getAllowedLocations() { <add> return this.allowedLocations; <add> } <add> <add> <ide> @Override <ide> protected Resource resolveResourceInternal(HttpServletRequest request, String requestPath, <ide> List<? extends Resource> locations, ResourceResolverChain chain) { <ide> else if (logger.isTraceEnabled()) { <ide> */ <ide> protected Resource getResource(String resourcePath, Resource location) throws IOException { <ide> Resource resource = location.createRelative(resourcePath); <del> return (resource.exists() && resource.isReadable() ? resource : null); <add> if (resource.exists() && resource.isReadable()) { <add> if (checkResource(resource, location)) { <add> return resource; <add> } <add> else { <add> if (logger.isTraceEnabled()) { <add> logger.trace("resourcePath=\"" + resourcePath + "\" was successfully resolved " + <add> "but resource=\"" + resource.getURL() + "\" is neither under the " + <add> "current location=\"" + location.getURL() + "\" nor under any of the " + <add> "allowed locations=" + getAllowedLocations()); <add> } <add> } <add> } <add> return null; <add> } <add> <add> /** <add> * Perform additional checks on a resolved resource beyond checking whether <add> * the resources exists and is readable. The default implementation also <add> * verifies the resource is either under the location relative to which it <add> * was found or is under one of the {@link #setAllowedLocations allowed <add> * locations}. <add> * @param resource the resource to check <add> * @param location the location relative to which the resource was found <add> * @return "true" if resource is in a valid location, "false" otherwise. <add> * @since 4.1.2 <add> */ <add> protected boolean checkResource(Resource resource, Resource location) throws IOException { <add> if (isResourceUnderLocation(resource, location)) { <add> return true; <add> } <add> if (getAllowedLocations() != null) { <add> for (Resource current : getAllowedLocations()) { <add> if (isResourceUnderLocation(resource, current)) { <add> return true; <add> } <add> } <add> } <add> return false; <add> } <add> <add> private boolean isResourceUnderLocation(Resource resource, Resource location) throws IOException { <add> if (!resource.getClass().equals(location.getClass())) { <add> return false; <add> } <add> String resourcePath; <add> String locationPath; <add> if (resource instanceof ClassPathResource) { <add> resourcePath = ((ClassPathResource) resource).getPath(); <add> locationPath = ((ClassPathResource) location).getPath(); <add> } <add> else if (resource instanceof UrlResource) { <add> resourcePath = resource.getURL().toExternalForm(); <add> locationPath = location.getURL().toExternalForm(); <add> } <add> else { <add> resourcePath = resource.getURL().getPath(); <add> locationPath = location.getURL().getPath(); <add> } <add> locationPath = (locationPath.endsWith("/") || locationPath.isEmpty() ? locationPath : locationPath + "/"); <add> if (!resourcePath.startsWith(locationPath)) { <add> return false; <add> } <add> if (resourcePath.contains("%")) { <add> // Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8 chars <add> if (URLDecoder.decode(resourcePath, "UTF-8").contains("../")) { <add> if (logger.isTraceEnabled()) { <add> logger.trace("Resolved resource path contains \"../\" after decoding: " + resourcePath); <add> } <add> return false; <add> } <add> } <add> return true; <ide> } <ide> <ide> } <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java <ide> <ide> import java.io.IOException; <ide> import java.io.InputStream; <add>import java.net.URLDecoder; <ide> import java.util.ArrayList; <ide> import java.util.List; <add> <ide> import javax.activation.FileTypeMap; <ide> import javax.activation.MimetypesFileTypeMap; <ide> import javax.servlet.ServletException; <ide> <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <del> <ide> import org.springframework.beans.factory.InitializingBean; <ide> import org.springframework.core.io.ClassPathResource; <ide> import org.springframework.core.io.Resource; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.ClassUtils; <ide> import org.springframework.util.CollectionUtils; <add>import org.springframework.util.ObjectUtils; <add>import org.springframework.util.ResourceUtils; <ide> import org.springframework.util.StreamUtils; <ide> import org.springframework.util.StringUtils; <ide> import org.springframework.web.HttpRequestHandler; <ide> public void afterPropertiesSet() throws Exception { <ide> logger.warn("Locations list is empty. No resources will be served unless a " + <ide> "custom ResourceResolver is configured as an alternative to PathResourceResolver."); <ide> } <add> initAllowedLocations(); <add> } <add> <add> /** <add> * Look for a {@link org.springframework.web.servlet.resource.PathResourceResolver} <add> * among the {@link #getResourceResolvers() resource resolvers} and configure <add> * its {@code "allowedLocations"} to match the value of the <add> * {@link #setLocations(java.util.List) locations} property unless the "allowed <add> * locations" of the {@code PathResourceResolver} is non-empty. <add> */ <add> protected void initAllowedLocations() { <add> if (CollectionUtils.isEmpty(this.locations)) { <add> return; <add> } <add> for (int i = getResourceResolvers().size()-1; i >= 0; i--) { <add> if (getResourceResolvers().get(i) instanceof PathResourceResolver) { <add> PathResourceResolver pathResolver = (PathResourceResolver) getResourceResolvers().get(i); <add> if (ObjectUtils.isEmpty(pathResolver.getAllowedLocations())) { <add> pathResolver.setAllowedLocations(getLocations().toArray(new Resource[getLocations().size()])); <add> } <add> break; <add> } <add> } <ide> } <ide> <ide> /** <ide> public void handleRequest(HttpServletRequest request, HttpServletResponse respon <ide> writeContent(response, resource); <ide> } <ide> <del> protected Resource getResource(HttpServletRequest request) throws IOException{ <add> protected Resource getResource(HttpServletRequest request) throws IOException { <ide> String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); <ide> if (path == null) { <ide> throw new IllegalStateException("Required request attribute '" + <ide> HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE + "' is not set"); <ide> } <add> path = processPath(path); <ide> if (!StringUtils.hasText(path) || isInvalidPath(path)) { <ide> if (logger.isTraceEnabled()) { <ide> logger.trace("Ignoring invalid resource path [" + path + "]"); <ide> } <ide> return null; <ide> } <add> if (path.contains("%")) { <add> try { <add> // Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8 chars <add> if (isInvalidPath(URLDecoder.decode(path, "UTF-8"))) { <add> if (logger.isTraceEnabled()) { <add> logger.trace("Ignoring invalid resource path with escape sequences [" + path + "]."); <add> } <add> return null; <add> } <add> } <add> catch (IllegalArgumentException ex) { <add> // ignore <add> } <add> } <ide> ResourceResolverChain resolveChain = new DefaultResourceResolverChain(getResourceResolvers()); <ide> Resource resource = resolveChain.resolveResource(request, path, getLocations()); <ide> if (resource == null || getResourceTransformers().isEmpty()) { <ide> protected Resource getResource(HttpServletRequest request) throws IOException{ <ide> } <ide> <ide> /** <del> * Validates the given path: returns {@code true} if the given path is not a valid resource path. <del> * <p>The default implementation rejects paths containing "WEB-INF" or "META-INF" as well as paths <del> * with relative paths ("../") that result in access of a parent directory. <add> * Process the given resource path to be used. <add> * <p>The default implementation replaces any combination of leading '/' and <add> * control characters (00-1F and 7F) with a single "/" or "". For example <add> * {@code " // /// //// foo/bar"} becomes {@code "/foo/bar"}. <add> * @since 3.2.12 <add> */ <add> protected String processPath(String path) { <add> boolean slash = false; <add> for (int i = 0; i < path.length(); i++) { <add> if (path.charAt(i) == '/') { <add> slash = true; <add> } <add> else if (path.charAt(i) > ' ' && path.charAt(i) != 127) { <add> if (i == 0 || (i == 1 && slash)) { <add> return path; <add> } <add> path = slash ? "/" + path.substring(i) : path.substring(i); <add> if (logger.isTraceEnabled()) { <add> logger.trace("Path after trimming leading '/' and control characters: " + path); <add> } <add> return path; <add> } <add> } <add> return (slash ? "/" : ""); <add> } <add> <add> /** <add> * Identifies invalid resource paths. By default rejects: <add> * <ul> <add> * <li>Paths that contain "WEB-INF" or "META-INF" <add> * <li>Paths that contain "../" after a call to <add> * {@link org.springframework.util.StringUtils#cleanPath}. <add> * <li>Paths that represent a {@link org.springframework.util.ResourceUtils#isUrl <add> * valid URL} or would represent one after the leading slash is removed. <add> * </ul> <add> * <p><strong>Note:</strong> this method assumes that leading, duplicate '/' <add> * or control characters (e.g. white space) have been trimmed so that the <add> * path starts predictably with a single '/' or does not have one. <ide> * @param path the path to validate <del> * @return {@code true} if the path has been recognized as invalid, {@code false} otherwise <add> * @return {@code true} if the path is invalid, {@code false} otherwise <ide> */ <ide> protected boolean isInvalidPath(String path) { <del> return (path.contains("WEB-INF") || path.contains("META-INF") || StringUtils.cleanPath(path).startsWith("..")); <add> if (logger.isTraceEnabled()) { <add> logger.trace("Applying \"invalid path\" checks to path: " + path); <add> } <add> if (path.contains("WEB-INF") || path.contains("META-INF")) { <add> if (logger.isTraceEnabled()) { <add> logger.trace("Path contains \"WEB-INF\" or \"META-INF\"."); <add> } <add> return true; <add> } <add> if (path.contains(":/")) { <add> String relativePath = (path.charAt(0) == '/' ? path.substring(1) : path); <add> if (ResourceUtils.isUrl(relativePath) || relativePath.startsWith("url:")) { <add> if (logger.isTraceEnabled()) { <add> logger.trace("Path represents URL or has \"url:\" prefix."); <add> } <add> return true; <add> } <add> } <add> if (path.contains("../")) { <add> path = StringUtils.cleanPath(path); <add> if (path.contains("../")) { <add> if (logger.isTraceEnabled()) { <add> logger.trace("Path contains \"../\" after call to StringUtils#cleanPath."); <add> } <add> return true; <add> } <add> } <add> return false; <ide> } <ide> <ide> /** <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/AppCacheManifestTransformerTests.java <ide> package org.springframework.web.servlet.resource; <ide> <ide> import java.util.ArrayList; <add>import java.util.Arrays; <ide> import java.util.Collections; <ide> import java.util.List; <ide> import javax.servlet.http.HttpServletRequest; <ide> public void syntaxErrorInManifest() throws Exception { <ide> @Test <ide> public void transformManifest() throws Exception { <ide> <del> VersionResourceResolver versionResourceResolver = new VersionResourceResolver(); <del> versionResourceResolver <del> .setStrategyMap(Collections.singletonMap("/**", new ContentVersionStrategy())); <add> VersionResourceResolver versionResolver = new VersionResourceResolver(); <add> versionResolver.setStrategyMap(Collections.singletonMap("/**", new ContentVersionStrategy())); <ide> <del> List<ResourceResolver> resolvers = new ArrayList<ResourceResolver>(); <del> resolvers.add(versionResourceResolver); <del> resolvers.add(new PathResourceResolver()); <add> PathResourceResolver pathResolver = new PathResourceResolver(); <add> pathResolver.setAllowedLocations(new ClassPathResource("test/", getClass())); <add> <add> List<ResourceResolver> resolvers = Arrays.asList(versionResolver, pathResolver); <ide> ResourceResolverChain resolverChain = new DefaultResourceResolverChain(resolvers); <ide> <ide> List<ResourceTransformer> transformers = new ArrayList<>(); <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/CssLinkResourceTransformerTests.java <ide> public class CssLinkResourceTransformerTests { <ide> <ide> @Before <ide> public void setUp() { <del> VersionResourceResolver resolver = new VersionResourceResolver(); <del> resolver.setStrategyMap(Collections.singletonMap("/**", new ContentVersionStrategy())); <add> VersionResourceResolver versionResolver = new VersionResourceResolver(); <add> versionResolver.setStrategyMap(Collections.singletonMap("/**", new ContentVersionStrategy())); <ide> <del> List<ResourceResolver> resolvers = Arrays.asList(resolver, new PathResourceResolver()); <add> PathResourceResolver pathResolver = new PathResourceResolver(); <add> pathResolver.setAllowedLocations(new ClassPathResource("test/", getClass())); <add> <add> List<ResourceResolver> resolvers = Arrays.asList(versionResolver, pathResolver); <ide> List<ResourceTransformer> transformers = Arrays.asList(new CssLinkResourceTransformer()); <ide> <ide> ResourceResolverChain resolverChain = new DefaultResourceResolverChain(resolvers); <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/PathResourceResolverTests.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> */ <ide> package org.springframework.web.servlet.resource; <ide> <del>import java.util.ArrayList; <del>import java.util.List; <add>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.assertNotNull; <add>import static org.junit.Assert.assertNull; <add>import static org.junit.Assert.assertTrue; <add> <add>import java.io.IOException; <add>import java.util.Arrays; <ide> <ide> import org.junit.Before; <ide> import org.junit.Test; <del> <ide> import org.springframework.core.io.ClassPathResource; <ide> import org.springframework.core.io.Resource; <del> <del>import static org.junit.Assert.*; <add>import org.springframework.core.io.UrlResource; <ide> <ide> /** <ide> * Unit tests for <ide> * {@link org.springframework.web.servlet.resource.PathResourceResolver}. <ide> * <ide> * @author Brian Clozel <add> * @author Rossen Stoyanchev <ide> */ <ide> public class PathResourceResolverTests { <ide> <del> private ResourceResolverChain chain; <add> private PathResourceResolver resolver; <ide> <del> private List<Resource> locations; <ide> <ide> @Before <ide> public void setup() { <add> this.resolver = new PathResourceResolver(); <add> } <ide> <del> List<ResourceResolver> resolvers = new ArrayList<>(); <del> resolvers.add(new PathResourceResolver()); <del> this.chain = new DefaultResourceResolverChain(resolvers); <add> @Test <add> public void resolveFromClasspath() throws IOException { <add> Resource location = new ClassPathResource("test/", PathResourceResolver.class); <add> String requestPath = "bar.css"; <add> Resource actual = this.resolver.resolveResource(null, requestPath, Arrays.asList(location), null); <add> assertEquals(location.createRelative(requestPath), actual); <add> } <add> <add> @Test <add> public void resolveFromClasspathRoot() throws IOException { <add> Resource location = new ClassPathResource("/"); <add> String requestPath = "org/springframework/web/servlet/resource/test/bar.css"; <add> Resource actual = this.resolver.resolveResource(null, requestPath, Arrays.asList(location), null); <add> assertNotNull(actual); <add> } <ide> <del> this.locations = new ArrayList<>(); <del> this.locations.add(new ClassPathResource("test/", getClass())); <add> @Test <add> public void checkResource() throws IOException { <add> Resource location = new ClassPathResource("test/", PathResourceResolver.class); <add> testCheckResource(location, "../testsecret/secret.txt"); <add> testCheckResource(location, "test/../../testsecret/secret.txt"); <add> <add> location = new UrlResource(getClass().getResource("./test/")); <add> String secretPath = new UrlResource(getClass().getResource("testsecret/secret.txt")).getURL().getPath(); <add> testCheckResource(location, "file:" + secretPath); <add> testCheckResource(location, "/file:" + secretPath); <add> testCheckResource(location, "/" + secretPath); <add> testCheckResource(location, "////../.." + secretPath); <add> testCheckResource(location, "/%2E%2E/testsecret/secret.txt"); <add> testCheckResource(location, "/%2e%2e/testsecret/secret.txt"); <add> testCheckResource(location, " " + secretPath); <add> testCheckResource(location, "/ " + secretPath); <add> testCheckResource(location, "url:" + secretPath); <ide> } <ide> <ide> @Test <del> public void resolveResourceInternal() { <del> String file = "bar.css"; <del> Resource expected = new ClassPathResource("test/" + file, getClass()); <del> Resource actual = this.chain.resolveResource(null, file, this.locations); <add> public void checkResourceWithAllowedLocations() { <add> this.resolver.setAllowedLocations( <add> new ClassPathResource("test/", PathResourceResolver.class), <add> new ClassPathResource("testalternatepath/", PathResourceResolver.class) <add> ); <add> <add> Resource location = new ClassPathResource("test/main.css", PathResourceResolver.class); <add> String actual = this.resolver.resolveUrlPath("../testalternatepath/bar.css", Arrays.asList(location), null); <add> assertEquals("../testalternatepath/bar.css", actual); <add> } <ide> <del> assertEquals(expected, actual); <add> private void testCheckResource(Resource location, String requestPath) throws IOException { <add> Resource actual = this.resolver.resolveResource(null, requestPath, Arrays.asList(location), null); <add> assertTrue(location.createRelative(requestPath).exists()); <add> assertNull(actual); <ide> } <ide> <ide> } <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandlerTests.java <ide> <ide> package org.springframework.web.servlet.resource; <ide> <add>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.assertSame; <add>import static org.junit.Assert.assertTrue; <add> <ide> import java.io.IOException; <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <ide> import java.util.List; <add> <ide> import javax.servlet.http.HttpServletResponse; <ide> <ide> import org.junit.Before; <ide> import org.junit.Test; <del> <ide> import org.springframework.core.io.ClassPathResource; <ide> import org.springframework.core.io.Resource; <add>import org.springframework.core.io.UrlResource; <ide> import org.springframework.mock.web.test.MockHttpServletRequest; <ide> import org.springframework.mock.web.test.MockHttpServletResponse; <ide> import org.springframework.mock.web.test.MockServletContext; <ide> import org.springframework.web.HttpRequestMethodNotSupportedException; <ide> import org.springframework.web.servlet.HandlerMapping; <ide> <del>import static org.junit.Assert.*; <del> <ide> /** <ide> * Unit tests for ResourceHttpRequestHandler. <ide> * <ide> public void getResourceFromSubDirectoryOfAlternatePath() throws Exception { <ide> } <ide> <ide> @Test <del> public void getResourceViaDirectoryTraversal() throws Exception { <del> this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "../testsecret/secret.txt"); <del> this.handler.handleRequest(this.request, this.response); <del> assertEquals(404, this.response.getStatus()); <add> public void invalidPath() throws Exception { <add> <add> Resource location = new ClassPathResource("test/", getClass()); <add> this.handler.setLocations(Arrays.asList(location)); <add> <add> testInvalidPath(location, "../testsecret/secret.txt"); <add> testInvalidPath(location, "test/../../testsecret/secret.txt"); <add> testInvalidPath(location, ":/../../testsecret/secret.txt"); <add> <add> location = new UrlResource(getClass().getResource("./test/")); <add> this.handler.setLocations(Arrays.asList(location)); <add> Resource secretResource = new UrlResource(getClass().getResource("testsecret/secret.txt")); <add> String secretPath = secretResource.getURL().getPath(); <add> <add> testInvalidPath(location, "file:" + secretPath); <add> testInvalidPath(location, "/file:" + secretPath); <add> testInvalidPath(location, "url:" + secretPath); <add> testInvalidPath(location, "/url:" + secretPath); <add> testInvalidPath(location, "/" + secretPath); <add> testInvalidPath(location, "////../.." + secretPath); <add> testInvalidPath(location, "/%2E%2E/testsecret/secret.txt"); <add> testInvalidPath(location, "/ " + secretPath); <add> testInvalidPath(location, "url:" + secretPath); <add> } <ide> <del> this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "test/../../testsecret/secret.txt"); <add> @Test <add> public void ignoreInvalidEscapeSequence() throws Exception { <add> this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "/%foo%/bar.txt"); <ide> this.response = new MockHttpServletResponse(); <ide> this.handler.handleRequest(this.request, this.response); <ide> assertEquals(404, this.response.getStatus()); <add> } <ide> <del> this.handler.setLocations(Arrays.<Resource>asList(new ClassPathResource("testsecret/", getClass()))); <del> this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "secret.txt"); <del> this.response = new MockHttpServletResponse(); <del> this.handler.handleRequest(this.request, this.response); <del> assertEquals(200, this.response.getStatus()); <del> assertEquals("text/plain", this.response.getContentType()); <del> assertEquals("big secret", this.response.getContentAsString()); <add> @Test <add> public void processPath() throws Exception { <add> assertSame("/foo/bar", this.handler.processPath("/foo/bar")); <add> assertSame("foo/bar", this.handler.processPath("foo/bar")); <add> <add> // leading whitespace control characters (00-1F) <add> assertEquals("/foo/bar", this.handler.processPath(" /foo/bar")); <add> assertEquals("/foo/bar", this.handler.processPath((char) 1 + "/foo/bar")); <add> assertEquals("/foo/bar", this.handler.processPath((char) 31 + "/foo/bar")); <add> assertEquals("foo/bar", this.handler.processPath(" foo/bar")); <add> assertEquals("foo/bar", this.handler.processPath((char) 31 + "foo/bar")); <add> <add> // leading control character 0x7F (DEL) <add> assertEquals("/foo/bar", this.handler.processPath((char) 127 + "/foo/bar")); <add> assertEquals("/foo/bar", this.handler.processPath((char) 127 + "/foo/bar")); <add> <add> // leading control and '/' characters <add> assertEquals("/foo/bar", this.handler.processPath(" / foo/bar")); <add> assertEquals("/foo/bar", this.handler.processPath(" / / foo/bar")); <add> assertEquals("/foo/bar", this.handler.processPath(" // /// //// foo/bar")); <add> assertEquals("/foo/bar", this.handler.processPath((char) 1 + " / " + (char) 127 + " // foo/bar")); <add> <add> // root or empty path <add> assertEquals("", this.handler.processPath(" ")); <add> assertEquals("/", this.handler.processPath("/")); <add> assertEquals("/", this.handler.processPath("///")); <add> assertEquals("/", this.handler.processPath("/ / / ")); <add> } <add> <add> @Test <add> public void initAllowedLocations() throws Exception { <add> PathResourceResolver resolver = (PathResourceResolver) this.handler.getResourceResolvers().get(0); <add> Resource[] locations = resolver.getAllowedLocations(); <add> <add> assertEquals(2, locations.length); <add> assertEquals("test/", ((ClassPathResource) locations[0]).getPath()); <add> assertEquals("testalternatepath/", ((ClassPathResource) locations[1]).getPath()); <add> } <add> <add> @Test <add> public void initAllowedLocationsWithExplicitConfiguration() throws Exception { <add> ClassPathResource location1 = new ClassPathResource("test/", getClass()); <add> ClassPathResource location2 = new ClassPathResource("testalternatepath/", getClass()); <add> <add> PathResourceResolver pathResolver = new PathResourceResolver(); <add> pathResolver.setAllowedLocations(location1); <add> <add> ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler(); <add> handler.setResourceResolvers(Arrays.asList(pathResolver)); <add> handler.setLocations(Arrays.asList(location1, location2)); <add> handler.afterPropertiesSet(); <add> <add> Resource[] locations = pathResolver.getAllowedLocations(); <add> assertEquals(1, locations.length); <add> assertEquals("test/", ((ClassPathResource) locations[0]).getPath()); <ide> } <ide> <ide> @Test <ide> private long resourceLastModified(String resourceName) throws IOException { <ide> return new ClassPathResource(resourceName, getClass()).getFile().lastModified(); <ide> } <ide> <add> private void testInvalidPath(Resource location, String requestPath) throws Exception { <add> this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, requestPath); <add> this.response = new MockHttpServletResponse(); <add> this.handler.handleRequest(this.request, this.response); <add> assertTrue(location.createRelative(requestPath).exists()); <add> assertEquals(404, this.response.getStatus()); <add> } <add> <ide> <ide> private static class TestServletContext extends MockServletContext { <ide> <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceTransformerSupportTests.java <ide> public class ResourceTransformerSupportTests { <ide> <ide> @Before <ide> public void setUp() { <del> VersionResourceResolver resolver = new VersionResourceResolver(); <del> resolver.setStrategyMap(Collections.singletonMap("/**", new ContentVersionStrategy())); <del> List<ResourceResolver> resolvers = Arrays.asList(resolver, new PathResourceResolver()); <add> VersionResourceResolver versionResolver = new VersionResourceResolver(); <add> versionResolver.setStrategyMap(Collections.singletonMap("/**", new ContentVersionStrategy())); <add> PathResourceResolver pathResolver = new PathResourceResolver(); <add> pathResolver.setAllowedLocations(new ClassPathResource("test/", getClass())); <add> List<ResourceResolver> resolvers = Arrays.asList(versionResolver, pathResolver); <ide> this.transformerChain = new DefaultResourceTransformerChain(new DefaultResourceResolverChain(resolvers), null); <ide> <ide> this.transformer = new TestResourceTransformerSupport();
7