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 | add hook functions and tests | 799164513891a258e858061fc7f86a415cb38821 | <ide><path>src/Illuminate/Validation/ValidatesWhenResolvedTrait.php
<ide> trait ValidatesWhenResolvedTrait
<ide> */
<ide> public function validate()
<ide> {
<add> $this->beforeValidation();
<ide> $instance = $this->getValidatorInstance();
<ide>
<ide> if (! $this->passesAuthorization()) {
<ide> $this->failedAuthorization();
<ide> } elseif (! $instance->passes()) {
<ide> $this->failedValidation($instance);
<ide> }
<add> $this->afterValidation();
<ide> }
<ide>
<ide> /**
<ide> protected function failedAuthorization()
<ide> {
<ide> throw new UnauthorizedException;
<ide> }
<add>
<add> /**
<add> * Provide a hook for taking action before validation
<add> *
<add> * @return void
<add> */
<add> protected function beforeValidation()
<add> {
<add> // no default action
<add> }
<add>
<add> /**
<add> * Provide a hook for taking action after validation
<add> *
<add> * @return void
<add> */
<add> protected function afterValidation()
<add> {
<add> // no default action
<add> }
<ide> }
<ide><path>tests/Foundation/FoundationFormRequestTest.php
<ide> public function testRedirectResponseIsProperlyCreatedWithGivenErrors()
<ide>
<ide> $request->response(['errors']);
<ide> }
<add>
<add> public function testValidateFunctionRunsBeforeValidationFunction()
<add> {
<add> $request = FoundationTestFormRequestHooks::create('/', 'GET', ['name' => 'abigail']);
<add> $request->setContainer($container = new Container);
<add> $factory = m::mock('Illuminate\Validation\Factory');
<add> $factory->shouldReceive('make')->once()->with(['name' => 'Taylor'], ['name' => 'required'], [], [])->andReturn(
<add> $validator = m::mock('Illuminate\Validation\Validator')
<add> );
<add> $container->instance('Illuminate\Contracts\Validation\Factory', $factory);
<add> $validator->shouldReceive('passes')->once()->andReturn(true);
<add>
<add> $request->validate($factory);
<add> }
<add>
<add> public function testValidateFunctionRunsAfterValidationFunctionIfValidationPasses()
<add> {
<add> $request = FoundationTestFormRequestStub::create('/', 'GET', ['name' => 'abigail']);
<add> $request->setContainer($container = new Container);
<add> $factory = m::mock('Illuminate\Validation\Factory');
<add> $factory->shouldReceive('make')->once()->with(['name' => 'abigail'], ['name' => 'required'], [], [])->andReturn(
<add> $validator = m::mock('Illuminate\Validation\Validator')
<add> );
<add> $container->instance('Illuminate\Contracts\Validation\Factory', $factory);
<add> $validator->shouldReceive('passes')->once()->andReturn(true);
<add>
<add> $request->validate($factory);
<add> $this->assertSame('Jeffrey', $request->get('name'));
<add> }
<ide> }
<ide>
<ide> class FoundationTestFormRequestStub extends Illuminate\Foundation\Http\FormRequest
<ide> public function authorize()
<ide> {
<ide> return true;
<ide> }
<add>
<add> public function afterValidation()
<add> {
<add> $this->replace(['name' => 'Jeffrey']);
<add> }
<ide> }
<ide>
<ide> class FoundationTestFormRequestForbiddenStub extends Illuminate\Foundation\Http\FormRequest
<ide> public function authorize()
<ide> return false;
<ide> }
<ide> }
<add>class FoundationTestFormRequestHooks extends Illuminate\Foundation\Http\FormRequest
<add>{
<add> public function rules()
<add> {
<add> return ['name' => 'required'];
<add> }
<add>
<add> public function authorize()
<add> {
<add> return true;
<add> }
<add>
<add> public function beforeValidation()
<add> {
<add> $this->replace(['name' => 'Taylor']);
<add> }
<add>} | 2 |
Ruby | Ruby | upgrade virtualenv to 16.1.0 | 77daf29c474bdf05945ca587292c01f498953fd7 | <ide><path>Library/Homebrew/language/python_virtualenv_constants.rb
<ide> PYTHON_VIRTUALENV_URL =
<del> "https://files.pythonhosted.org/packages/33/bc" \
<del> "/fa0b5347139cd9564f0d44ebd2b147ac97c36b2403943dbee8a25fd74012" \
<del> "/virtualenv-16.0.0.tar.gz".freeze
<add> "https://files.pythonhosted.org/packages/4e/8b" \
<add> "/75469c270ac544265f0020aa7c4ea925c5284b23e445cf3aa8b99f662690" \
<add> "/virtualenv-16.1.0.tar.gz".freeze
<ide> PYTHON_VIRTUALENV_SHA256 =
<del> "ca07b4c0b54e14a91af9f34d0919790b016923d157afda5efdde55c96718f752".freeze
<add> "f899fafcd92e1150f40c8215328be38ff24b519cd95357fa6e78e006c7638208".freeze | 1 |
Text | Text | use year of first publication | efae2e08c3f902149431732cbd550aea09748acc | <ide><path>LICENSE.md
<del>Copyright (c) 2016 GitHub Inc.
<add>Copyright (c) 2014 GitHub Inc.
<ide>
<ide> Permission is hereby granted, free of charge, to any person obtaining
<ide> a copy of this software and associated documentation files (the | 1 |
PHP | PHP | remove use of folder from assetstask | c048fb30e78b6efc1f0ec967e17a799022613c87 | <ide><path>src/Filesystem/Filesystem.php
<ide> public function mkdir(string $dir, int $mode = 0755): void
<ide>
<ide> umask($old);
<ide> }
<add>
<add> public function deleteDir(string $path): bool
<add> {
<add> if (!file_exists($path)) {
<add> return true;
<add> }
<add>
<add> if (!is_dir($path)) {
<add> throw new Exception(sprintf('"%s" is not a directory', $path));
<add> }
<add>
<add> $iterator = new RecursiveIteratorIterator(
<add> new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
<add> RecursiveIteratorIterator::CHILD_FIRST
<add> );
<add>
<add> $result = true;
<add> foreach ($iterator as $fileInfo) {
<add> switch ($fileInfo->getType()) {
<add> case 'dir':
<add> // @codingStandardsIgnoreLine
<add> $result = $result && @rmdir($fileInfo->getRealPath());
<add> break;
<add> case 'link':
<add> // @codingStandardsIgnoreLine
<add> $result = $result && @unlink($fileInfo->getPathname());
<add> break;
<add> default:
<add> // @codingStandardsIgnoreLine
<add> $result = $result && @unlink($fileInfo->getRealPath());
<add> }
<add> }
<add>
<add> // @codingStandardsIgnoreLine
<add> $result = $result && @rmdir($path);
<add>
<add> return $result;
<add> }
<add>
<add> public function copyDir(string $source, string $destination): bool
<add> {
<add> $destination = (new SplFileInfo($destination))->getPathname();
<add>
<add> if (!is_dir($destination)) {
<add> $this->mkdir($destination);
<add> }
<add>
<add> $iterator = new FilesystemIterator($source);
<add>
<add> $result = true;
<add> foreach ($iterator as $fileInfo) {
<add> if ($fileInfo->isDir()) {
<add> $result = $result && $this->copyDir(
<add> $fileInfo->getRealPath(),
<add> $destination . DIRECTORY_SEPARATOR . $fileInfo->getFilename()
<add> );
<add> } else {
<add> // @codingStandardsIgnoreLine
<add> $result = $result && @copy(
<add> $fileInfo->getRealPath(),
<add> $destination . DIRECTORY_SEPARATOR . $fileInfo->getFilename()
<add> );
<add> }
<add> }
<add>
<add> return $result;
<add> }
<ide> }
<ide><path>src/Shell/Task/AssetsTask.php
<ide> use Cake\Console\Shell;
<ide> use Cake\Core\Configure;
<ide> use Cake\Core\Plugin;
<del>use Cake\Filesystem\Folder;
<add>use Cake\Filesystem\Filesystem;
<ide> use Cake\Utility\Inflector;
<ide>
<ide> /**
<ide> protected function _remove(array $config): bool
<ide> }
<ide> }
<ide>
<del> $folder = new Folder($dest);
<del> if ($folder->delete()) {
<add> $fs = new Filesystem();
<add> if ($fs->deleteDir($dest)) {
<ide> $this->out('Deleted ' . $dest);
<ide>
<ide> return true;
<ide> protected function _createSymlink(string $target, string $link): bool
<ide> */
<ide> protected function _copyDirectory(string $source, string $destination): bool
<ide> {
<del> $folder = new Folder($source);
<del> if ($folder->copy($destination)) {
<add> $fs = new Filesystem();
<add> if ($fs->copyDir($source, $destination)) {
<ide> $this->out('Copied assets to directory ' . $destination);
<ide>
<ide> return true;
<ide><path>tests/TestCase/Shell/Task/AssetsTaskTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Shell\Task;
<ide>
<add>use Cake\Core\Configure;
<ide> use Cake\Core\Plugin;
<del>use Cake\Filesystem\Folder;
<add>use Cake\Filesystem\Filesystem;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> /**
<ide> * AssetsTaskTest class
<ide> */
<ide> class AssetsTaskTest extends TestCase
<ide> {
<add> protected $wwwRoot;
<add>
<add> /**
<add> * @var Cake\Filessytem\Filesystem;
<add> */
<add> protected $fs;
<add>
<ide> /**
<ide> * setUp method
<ide> *
<ide> public function setUp()
<ide> ->setMethods(['in', 'out', 'err', '_stop'])
<ide> ->setConstructorArgs([$this->io])
<ide> ->getMock();
<add>
<add> $this->wwwRoot = TMP . 'assets_task_webroot' . DS;
<add> Configure::write('App.wwwRoot', $this->wwwRoot);
<add>
<add> $this->fs = new Filesystem();
<add> $this->fs->deleteDir($this->wwwRoot);
<add> $this->fs->copyDir(WWW_ROOT, $this->wwwRoot);
<ide> }
<ide>
<ide> /**
<ide> public function testSymlink()
<ide>
<ide> $this->Task->symlink();
<ide>
<del> $path = WWW_ROOT . 'test_plugin';
<add> $path = $this->wwwRoot . 'test_plugin';
<ide> $this->assertFileExists($path . DS . 'root.js');
<ide> if (DS === '\\') {
<ide> $this->assertDirectoryExists($path);
<del> $folder = new Folder($path);
<del> $folder->delete();
<ide> } else {
<ide> $this->assertTrue(is_link($path));
<del> unlink($path);
<ide> }
<ide>
<del> $path = WWW_ROOT . 'company' . DS . 'test_plugin_three';
<add> $path = $this->wwwRoot . 'company' . DS . 'test_plugin_three';
<ide> // If "company" directory exists beforehand "test_plugin_three" would
<ide> // be a link. But if the directory is created by the shell itself
<ide> // symlinking fails and the assets folder is copied as fallback.
<ide> $this->assertDirectoryExists($path);
<ide> $this->assertFileExists($path . DS . 'css' . DS . 'company.css');
<del> $folder = new Folder(WWW_ROOT . 'company');
<del> $folder->delete();
<ide> }
<ide>
<ide> /**
<ide> public function testSymlinkWhenVendorDirectoryExits()
<ide> {
<ide> $this->loadPlugins(['Company/TestPluginThree']);
<ide>
<del> mkdir(WWW_ROOT . 'company');
<add> mkdir($this->wwwRoot . 'company');
<ide>
<ide> $this->Task->symlink();
<del> $path = WWW_ROOT . 'company' . DS . 'test_plugin_three';
<add> $path = $this->wwwRoot . 'company' . DS . 'test_plugin_three';
<ide> if (DS === '\\') {
<ide> $this->assertDirectoryExits($path);
<ide> } else {
<ide> $this->assertTrue(is_link($path));
<ide> }
<ide> $this->assertFileExists($path . DS . 'css' . DS . 'company.css');
<del> $folder = new Folder(WWW_ROOT . 'company');
<del> $folder->delete();
<ide> }
<ide>
<ide> /**
<ide> public function testSymlinkWhenTargetAlreadyExits()
<ide> ->setConstructorArgs([$this->io])
<ide> ->getMock();
<ide>
<del> $this->assertDirectoryExists(WWW_ROOT . 'test_theme');
<add> $this->assertDirectoryExists($this->wwwRoot . 'test_theme');
<ide>
<ide> $shell->expects($this->never())->method('_createSymlink');
<ide> $shell->expects($this->never())->method('_copyDirectory');
<ide> public function testForPluginWithoutWebroot()
<ide> $this->loadPlugins(['TestPluginTwo']);
<ide>
<ide> $this->Task->symlink();
<del> $this->assertFileNotExists(WWW_ROOT . 'test_plugin_two');
<add> $this->assertFileNotExists($this->wwwRoot . 'test_plugin_two');
<ide> }
<ide>
<ide> /**
<ide> public function testSymlinkingSpecifiedPlugin()
<ide>
<ide> $this->Task->symlink('TestPlugin');
<ide>
<del> $path = WWW_ROOT . 'test_plugin';
<add> $path = $this->wwwRoot . 'test_plugin';
<ide> $link = new \SplFileInfo($path);
<ide> $this->assertFileExists($path . DS . 'root.js');
<ide> unlink($path);
<ide>
<del> $path = WWW_ROOT . 'company' . DS . 'test_plugin_three';
<add> $path = $this->wwwRoot . 'company' . DS . 'test_plugin_three';
<ide> $this->assertDirectoryNotExists($path);
<ide> $this->assertFalse(is_link($path));
<ide> }
<ide> public function testCopy()
<ide>
<ide> $this->Task->copy();
<ide>
<del> $path = WWW_ROOT . 'test_plugin';
<add> $path = $this->wwwRoot . 'test_plugin';
<ide> $this->assertDirectoryExists($path);
<ide> $this->assertFileExists($path . DS . 'root.js');
<ide>
<del> $folder = new Folder($path);
<del> $folder->delete();
<del>
<del> $path = WWW_ROOT . 'company' . DS . 'test_plugin_three';
<add> $path = $this->wwwRoot . 'company' . DS . 'test_plugin_three';
<ide> $this->assertDirectoryExists($path);
<ide> $this->assertFileExists($path . DS . 'css' . DS . 'company.css');
<del>
<del> $folder = new Folder(WWW_ROOT . 'company');
<del> $folder->delete();
<ide> }
<ide>
<ide> /**
<ide> public function testCopyOverwrite()
<ide>
<ide> $pluginPath = TEST_APP . 'Plugin' . DS . 'TestPlugin' . DS . 'webroot';
<ide>
<del> $path = WWW_ROOT . 'test_plugin';
<add> $path = $this->wwwRoot . 'test_plugin';
<ide> $dir = new \SplFileInfo($path);
<ide> $this->assertTrue($dir->isDir());
<ide> $this->assertFileExists($path . DS . 'root.js');
<ide> public function testCopyOverwrite()
<ide> $this->Task->copy();
<ide>
<ide> $this->assertFileEquals($path . DS . 'root.js', $pluginPath . DS . 'root.js');
<del>
<del> $folder = new Folder($path);
<del> $folder->delete();
<ide> }
<ide>
<ide> /**
<ide> public function testRemoveSymlink()
<ide>
<ide> $this->loadPlugins(['TestPlugin', 'Company/TestPluginThree']);
<ide>
<del> mkdir(WWW_ROOT . 'company');
<add> mkdir($this->wwwRoot . 'company');
<ide>
<ide> $this->Task->symlink();
<ide>
<del> $this->assertTrue(is_link(WWW_ROOT . 'test_plugin'));
<add> $this->assertTrue(is_link($this->wwwRoot . 'test_plugin'));
<ide>
<del> $path = WWW_ROOT . 'company' . DS . 'test_plugin_three';
<add> $path = $this->wwwRoot . 'company' . DS . 'test_plugin_three';
<ide> $this->assertTrue(is_link($path));
<ide>
<ide> $this->Task->remove();
<ide>
<del> $this->assertFalse(is_link(WWW_ROOT . 'test_plugin'));
<add> $this->assertFalse(is_link($this->wwwRoot . 'test_plugin'));
<ide> $this->assertFalse(is_link($path));
<del> $this->assertDirectoryExists(WWW_ROOT . 'company', 'Ensure namespace folder isn\'t removed');
<add> $this->assertDirectoryExists($this->wwwRoot . 'company', 'Ensure namespace folder isn\'t removed');
<ide>
<del> rmdir(WWW_ROOT . 'company');
<add> rmdir($this->wwwRoot . 'company');
<ide> }
<ide>
<ide> /**
<ide> public function testRemoveFolder()
<ide>
<ide> $this->Task->copy();
<ide>
<del> $this->assertTrue(is_dir(WWW_ROOT . 'test_plugin'));
<add> $this->assertTrue(is_dir($this->wwwRoot . 'test_plugin'));
<ide>
<del> $this->assertTrue(is_dir(WWW_ROOT . 'company' . DS . 'test_plugin_three'));
<add> $this->assertTrue(is_dir($this->wwwRoot . 'company' . DS . 'test_plugin_three'));
<ide>
<ide> $this->Task->remove();
<ide>
<del> $this->assertDirectoryNotExists(WWW_ROOT . 'test_plugin');
<del> $this->assertDirectoryNotExists(WWW_ROOT . 'company' . DS . 'test_plugin_three');
<del> $this->assertDirectoryExists(WWW_ROOT . 'company', 'Ensure namespace folder isn\'t removed');
<add> $this->assertDirectoryNotExists($this->wwwRoot . 'test_plugin');
<add> $this->assertDirectoryNotExists($this->wwwRoot . 'company' . DS . 'test_plugin_three');
<add> $this->assertDirectoryExists($this->wwwRoot . 'company', 'Ensure namespace folder isn\'t removed');
<ide>
<del> rmdir(WWW_ROOT . 'company');
<add> rmdir($this->wwwRoot . 'company');
<ide> }
<ide>
<ide> /**
<ide> public function testOverwrite()
<ide> {
<ide> $this->loadPlugins(['TestPlugin', 'Company/TestPluginThree']);
<ide>
<del> $path = WWW_ROOT . 'test_plugin';
<add> $path = $this->wwwRoot . 'test_plugin';
<ide>
<ide> mkdir($path);
<ide> $filectime = filectime($path);
<ide> public function testOverwrite()
<ide> $this->assertTrue($newfilectime !== $filectime);
<ide>
<ide> if (DS === '\\') {
<del> $folder = new Folder($path);
<del> $folder->delete();
<add> $this->fs->deleteDir($path);
<ide> } else {
<ide> unlink($path);
<ide> }
<ide>
<del> $path = WWW_ROOT . 'company' . DS . 'test_plugin_three';
<add> $path = $this->wwwRoot . 'company' . DS . 'test_plugin_three';
<ide> mkdir($path, 0777, true);
<ide> $filectime = filectime($path);
<ide>
<ide> public function testOverwrite()
<ide>
<ide> $newfilectime = filectime($path);
<ide> $this->assertTrue($newfilectime > $filectime);
<del>
<del> $folder = new Folder(WWW_ROOT . 'company');
<del> $folder->delete();
<ide> }
<ide> } | 3 |
Javascript | Javascript | update docs with releases information | 59ed3f835193dec57cf423aed4995c8913dd4281 | <ide><path>website/src/react-native/versions.js
<ide> module.exports = React.createClass({
<ide> <section className="content wrap documentationContent nosidebar">
<ide> <div className="inner-content">
<ide> <h1>React Native Versions</h1>
<del> <p>React Native follows a 2-week release train. Every two weeks, a new branch created off master enters the <a href="versions.html#rc">Release Candidate</a> phase, and the previous Release Candidate branch is released and considered <a href="versions.html#latest">stable</a>.</p>
<add> <p>React Native follows a monthly release train. Every month, a new branch created off master enters the <a href="versions.html#rc">Release Candidate</a> phase, and the previous Release Candidate branch is released and considered <a href="versions.html#latest">stable</a>.</p>
<ide> <a name="latest" />
<ide> <h3>Current Version (Stable)</h3>
<ide> <table className="versions"> | 1 |
Python | Python | resolve unittest compat | 24a2c3f5c3349ec941790240c1f372a6de723e1b | <ide><path>rest_framework/compat.py
<ide> def distinct(queryset, base):
<ide> import unittest
<ide> unittest.skipUnless
<ide> except (ImportError, AttributeError):
<del> from django.test.utils import unittest
<add> from django.utils import unittest
<ide>
<ide>
<ide> # contrib.postgres only supported from 1.8 onwards. | 1 |
PHP | PHP | refactor the request class | 3d48b323c3120aee917291b7b2e699409a36acfc | <ide><path>system/request.php
<ide> public static function uri()
<ide> {
<ide> if ( ! is_null(static::$uri)) return static::$uri;
<ide>
<del> $uri = static::raw_uri();
<del>
<del> if (strpos($uri, $base = parse_url(Config::get('application.url'), PHP_URL_PATH)) === 0)
<del> {
<del> $uri = substr($uri, strlen($base));
<del> }
<del>
<del> if (strpos($uri, $index = '/index.php') === 0)
<del> {
<del> $uri = substr($uri, strlen($index));
<del> }
<del>
<del> return static::$uri = (($uri = trim($uri, '/')) == '') ? '/' : $uri;
<del> }
<del>
<del> /**
<del> * Get the raw request URI from the $_SERVER array.
<del> *
<del> * @return string
<del> */
<del> private static function raw_uri()
<del> {
<ide> if (isset($_SERVER['PATH_INFO']))
<ide> {
<ide> $uri = $_SERVER['PATH_INFO'];
<ide> private static function raw_uri()
<ide> throw new \Exception("Malformed request URI. Request terminated.");
<ide> }
<ide>
<del> return $uri;
<add> if (strpos($uri, $base = parse_url(Config::get('application.url'), PHP_URL_PATH)) === 0)
<add> {
<add> $uri = substr($uri, strlen($base));
<add> }
<add>
<add> if (strpos($uri, $index = '/index.php') === 0)
<add> {
<add> $uri = substr($uri, strlen($index));
<add> }
<add>
<add> return static::$uri = (($uri = trim($uri, '/')) == '') ? '/' : $uri;
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | fix minor lint warnings | 29ed7c6c8c2dd0546c453322d7549954b8bf6df0 | <ide><path>src/renderers/dom/client/syntheticEvents/SyntheticEvent.js
<ide> Object.assign(SyntheticEvent.prototype, {
<ide> this[shouldBeReleasedProperties[i]] = null;
<ide> }
<ide> if (__DEV__) {
<del> Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));
<del> Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', emptyFunction));
<del> Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', emptyFunction));
<add> Object.defineProperty(
<add> this,
<add> 'nativeEvent',
<add> getPooledWarningPropertyDefinition('nativeEvent', null)
<add> );
<add> Object.defineProperty(
<add> this,
<add> 'preventDefault',
<add> getPooledWarningPropertyDefinition('preventDefault', emptyFunction)
<add> );
<add> Object.defineProperty(
<add> this,
<add> 'stopPropagation',
<add> getPooledWarningPropertyDefinition('stopPropagation', emptyFunction)
<add> );
<ide> }
<ide> },
<ide>
<ide><path>src/renderers/native/ReactNativeAttributePayload.js
<ide> function diffProperties(
<ide> // default: fallthrough case when nested properties are defined
<ide> removedKeys = null;
<ide> removedKeyCount = 0;
<del> // $FlowFixMe - We think that attributeConfig is not CustomAttributeConfiguration at this point so we assume it must be AttributeConfiguration.
<add> // $FlowFixMe - We think that attributeConfig is not
<add> // CustomAttributeConfiguration at this point so we assume
<add> // it must be AttributeConfiguration.
<ide> updatePayload = diffNestedProperty(
<ide> updatePayload,
<ide> prevProp,
<ide><path>src/renderers/shared/fiber/isomorphic/ReactCoroutine.js
<ide> export type ReactYield = {
<ide> continuation: mixed
<ide> };
<ide>
<del>exports.createCoroutine = function<T>(children : mixed, handler : CoroutineHandler<T>, props : T, key : ?string = null) : ReactCoroutine {
<add>exports.createCoroutine = function<T>(
<add> children : mixed,
<add> handler : CoroutineHandler<T>,
<add> props : T,
<add> key : ?string = null
<add>) : ReactCoroutine {
<ide> var coroutine = {
<ide> // This tag allow us to uniquely identify this as a React Coroutine
<ide> $$typeof: REACT_COROUTINE_TYPE, | 3 |
PHP | PHP | add support for configuring aws s3 region | 5da4d51f0bfead3157ffb242041d0ee9760070ff | <ide><path>config/filesystems.php
<ide> 'driver' => 's3',
<ide> 'key' => 'your-key',
<ide> 'secret' => 'your-secret',
<add> 'region' => 'your-region',
<ide> 'bucket' => 'your-bucket',
<ide> ],
<ide> | 1 |
Ruby | Ruby | fix last remaining style issues | eaae7f3a5b7dcce0d6c4a3238547996e886b7144 | <ide><path>Library/Homebrew/cask/lib/hbc/audit.rb
<ide> def check_single_pre_postflight
<ide> add_warning "only a single preflight stanza is allowed"
<ide> end
<ide>
<del> if cask.artifacts.count { |k| k.is_a?(Hbc::Artifact::PostflightBlock) && k.directives.key?(:postflight) } > 1
<del> add_warning "only a single postflight stanza is allowed"
<del> end
<add> return unless cask.artifacts.count { |k| k.is_a?(Hbc::Artifact::PostflightBlock) && k.directives.key?(:postflight) } > 1
<add> add_warning "only a single postflight stanza is allowed"
<ide> end
<ide>
<ide> def check_single_uninstall_zap
<ide> def check_single_uninstall_zap
<ide> add_warning "only a single uninstall_postflight stanza is allowed"
<ide> end
<ide>
<del> if cask.artifacts.count { |k| k.is_a?(Hbc::Artifact::Zap) } > 1
<del> add_warning "only a single zap stanza is allowed"
<del> end
<add> return unless cask.artifacts.count { |k| k.is_a?(Hbc::Artifact::Zap) } > 1
<add> add_warning "only a single zap stanza is allowed"
<ide> end
<ide>
<ide> def check_required_stanzas | 1 |
Javascript | Javascript | allow binding to this | e57f0c04219f86683bbe32a2a1d802caec98809c | <ide><path>packages/sproutcore-handlebars/lib/helpers/view.js
<ide> SC.Handlebars.ViewHelper = SC.Object.create({
<ide> if (PARENT_VIEW_PATH.test(path)) {
<ide> SC.Logger.warn("As of SproutCore 2.0 beta 3, it is no longer necessary to bind to parentViews. Instead, please provide binding paths relative to the current Handlebars context.");
<ide> } else {
<del> options[prop] = 'bindingContext.'+path;
<add> if (path === 'this') {
<add> options[prop] = 'bindingContext';
<add> } else {
<add> options[prop] = 'bindingContext.'+path;
<add> }
<ide> }
<ide> }
<ide> }
<ide><path>packages/sproutcore-handlebars/tests/handlebars_test.js
<ide> test("bindings should be relative to the current context", function() {
<ide> equals($.trim(view.$().text()), "Name: SFMoMA Price: $20", "should print baz twice");
<ide> });
<ide>
<add>test("bindings can be 'this', in which case they *are* the current context", function() {
<add> view = SC.View.create({
<add> museumOpen: true,
<add>
<add> museumDetails: SC.Object.create({
<add> name: "SFMoMA",
<add> price: 20,
<add> museumView: SC.View.extend({
<add> template: SC.Handlebars.compile('Name: {{museum.name}} Price: ${{museum.price}}')
<add> }),
<add> }),
<add>
<add>
<add> template: SC.Handlebars.compile('{{#if museumOpen}} {{#with museumDetails}}{{view museumView museumBinding="this"}} {{/with}}{{/if}}')
<add> });
<add>
<add> SC.run(function() {
<add> view.appendTo('#qunit-fixture');
<add> });
<add>
<add> equals($.trim(view.$().text()), "Name: SFMoMA Price: $20", "should print baz twice");
<add>});
<ide>
<ide> // https://github.com/sproutcore/sproutcore20/issues/120
<ide> | 2 |
Javascript | Javascript | add regenerator path | 64e414160d212cb32ce90979192c452aeee3a01e | <ide><path>packages/next/build/webpack/loaders/next-swc-loader.js
<ide> function getSWCOptions({
<ide> },
<ide> },
<ide> },
<add> regenerator: {
<add> importPath: require.resolve('regenerator-runtime'),
<add> },
<ide> },
<ide> }
<ide>
<ide><path>test/integration/pnpm-support/app/pages/regenerator.js
<add>import { useState, useEffect } from 'react'
<add>
<add>export default function RegeneratorTest() {
<add> const [message, setMessage] = useState('')
<add> useEffect(() => {
<add> ;(async () => {
<add> await new Promise((resolve) => setTimeout(resolve, 50))
<add> setMessage('Hello World')
<add> })()
<add> }, [])
<add> return <h1>{message}</h1>
<add>}
<ide><path>test/integration/pnpm-support/test/index.test.js
<ide> const packagesDir = path.join(__dirname, '..', '..', '..', '..', 'packages')
<ide> const appDir = path.join(__dirname, '..', 'app')
<ide>
<ide> const runNpm = (cwd, ...args) => execa('npm', [...args], { cwd })
<del>const runPnpm = (cwd, ...args) => execa('npx', ['pnpm', ...args], { cwd })
<add>const runPnpm = async (cwd, ...args) => {
<add> try {
<add> return await execa('npx', ['pnpm', ...args], { cwd })
<add> } catch (err) {
<add> console.error({ err })
<add> throw err
<add> }
<add>}
<ide>
<ide> async function usingTempDir(fn) {
<ide> const folder = path.join(os.tmpdir(), Math.random().toString(36).substring(2)) | 3 |
PHP | PHP | fix failing test | 70249eff5becbcab8d924bc825252fd946f7f3a4 | <ide><path>tests/Database/DatabaseConnectionTest.php
<ide> public function testTransactionRetriesOnSerializationFailure()
<ide>
<ide> $pdo = $this->getMockBuilder(DatabaseConnectionTestMockPDO::class)->setMethods(['beginTransaction', 'commit', 'rollBack'])->getMock();
<ide> $mock = $this->getMockConnection([], $pdo);
<del> $pdo->method('commit')->will($this->throwException(new DatabaseConnectionTestMockPDOException('Serialization failure', '40001')));
<add> $pdo->expects($this->exactly(3))->method('commit')->will($this->throwException(new DatabaseConnectionTestMockPDOException('Serialization failure', '40001')));
<ide> $pdo->expects($this->exactly(3))->method('beginTransaction');
<ide> $pdo->expects($this->never())->method('rollBack');
<del> $pdo->expects($this->exactly(3))->method('commit');
<ide> $mock->transaction(function () {
<ide> }, 3);
<ide> } | 1 |
Go | Go | update comments about `initrouter` | dbd4c290b7029d31fa69c906a8da864589f19e09 | <ide><path>api/server/server.go
<ide> func (s *Server) makeHTTPHandler(handler httputils.APIFunc) http.HandlerFunc {
<ide> }
<ide>
<ide> // InitRouter initializes the list of routers for the server.
<del>// This method also enables the Go profiler if enableProfiler is true.
<add>// This method also enables the Go profiler.
<ide> func (s *Server) InitRouter(routers ...router.Router) {
<ide> s.routers = append(s.routers, routers...)
<ide> | 1 |
Ruby | Ruby | remove duplicate private statement | fe08c816d07ec5081366630e33c18caa327e4080 | <ide><path>actionview/lib/action_view/renderer/partial_renderer.rb
<ide> def render_partial
<ide> content
<ide> end
<ide>
<del> private
<del>
<ide> # Sets up instance variables needed for rendering a partial. This method
<ide> # finds the options and details and extracts them. The method also contains
<ide> # logic that handles the type of object passed in as the partial. | 1 |
Python | Python | fix np.ma.maskedarray.anom when input is masked | c3faa8e566a8f37334fb347981f608c420687d2d | <ide><path>numpy/ma/core.py
<ide> def anom(self, axis=None, dtype=None):
<ide>
<ide> """
<ide> m = self.mean(axis, dtype)
<del> if m is masked:
<del> return m
<del>
<ide> if not axis:
<ide> return self - m
<ide> else:
<ide><path>numpy/ma/tests/test_core.py
<ide> def test_meananom_object(self):
<ide> assert_equal(a.mean(), 2)
<ide> assert_equal(a.anom(), [-1, 0, 1])
<ide>
<add> def test_anom_shape(self):
<add> a = masked_array([1, 2, 3])
<add> assert_equal(a.anom().shape, a.shape)
<add> a.mask = True
<add> assert_equal(a.anom().shape, a.shape)
<add> assert_(np.ma.is_masked(a.anom()))
<add>
<add> def test_anom(self):
<add> a = masked_array(np.arange(1, 7).reshape(2, 3))
<add> assert_almost_equal(a.anom(),
<add> [[-2.5, -1.5, -0.5], [0.5, 1.5, 2.5]])
<add> assert_almost_equal(a.anom(axis=0),
<add> [[-1.5, -1.5, -1.5], [1.5, 1.5, 1.5]])
<add> assert_almost_equal(a.anom(axis=1),
<add> [[-1., 0., 1.], [-1., 0., 1.]])
<add> a.mask = [[0, 0, 1], [0, 1, 0]]
<add> mval = -99
<add> assert_almost_equal(a.anom().filled(mval),
<add> [[-2.25, -1.25, mval], [0.75, mval, 2.75]])
<add> assert_almost_equal(a.anom(axis=0).filled(mval),
<add> [[-1.5, 0.0, mval], [1.5, mval, 0.0]])
<add> assert_almost_equal(a.anom(axis=1).filled(mval),
<add> [[-0.5, 0.5, mval], [-1.0, mval, 1.0]])
<add>
<ide> def test_trace(self):
<ide> # Tests trace on MaskedArrays.
<ide> (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d | 2 |
Go | Go | add lock around write operations in graph | 957db15ef4cef2f3a6b2933260a7806d69ff68e0 | <ide><path>gograph/gograph.go
<ide> import (
<ide> "database/sql"
<ide> "fmt"
<ide> "path"
<add> "sync"
<ide> )
<ide>
<ide> const (
<ide> type WalkFunc func(fullPath string, entity *Entity) error
<ide> // Graph database for storing entities and their relationships
<ide> type Database struct {
<ide> conn *sql.DB
<add> mux sync.Mutex
<ide> }
<ide>
<ide> // Create a new graph database initialized with a root entity
<ide> func NewDatabase(conn *sql.DB, init bool) (*Database, error) {
<ide> if conn == nil {
<ide> return nil, fmt.Errorf("Database connection cannot be nil")
<ide> }
<del> db := &Database{conn}
<add> db := &Database{conn: conn}
<ide>
<ide> if init {
<ide> if _, err := conn.Exec(createEntityTable); err != nil {
<ide> func (db *Database) Close() error {
<ide>
<ide> // Set the entity id for a given path
<ide> func (db *Database) Set(fullPath, id string) (*Entity, error) {
<del> // FIXME: is rollback implicit when closing the connection?
<add> db.mux.Lock()
<add> defer db.mux.Unlock()
<add>
<ide> rollback := func() {
<ide> db.conn.Exec("ROLLBACK")
<ide> }
<ide> func (db *Database) RefPaths(id string) Edges {
<ide>
<ide> // Delete the reference to an entity at a given path
<ide> func (db *Database) Delete(name string) error {
<add> db.mux.Lock()
<add> defer db.mux.Unlock()
<add>
<ide> if name == "/" {
<ide> return fmt.Errorf("Cannot delete root entity")
<ide> }
<ide> func (db *Database) Delete(name string) error {
<ide> // Walk the graph to make sure all references to the entity
<ide> // are removed and return the number of references removed
<ide> func (db *Database) Purge(id string) (int, error) {
<add> db.mux.Lock()
<add> defer db.mux.Unlock()
<add>
<ide> rollback := func() {
<ide> db.conn.Exec("ROLLBACK")
<ide> }
<ide> func (db *Database) Purge(id string) (int, error) {
<ide>
<ide> // Rename an edge for a given path
<ide> func (db *Database) Rename(currentName, newName string) error {
<add> db.mux.Lock()
<add> defer db.mux.Unlock()
<add>
<ide> parentPath, name := splitPath(currentName)
<ide> newParentPath, newEdgeName := splitPath(newName)
<ide>
<ide><path>gograph/gograph_test.go
<ide> package gograph
<ide> import (
<ide> _ "code.google.com/p/gosqlite/sqlite3"
<ide> "database/sql"
<add> "fmt"
<ide> "os"
<ide> "path"
<ide> "strconv"
<ide> func TestGetNameWithTrailingSlash(t *testing.T) {
<ide> t.Fatalf("Entity should not be nil")
<ide> }
<ide> }
<add>
<add>func TestConcurrentWrites(t *testing.T) {
<add> db, dbpath := newTestDb(t)
<add> defer destroyTestDb(dbpath)
<add>
<add> errs := make(chan error, 2)
<add>
<add> save := func(name string, id string) {
<add> if _, err := db.Set(fmt.Sprintf("/%s", name), id); err != nil {
<add> errs <- err
<add> }
<add> errs <- nil
<add> }
<add> purge := func(id string) {
<add> if _, err := db.Purge(id); err != nil {
<add> errs <- err
<add> }
<add> errs <- nil
<add> }
<add>
<add> save("/1", "1")
<add>
<add> go purge("1")
<add> go save("/2", "2")
<add>
<add> any := false
<add> for i := 0; i < 2; i++ {
<add> if err := <-errs; err != nil {
<add> any = true
<add> t.Log(err)
<add> }
<add> }
<add> if any {
<add> t.Fatal()
<add> }
<add>} | 2 |
Javascript | Javascript | fix remaining reactelement references | b77b760810c192a3b13149a467db934090d841c0 | <ide><path>Examples/UIExplorer/js/ExampleTypes.js
<ide> */
<ide> 'use strict';
<ide>
<add>import type React from 'react';
<add>
<ide> export type Example = {
<ide> title: string,
<ide> render: () => ?React.Element<any>,
<ide> description?: string,
<del> platform?: string;
<add> platform?: string,
<ide> };
<ide>
<ide> export type ExampleModule = {
<del> title: string;
<del> description: string;
<del> examples: Array<Example>;
<del> external?: bool;
<add> title: string,
<add> description: string,
<add> examples: Array<Example>,
<add> external?: bool,
<ide> };
<ide><path>Libraries/NavigationExperimental/NavigationTypeDefinition.js
<ide>
<ide> const Animated = require('Animated');
<ide>
<add>import type React from 'react';
<add>
<ide> // Object Instances
<ide>
<ide> export type NavigationAnimatedValue = Animated.Value;
<ide> export type NavigationAnimationSetter = (
<ide>
<ide> export type NavigationSceneRenderer = (
<ide> props: NavigationSceneRendererProps,
<del>) => ?ReactElement<any>;
<add>) => ?React.Element<any>;
<ide>
<ide> export type NavigationStyleInterpolator = (
<ide> props: NavigationSceneRendererProps,
<ide><path>Libraries/ReactNative/UIManager.js
<ide> const defineLazyObjectProperty = require('defineLazyObjectProperty');
<ide> const findNodeHandle = require('react/lib/findNodeHandle');
<ide> const invariant = require('fbjs/lib/invariant');
<ide>
<add>import type React from 'react';
<add>
<ide> const { UIManager } = NativeModules;
<ide>
<ide> invariant(UIManager, 'UIManager is undefined. The native module config is probably incorrect.');
<ide> const _takeSnapshot = UIManager.takeSnapshot;
<ide> * @platform ios
<ide> */
<ide> UIManager.takeSnapshot = async function(
<del> view ?: 'window' | ReactElement<any> | number,
<add> view ?: 'window' | React.Element<any> | number,
<ide> options ?: {
<ide> width ?: number,
<ide> height ?: number, | 3 |
Javascript | Javascript | update example to use a module | d28a0bf49e81037fd73d52449c04d571218fc787 | <ide><path>src/ng/directive/ngInclude.js
<ide> * - Otherwise enable scrolling only if the expression evaluates to truthy value.
<ide> *
<ide> * @example
<del> <example module="ngAnimate" deps="angular-animate.js" animations="true">
<add> <example module="includeExample" deps="angular-animate.js" animations="true">
<ide> <file name="index.html">
<del> <div ng-controller="Ctrl">
<add> <div ng-controller="ExampleController">
<ide> <select ng-model="template" ng-options="t.name for t in templates">
<ide> <option value="">(blank)</option>
<ide> </select>
<ide> </div>
<ide> </file>
<ide> <file name="script.js">
<del> function Ctrl($scope) {
<del> $scope.templates =
<del> [ { name: 'template1.html', url: 'template1.html'},
<del> { name: 'template2.html', url: 'template2.html'} ];
<del> $scope.template = $scope.templates[0];
<del> }
<add> angular.module('includeExample', ['ngAnimate'])
<add> .controller('ExampleController', ['$scope', function($scope) {
<add> $scope.templates =
<add> [ { name: 'template1.html', url: 'template1.html'},
<add> { name: 'template2.html', url: 'template2.html'} ];
<add> $scope.template = $scope.templates[0];
<add> }]);
<ide> </file>
<ide> <file name="template1.html">
<ide> Content of template1.html | 1 |
Ruby | Ruby | add failing test for array values and procs | 06992d50522c5dd2e7fa26bc257cc416b7f47cc8 | <ide><path>activesupport/test/parameter_filter_test.rb
<ide> class ParameterFilterTest < ActiveSupport::TestCase
<ide> value.replace("world!") if original_params["barg"]["blah"] == "bar" && key == "hello"
<ide> }
<ide>
<add>
<add> filter_words << lambda { |key, value|
<add> value.upcase! if key == "array_elements"
<add> }
<add>
<ide> parameter_filter = ActiveSupport::ParameterFilter.new(filter_words)
<ide> before_filter["barg"] = { :bargain => "gain", "blah" => "bar", "bar" => { "bargain" => { "blah" => "foo", "hello" => "world" } } }
<ide> after_filter["barg"] = { :bargain => "niag", "blah" => "[FILTERED]", "bar" => { "bargain" => { "blah" => "[FILTERED]", "hello" => "world!" } } }
<ide>
<add> before_filter["array_elements"] = %w(element1 element2)
<add> after_filter["array_elements"] = %w(ELEMENT1 ELEMENT2)
<add>
<ide> assert_equal after_filter, parameter_filter.filter(before_filter)
<ide> end
<ide> end | 1 |
Javascript | Javascript | add missing "getpolyfills" tag | 98e61de19f0e4d57a3e56a542331bf6f54b1f316 | <ide><path>local-cli/dependencies/dependencies.js
<ide> function dependencies(argv, config, args, packagerInstance) {
<ide> const packageOpts = {
<ide> projectRoots: config.getProjectRoots(),
<ide> blacklistRE: config.getBlacklistRE(),
<add> getPolyfills: config.getPolyfills,
<ide> getTransformOptions: config.getTransformOptions,
<ide> hasteImpl: config.hasteImpl,
<ide> transformModulePath: transformModulePath, | 1 |
Text | Text | simplify ajax options | 5386cd96652570669a47abd5a0d5b46b7c63003e | <ide><path>docs/docs/tutorial.md
<ide> var CommentBox = React.createClass({
<ide> getInitialState: function() {
<ide> $.ajax({
<ide> url: 'comments.json',
<del> dataType: 'json',
<del> mimeType: 'textPlain',
<ide> success: function(data) {
<ide> this.setState({data: data});
<ide> }.bind(this)
<ide> var CommentBox = React.createClass({
<ide> loadCommentsFromServer: function() {
<ide> $.ajax({
<ide> url: this.props.url,
<del> dataType: 'json',
<del> mimeType: 'textPlain',
<ide> success: function(data) {
<ide> this.setState({data: data});
<ide> }.bind(this)
<ide> var CommentBox = React.createClass({
<ide> },
<ide> componentWillMount: function() {
<ide> this.loadCommentsFromServer();
<del> setInterval(
<del> this.loadCommentsFromServer.bind(this),
<del> this.props.pollInterval
<del> );
<add> setInterval(this.loadCommentsFromServer, this.props.pollInterval);
<ide> },
<ide> render: function() {
<ide> return (
<ide> var CommentBox = React.createClass({
<ide> });
<ide>
<ide> React.renderComponent(
<del> <CommentBox url="comments.json" pollInterval={5000} />,
<add> <CommentBox url="comments.json" pollInterval={2000} />,
<ide> document.getElementById('content')
<ide> );
<ide>
<ide> ```
<ide>
<del>All we have done here is move the AJAX call to a separate method and call it when the component is first loaded and every 5 seconds after that. Try running this in your browser and changing the `comments.json` file; within 5 seconds, the changes will show!
<add>All we have done here is move the AJAX call to a separate method and call it when the component is first loaded and every 2 seconds after that. Try running this in your browser and changing the `comments.json` file; within 2 seconds, the changes will show!
<ide>
<ide> ### Adding new comments
<ide>
<ide> var CommentForm = React.createClass({
<ide> <form className="commentForm">
<ide> <input type="text" placeholder="Your name" />
<ide> <input type="text" placeholder="Say something..." />
<del> <input type="submit" />
<add> <input type="submit" value="Post" />
<ide> </form>
<ide> );
<ide> }
<ide> var CommentForm = React.createClass({
<ide> placeholder="Say something..."
<ide> ref="text"
<ide> />
<del> <input type="submit" />
<add> <input type="submit" value="Post" />
<ide> </form>
<ide> );
<ide> }
<ide> var CommentBox = React.createClass({
<ide> loadCommentsFromServer: function() {
<ide> $.ajax({
<ide> url: this.props.url,
<del> dataType: 'json',
<del> mimeType: 'textPlain',
<ide> success: function(data) {
<ide> this.setState({data: data});
<ide> }.bind(this)
<ide> var CommentBox = React.createClass({
<ide> },
<ide> componentWillMount: function() {
<ide> this.loadCommentsFromServer();
<del> setInterval(
<del> this.loadCommentsFromServer.bind(this),
<del> this.props.pollInterval
<del> );
<add> setInterval(this.loadCommentsFromServer, this.props.pollInterval);
<ide> },
<ide> render: function() {
<ide> return (
<ide> var CommentForm = React.createClass({
<ide> placeholder="Say something..."
<ide> ref="text"
<ide> />
<del> <input type="submit" />
<add> <input type="submit" value="Post" />
<ide> </form>
<ide> );
<ide> }
<ide> var CommentBox = React.createClass({
<ide> loadCommentsFromServer: function() {
<ide> $.ajax({
<ide> url: this.props.url,
<del> dataType: 'json',
<del> mimeType: 'textPlain',
<ide> success: function(data) {
<ide> this.setState({data: data});
<ide> }.bind(this)
<ide> var CommentBox = React.createClass({
<ide> handleCommentSubmit: function(comment) {
<ide> $.ajax({
<ide> url: this.props.url,
<add> type: 'POST',
<ide> data: comment,
<del> dataType: 'json',
<del> mimeType: 'textPlain',
<ide> success: function(data) {
<ide> this.setState({data: data});
<ide> }.bind(this)
<ide> var CommentBox = React.createClass({
<ide> },
<ide> componentWillMount: function() {
<ide> this.loadCommentsFromServer();
<del> setInterval(
<del> this.loadCommentsFromServer.bind(this),
<del> this.props.pollInterval
<del> );
<add> setInterval(this.loadCommentsFromServer, this.props.pollInterval);
<ide> },
<ide> render: function() {
<ide> return (
<ide> var CommentBox = React.createClass({
<ide> loadCommentsFromServer: function() {
<ide> $.ajax({
<ide> url: this.props.url,
<del> dataType: 'json',
<del> mimeType: 'textPlain',
<ide> success: function(data) {
<ide> this.setState({data: data});
<ide> }.bind(this)
<ide> var CommentBox = React.createClass({
<ide> this.setState({data: comments});
<ide> $.ajax({
<ide> url: this.props.url,
<add> type: 'POST',
<ide> data: comment,
<del> dataType: 'json',
<del> mimeType: 'textPlain',
<ide> success: function(data) {
<ide> this.setState({data: data});
<ide> }.bind(this)
<ide> var CommentBox = React.createClass({
<ide> },
<ide> componentWillMount: function() {
<ide> this.loadCommentsFromServer();
<del> setInterval(
<del> this.loadCommentsFromServer.bind(this),
<del> this.props.pollInterval
<del> );
<add> setInterval(this.loadCommentsFromServer, this.props.pollInterval);
<ide> },
<ide> render: function() {
<ide> return ( | 1 |
Ruby | Ruby | use version 20 to support python 3.9 | 43648100b4164944783cdc21c4dca74d8c4c2263 | <ide><path>Library/Homebrew/language/python.rb
<ide> module Virtualenv
<ide> def self.included(base)
<ide> base.class_eval do
<ide> resource "homebrew-virtualenv" do
<del> url "https://files.pythonhosted.org/packages/11/74" \
<del> "/2c151a13ef41ab9fb43b3c4ff9e788e0496ed7923b2078d42cab30622bdf/virtualenv-16.7.4.tar.gz"
<del> sha256 "94a6898293d07f84a98add34c4df900f8ec64a570292279f6d91c781d37fd305"
<add> url "https://files.pythonhosted.org/packages/85/3e/6c3abf78b2207f3565ebadd0b99d1945f4ff18abdc6879617a4f6d939e41/virtualenv-20.0.33.tar.gz"
<add> sha256 "a5e0d253fe138097c6559c906c528647254f437d1019af9d5a477b09bfa7300f"
<add> end
<add>
<add> resource "homebrew-appdirs" do
<add> url "https://files.pythonhosted.org/packages/d7/d8/05696357e0311f5b5c316d7b95f46c669dd9c15aaeecbb48c7d0aeb88c40/appdirs-1.4.4.tar.gz"
<add> sha256 "7d5d0167b2b1ba821647616af46a749d1c653740dd0d2415100fe26e27afdf41"
<add> end
<add>
<add> resource "homebrew-distlib" do
<add> url "https://files.pythonhosted.org/packages/2f/83/1eba07997b8ba58d92b3e51445d5bf36f9fba9cb8166bcae99b9c3464841/distlib-0.3.1.zip"
<add> sha256 "edf6116872c863e1aa9d5bb7cb5e05a022c519a4594dc703843343a9ddd9bff1"
<add> end
<add>
<add> resource "homebrew-filelock" do
<add> url "https://files.pythonhosted.org/packages/14/ec/6ee2168387ce0154632f856d5cc5592328e9cf93127c5c9aeca92c8c16cb/filelock-3.0.12.tar.gz"
<add> sha256 "18d82244ee114f543149c66a6e0c14e9c4f8a1044b5cdaadd0f82159d6a6ff59"
<add> end
<add>
<add> resource "homebrew-six" do
<add> url "https://files.pythonhosted.org/packages/6b/34/415834bfdafca3c5f451532e8a8d9ba89a21c9743a0c59fbd0205c7f9426/six-1.15.0.tar.gz"
<add> sha256 "30639c035cdb23534cd4aa2dd52c3bf48f06e5f4a941509c8bafd8ce11080259"
<ide> end
<ide> end
<ide> end
<ide> def create
<ide> old_pythonpath = ENV.delete "PYTHONPATH"
<ide> begin
<ide> staging = Pathname.new(stage.staging.tmpdir)
<add>
<add> ENV.prepend_create_path "PYTHONPATH", staging/"target/vendor"/Language::Python.site_packages(@python)
<add> %w[appdirs distlib filelock six].each do |virtualenv_dependency|
<add> @formula.resource("homebrew-#{virtualenv_dependency}").stage do
<add> @formula.system @python, *Language::Python.setup_install_args(staging/"target/vendor")
<add> end
<add> end
<add>
<ide> ENV.prepend_create_path "PYTHONPATH", staging/"target"/Language::Python.site_packages(@python)
<ide> @formula.system @python, *Language::Python.setup_install_args(staging/"target")
<ide> @formula.system @python, "-s", staging/"target/bin/virtualenv", "-p", @python, @venv_root | 1 |
Javascript | Javascript | inject the update queue into classes | 1224a203bb9fa6dbbc41dd6bd907f599b5d5f93b | <ide><path>src/isomorphic/classic/class/ReactClass.js
<ide> var ReactElement = require('ReactElement');
<ide> var ReactErrorUtils = require('ReactErrorUtils');
<ide> var ReactPropTypeLocations = require('ReactPropTypeLocations');
<ide> var ReactPropTypeLocationNames = require('ReactPropTypeLocationNames');
<del>var ReactUpdateQueue = require('ReactUpdateQueue');
<add>var ReactNoopUpdateQueue = require('ReactNoopUpdateQueue');
<ide>
<ide> var assign = require('Object.assign');
<add>var emptyObject = require('emptyObject');
<ide> var invariant = require('invariant');
<ide> var keyMirror = require('keyMirror');
<ide> var keyOf = require('keyOf');
<ide> var ReactClassMixin = {
<ide> * type signature and the only use case for this, is to avoid that.
<ide> */
<ide> replaceState: function(newState, callback) {
<del> ReactUpdateQueue.enqueueReplaceState(this, newState);
<add> this.updater.enqueueReplaceState(this, newState);
<ide> if (callback) {
<del> ReactUpdateQueue.enqueueCallback(this, callback);
<add> this.updater.enqueueCallback(this, callback);
<ide> }
<ide> },
<ide>
<ide> var ReactClassMixin = {
<ide> * @final
<ide> */
<ide> isMounted: function() {
<del> return ReactUpdateQueue.isMounted(this);
<add> return this.updater.isMounted(this);
<ide> },
<ide>
<ide> /**
<ide> var ReactClassMixin = {
<ide> * @deprecated
<ide> */
<ide> setProps: function(partialProps, callback) {
<del> ReactUpdateQueue.enqueueSetProps(this, partialProps);
<add> this.updater.enqueueSetProps(this, partialProps);
<ide> if (callback) {
<del> ReactUpdateQueue.enqueueCallback(this, callback);
<add> this.updater.enqueueCallback(this, callback);
<ide> }
<ide> },
<ide>
<ide> var ReactClassMixin = {
<ide> * @deprecated
<ide> */
<ide> replaceProps: function(newProps, callback) {
<del> ReactUpdateQueue.enqueueReplaceProps(this, newProps);
<add> this.updater.enqueueReplaceProps(this, newProps);
<ide> if (callback) {
<del> ReactUpdateQueue.enqueueCallback(this, callback);
<add> this.updater.enqueueCallback(this, callback);
<ide> }
<ide> },
<ide> };
<ide> var ReactClass = {
<ide> * @public
<ide> */
<ide> createClass: function(spec) {
<del> var Constructor = function(props, context) {
<add> var Constructor = function(props, context, updater) {
<ide> // This constructor is overridden by mocks. The argument is used
<ide> // by mocks to assert on what gets mounted.
<ide>
<ide> var ReactClass = {
<ide>
<ide> this.props = props;
<ide> this.context = context;
<add> this.refs = emptyObject;
<add> this.updater = updater || ReactNoopUpdateQueue;
<add>
<ide> this.state = null;
<ide>
<ide> // ReactClasses doesn't have constructors. Instead, they use the
<ide><path>src/isomorphic/modern/class/ReactComponent.js
<ide>
<ide> 'use strict';
<ide>
<del>var ReactUpdateQueue = require('ReactUpdateQueue');
<add>var ReactNoopUpdateQueue = require('ReactNoopUpdateQueue');
<ide>
<add>var emptyObject = require('emptyObject');
<ide> var invariant = require('invariant');
<ide> var warning = require('warning');
<ide>
<ide> /**
<ide> * Base class helpers for the updating state of a component.
<ide> */
<del>function ReactComponent(props, context) {
<add>function ReactComponent(props, context, updater) {
<ide> this.props = props;
<ide> this.context = context;
<add> this.refs = emptyObject;
<add> // We initialize the default updater but the real one gets injected by the
<add> // renderer.
<add> this.updater = updater || ReactNoopUpdateQueue;
<ide> }
<ide>
<ide> /**
<ide> ReactComponent.prototype.setState = function(partialState, callback) {
<ide> 'instead, use forceUpdate().'
<ide> );
<ide> }
<del> ReactUpdateQueue.enqueueSetState(this, partialState);
<add> this.updater.enqueueSetState(this, partialState);
<ide> if (callback) {
<del> ReactUpdateQueue.enqueueCallback(this, callback);
<add> this.updater.enqueueCallback(this, callback);
<ide> }
<ide> };
<ide>
<ide> ReactComponent.prototype.setState = function(partialState, callback) {
<ide> * @protected
<ide> */
<ide> ReactComponent.prototype.forceUpdate = function(callback) {
<del> ReactUpdateQueue.enqueueForceUpdate(this);
<add> this.updater.enqueueForceUpdate(this);
<ide> if (callback) {
<del> ReactUpdateQueue.enqueueCallback(this, callback);
<add> this.updater.enqueueCallback(this, callback);
<ide> }
<ide> };
<ide>
<ide><path>src/isomorphic/modern/class/ReactNoopUpdateQueue.js
<add>/**
<add> * Copyright 2015, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule ReactNoopUpdateQueue
<add> */
<add>
<add>'use strict';
<add>
<add>var warning = require('warning');
<add>
<add>function warnTDZ(publicInstance, callerName) {
<add> if (__DEV__) {
<add> warning(
<add> false,
<add> '%s(...): Can only update a mounted or mounting component. ' +
<add> 'This usually means you called %s() on an unmounted component. ' +
<add> 'This is a no-op. Please check the code for the %s component.',
<add> callerName,
<add> callerName,
<add> publicInstance.constructor && publicInstance.constructor.displayName || ''
<add> );
<add> }
<add>}
<add>
<add>/**
<add> * This is the abstract API for an update queue.
<add> */
<add>var ReactNoopUpdateQueue = {
<add>
<add> /**
<add> * Checks whether or not this composite component is mounted.
<add> * @param {ReactClass} publicInstance The instance we want to test.
<add> * @return {boolean} True if mounted, false otherwise.
<add> * @protected
<add> * @final
<add> */
<add> isMounted: function(publicInstance) {
<add> return false;
<add> },
<add>
<add> /**
<add> * Enqueue a callback that will be executed after all the pending updates
<add> * have processed.
<add> *
<add> * @param {ReactClass} publicInstance The instance to use as `this` context.
<add> * @param {?function} callback Called after state is updated.
<add> * @internal
<add> */
<add> enqueueCallback: function(publicInstance, callback) { },
<add>
<add> /**
<add> * Forces an update. This should only be invoked when it is known with
<add> * certainty that we are **not** in a DOM transaction.
<add> *
<add> * You may want to call this when you know that some deeper aspect of the
<add> * component's state has changed but `setState` was not called.
<add> *
<add> * This will not invoke `shouldComponentUpdate`, but it will invoke
<add> * `componentWillUpdate` and `componentDidUpdate`.
<add> *
<add> * @param {ReactClass} publicInstance The instance that should rerender.
<add> * @internal
<add> */
<add> enqueueForceUpdate: function(publicInstance) {
<add> warnTDZ(publicInstance, 'forceUpdate');
<add> },
<add>
<add> /**
<add> * Replaces all of the state. Always use this or `setState` to mutate state.
<add> * You should treat `this.state` as immutable.
<add> *
<add> * There is no guarantee that `this.state` will be immediately updated, so
<add> * accessing `this.state` after calling this method may return the old value.
<add> *
<add> * @param {ReactClass} publicInstance The instance that should rerender.
<add> * @param {object} completeState Next state.
<add> * @internal
<add> */
<add> enqueueReplaceState: function(publicInstance, completeState) {
<add> warnTDZ(publicInstance, 'replaceState');
<add> },
<add>
<add> /**
<add> * Sets a subset of the state. This only exists because _pendingState is
<add> * internal. This provides a merging strategy that is not available to deep
<add> * properties which is confusing. TODO: Expose pendingState or don't use it
<add> * during the merge.
<add> *
<add> * @param {ReactClass} publicInstance The instance that should rerender.
<add> * @param {object} partialState Next partial state to be merged with state.
<add> * @internal
<add> */
<add> enqueueSetState: function(publicInstance, partialState) {
<add> warnTDZ(publicInstance, 'setState');
<add> },
<add>
<add> /**
<add> * Sets a subset of the props.
<add> *
<add> * @param {ReactClass} publicInstance The instance that should rerender.
<add> * @param {object} partialProps Subset of the next props.
<add> * @internal
<add> */
<add> enqueueSetProps: function(publicInstance, partialProps) {
<add> warnTDZ(publicInstance, 'setProps');
<add> },
<add>
<add> /**
<add> * Replaces all of the props.
<add> *
<add> * @param {ReactClass} publicInstance The instance that should rerender.
<add> * @param {object} props New props.
<add> * @internal
<add> */
<add> enqueueReplaceProps: function(publicInstance, props) {
<add> warnTDZ(publicInstance, 'replaceProps');
<add> },
<add>
<add>};
<add>
<add>module.exports = ReactNoopUpdateQueue;
<ide><path>src/renderers/shared/reconciler/ReactCompositeComponent.js
<ide> var ReactPerf = require('ReactPerf');
<ide> var ReactPropTypeLocations = require('ReactPropTypeLocations');
<ide> var ReactPropTypeLocationNames = require('ReactPropTypeLocationNames');
<ide> var ReactReconciler = require('ReactReconciler');
<add>var ReactUpdateQueue = require('ReactUpdateQueue');
<ide>
<ide> var assign = require('Object.assign');
<ide> var emptyObject = require('emptyObject');
<ide> var ReactCompositeComponentMixin = {
<ide> );
<ide>
<ide> // Initialize the public class
<del> var inst = new Component(publicProps, publicContext);
<add> var inst = new Component(publicProps, publicContext, ReactUpdateQueue);
<ide>
<ide> if (__DEV__) {
<ide> // This will throw later in _renderValidatedComponent, but add an early
<ide> var ReactCompositeComponentMixin = {
<ide> inst.props = publicProps;
<ide> inst.context = publicContext;
<ide> inst.refs = emptyObject;
<add> inst.updater = ReactUpdateQueue;
<ide>
<ide> this._instance = inst;
<ide> | 4 |
Python | Python | fix mypy annotations for arithmetic_analysis | 533eea5afa916fbe1d0db6db8da76c68b2928ca0 | <ide><path>arithmetic_analysis/gaussian_elimination.py
<ide>
<ide>
<ide> import numpy as np
<add>from numpy import float64
<add>from numpy.typing import NDArray
<ide>
<ide>
<del>def retroactive_resolution(coefficients: np.matrix, vector: np.ndarray) -> np.ndarray:
<add>def retroactive_resolution(
<add> coefficients: NDArray[float64], vector: NDArray[float64]
<add>) -> NDArray[float64]:
<ide> """
<ide> This function performs a retroactive linear system resolution
<ide> for triangular matrix
<ide> def retroactive_resolution(coefficients: np.matrix, vector: np.ndarray) -> np.nd
<ide>
<ide> rows, columns = np.shape(coefficients)
<ide>
<del> x = np.zeros((rows, 1), dtype=float)
<add> x: NDArray[float64] = np.zeros((rows, 1), dtype=float)
<ide> for row in reversed(range(rows)):
<ide> sum = 0
<ide> for col in range(row + 1, columns):
<ide> def retroactive_resolution(coefficients: np.matrix, vector: np.ndarray) -> np.nd
<ide> return x
<ide>
<ide>
<del>def gaussian_elimination(coefficients: np.matrix, vector: np.ndarray) -> np.ndarray:
<add>def gaussian_elimination(
<add> coefficients: NDArray[float64], vector: NDArray[float64]
<add>) -> NDArray[float64]:
<ide> """
<ide> This function performs Gaussian elimination method
<ide>
<ide> def gaussian_elimination(coefficients: np.matrix, vector: np.ndarray) -> np.ndar
<ide> return np.array((), dtype=float)
<ide>
<ide> # augmented matrix
<del> augmented_mat = np.concatenate((coefficients, vector), axis=1)
<add> augmented_mat: NDArray[float64] = np.concatenate((coefficients, vector), axis=1)
<ide> augmented_mat = augmented_mat.astype("float64")
<ide>
<ide> # scale the matrix leaving it triangular
<ide><path>arithmetic_analysis/in_static_equilibrium.py
<ide> """
<ide> from __future__ import annotations
<ide>
<del>from numpy import array, cos, cross, ndarray, radians, sin
<add>from numpy import array, cos, cross, float64, radians, sin
<add>from numpy.typing import NDArray
<ide>
<ide>
<ide> def polar_force(
<ide> def polar_force(
<ide>
<ide>
<ide> def in_static_equilibrium(
<del> forces: ndarray, location: ndarray, eps: float = 10**-1
<add> forces: NDArray[float64], location: NDArray[float64], eps: float = 10**-1
<ide> ) -> bool:
<ide> """
<ide> Check if a system is in equilibrium.
<ide> def in_static_equilibrium(
<ide> False
<ide> """
<ide> # summation of moments is zero
<del> moments: ndarray = cross(location, forces)
<add> moments: NDArray[float64] = cross(location, forces)
<ide> sum_moments: float = sum(moments)
<ide> return abs(sum_moments) < eps
<ide>
<ide> def in_static_equilibrium(
<ide> ]
<ide> )
<ide>
<del> location = array([[0, 0], [0, 0], [0, 0]])
<add> location: NDArray[float64] = array([[0, 0], [0, 0], [0, 0]])
<ide>
<ide> assert in_static_equilibrium(forces, location)
<ide>
<ide><path>arithmetic_analysis/jacobi_iteration_method.py
<ide> from __future__ import annotations
<ide>
<ide> import numpy as np
<add>from numpy import float64
<add>from numpy.typing import NDArray
<ide>
<ide>
<ide> # Method to find solution of system of linear equations
<ide> def jacobi_iteration_method(
<del> coefficient_matrix: np.ndarray,
<del> constant_matrix: np.ndarray,
<del> init_val: list,
<add> coefficient_matrix: NDArray[float64],
<add> constant_matrix: NDArray[float64],
<add> init_val: list[int],
<ide> iterations: int,
<ide> ) -> list[float]:
<ide> """
<ide> def jacobi_iteration_method(
<ide> if iterations <= 0:
<ide> raise ValueError("Iterations must be at least 1")
<ide>
<del> table = np.concatenate((coefficient_matrix, constant_matrix), axis=1)
<add> table: NDArray[float64] = np.concatenate(
<add> (coefficient_matrix, constant_matrix), axis=1
<add> )
<ide>
<ide> rows, cols = table.shape
<ide>
<ide> def jacobi_iteration_method(
<ide>
<ide>
<ide> # Checks if the given matrix is strictly diagonally dominant
<del>def strictly_diagonally_dominant(table: np.ndarray) -> bool:
<add>def strictly_diagonally_dominant(table: NDArray[float64]) -> bool:
<ide> """
<ide> >>> table = np.array([[4, 1, 1, 2], [1, 5, 2, -6], [1, 2, 4, -4]])
<ide> >>> strictly_diagonally_dominant(table)
<ide><path>arithmetic_analysis/lu_decomposition.py
<ide> from __future__ import annotations
<ide>
<ide> import numpy as np
<add>import numpy.typing as NDArray
<add>from numpy import float64
<ide>
<ide>
<del>def lower_upper_decomposition(table: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
<add>def lower_upper_decomposition(
<add> table: NDArray[float64],
<add>) -> tuple[NDArray[float64], NDArray[float64]]:
<ide> """Lower-Upper (LU) Decomposition
<ide>
<ide> Example: | 4 |
Ruby | Ruby | improve ordering of multiple columns on postgresql | 9734a416faaa8149fa5914b0afe2e6761ad5ec20 | <ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> def distinct(columns, orders) #:nodoc:
<ide>
<ide> # Construct a clean list of column names from the ORDER BY clause, removing
<ide> # any ASC/DESC modifiers
<del> order_columns = orders.collect { |s| s =~ /^(.+)\s+(ASC|DESC)\s*$/i ? $1 : s }
<add> order_columns = orders.collect { |s| s.gsub(/\s+(ASC|DESC)\s*/i, '') }
<ide> order_columns.delete_if { |c| c.blank? }
<ide> order_columns = order_columns.zip((0...order_columns.size).to_a).map { |s,i| "#{s} AS alias_#{i}" }
<ide>
<ide><path>activerecord/test/cases/relations_test.rb
<ide> def test_finding_with_order_and_take
<ide> assert_equal entrants(:first).name, entrants.first.name
<ide> end
<ide>
<add> def test_finding_with_cross_table_order_and_limit
<add> tags = Tag.includes(:taggings) \
<add> .order("tags.name asc, taggings.taggable_id asc, REPLACE('abc', taggings.taggable_type, taggings.taggable_type)") \
<add> .limit(1).to_a
<add> assert_equal 1, tags.length
<add> end
<add>
<ide> def test_finding_with_complex_order_and_limit
<ide> tags = Tag.includes(:taggings).order("REPLACE('abc', taggings.taggable_type, taggings.taggable_type)").limit(1).to_a
<ide> assert_equal 1, tags.length | 2 |
Javascript | Javascript | add wrapper css builder to subs caps button | e5af0a5e21575323fe93ce849caf09a7c5e1a38b | <ide><path>src/js/control-bar/text-track-controls/subs-caps-button.js
<ide> class SubsCapsButton extends TextTrackButton {
<ide> return `vjs-subs-caps-button ${super.buildCSSClass()}`;
<ide> }
<ide>
<add> buildWrapperCSSClass() {
<add> return `vjs-subs-caps-button ${super.buildWrapperCSSClass()}`;
<add> }
<add>
<ide> /**
<ide> * Update caption menu items
<ide> * | 1 |
Python | Python | consider regression model in predict mode | 83f355bb45f037ea39f5c92cb6446317193b5a75 | <ide><path>official/nlp/bert/run_classifier.py
<ide> def custom_main(custom_callbacks=None, custom_metrics=None):
<ide> if FLAGS.mode == 'predict':
<ide> with strategy.scope():
<ide> classifier_model = bert_models.classifier_model(
<del> bert_config, input_meta_data['num_labels'])[0]
<add> bert_config, input_meta_data.get('num_labels', 1))[0]
<ide> checkpoint = tf.train.Checkpoint(model=classifier_model)
<ide> latest_checkpoint_file = (
<ide> FLAGS.predict_checkpoint_path or | 1 |
PHP | PHP | remove interactive mode from templatetask | a0670aa7ad19c95f10a6f9f1858b843e7834f675 | <ide><path>src/Console/Command/Task/TemplateTask.php
<ide> /**
<ide> * Template Task can generate templated output Used in other Tasks.
<ide> * Acts like a simplified View class.
<del> *
<ide> */
<ide> class TemplateTask extends Shell {
<ide>
<ide> protected function _findThemes() {
<ide> }
<ide>
<ide> $core = current(App::core('Console'));
<del> $separator = DS === '/' ? '/' : '\\\\';
<del> $core = preg_replace('#shells' . $separator . '$#', '', $core);
<del>
<ide> $Folder = new Folder($core . 'Templates/default');
<ide>
<ide> $contents = $Folder->read();
<ide> protected function _findThemes() {
<ide> $paths[$i] = rtrim($path, DS) . DS;
<ide> }
<ide>
<add> $this->_io->verbose('Found the following bake themes:');
<add>
<ide> $themes = [];
<ide> foreach ($paths as $path) {
<ide> $Folder = new Folder($path . 'Templates', false);
<ide> $contents = $Folder->read();
<ide> $subDirs = $contents[0];
<ide> foreach ($subDirs as $dir) {
<del> if (empty($dir) || preg_match('@^skel$|_skel$@', $dir)) {
<del> continue;
<del> }
<ide> $Folder = new Folder($path . 'Templates/' . $dir);
<ide> $contents = $Folder->read();
<ide> $subDirs = $contents[0];
<ide> if (array_intersect($contents[0], $themeFolders)) {
<ide> $templateDir = $path . 'Templates/' . $dir . DS;
<ide> $themes[$dir] = $templateDir;
<add>
<add> $this->_io->verbose(sprintf("- %s -> %s", $dir, $templateDir));
<ide> }
<ide> }
<ide> }
<ide> public function generate($directory, $filename, $vars = null) {
<ide> * If there is more than one installed theme user interaction will happen
<ide> *
<ide> * @return string returns the path to the selected theme.
<add> * @throws \RuntimeException When the chosen theme cannot be found.
<ide> */
<ide> public function getThemePath() {
<del> if (count($this->templatePaths) === 1) {
<del> $paths = array_values($this->templatePaths);
<del> return $paths[0];
<del> }
<del> if (!empty($this->params['theme']) && isset($this->templatePaths[$this->params['theme']])) {
<del> return $this->templatePaths[$this->params['theme']];
<add> if (empty($this->params['theme'])) {
<add> $this->params['theme'] = 'default';
<ide> }
<del>
<del> $this->hr();
<del> $this->out(__d('cake_console', 'You have more than one set of templates installed.'));
<del> $this->out(__d('cake_console', 'Please choose the template set you wish to use:'));
<del> $this->hr();
<del>
<del> $i = 1;
<del> $indexedPaths = [];
<del> foreach ($this->templatePaths as $key => $path) {
<del> $this->out($i . '. ' . $key);
<del> $indexedPaths[$i] = $path;
<del> $i++;
<add> if (!isset($this->templatePaths[$this->params['theme']])) {
<add> throw new \RuntimeException('Unable to locate templates to bake with.');
<ide> }
<del> $index = $this->in(__d('cake_console', 'Which bake theme would you like to use?'), range(1, $i - 1), 1);
<del> $themeNames = array_keys($this->templatePaths);
<del> $this->params['theme'] = $themeNames[$index - 1];
<del> return $indexedPaths[$index];
<add> $this->_io->verbose(sprintf('Using "%s" bake theme', $this->params['theme']));
<add> return $this->templatePaths[$this->params['theme']];
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Console/Command/Task/TemplateTaskTest.php
<ide> public function testFindingInstalledThemesForBake() {
<ide> */
<ide> public function testGetThemePath() {
<ide> $defaultTheme = CAKE . 'Console/Templates/default/';
<del> $this->Task->templatePaths = array('default' => $defaultTheme);
<del>
<del> $this->Task->expects($this->exactly(1))->method('in')->will($this->returnValue('1'));
<add> $this->Task->templatePaths = ['default' => $defaultTheme];
<ide>
<ide> $result = $this->Task->getThemePath();
<ide> $this->assertEquals($defaultTheme, $result);
<ide>
<del> $this->Task->templatePaths = array('other' => '/some/path', 'default' => $defaultTheme);
<add> $this->Task->templatePaths = ['other' => '/some/path', 'default' => $defaultTheme];
<ide> $this->Task->params['theme'] = 'other';
<ide> $result = $this->Task->getThemePath();
<ide> $this->assertEquals('/some/path', $result);
<ide>
<ide> $this->Task->params = array();
<ide> $result = $this->Task->getThemePath();
<del> $this->assertEquals('/some/path', $result);
<del> $this->assertEquals('other', $this->Task->params['theme']);
<add> $this->assertEquals($defaultTheme, $result);
<add> $this->assertEquals('default', $this->Task->params['theme']);
<ide> }
<ide>
<ide> /** | 2 |
Python | Python | add missing test comment and fix the typo | aaf5f696de13dea81a032bcda1ac879815cb2ac9 | <ide><path>numpy/core/tests/test_simd.py
<ide> class _SIMD_FP32(_Test_Utility):
<ide> def test_conversions(self):
<ide> """
<ide> Round to nearest even integer, assume CPU control register is set to rounding.
<del> Test intrinics:
<add> Test intrinsics:
<ide> npyv_round_s32_##SFX
<ide> """
<ide> features = self._cpu_features()
<ide> class _SIMD_FP64(_Test_Utility):
<ide> def test_conversions(self):
<ide> """
<ide> Round to nearest even integer, assume CPU control register is set to rounding.
<del> Test intrinics:
<add> Test intrinsics:
<ide> npyv_round_s32_##SFX
<ide> """
<ide> vdata_a = self.load(self._data())
<ide> def test_square(self):
<ide> assert square == data_square
<ide>
<ide> def test_max(self):
<add> """
<add> Test intrinsics:
<add> npyv_max_##SFX
<add> npyv_maxp_##SFX
<add> """
<ide> data_a = self._data()
<ide> data_b = self._data(self.nlanes)
<ide> vdata_a, vdata_b = self.load(data_a), self.load(data_b)
<ide> def test_max(self):
<ide> assert _max == data_max
<ide>
<ide> def test_min(self):
<add> """
<add> Test intrinsics:
<add> npyv_min_##SFX
<add> npyv_minp_##SFX
<add> """
<ide> data_a = self._data()
<ide> data_b = self._data(self.nlanes)
<ide> vdata_a, vdata_b = self.load(data_a), self.load(data_b)
<ide> def test_reciprocal(self):
<ide>
<ide> def test_special_cases(self):
<ide> """
<del> Compare Not NaN. Test intrinics:
<add> Compare Not NaN. Test intrinsics:
<ide> npyv_notnan_##SFX
<ide> """
<ide> nnan = self.notnan(self.setall(self._nan()))
<ide> def test_conversion_boolean(self):
<ide>
<ide> def test_conversion_expand(self):
<ide> """
<del> Test expand intrinics:
<add> Test expand intrinsics:
<ide> npyv_expand_u16_u8
<ide> npyv_expand_u32_u16
<ide> """
<ide> def test_arithmetic_div(self):
<ide>
<ide> def test_arithmetic_intdiv(self):
<ide> """
<del> Test integer division intrinics:
<add> Test integer division intrinsics:
<ide> npyv_divisor_##sfx
<ide> npyv_divc_##sfx
<ide> """
<ide> def trunc_div(a, d):
<ide>
<ide> def test_arithmetic_reduce_sum(self):
<ide> """
<del> Test reduce sum intrinics:
<add> Test reduce sum intrinsics:
<ide> npyv_sum_##sfx
<ide> """
<ide> if self.sfx not in ("u32", "u64", "f32", "f64"):
<ide> def test_arithmetic_reduce_sum(self):
<ide>
<ide> def test_arithmetic_reduce_sumup(self):
<ide> """
<del> Test extend reduce sum intrinics:
<add> Test extend reduce sum intrinsics:
<ide> npyv_sumup_##sfx
<ide> """
<ide> if self.sfx not in ("u8", "u16"):
<ide> def test_arithmetic_reduce_sumup(self):
<ide> def test_mask_conditional(self):
<ide> """
<ide> Conditional addition and subtraction for all supported data types.
<del> Test intrinics:
<add> Test intrinsics:
<ide> npyv_ifadd_##SFX, npyv_ifsub_##SFX
<ide> """
<ide> vdata_a = self.load(self._data()) | 1 |
Java | Java | add setoutputstreaming option for http factory | 92ad66bf10b570dde25af44d8ff3f958dfec2a9d | <ide><path>spring-web/src/main/java/org/springframework/http/client/SimpleBufferingClientHttpRequest.java
<ide> /*
<del> * Copyright 2002-2011 the original author or authors.
<add> * Copyright 2002-2013 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> final class SimpleBufferingClientHttpRequest extends AbstractBufferingClientHttp
<ide>
<ide> private final HttpURLConnection connection;
<ide>
<add> private final boolean outputStreaming;
<ide>
<del> SimpleBufferingClientHttpRequest(HttpURLConnection connection) {
<add>
<add> SimpleBufferingClientHttpRequest(HttpURLConnection connection, boolean outputStreaming) {
<ide> this.connection = connection;
<add> this.outputStreaming = outputStreaming;
<ide> }
<ide>
<ide>
<ide> protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] buffere
<ide> }
<ide> }
<ide>
<del> if (this.connection.getDoOutput()) {
<add> if (this.connection.getDoOutput() && this.outputStreaming) {
<ide> this.connection.setFixedLengthStreamingMode(bufferedOutput.length);
<ide> }
<ide> this.connection.connect();
<ide><path>spring-web/src/main/java/org/springframework/http/client/SimpleClientHttpRequestFactory.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2013 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public class SimpleClientHttpRequestFactory implements ClientHttpRequestFactory
<ide>
<ide> private int readTimeout = -1;
<ide>
<add> private boolean outputStreaming = true;
<add>
<ide>
<ide> /**
<ide> * Set the {@link Proxy} to use for this request factory.
<ide> public void setReadTimeout(int readTimeout) {
<ide> this.readTimeout = readTimeout;
<ide> }
<ide>
<add> /**
<add> * Set if the underlying URLConnection can be set to 'output streaming' mode. When
<add> * output streaming is enabled, authentication and redirection cannot be handled
<add> * automatically. If output streaming is disabled the
<add> * {@link HttpURLConnection#setFixedLengthStreamingMode(int)
<add> * setFixedLengthStreamingMode} and
<add> * {@link HttpURLConnection#setChunkedStreamingMode(int) setChunkedStreamingMode}
<add> * methods of the underlying connection will never be called.
<add> * <p>Default is {@code true}.
<add> * @param outputStreaming if output streaming is enabled
<add> */
<add> public void setOutputStreaming(boolean outputStreaming) {
<add> this.outputStreaming = outputStreaming;
<add> }
<add>
<ide>
<ide> public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
<ide> HttpURLConnection connection = openConnection(uri.toURL(), this.proxy);
<ide> prepareConnection(connection, httpMethod.name());
<ide> if (this.bufferRequestBody) {
<del> return new SimpleBufferingClientHttpRequest(connection);
<add> return new SimpleBufferingClientHttpRequest(connection, this.outputStreaming);
<ide> }
<ide> else {
<del> return new SimpleStreamingClientHttpRequest(connection, this.chunkSize);
<add> return new SimpleStreamingClientHttpRequest(connection, this.chunkSize,
<add> this.outputStreaming);
<ide> }
<ide> }
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/client/SimpleStreamingClientHttpRequest.java
<ide> final class SimpleStreamingClientHttpRequest extends AbstractClientHttpRequest {
<ide>
<ide> private OutputStream body;
<ide>
<add> private final boolean outputStreaming;
<ide>
<del> SimpleStreamingClientHttpRequest(HttpURLConnection connection, int chunkSize) {
<add>
<add> SimpleStreamingClientHttpRequest(HttpURLConnection connection, int chunkSize,
<add> boolean outputStreaming) {
<ide> this.connection = connection;
<ide> this.chunkSize = chunkSize;
<add> this.outputStreaming = outputStreaming;
<ide> }
<ide>
<ide> public HttpMethod getMethod() {
<ide> public URI getURI() {
<ide> @Override
<ide> protected OutputStream getBodyInternal(HttpHeaders headers) throws IOException {
<ide> if (this.body == null) {
<del> int contentLength = (int) headers.getContentLength();
<del> if (contentLength >= 0) {
<del> this.connection.setFixedLengthStreamingMode(contentLength);
<del> }
<del> else {
<del> this.connection.setChunkedStreamingMode(this.chunkSize);
<add> if(this.outputStreaming) {
<add> int contentLength = (int) headers.getContentLength();
<add> if (contentLength >= 0) {
<add> this.connection.setFixedLengthStreamingMode(contentLength);
<add> }
<add> else {
<add> this.connection.setChunkedStreamingMode(this.chunkSize);
<add> }
<ide> }
<ide> writeHeaders(headers);
<ide> this.connection.connect();
<ide><path>spring-web/src/test/java/org/springframework/http/client/NoOutputStreamingBufferedSimpleHttpRequestFactoryTests.java
<add>/*
<add> * Copyright 2002-2013 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.http.client;
<add>
<add>
<add>public class NoOutputStreamingBufferedSimpleHttpRequestFactoryTests extends AbstractHttpRequestFactoryTestCase {
<add>
<add> @Override
<add> protected ClientHttpRequestFactory createRequestFactory() {
<add> SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
<add> factory.setOutputStreaming(false);
<add> return factory;
<add> }
<add>
<add>}
<ide><path>spring-web/src/test/java/org/springframework/http/client/NoOutputStreamingStreamingSimpleHttpRequestFactoryTests.java
<add>/*
<add> * Copyright 2002-2013 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.http.client;
<add>
<add>
<add>public class NoOutputStreamingStreamingSimpleHttpRequestFactoryTests extends AbstractHttpRequestFactoryTestCase {
<add>
<add> @Override
<add> protected ClientHttpRequestFactory createRequestFactory() {
<add> SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
<add> factory.setBufferRequestBody(false);
<add> factory.setOutputStreaming(false);
<add> return factory;
<add> }
<add>} | 5 |
Text | Text | fix some signatures of .end() methods | ab9b8e73eb1d664c0959e361478f47a546bda223 | <ide><path>doc/api/http.md
<ide> deprecated: REPLACEME
<ide>
<ide> See [`response.socket`][].
<ide>
<del>### response.end([data][, encoding][, callback])
<add>### response.end([data[, encoding]][, callback])
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> changes:
<ide><path>doc/api/http2.md
<ide> deprecated: REPLACEME
<ide>
<ide> See [`response.socket`][].
<ide>
<del>#### response.end([data][, encoding][, callback])
<add>#### response.end([data[, encoding]][, callback])
<ide> <!-- YAML
<ide> added: v8.4.0
<ide> changes:
<ide><path>doc/api/stream.md
<ide> added: v8.0.0
<ide>
<ide> Is `true` after [`writable.destroy()`][writable-destroy] has been called.
<ide>
<del>##### writable.end([chunk][, encoding][, callback])
<add>##### writable.end([chunk[, encoding]][, callback])
<ide> <!-- YAML
<ide> added: v0.9.4
<ide> changes: | 3 |
PHP | PHP | throw exception on empty collection | 339928401af2b22c4bcec562d4669176b237020f | <ide><path>src/Illuminate/Support/Testing/Fakes/NotificationFake.php
<ide>
<ide> namespace Illuminate\Support\Testing\Fakes;
<ide>
<add>use Exception;
<ide> use Illuminate\Contracts\Notifications\Dispatcher as NotificationDispatcher;
<ide> use Illuminate\Contracts\Notifications\Factory as NotificationFactory;
<ide> use Illuminate\Contracts\Translation\HasLocalePreference;
<ide> class NotificationFake implements NotificationDispatcher, NotificationFactory
<ide> * @param string $notification
<ide> * @param callable|null $callback
<ide> * @return void
<add> *
<add> * @throws \Exception
<ide> */
<ide> public function assertSentTo($notifiable, $notification, $callback = null)
<ide> {
<ide> if (is_array($notifiable) || $notifiable instanceof Collection) {
<add> if (count($notifiable) === 0) {
<add> throw new Exception('No notifiable given.');
<add> }
<add>
<ide> foreach ($notifiable as $singleNotifiable) {
<ide> $this->assertSentTo($singleNotifiable, $notification, $callback);
<ide> }
<ide> public function assertSentToTimes($notifiable, $notification, $times = 1)
<ide> * @param string $notification
<ide> * @param callable|null $callback
<ide> * @return void
<add> *
<add> * @throws \Exception
<ide> */
<ide> public function assertNotSentTo($notifiable, $notification, $callback = null)
<ide> {
<ide> if (is_array($notifiable) || $notifiable instanceof Collection) {
<add> if (count($notifiable) === 0) {
<add> throw new Exception('No notifiable given.');
<add> }
<add>
<ide> foreach ($notifiable as $singleNotifiable) {
<ide> $this->assertNotSentTo($singleNotifiable, $notification, $callback);
<ide> }
<ide><path>tests/Support/SupportTestingNotificationFakeTest.php
<ide>
<ide> namespace Illuminate\Tests\Support;
<ide>
<add>use Exception;
<ide> use Illuminate\Contracts\Translation\HasLocalePreference;
<ide> use Illuminate\Foundation\Auth\User;
<ide> use Illuminate\Notifications\Notification;
<add>use Illuminate\Support\Collection;
<ide> use Illuminate\Support\Testing\Fakes\NotificationFake;
<ide> use PHPUnit\Framework\Constraint\ExceptionMessage;
<ide> use PHPUnit\Framework\ExpectationFailedException;
<ide> public function testAssertNotSentTo()
<ide> }
<ide> }
<ide>
<add> public function testAssertSentToFailsForEmptyArray()
<add> {
<add> $this->expectException(Exception::class);
<add>
<add> $this->fake->assertSentTo([], NotificationStub::class);
<add> }
<add>
<add> public function testAssertSentToFailsForEmptyCollection()
<add> {
<add> $this->expectException(Exception::class);
<add>
<add> $this->fake->assertSentTo(new Collection, NotificationStub::class);
<add> }
<add>
<ide> public function testResettingNotificationId()
<ide> {
<ide> $this->fake->send($this->user, $this->notification); | 2 |
Javascript | Javascript | improve performance caused by primordials | 22799be7a9a87ec32b438b22090622f9884baeb4 | <ide><path>lib/buffer.js
<ide>
<ide> 'use strict';
<ide>
<del>const { Math, Object } = primordials;
<add>const {
<add> Object: {
<add> defineProperties: ObjectDefineProperties,
<add> defineProperty: ObjectDefineProperty,
<add> setPrototypeOf: ObjectSetPrototypeOf,
<add> create: ObjectCreate
<add> },
<add> Math: {
<add> floor: MathFloor,
<add> trunc: MathTrunc,
<add> min: MathMin
<add> }
<add>} = primordials;
<ide>
<ide> const {
<ide> byteLengthUtf8,
<ide> FastBuffer.prototype.constructor = Buffer;
<ide> Buffer.prototype = FastBuffer.prototype;
<ide> addBufferPrototypeMethods(Buffer.prototype);
<ide>
<del>const constants = Object.defineProperties({}, {
<add>const constants = ObjectDefineProperties({}, {
<ide> MAX_LENGTH: {
<ide> value: kMaxLength,
<ide> writable: false,
<ide> let poolSize, poolOffset, allocPool;
<ide> // do not own the ArrayBuffer allocator. Zero fill is always on in that case.
<ide> const zeroFill = bindingZeroFill || [0];
<ide>
<del>const encodingsMap = Object.create(null);
<add>const encodingsMap = ObjectCreate(null);
<ide> for (let i = 0; i < encodings.length; ++i)
<ide> encodingsMap[encodings[i]] = i;
<ide>
<ide> function toInteger(n, defaultVal) {
<ide> if (!Number.isNaN(n) &&
<ide> n >= Number.MIN_SAFE_INTEGER &&
<ide> n <= Number.MAX_SAFE_INTEGER) {
<del> return ((n % 1) === 0 ? n : Math.floor(n));
<add> return ((n % 1) === 0 ? n : MathFloor(n));
<ide> }
<ide> return defaultVal;
<ide> }
<ide> function Buffer(arg, encodingOrOffset, length) {
<ide> return Buffer.from(arg, encodingOrOffset, length);
<ide> }
<ide>
<del>Object.defineProperty(Buffer, Symbol.species, {
<add>ObjectDefineProperty(Buffer, Symbol.species, {
<ide> enumerable: false,
<ide> configurable: true,
<ide> get() { return FastBuffer; }
<ide> const of = (...items) => {
<ide> };
<ide> Buffer.of = of;
<ide>
<del>Object.setPrototypeOf(Buffer, Uint8Array);
<add>ObjectSetPrototypeOf(Buffer, Uint8Array);
<ide>
<ide> // The 'assertSize' method will remove itself from the callstack when an error
<ide> // occurs. This is done simply to keep the internal details of the
<ide> function SlowBuffer(length) {
<ide> return createUnsafeBuffer(length);
<ide> }
<ide>
<del>Object.setPrototypeOf(SlowBuffer.prototype, Uint8Array.prototype);
<del>Object.setPrototypeOf(SlowBuffer, Uint8Array);
<add>ObjectSetPrototypeOf(SlowBuffer.prototype, Uint8Array.prototype);
<add>ObjectSetPrototypeOf(SlowBuffer, Uint8Array);
<ide>
<ide> function allocate(size) {
<ide> if (size <= 0) {
<ide> function byteLength(string, encoding) {
<ide> Buffer.byteLength = byteLength;
<ide>
<ide> // For backwards compatibility.
<del>Object.defineProperty(Buffer.prototype, 'parent', {
<add>ObjectDefineProperty(Buffer.prototype, 'parent', {
<ide> enumerable: true,
<ide> get() {
<ide> if (!(this instanceof Buffer))
<ide> return undefined;
<ide> return this.buffer;
<ide> }
<ide> });
<del>Object.defineProperty(Buffer.prototype, 'offset', {
<add>ObjectDefineProperty(Buffer.prototype, 'offset', {
<ide> enumerable: true,
<ide> get() {
<ide> if (!(this instanceof Buffer))
<ide> let INSPECT_MAX_BYTES = 50;
<ide> // Override how buffers are presented by util.inspect().
<ide> Buffer.prototype[customInspectSymbol] = function inspect(recurseTimes, ctx) {
<ide> const max = INSPECT_MAX_BYTES;
<del> const actualMax = Math.min(max, this.length);
<add> const actualMax = MathMin(max, this.length);
<ide> const remaining = this.length - max;
<ide> let str = this.hexSlice(0, actualMax).replace(/(.{2})/g, '$1 ').trim();
<ide> if (remaining > 0)
<ide> Buffer.prototype[customInspectSymbol] = function inspect(recurseTimes, ctx) {
<ide> extras = true;
<ide> obj[key] = this[key];
<ide> return obj;
<del> }, Object.create(null));
<add> }, ObjectCreate(null));
<ide> if (extras) {
<ide> if (this.length !== 0)
<ide> str += ', ';
<ide> Buffer.prototype.toJSON = function toJSON() {
<ide> function adjustOffset(offset, length) {
<ide> // Use Math.trunc() to convert offset to an integer value that can be larger
<ide> // than an Int32. Hence, don't use offset | 0 or similar techniques.
<del> offset = Math.trunc(offset);
<add> offset = MathTrunc(offset);
<ide> if (offset === 0) {
<ide> return 0;
<ide> }
<ide> module.exports = {
<ide> kStringMaxLength
<ide> };
<ide>
<del>Object.defineProperties(module.exports, {
<add>ObjectDefineProperties(module.exports, {
<ide> constants: {
<ide> configurable: false,
<ide> enumerable: true, | 1 |
Javascript | Javascript | remove most `assert()` calls (issue 8506) | 814fa1dee36d6ee00ac1e7e582e2c5035b37f2f1 | <ide><path>src/core/cff_parser.js
<ide> */
<ide>
<ide> import {
<del> assert, bytesToString, FormatError, info, isArray, stringToBytes, Util, warn
<add> bytesToString, FormatError, info, isArray, stringToBytes, Util, warn
<ide> } from '../shared/util';
<ide> import {
<ide> ExpertCharset, ExpertSubsetCharset, ISOAdobeCharset
<ide> var CFFParser = (function CFFParserClosure() {
<ide> default:
<ide> throw new FormatError(`parseFDSelect: Unknown format "${format}".`);
<ide> }
<del> assert(fdSelect.length === length, 'parseFDSelect: Invalid font data.');
<add> if (fdSelect.length !== length) {
<add> throw new FormatError('parseFDSelect: Invalid font data.');
<add> }
<ide>
<ide> return new CFFFDSelect(fdSelect, rawBytes);
<ide> },
<ide> var CFFCompiler = (function CFFCompilerClosure() {
<ide> output) {
<ide> for (var i = 0, ii = dicts.length; i < ii; ++i) {
<ide> var fontDict = dicts[i];
<del> assert(fontDict.privateDict && fontDict.hasName('Private'),
<del> 'There must be an private dictionary.');
<ide> var privateDict = fontDict.privateDict;
<add> if (!privateDict || !fontDict.hasName('Private')) {
<add> throw new FormatError('There must be a private dictionary.');
<add> }
<ide> var privateDictTracker = new CFFOffsetTracker();
<ide> var privateDictData = this.compileDict(privateDict, privateDictTracker);
<ide>
<ide><path>src/core/chunked_stream.js
<ide> */
<ide>
<ide> import {
<del> arrayByteLength, arraysToBytes, assert, createPromiseCapability, isEmptyObj,
<del> isInt, MissingDataException
<add> arrayByteLength, arraysToBytes, createPromiseCapability, isEmptyObj, isInt,
<add> MissingDataException
<ide> } from '../shared/util';
<ide>
<ide> var ChunkedStream = (function ChunkedStreamClosure() {
<ide> var ChunkedStream = (function ChunkedStreamClosure() {
<ide> onReceiveData: function ChunkedStream_onReceiveData(begin, chunk) {
<ide> var end = begin + chunk.byteLength;
<ide>
<del> assert(begin % this.chunkSize === 0, 'Bad begin offset: ' + begin);
<add> if (begin % this.chunkSize !== 0) {
<add> throw new Error(`Bad begin offset: ${begin}`);
<add> }
<ide> // Using this.length is inaccurate here since this.start can be moved
<ide> // See ChunkedStream.moveStart()
<ide> var length = this.bytes.length;
<del> assert(end % this.chunkSize === 0 || end === length,
<del> 'Bad end offset: ' + end);
<add> if (end % this.chunkSize !== 0 && end !== length) {
<add> throw new Error(`Bad end offset: ${end}`);
<add> }
<ide>
<ide> this.bytes.set(new Uint8Array(chunk), begin);
<ide> var chunkSize = this.chunkSize;
<ide><path>src/core/cmap.js
<ide> */
<ide>
<ide> import {
<del> assert, CMapCompressionType, FormatError, isInt, isString,
<del> MissingDataException, Util, warn
<add> CMapCompressionType, FormatError, isInt, isString, MissingDataException, Util,
<add> warn
<ide> } from '../shared/util';
<ide> import { isCmd, isEOF, isName, isStream } from './primitives';
<ide> import { Lexer } from './parser';
<ide> var BinaryCMapReader = (function BinaryCMapReaderClosure() {
<ide> var sequence = !!(b & 0x10);
<ide> var dataSize = b & 15;
<ide>
<del> assert(dataSize + 1 <= MAX_NUM_SIZE);
<add> if (dataSize + 1 > MAX_NUM_SIZE) {
<add> throw new Error('processBinaryCMap: Invalid dataSize.');
<add> }
<ide>
<ide> var ucs2DataSize = 1;
<ide> var subitemsCount = stream.readNumber();
<ide> var CMapFactory = (function CMapFactoryClosure() {
<ide> if (BUILT_IN_CMAPS.indexOf(name) === -1) {
<ide> return Promise.reject(new Error('Unknown CMap name: ' + name));
<ide> }
<del> assert(fetchBuiltInCMap, 'Built-in CMap parameters are not provided.');
<add> if (!fetchBuiltInCMap) {
<add> return Promise.reject(new Error(
<add> 'Built-in CMap parameters are not provided.'));
<add> }
<ide>
<ide> return fetchBuiltInCMap(name).then(function (data) {
<ide> var cMapData = data.cMapData, compressionType = data.compressionType;
<ide> var CMapFactory = (function CMapFactoryClosure() {
<ide> return extendCMap(cMap, fetchBuiltInCMap, useCMap);
<ide> });
<ide> }
<del> assert(compressionType === CMapCompressionType.NONE,
<del> 'TODO: Only BINARY/NONE CMap compression is currently supported.');
<del> // Uncompressed CMap.
<del> var lexer = new Lexer(new Stream(cMapData));
<del> return parseCMap(cMap, lexer, fetchBuiltInCMap, null);
<add> if (compressionType === CMapCompressionType.NONE) {
<add> var lexer = new Lexer(new Stream(cMapData));
<add> return parseCMap(cMap, lexer, fetchBuiltInCMap, null);
<add> }
<add> return Promise.reject(new Error(
<add> 'TODO: Only BINARY/NONE CMap compression is currently supported.'));
<ide> });
<ide> }
<ide>
<ide><path>src/core/crypto.js
<ide> */
<ide>
<ide> import {
<del> assert, bytesToString, FormatError, isInt, PasswordException,
<del> PasswordResponses, stringToBytes, utf8StringToString, warn
<add> bytesToString, FormatError, isInt, PasswordException, PasswordResponses,
<add> stringToBytes, utf8StringToString, warn
<ide> } from '../shared/util';
<ide> import { isDict, isName, Name } from './primitives';
<ide> import { DecryptStream } from './stream';
<ide> var CipherTransformFactory = (function CipherTransformFactoryClosure() {
<ide> }
<ide>
<ide> function buildCipherConstructor(cf, name, num, gen, key) {
<del> assert(isName(name), 'Invalid crypt filter name.');
<add> if (!isName(name)) {
<add> throw new FormatError('Invalid crypt filter name.');
<add> }
<ide> var cryptFilter = cf.get(name.name);
<ide> var cfm;
<ide> if (cryptFilter !== null && cryptFilter !== undefined) {
<ide><path>src/core/document.js
<ide> * limitations under the License.
<ide> */
<ide>
<del>import {
<del> assert, info, isArray, isArrayBuffer, isNum, isSpace, isString,
<del> MissingDataException, OPS, shadow, stringToBytes, stringToPDFString, Util,
<del> warn
<del>} from '../shared/util';
<ide> import { Catalog, ObjectLoader, XRef } from './obj';
<ide> import { Dict, isDict, isName, isStream } from './primitives';
<add>import {
<add> info, isArray, isArrayBuffer, isNum, isSpace, isString, MissingDataException,
<add> OPS, shadow, stringToBytes, stringToPDFString, Util, warn
<add>} from '../shared/util';
<ide> import { NullStream, Stream, StreamsSequenceStream } from './stream';
<ide> import { OperatorList, PartialEvaluator } from './evaluator';
<ide> import { AnnotationFactory } from './annotation';
<ide> var PDFDocument = (function PDFDocumentClosure() {
<ide> } else {
<ide> throw new Error('PDFDocument: Unknown argument type');
<ide> }
<del> assert(stream.length > 0, 'stream must have data');
<add> if (stream.length <= 0) {
<add> throw new Error('PDFDocument: stream must have data');
<add> }
<ide>
<ide> this.pdfManager = pdfManager;
<ide> this.stream = stream;
<ide><path>src/core/evaluator.js
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide>
<ide> var fontRef, xref = this.xref;
<ide> if (font) { // Loading by ref.
<del> assert(isRef(font));
<add> if (!isRef(font)) {
<add> throw new Error('The "font" object should be a reference.');
<add> }
<ide> fontRef = font;
<ide> } else { // Loading by name.
<ide> var fontRes = resources.get('Font');
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> resources = resources || Dict.empty;
<ide> initialState = initialState || new EvalState();
<ide>
<del> assert(operatorList, 'getOperatorList: missing "operatorList" parameter');
<add> if (!operatorList) {
<add> throw new Error('getOperatorList: missing "operatorList" parameter');
<add> }
<ide>
<ide> var self = this;
<ide> var xref = this.xref;
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide>
<ide> var xobj = xobjs.get(name);
<ide> if (xobj) {
<del> assert(isStream(xobj), 'XObject should be a stream');
<add> if (!isStream(xobj)) {
<add> throw new FormatError('XObject should be a stream');
<add> }
<ide>
<ide> var type = xobj.dict.get('Subtype');
<del> assert(isName(type), 'XObject should have a Name subtype');
<add> if (!isName(type)) {
<add> throw new FormatError('XObject should have a Name subtype');
<add> }
<ide>
<ide> if (type.name === 'Form') {
<ide> stateManager.save();
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide>
<ide> case OPS.shadingFill:
<ide> var shadingRes = resources.get('Shading');
<del> assert(shadingRes, 'No shading resource found');
<add> if (!shadingRes) {
<add> throw new FormatError('No shading resource found');
<add> }
<ide>
<ide> var shading = shadingRes.get(args[0].name);
<del> assert(shading, 'No shading object found');
<add> if (!shading) {
<add> throw new FormatError('No shading object found');
<add> }
<ide>
<ide> var shadingFill = Pattern.parseShading(shading, null, xref,
<ide> resources, self.handler);
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> if (!xobj) {
<ide> break;
<ide> }
<del> assert(isStream(xobj), 'XObject should be a stream');
<add> if (!isStream(xobj)) {
<add> throw new FormatError('XObject should be a stream');
<add> }
<ide>
<ide> var type = xobj.dict.get('Subtype');
<del> assert(isName(type), 'XObject should have a Name subtype');
<add> if (!isName(type)) {
<add> throw new FormatError('XObject should have a Name subtype');
<add> }
<ide>
<ide> if (type.name !== 'Form') {
<ide> skipEmptyXObjs[name] = true;
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> var cMap = properties.cMap;
<ide> toUnicode = [];
<ide> cMap.forEach(function(charcode, cid) {
<del> assert(cid <= 0xffff, 'Max size of CID is 65,535');
<add> if (cid > 0xffff) {
<add> throw new FormatError('Max size of CID is 65,535');
<add> }
<ide> // e) Map the CID obtained in step (a) according to the CMap
<ide> // obtained in step (d), producing a Unicode value.
<ide> var ucs2 = ucs2CMap.lookup(cid);
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> preEvaluateFont: function PartialEvaluator_preEvaluateFont(dict) {
<ide> var baseDict = dict;
<ide> var type = dict.get('Subtype');
<del> assert(isName(type), 'invalid font Subtype');
<add> if (!isName(type)) {
<add> throw new FormatError('invalid font Subtype');
<add> }
<ide>
<ide> var composite = false;
<ide> var uint8array;
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> // - set the type according to the descendant font
<ide> // - get the FontDescriptor from the descendant font
<ide> var df = dict.get('DescendantFonts');
<del> assert(df, 'Descendant fonts are not specified');
<add> if (!df) {
<add> throw new FormatError('Descendant fonts are not specified');
<add> }
<ide> dict = (isArray(df) ? this.xref.fetchIfRef(df[0]) : df);
<ide>
<ide> type = dict.get('Subtype');
<del> assert(isName(type), 'invalid font Subtype');
<add> if (!isName(type)) {
<add> throw new FormatError('invalid font Subtype');
<add> }
<ide> composite = true;
<ide> }
<ide>
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> // FontDescriptor was not required.
<ide> // This case is here for compatibility.
<ide> var baseFontName = dict.get('BaseFont');
<del> assert(isName(baseFontName), 'Base font is not specified');
<add> if (!isName(baseFontName)) {
<add> throw new FormatError('Base font is not specified');
<add> }
<ide>
<ide> // Using base font name as a font name.
<ide> baseFontName = baseFontName.name.replace(/[,_]/g, '-');
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> }
<ide> fontName = (fontName || baseFont);
<ide>
<del> assert(isName(fontName), 'invalid font name');
<add> if (!isName(fontName)) {
<add> throw new FormatError('invalid font name');
<add> }
<ide>
<ide> var fontFile = descriptor.get('FontFile', 'FontFile2', 'FontFile3');
<ide> if (fontFile) {
<ide> var TranslatedFont = (function TranslatedFontClosure() {
<ide> this.sent = true;
<ide> },
<ide> loadType3Data(evaluator, resources, parentOperatorList, task) {
<del> assert(this.font.isType3Font);
<add> if (!this.font.isType3Font) {
<add> throw new Error('Must be a Type3 font.');
<add> }
<ide>
<ide> if (this.type3Loaded) {
<ide> return this.type3Loaded;
<ide> var EvaluatorPreprocessor = (function EvaluatorPreprocessorClosure() {
<ide> args = [];
<ide> }
<ide> args.push(obj);
<del> assert(args.length <= 33, 'Too many arguments');
<add> if (args.length > 33) {
<add> throw new FormatError('Too many arguments');
<add> }
<ide> }
<ide> }
<ide> },
<ide><path>src/core/fonts.js
<ide> */
<ide>
<ide> import {
<del> assert, bytesToString, FONT_IDENTITY_MATRIX, FontType, FormatError, info,
<del> isArray, isInt, isNum, isSpace, MissingDataException, readUint32, shadow,
<del> string32, warn
<add> bytesToString, FONT_IDENTITY_MATRIX, FontType, FormatError, info, isArray,
<add> isInt, isNum, isSpace, MissingDataException, readUint32, shadow, string32,
<add> warn
<ide> } from '../shared/util';
<ide> import {
<ide> CFF, CFFCharset, CFFCompiler, CFFHeader, CFFIndex, CFFParser, CFFPrivateDict,
<ide> var Font = (function FontClosure() {
<ide> var isCidToGidMapEmpty = cidToGidMap.length === 0;
<ide>
<ide> properties.cMap.forEach(function(charCode, cid) {
<del> assert(cid <= 0xffff, 'Max size of CID is 65,535');
<add> if (cid > 0xffff) {
<add> throw new FormatError('Max size of CID is 65,535');
<add> }
<ide> var glyphId = -1;
<ide> if (isCidToGidMapEmpty) {
<ide> glyphId = cid;
<ide><path>src/core/obj.js
<ide> */
<ide>
<ide> import {
<del> assert, bytesToString, createPromiseCapability, createValidAbsoluteUrl,
<del> FormatError, info, InvalidPDFException, isArray, isBool, isInt, isString,
<add> bytesToString, createPromiseCapability, createValidAbsoluteUrl, FormatError,
<add> info, InvalidPDFException, isArray, isBool, isInt, isString,
<ide> MissingDataException, shadow, stringToPDFString, stringToUTF8String, Util,
<ide> warn, XRefParseException
<ide> } from '../shared/util';
<ide> var Catalog = (function CatalogClosure() {
<ide> this.pdfManager = pdfManager;
<ide> this.xref = xref;
<ide> this.catDict = xref.getCatalogObj();
<del> assert(isDict(this.catDict), 'catalog object is not a dictionary');
<add> if (!isDict(this.catDict)) {
<add> throw new FormatError('catalog object is not a dictionary');
<add> }
<ide>
<ide> this.fontCache = new RefSetCache();
<ide> this.builtInCMapCache = Object.create(null);
<ide> var Catalog = (function CatalogClosure() {
<ide> },
<ide> get toplevelPagesDict() {
<ide> var pagesObj = this.catDict.get('Pages');
<del> assert(isDict(pagesObj), 'invalid top-level pages dictionary');
<add> if (!isDict(pagesObj)) {
<add> throw new FormatError('invalid top-level pages dictionary');
<add> }
<ide> // shadow the prototype getter
<ide> return shadow(this, 'toplevelPagesDict', pagesObj);
<ide> },
<ide> var Catalog = (function CatalogClosure() {
<ide> if (outlineDict === null) {
<ide> continue;
<ide> }
<del> assert(outlineDict.has('Title'), 'Invalid outline item');
<add> if (!outlineDict.has('Title')) {
<add> throw new FormatError('Invalid outline item');
<add> }
<ide>
<ide> var data = { url: null, dest: null, };
<ide> Catalog.parseDestDictionary({
<ide> var Catalog = (function CatalogClosure() {
<ide> },
<ide> get numPages() {
<ide> var obj = this.toplevelPagesDict.get('Count');
<del> assert(
<del> isInt(obj),
<del> 'page count in top level pages object is not an integer'
<del> );
<add> if (!isInt(obj)) {
<add> throw new FormatError(
<add> 'page count in top level pages object is not an integer');
<add> }
<ide> // shadow the prototype getter
<ide> return shadow(this, 'numPages', obj);
<ide> },
<ide> var Catalog = (function CatalogClosure() {
<ide> for (var i = 0, ii = this.numPages; i < ii; i++) {
<ide> if (i in nums) {
<ide> var labelDict = nums[i];
<del> assert(isDict(labelDict), 'The PageLabel is not a dictionary.');
<add> if (!isDict(labelDict)) {
<add> throw new FormatError('The PageLabel is not a dictionary.');
<add> }
<ide>
<ide> var type = labelDict.get('Type');
<del> assert(!type || isName(type, 'PageLabel'),
<del> 'Invalid type in PageLabel dictionary.');
<add> if (type && !isName(type, 'PageLabel')) {
<add> throw new FormatError('Invalid type in PageLabel dictionary.');
<add> }
<ide>
<ide> var s = labelDict.get('S');
<del> assert(!s || isName(s), 'Invalid style in PageLabel dictionary.');
<add> if (s && !isName(s)) {
<add> throw new FormatError('Invalid style in PageLabel dictionary.');
<add> }
<ide> style = s ? s.name : null;
<ide>
<ide> var p = labelDict.get('P');
<del> assert(!p || isString(p), 'Invalid prefix in PageLabel dictionary.');
<add> if (p && !isString(p)) {
<add> throw new FormatError('Invalid prefix in PageLabel dictionary.');
<add> }
<ide> prefix = p ? stringToPDFString(p) : '';
<ide>
<ide> var st = labelDict.get('St');
<del> assert(!st || (isInt(st) && st >= 1),
<del> 'Invalid start in PageLabel dictionary.');
<add> if (st && !(isInt(st) && st >= 1)) {
<add> throw new FormatError('Invalid start in PageLabel dictionary.');
<add> }
<ide> currentIndex = st || 1;
<ide> }
<ide>
<ide> var Catalog = (function CatalogClosure() {
<ide> currentLabel = charBuf.join('');
<ide> break;
<ide> default:
<del> assert(!style,
<del> 'Invalid style "' + style + '" in PageLabel dictionary.');
<add> if (style) {
<add> throw new FormatError(
<add> `Invalid style "${style}" in PageLabel dictionary.`);
<add> }
<ide> }
<ide> pageLabels[i] = prefix + currentLabel;
<ide>
<ide> var Catalog = (function CatalogClosure() {
<ide> }
<ide>
<ide> // Must be a child page dictionary.
<del> assert(isDict(currentNode),
<del> 'page dictionary kid reference points to wrong type of object');
<add> if (!isDict(currentNode)) {
<add> capability.reject(new FormatError(
<add> 'page dictionary kid reference points to wrong type of object'));
<add> return;
<add> }
<ide>
<ide> count = currentNode.get('Count');
<ide> // Cache the Kids count, since it can reduce redundant lookups in long
<ide> var Catalog = (function CatalogClosure() {
<ide> }
<ide>
<ide> var kids = currentNode.get('Kids');
<del> assert(isArray(kids), 'page dictionary kids object is not an array');
<add> if (!isArray(kids)) {
<add> capability.reject(new FormatError(
<add> 'page dictionary kids object is not an array'));
<add> return;
<add> }
<ide>
<ide> // Always check all `Kids` nodes, to avoid getting stuck in an empty
<ide> // node further down in the tree (see issue5644.pdf, issue8088.pdf),
<ide> var Catalog = (function CatalogClosure() {
<ide> nodesToVisit.push(kids[last]);
<ide> }
<ide> }
<del> capability.reject('Page index ' + pageIndex + ' not found.');
<add> capability.reject(new Error('Page index ' + pageIndex + ' not found.'));
<ide> }
<ide> next();
<ide> return capability.promise;
<ide> var Catalog = (function CatalogClosure() {
<ide> return xref.fetchAsync(kidRef).then(function (node) {
<ide> if (isRefsEqual(kidRef, pageRef) && !isDict(node, 'Page') &&
<ide> !(isDict(node) && !node.has('Type') && node.has('Contents'))) {
<del> throw new Error('The reference does not point to a /Page Dict.');
<add> throw new FormatError(
<add> 'The reference does not point to a /Page Dict.');
<ide> }
<ide> if (!node) {
<ide> return null;
<ide> }
<del> assert(isDict(node), 'node must be a Dict.');
<add> if (!isDict(node)) {
<add> throw new FormatError('node must be a Dict.');
<add> }
<ide> parentRef = node.getRaw('Parent');
<ide> return node.getAsync('Parent');
<ide> }).then(function (parent) {
<ide> if (!parent) {
<ide> return null;
<ide> }
<del> assert(isDict(parent), 'parent must be a Dict.');
<add> if (!isDict(parent)) {
<add> throw new FormatError('parent must be a Dict.');
<add> }
<ide> return parent.getAsync('Kids');
<ide> }).then(function (kids) {
<ide> if (!kids) {
<ide> var Catalog = (function CatalogClosure() {
<ide> var found = false;
<ide> for (var i = 0; i < kids.length; i++) {
<ide> var kid = kids[i];
<del> assert(isRef(kid), 'kid must be a Ref.');
<add> if (!isRef(kid)) {
<add> throw new FormatError('kid must be a Ref.');
<add> }
<ide> if (kid.num === kidRef.num) {
<ide> found = true;
<ide> break;
<ide> var XRef = (function XRefClosure() {
<ide> },
<ide>
<ide> fetch: function XRef_fetch(ref, suppressEncryption) {
<del> assert(isRef(ref), 'ref object is not a reference');
<add> if (!isRef(ref)) {
<add> throw new Error('ref object is not a reference');
<add> }
<ide> var num = ref.num;
<ide> if (num in this.cache) {
<ide> var cacheEntry = this.cache[num];
<ide> var NameOrNumberTree = (function NameOrNumberTreeClosure() {
<ide> var kids = obj.get('Kids');
<ide> for (i = 0, n = kids.length; i < n; i++) {
<ide> var kid = kids[i];
<del> assert(!processed.has(kid),
<del> 'Duplicate entry in "' + this._type + '" tree.');
<add> if (processed.has(kid)) {
<add> throw new FormatError(`Duplicate entry in "${this._type}" tree.`);
<add> }
<ide> queue.push(kid);
<ide> processed.put(kid);
<ide> }
<ide><path>src/core/pattern.js
<ide> Shadings.Mesh = (function MeshClosure() {
<ide> var coord = reader.readCoordinate();
<ide> var color = reader.readComponents();
<ide> if (verticesLeft === 0) { // ignoring flags if we started a triangle
<del> assert((0 <= f && f <= 2), 'Unknown type4 flag');
<add> if (!(0 <= f && f <= 2)) {
<add> throw new FormatError('Unknown type4 flag');
<add> }
<ide> switch (f) {
<ide> case 0:
<ide> verticesLeft = 3;
<ide> Shadings.Mesh = (function MeshClosure() {
<ide> var cs = new Int32Array(4); // c00, c30, c03, c33
<ide> while (reader.hasData) {
<ide> var f = reader.readFlag();
<del> assert((0 <= f && f <= 3), 'Unknown type6 flag');
<add> if (!(0 <= f && f <= 3)) {
<add> throw new FormatError('Unknown type6 flag');
<add> }
<ide> var i, ii;
<ide> var pi = coords.length;
<ide> for (i = 0, ii = (f !== 0 ? 8 : 12); i < ii; i++) {
<ide> Shadings.Mesh = (function MeshClosure() {
<ide> var cs = new Int32Array(4); // c00, c30, c03, c33
<ide> while (reader.hasData) {
<ide> var f = reader.readFlag();
<del> assert((0 <= f && f <= 3), 'Unknown type7 flag');
<add> if (!(0 <= f && f <= 3)) {
<add> throw new FormatError('Unknown type7 flag');
<add> }
<ide> var i, ii;
<ide> var pi = coords.length;
<ide> for (i = 0, ii = (f !== 0 ? 12 : 16); i < ii; i++) {
<ide> Shadings.Mesh = (function MeshClosure() {
<ide> }
<ide>
<ide> function Mesh(stream, matrix, xref, res) {
<del> assert(isStream(stream), 'Mesh data is not a stream');
<add> if (!isStream(stream)) {
<add> throw new FormatError('Mesh data is not a stream');
<add> }
<ide> var dict = stream.dict;
<ide> this.matrix = matrix;
<ide> this.shadingType = dict.get('ShadingType');
<ide> Shadings.Mesh = (function MeshClosure() {
<ide> break;
<ide> case ShadingType.LATTICE_FORM_MESH:
<ide> var verticesPerRow = dict.get('VerticesPerRow') | 0;
<del> assert(verticesPerRow >= 2, 'Invalid VerticesPerRow');
<add> if (verticesPerRow < 2) {
<add> throw new FormatError('Invalid VerticesPerRow');
<add> }
<ide> decodeType5Shading(this, reader, verticesPerRow);
<ide> break;
<ide> case ShadingType.COONS_PATCH_MESH:
<ide><path>src/core/worker.js
<ide> var WorkerMessageHandler = {
<ide> if (source.chunkedViewerLoading) {
<ide> pdfStream = new PDFWorkerStream(source, handler);
<ide> } else {
<del> assert(PDFNetworkStream, './network module is not loaded');
<add> if (!PDFNetworkStream) {
<add> throw new Error('./network module is not loaded');
<add> }
<ide> pdfStream = new PDFNetworkStream(data);
<ide> }
<ide> } catch (ex) {
<ide><path>src/display/canvas.js
<ide> */
<ide>
<ide> import {
<del> assert, FONT_IDENTITY_MATRIX, IDENTITY_MATRIX, ImageKind, info, isArray,
<add> FONT_IDENTITY_MATRIX, IDENTITY_MATRIX, ImageKind, info, isArray,
<ide> isLittleEndian, isNum, OPS, shadow, TextRenderingMode, Util, warn
<ide> } from '../shared/util';
<ide> import { getShadingPatternFromIR, TilingPattern } from './pattern_helper';
<ide> var CanvasGraphics = (function CanvasGraphicsClosure() {
<ide> if (group.matrix) {
<ide> currentCtx.transform.apply(currentCtx, group.matrix);
<ide> }
<del> assert(group.bbox, 'Bounding box is required.');
<add> if (!group.bbox) {
<add> throw new Error('Bounding box is required.');
<add> }
<ide>
<ide> // Based on the current transform figure out how big the bounding box
<ide> // will actually be.
<ide><path>src/display/dom_utils.js
<ide> */
<ide>
<ide> import {
<del> assert, CMapCompressionType, createValidAbsoluteUrl, deprecated, globalScope,
<add> CMapCompressionType, createValidAbsoluteUrl, deprecated, globalScope,
<ide> removeNullCharacters, stringToBytes, warn
<ide> } from '../shared/util';
<ide>
<ide> var DEFAULT_LINK_REL = 'noopener noreferrer nofollow';
<ide>
<ide> class DOMCanvasFactory {
<ide> create(width, height) {
<del> assert(width > 0 && height > 0, 'invalid canvas size');
<add> if (width <= 0 || height <= 0) {
<add> throw new Error('invalid canvas size');
<add> }
<ide> let canvas = document.createElement('canvas');
<ide> let context = canvas.getContext('2d');
<ide> canvas.width = width;
<ide> class DOMCanvasFactory {
<ide> }
<ide>
<ide> reset(canvasAndContext, width, height) {
<del> assert(canvasAndContext.canvas, 'canvas is not specified');
<del> assert(width > 0 && height > 0, 'invalid canvas size');
<add> if (!canvasAndContext.canvas) {
<add> throw new Error('canvas is not specified');
<add> }
<add> if (width <= 0 || height <= 0) {
<add> throw new Error('invalid canvas size');
<add> }
<ide> canvasAndContext.canvas.width = width;
<ide> canvasAndContext.canvas.height = height;
<ide> }
<ide>
<ide> destroy(canvasAndContext) {
<del> assert(canvasAndContext.canvas, 'canvas is not specified');
<add> if (!canvasAndContext.canvas) {
<add> throw new Error('canvas is not specified');
<add> }
<ide> // Zeroing the width and height cause Firefox to release graphics
<ide> // resources immediately, which can greatly reduce memory consumption.
<ide> canvasAndContext.canvas.width = 0; | 12 |
Javascript | Javascript | improve `filehandle.prototype.write` coverage | 46f54bda48610e62da8724a35dfa940fe3654649 | <ide><path>test/parallel/test-fs-promises-file-handle-write.js
<ide> async function validateNonUint8ArrayWrite() {
<ide> async function validateNonStringValuesWrite() {
<ide> const filePathForHandle = path.resolve(tmpDir, 'tmp-non-string-write.txt');
<ide> const fileHandle = await open(filePathForHandle, 'w+');
<del> const nonStringValues = [123, {}, new Map()];
<add> const nonStringValues = [123, {}, new Map(), null, undefined, 0n, () => {}, Symbol(), true];
<ide> for (const nonStringValue of nonStringValues) {
<ide> await assert.rejects(
<ide> fileHandle.write(nonStringValue), | 1 |
Text | Text | add more projects to build-status.md | 0498e3699358b2c533bcb26d3dafa56b9e28a54d | <ide><path>docs/build-instructions/build-status.md
<ide> | About | [![OS X Build Status](https://travis-ci.org/atom/about.svg?branch=master)](https://travis-ci.org/atom/about) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/msprea3vq47l8oce/branch/master?svg=true)](https://ci.appveyor.com/project/atom/about/branch/master) | [![Dependency Status](https://david-dm.org/atom/about.svg)](https://david-dm.org/atom/about) |
<ide> | Archive View | [![OS X Build Status](https://travis-ci.org/atom/archive-view.svg?branch=master)](https://travis-ci.org/atom/archive-view) | [![Windows Build status](https://ci.appveyor.com/api/projects/status/u3qfgaod4lhriqlj/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/archive-view/branch/master) | [![Dependency Status](https://david-dm.org/atom/archive-view.svg)](https://david-dm.org/atom/archive-view) |
<ide> | AutoComplete Atom API | [![OS X Build Status](https://travis-ci.org/atom/autocomplete-atom-api.svg?branch=master)](https://travis-ci.org/atom/autocomplete-atom-api) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/1x3uqd9ddchpe555/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/autocomplete-atom-api/branch/master) | [![Dependency Status](https://david-dm.org/atom/autocomplete-atom-api.svg)](https://david-dm.org/atom/autocomplete-atom-api) |
<add>| Atom Space Pen Views | [![OS X Build Status](https://travis-ci.org/atom/atom-space-pen-views.svg?branch=master)](https://travis-ci.org/atom/atom-space-pen-views) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/5lgv47has6n8uhuv/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/atom-space-pen-views/branch/master) | [![Dependency Status](https://david-dm.org/atom/atom-space-pen-views.svg)](https://david-dm.org/atom/atom-space-pen-views) |
<ide> | AutoComplete CSS | [![OS X Build Status](https://travis-ci.org/atom/autocomplete-css.svg?branch=master)](https://travis-ci.org/atom/autocomplete-css) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/k3e5uvpmpc5bkja9/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/autocomplete-css/branch/master) | [![Dependency Status](https://david-dm.org/atom/autocomplete-css.svg)](https://david-dm.org/atom/autocomplete-css) |
<ide> | AutoComplete HTML | [![OS X Build Status](https://travis-ci.org/atom/autocomplete-html.svg?branch=master)](https://travis-ci.org/atom/autocomplete-html) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/bsaqbg1fljpd9q1b/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/autocomplete-html/branch/master) | [![Dependency Status](https://david-dm.org/atom/autocomplete-html.svg)](https://david-dm.org/atom/autocomplete-html) |
<ide> | AutoComplete+ | [![OS X Build Status](https://travis-ci.org/atom/autocomplete-plus.svg?branch=master)](https://travis-ci.org/atom/autocomplete-plus) | [![Windows Build status](https://ci.appveyor.com/api/projects/status/9bpokrud2apgqsq0/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/autocomplete-plus/branch/master) | [![Dependency Status](https://david-dm.org/atom/autocomplete-plus.svg)](https://david-dm.org/atom/autocomplete-plus) |
<ide>
<ide> | Library | OS X | Windows | Dependencies |
<ide> |---------|------|---------|--------------|
<del>| Atom Space Pen Views | [![OS X Build Status](https://travis-ci.org/atom/atom-space-pen-views.svg?branch=master)](https://travis-ci.org/atom/atom-space-pen-views) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/5lgv47has6n8uhuv/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/atom-space-pen-views/branch/master) | [![Dependency Status](https://david-dm.org/atom/atom-space-pen-views.svg)](https://david-dm.org/atom/atom-space-pen-views) |
<ide> | Clear Cut | [![OS X Build Status](https://travis-ci.org/atom/clear-cut.png?branch=master)](https://travis-ci.org/atom/clear-cut) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/civ54x89l06286m9/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/clear-cut/branch/master) | [![Dependency Status](https://david-dm.org/atom/clear-cut.svg)](https://david-dm.org/atom/clear-cut) |
<ide> | Event Kit | [![OS X Build Status](https://travis-ci.org/atom/event-kit.svg?branch=master)](https://travis-ci.org/atom/event-kit) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/lb32q70204lpmlxo/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/event-kit/branch/master) | [![Dependency Status](https://david-dm.org/atom/event-kit.svg)](https://david-dm.org/atom/event-kit) |
<ide> | Fs Plus | [![OS X Build Status](https://travis-ci.org/atom/fs-plus.svg?branch=master)](https://travis-ci.org/atom/fs-plus) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/gf2tleqp0hdek3o3/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/fs-plus/branch/master) | [![Dependency Status](https://david-dm.org/atom/fs-plus.svg)](https://david-dm.org/atom/fs-plus) |
<ide> | Grim | [![OS X Build Status](https://travis-ci.org/atom/grim.svg)](https://travis-ci.org/atom/grim) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/i4m37pol77vygrvb/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/grim/branch/master) | [![Dependency Status](https://david-dm.org/atom/grim.svg)](https://david-dm.org/atom/grim) |
<add>| Jasmine Focused | [![OS X Build Status](https://travis-ci.org/atom/grim.svg)](https://travis-ci.org/atom/grim) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/af0ipfqqxn7aygoe/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/jasmine-focused/branch/master) | [![Dependency Status](https://david-dm.org/atom/jasmine-focused.svg)](https://david-dm.org/atom/jasmine-focused) |
<add>| Property Accessors | [![OS X Build Status](https://travis-ci.org/atom/property-accessors.svg?branch=master)](https://travis-ci.org/atom/property-accessors) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/ww4d10hi4v5h7kbp/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/property-accessors/branch/master) | [![Dependency Status](https://david-dm.org/atom/property-accessors.svg)](https://david-dm.org/atom/property-accessors) |
<add>| TextBuffer | [![OS X Build Status](https://travis-ci.org/atom/text-buffer.svg?branch=master)](https://travis-ci.org/atom/text-buffer) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/48xl8do1sm2thf5p/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/text-buffer/branch/master) | [![Dependency Status](https://david-dm.org/atom/text-buffer.svg)](https://david-dm.org/atom/text-buffer) |
<add>| Underscore-Plus | [![OS X Build Status](https://travis-ci.org/atom/underscore-plus.svg?branch=master)](https://travis-ci.org/atom/underscore-plus) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/c7l8009vgpaojxcd/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/underscore-plus/branch/master) | [![Dependency Status](https://david-dm.org/atom/underscore-plus.svg)](https://david-dm.org/atom/underscore-plus) |
<ide>
<ide>
<del>## Languages
<del>
<add>## Tools
<ide> | Language | OS X | Windows | Dependencies |
<ide> |----------|------|---------|--------------|
<del>| C/C++ | [![OS X Build Status](https://travis-ci.org/atom/language-c.svg?branch=master)](https://travis-ci.org/atom/language-c) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/8oy1hmp4yrij7c32/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-c/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-c.svg)](https://david-dm.org/atom/language-c) |
<del>| C# | [![OS X Build Status](https://travis-ci.org/atom/language-csharp.svg?branch=master)](https://travis-ci.org/atom/language-csharp) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/j1as3753y5t90obn/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-csharp/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-csharp.svg)](https://david-dm.org/atom/language-csharp) |
<del>| Clojure | [![OS X Build Status](https://travis-ci.org/atom/language-clojure.svg?branch=master)](https://travis-ci.org/atom/language-clojure) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/6kd5fs48y5hixde6/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-clojure/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-clojure.svg)](https://david-dm.org/atom/language-clojure) |
<del>| CoffeeScript | [![OS X Build Status](https://travis-ci.org/atom/language-coffee-script.svg?branch=master)](https://travis-ci.org/atom/language-coffee-script) | [![Windows Build status](https://ci.appveyor.com/api/projects/status/4j9aak7iwn2f2x7a/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-coffee-script/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-coffee-script.svg)](https://david-dm.org/atom/language-coffee-script) |
<del>| CSS | [![OS X Build Status](https://travis-ci.org/atom/language-css.svg?branch=master)](https://travis-ci.org/atom/language-css) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/v8rvm88dxp73ko2y/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-css/branch/master)| [![Dependency Status](https://david-dm.org/atom/language-css.svg)](https://david-dm.org/atom/language-css) |
<del>| Git | [![OS X Build Status](https://travis-ci.org/atom/language-git.svg?branch=master)](https://travis-ci.org/atom/language-git) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/481319gyrr1feo8b/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-git/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-git.svg)](https://david-dm.org/atom/language-git) |
<del>| GitHub Flavored Markdown | [![OS X Build Status](https://travis-ci.org/atom/language-gfm.svg?branch=master)](https://travis-ci.org/atom/language-gfm) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/rpub8qjyd8lt7wai/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-gfm/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-gfm.svg)](https://david-dm.org/atom/language-gfm) |
<del>| Go | [![OS X Build Status](https://travis-ci.org/atom/language-go.svg?branch=master)](https://travis-ci.org/atom/language-go) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/3fxxvv05p4hv92pn/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-go/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-go.svg)](https://david-dm.org/atom/language-go) |
<del>| HTML | [![OS X Build Status](https://travis-ci.org/atom/language-html.svg?branch=master)](https://travis-ci.org/atom/language-html) | [![Windows Build status](https://ci.appveyor.com/api/projects/status/t6pk6mmdgcelfg85/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-html/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-html.svg)](https://david-dm.org/atom/language-html) |
<del>| Hyperlink | [![OS X Build Status](https://travis-ci.org/atom/language-hyperlink.svg?branch=master)](https://travis-ci.org/atom/language-hyperlink) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/5tgvhph394r684l8/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-hyperlink/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-hyperlink.svg)](https://david-dm.org/atom/language-hyperlink) |
<del>| Java | [![OS X Build Status](https://travis-ci.org/atom/language-java.svg?branch=master)](https://travis-ci.org/atom/language-java) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/utoftje56n9u5x4h/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-java/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-java.svg)](https://david-dm.org/atom/language-java) |
<del>| JavaScript | [![OS X Build Status](https://travis-ci.org/atom/language-javascript.svg?branch=master)](https://travis-ci.org/atom/language-javascript) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/ktooccwna96ssiyr/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-javascript-dijf8/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-javascript.svg)](https://david-dm.org/atom/language-javascript) |
<del>| JSON | [![OS X Build Status](https://travis-ci.org/atom/language-json.svg?branch=master)](https://travis-ci.org/atom/language-json) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/5rx05vhdikk6c4cl/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-json/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-json.svg)](https://david-dm.org/atom/language-json) |
<del>| Less | [![OS X Build Status](https://travis-ci.org/atom/language-less.svg?branch=master)](https://travis-ci.org/atom/language-less) | [![Windows Build Sstatus](https://ci.appveyor.com/api/projects/status/aeina4fr4b0i7yay/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-less/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-less.svg)](https://david-dm.org/atom/language-less) |
<del>| Make | [![OS X Build Status](https://travis-ci.org/atom/language-make.svg?branch=master)](https://travis-ci.org/atom/language-make) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/vq1aascey21wxjh7/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-make/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-make.svg)](https://david-dm.org/atom/language-make) |
<del>| Mustache | [![OS X Build Status](https://travis-ci.org/atom/language-mustache.svg?branch=master)](https://travis-ci.org/atom/language-mustache) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/mbxnxaojqp0g7ldv/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-mustache/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-mustache.svg)](https://david-dm.org/atom/language-mustache) |
<del>| Objective-C | [![OS X Build Status](https://travis-ci.org/atom/language-objective-c.svg?branch=master)](https://travis-ci.org/atom/language-objective-c) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/27j8vfv5u95fjhkw/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-objective-c/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-objective-c.svg)](https://david-dm.org/atom/language-objective-c) |
<del>| Perl | [![OS X Build Status](https://travis-ci.org/atom/language-perl.svg?branch=master)](https://travis-ci.org/atom/language-perl) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/dfs9inkkg40hchf8/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-perl/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-perl.svg)](https://david-dm.org/atom/language-perl) |
<del>| PHP | [![OS X Build Status](https://travis-ci.org/atom/language-php.svg?branch=master)](https://travis-ci.org/atom/language-php) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/y9h45ag4b72726jy/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-php/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-php.svg)](https://david-dm.org/atom/language-php) |
<del>| Python | [![OS X Build Status](https://travis-ci.org/atom/language-python.svg?branch=master)](https://travis-ci.org/atom/language-python) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/hmxrb9jttjh41es9/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-python/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-python.svg)](https://david-dm.org/atom/language-python) |
<del>| Ruby | [![OS X Build Status](https://travis-ci.org/atom/language-ruby.svg?branch=master)](https://travis-ci.org/atom/language-ruby) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/71as182rm1adf2br/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-ruby/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-ruby.svg)](https://david-dm.org/atom/language-ruby) |
<del>| Ruby on Rails | [![OS X Build Status](https://travis-ci.org/atom/language-ruby-on-rails.svg?branch=master)](https://travis-ci.org/atom/language-ruby-on-rails) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/5t4pa451fu5e0ghg/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-ruby-on-rails/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-ruby-on-rails.svg)](https://david-dm.org/atom/language-ruby-on-rails) |
<del>| Sass | [![OS X Build Status](https://travis-ci.org/atom/language-sass.svg?branch=master)](https://travis-ci.org/atom/language-sass) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/g7p16vainm4iuoot/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-sass/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-sass.svg)](https://david-dm.org/atom/language-sass) |
<del>| ShellScript | [![OS X Build Status](https://travis-ci.org/atom/language-shellscript.svg?branch=master)](https://travis-ci.org/atom/language-shellscript) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/p4um3lowgrg8y0ty/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-shellscript/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-shellscript.svg)](https://david-dm.org/atom/language-shellscript) |
<del>| SQL | [![OS X Build Status](https://travis-ci.org/atom/language-sql.svg?branch=master)](https://travis-ci.org/atom/language-sql) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/ji31ouk5ehs4jdu1/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-sql/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-sql.svg)](https://david-dm.org/atom/language-sql) |
<del>| TODO | [![OS X Build Status](https://travis-ci.org/atom/language-todo.svg?branch=master)](https://travis-ci.org/atom/language-todo) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/gcgb9m7h146lv6qp/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-todo/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-todo.svg)](https://david-dm.org/atom/language-todo) |
<del>| TOML | [![OS X Build Status](https://travis-ci.org/atom/language-toml.png?branch=master)](https://travis-ci.org/atom/language-toml) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/kohao3fjyk6xv0sc/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-toml/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-toml.svg)](https://david-dm.org/atom/language-toml) |
<del>| XML | [![OS X Build Status](https://travis-ci.org/atom/language-xml.png?branch=master)](https://travis-ci.org/atom/language-xml) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/m5f6rn74a6h3q5uq/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-xml/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-xml.svg)](https://david-dm.org/atom/language-xml) |
<del>| YAML | [![OS X Build Status](https://travis-ci.org/atom/language-yaml.svg?branch=master)](https://travis-ci.org/atom/language-yaml) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/eaa4ql7kipgphc2n/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-yaml/branch/master) | [![Dependency Status](https://david-dm.org/atom/language-yaml.svg)](https://david-dm.org/atom/language-yaml) |
<add>| AtomDoc | [![OS X Build Status](https://travis-ci.org/atom/atomdoc.svg?branch=master)](https://travis-ci.org/atom/atomdoc) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/chi2bmaafr3puyq2/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/atomdoc/branch/master) | [![Dependency Status](https://david-dm.org/atom/atomdoc.svg)](https://david-dm.org/atom/atomdoc)
<add>
<add>## Languages
<add>
<add>| Language | OS X | Windows |
<add>|----------|------|---------|
<add>| C/C++ | [![OS X Build Status](https://travis-ci.org/atom/language-c.svg?branch=master)](https://travis-ci.org/atom/language-c) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/8oy1hmp4yrij7c32/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-c/branch/master) |
<add>| C# | [![OS X Build Status](https://travis-ci.org/atom/language-csharp.svg?branch=master)](https://travis-ci.org/atom/language-csharp) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/j1as3753y5t90obn/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-csharp/branch/master) |
<add>| Clojure | [![OS X Build Status](https://travis-ci.org/atom/language-clojure.svg?branch=master)](https://travis-ci.org/atom/language-clojure) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/6kd5fs48y5hixde6/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-clojure/branch/master) |
<add>| CoffeeScript | [![OS X Build Status](https://travis-ci.org/atom/language-coffee-script.svg?branch=master)](https://travis-ci.org/atom/language-coffee-script) | [![Windows Build status](https://ci.appveyor.com/api/projects/status/4j9aak7iwn2f2x7a/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-coffee-script/branch/master) |
<add>| CSS | [![OS X Build Status](https://travis-ci.org/atom/language-css.svg?branch=master)](https://travis-ci.org/atom/language-css) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/v8rvm88dxp73ko2y/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-css/branch/master) |
<add>| Git | [![OS X Build Status](https://travis-ci.org/atom/language-git.svg?branch=master)](https://travis-ci.org/atom/language-git) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/481319gyrr1feo8b/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-git/branch/master) |
<add>| GitHub Flavored Markdown | [![OS X Build Status](https://travis-ci.org/atom/language-gfm.svg?branch=master)](https://travis-ci.org/atom/language-gfm) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/rpub8qjyd8lt7wai/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-gfm/branch/master) |
<add>| Go | [![OS X Build Status](https://travis-ci.org/atom/language-go.svg?branch=master)](https://travis-ci.org/atom/language-go) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/3fxxvv05p4hv92pn/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-go/branch/master) |
<add>| HTML | [![OS X Build Status](https://travis-ci.org/atom/language-html.svg?branch=master)](https://travis-ci.org/atom/language-html) | [![Windows Build status](https://ci.appveyor.com/api/projects/status/t6pk6mmdgcelfg85/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-html/branch/master) |
<add>| Hyperlink | [![OS X Build Status](https://travis-ci.org/atom/language-hyperlink.svg?branch=master)](https://travis-ci.org/atom/language-hyperlink) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/5tgvhph394r684l8/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-hyperlink/branch/master) |
<add>| Java | [![OS X Build Status](https://travis-ci.org/atom/language-java.svg?branch=master)](https://travis-ci.org/atom/language-java) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/utoftje56n9u5x4h/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-java/branch/master) |
<add>| JavaScript | [![OS X Build Status](https://travis-ci.org/atom/language-javascript.svg?branch=master)](https://travis-ci.org/atom/language-javascript) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/ktooccwna96ssiyr/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-javascript-dijf8/branch/master) |
<add>| JSON | [![OS X Build Status](https://travis-ci.org/atom/language-json.svg?branch=master)](https://travis-ci.org/atom/language-json) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/5rx05vhdikk6c4cl/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-json/branch/master) |
<add>| Less | [![OS X Build Status](https://travis-ci.org/atom/language-less.svg?branch=master)](https://travis-ci.org/atom/language-less) | [![Windows Build Sstatus](https://ci.appveyor.com/api/projects/status/aeina4fr4b0i7yay/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-less/branch/master) |
<add>| Make | [![OS X Build Status](https://travis-ci.org/atom/language-make.svg?branch=master)](https://travis-ci.org/atom/language-make) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/vq1aascey21wxjh7/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-make/branch/master) |
<add>| Mustache | [![OS X Build Status](https://travis-ci.org/atom/language-mustache.svg?branch=master)](https://travis-ci.org/atom/language-mustache) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/mbxnxaojqp0g7ldv/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-mustache/branch/master) |
<add>| Objective-C | [![OS X Build Status](https://travis-ci.org/atom/language-objective-c.svg?branch=master)](https://travis-ci.org/atom/language-objective-c) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/27j8vfv5u95fjhkw/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-objective-c/branch/master) |
<add>| Perl | [![OS X Build Status](https://travis-ci.org/atom/language-perl.svg?branch=master)](https://travis-ci.org/atom/language-perl) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/dfs9inkkg40hchf8/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-perl/branch/master) |
<add>| PHP | [![OS X Build Status](https://travis-ci.org/atom/language-php.svg?branch=master)](https://travis-ci.org/atom/language-php) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/y9h45ag4b72726jy/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-php/branch/master) |
<add>| Python | [![OS X Build Status](https://travis-ci.org/atom/language-python.svg?branch=master)](https://travis-ci.org/atom/language-python) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/hmxrb9jttjh41es9/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-python/branch/master) |
<add>| Ruby | [![OS X Build Status](https://travis-ci.org/atom/language-ruby.svg?branch=master)](https://travis-ci.org/atom/language-ruby) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/71as182rm1adf2br/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-ruby/branch/master) |
<add>| Ruby on Rails | [![OS X Build Status](https://travis-ci.org/atom/language-ruby-on-rails.svg?branch=master)](https://travis-ci.org/atom/language-ruby-on-rails) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/5t4pa451fu5e0ghg/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-ruby-on-rails/branch/master) |
<add>| Sass | [![OS X Build Status](https://travis-ci.org/atom/language-sass.svg?branch=master)](https://travis-ci.org/atom/language-sass) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/g7p16vainm4iuoot/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-sass/branch/master) |
<add>| ShellScript | [![OS X Build Status](https://travis-ci.org/atom/language-shellscript.svg?branch=master)](https://travis-ci.org/atom/language-shellscript) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/p4um3lowgrg8y0ty/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-shellscript/branch/master) |
<add>| SQL | [![OS X Build Status](https://travis-ci.org/atom/language-sql.svg?branch=master)](https://travis-ci.org/atom/language-sql) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/ji31ouk5ehs4jdu1/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-sql/branch/master) |
<add>| TODO | [![OS X Build Status](https://travis-ci.org/atom/language-todo.svg?branch=master)](https://travis-ci.org/atom/language-todo) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/gcgb9m7h146lv6qp/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-todo/branch/master) |
<add>| TOML | [![OS X Build Status](https://travis-ci.org/atom/language-toml.png?branch=master)](https://travis-ci.org/atom/language-toml) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/kohao3fjyk6xv0sc/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-toml/branch/master) |
<add>| XML | [![OS X Build Status](https://travis-ci.org/atom/language-xml.png?branch=master)](https://travis-ci.org/atom/language-xml) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/m5f6rn74a6h3q5uq/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-xml/branch/master) |
<add>| YAML | [![OS X Build Status](https://travis-ci.org/atom/language-yaml.svg?branch=master)](https://travis-ci.org/atom/language-yaml) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/eaa4ql7kipgphc2n/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-yaml/branch/master) | | 1 |
Javascript | Javascript | use `directconnect` locally to speed up tests | 56d456360bb5bae9b30623c6ef91a69e5b9b5aa1 | <ide><path>protractor-conf.js
<ide> config.capabilities = {
<ide> browserName: 'chrome'
<ide> };
<ide>
<add>config.directConnect = true;
<add>
<ide> exports.config = config; | 1 |
Text | Text | add v3.18.0-beta.4 to changelog | 5e90b4928186d8a14d346ecc56b41ff31aab7b79 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.18.0-beta.4 (March 31, 2020)
<add>
<add>- [#18837](https://github.com/emberjs/ember.js/pull/18837) [BUGFIX] Fix `willDestroy` on class helpers
<add>- [#18838](https://github.com/emberjs/ember.js/pull/18838) [BUGFIX] Ensure destructors (e.g. `will-destroy` modifier, `@ember/component`s with `willDestroyElement`, etc) fire when used within an `{{#each}}` block.
<add>
<ide> ### v3.18.0-beta.3 (March 23, 2020)
<ide>
<ide> - [#18831](https://github.com/emberjs/ember.js/pull/18831) [BUGFIX] Fix transpilation issues (e.g. `_createSuper` is not a function) when used with Babel 7.9.0+. | 1 |
Javascript | Javascript | introduce $cancelupdate to cancel pending updates | 940fcb4090e96824a4abc50252aa36aaf239e937 | <ide><path>src/ng/directive/input.js
<ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
<ide>
<ide> var ngModelGet = $parse($attr.ngModel),
<ide> ngModelSet = ngModelGet.assign,
<del> pendingDebounce = null;
<add> pendingDebounce = null,
<add> ctrl = this;
<ide>
<ide> if (!ngModelSet) {
<ide> throw minErr('ngModel')('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
<ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
<ide>
<ide> /**
<ide> * @ngdoc method
<del> * @name ngModel.NgModelController#$cancelDebounce
<add> * @name ngModel.NgModelController#$cancelUpdate
<ide> *
<ide> * @description
<del> * Cancel a pending debounced update.
<add> * Cancel an update and reset the input element's value to prevent an update to the `$viewValue`,
<add> * which may be caused by a pending debounced event or because the input is waiting for a some
<add> * future event.
<ide> *
<del> * This method should be called before directly update a debounced model from the scope in
<del> * order to prevent unintended future changes of the model value because of a delayed event.
<add> * If you have an input that uses `ng-model-options` to set up debounced events or events such
<add> * as blur you can have a situation where there is a period when the value of the input element
<add> * is out of synch with the ngModel's `$viewValue`. You can run into difficulties if you try to
<add> * update the ngModel's `$modelValue` programmatically before these debounced/future events have
<add> * completed, because Angular's dirty checking mechanism is not able to tell whether the model
<add> * has actually changed or not. This method should be called before directly updating a model
<add> * from the scope in case you have an input with `ng-model-options` that do not include immediate
<add> * update of the default trigger. This is important in order to make sure that this input field
<add> * will be updated with the new value and any pending operation will be canceled.
<ide> */
<del> this.$cancelDebounce = function() {
<del> if ( pendingDebounce ) {
<del> $timeout.cancel(pendingDebounce);
<del> pendingDebounce = null;
<del> }
<add> this.$cancelUpdate = function() {
<add> $timeout.cancel(pendingDebounce);
<add> this.$render();
<ide> };
<ide>
<ide> // update the view value
<ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
<ide> * @param {string} trigger Event that triggered the update.
<ide> */
<ide> this.$setViewValue = function(value, trigger) {
<del> var that = this;
<ide> var debounceDelay = this.$options && (isObject(this.$options.debounce)
<ide> ? (this.$options.debounce[trigger] || this.$options.debounce['default'] || 0)
<ide> : this.$options.debounce) || 0;
<ide>
<del> that.$cancelDebounce();
<del> if ( debounceDelay ) {
<add> $timeout.cancel(pendingDebounce);
<add> if (debounceDelay) {
<ide> pendingDebounce = $timeout(function() {
<del> pendingDebounce = null;
<del> that.$$realSetViewValue(value);
<add> ctrl.$$realSetViewValue(value);
<ide> }, debounceDelay);
<ide> } else {
<del> that.$$realSetViewValue(value);
<add> this.$$realSetViewValue(value);
<ide> }
<ide> };
<ide>
<ide> // model -> value
<del> var ctrl = this;
<del>
<ide> $scope.$watch(function ngModelWatch() {
<ide> var value = ngModelGet($scope);
<ide>
<ide> var ngModelOptionsDirective = function() {
<ide> }
<ide> }]
<ide> };
<del>};
<ide>\ No newline at end of file
<add>};
<ide><path>test/ng/directive/inputSpec.js
<ide> describe('input', function() {
<ide> dealoc(doc);
<ide> }));
<ide>
<del>
<del> it('should allow cancelling pending updates', inject(function($timeout) {
<add> it('should allow canceling pending updates', inject(function($timeout) {
<ide> compileInput(
<del> '<form name="test">'+
<del> '<input type="text" ng-model="name" name="alias" '+
<del> 'ng-model-options="{ debounce: 10000 }" />'+
<del> '</form>');
<add> '<input type="text" ng-model="name" name="alias" '+
<add> 'ng-model-options="{ debounce: 10000 }" />');
<add>
<ide> changeInputValueTo('a');
<ide> expect(scope.name).toEqual(undefined);
<ide> $timeout.flush(2000);
<del> scope.test.alias.$cancelDebounce();
<add> scope.form.alias.$cancelUpdate();
<ide> expect(scope.name).toEqual(undefined);
<ide> $timeout.flush(10000);
<ide> expect(scope.name).toEqual(undefined);
<ide> }));
<ide>
<add> it('should reset input val if cancelUpdate called during pending update', function() {
<add> compileInput(
<add> '<input type="text" ng-model="name" name="alias" '+
<add> 'ng-model-options="{ updateOn: \'blur\' }" />');
<add> scope.$digest();
<add>
<add> changeInputValueTo('a');
<add> expect(inputElm.val()).toBe('a');
<add> scope.form.alias.$cancelUpdate();
<add> expect(inputElm.val()).toBe('');
<add> browserTrigger(inputElm, 'blur');
<add> expect(inputElm.val()).toBe('');
<add> });
<add>
<add> it('should reset input val if cancelUpdate called during debounce', inject(function($timeout) {
<add> compileInput(
<add> '<input type="text" ng-model="name" name="alias" '+
<add> 'ng-model-options="{ debounce: 2000 }" />');
<add> scope.$digest();
<add>
<add> changeInputValueTo('a');
<add> expect(inputElm.val()).toBe('a');
<add> scope.form.alias.$cancelUpdate();
<add> expect(inputElm.val()).toBe('');
<add> $timeout.flush(3000);
<add> expect(inputElm.val()).toBe('');
<add> }));
<add>
<ide> });
<ide>
<ide> it('should allow complex reference binding', function() { | 2 |
Javascript | Javascript | incorporate line3 into plane | 3c5986bf7996a00c91378337c6b528012e4955dd | <ide><path>src/math/Plane.js
<ide> THREE.extend( THREE.Plane.prototype, {
<ide>
<ide> },
<ide>
<del> isIntersectionLine: function ( startPoint, endPoint ) {
<add> isIntersectionLine: function ( line ) {
<ide>
<ide> // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
<ide>
<del> var startSign = this.distanceToPoint( startPoint );
<del> var endSign = this.distanceToPoint( endPoint );
<add> var startSign = this.distanceToPoint( line.start );
<add> var endSign = this.distanceToPoint( line.end );
<ide>
<ide> return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
<ide>
<ide> THREE.extend( THREE.Plane.prototype, {
<ide>
<ide> var v1 = new THREE.Vector3();
<ide>
<del> return function ( startPoint, endPoint, optionalTarget ) {
<add> return function ( line, optionalTarget ) {
<ide>
<ide> var result = optionalTarget || new THREE.Vector3();
<ide>
<del> var direction = v1.subVectors( endPoint, startPoint );
<add> var direction = line.delta( v1 );
<ide>
<ide> var denominator = this.normal.dot( direction );
<ide>
<ide> if ( denominator == 0 ) {
<ide>
<ide> // line is coplanar, return origin
<del> if( this.distanceToPoint( startPoint ) == 0 ) {
<add> if( this.distanceToPoint( line.start ) == 0 ) {
<ide>
<del> return result.copy( startPoint );
<add> return result.copy( line.start );
<ide>
<ide> }
<ide>
<ide> THREE.extend( THREE.Plane.prototype, {
<ide>
<ide> }
<ide>
<del> var t = - ( startPoint.dot( this.normal ) + this.constant ) / denominator;
<add> var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
<ide>
<ide> if( t < 0 || t > 1 ) {
<ide>
<ide> return undefined;
<ide>
<ide> }
<ide>
<del> return result.copy( direction ).multiplyScalar( t ).add( startPoint );
<add> return result.copy( direction ).multiplyScalar( t ).add( line.start );
<ide>
<ide> };
<ide>
<ide><path>test/unit/math/Plane.js
<ide> test( "distanceToSphere", function() {
<ide> test( "isInterestionLine/intersectLine", function() {
<ide> var a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), 0 );
<ide>
<del> ok( a.isIntersectionLine( new THREE.Vector3( -10, 0, 0 ), new THREE.Vector3( 10, 0, 0 ) ), "Passed!" );
<del> ok( a.intersectLine( new THREE.Vector3( -10, 0, 0 ), new THREE.Vector3( 10, 0, 0 ) ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" );
<add> var l1 = new THREE.Line3( new THREE.Vector3( -10, 0, 0 ), new THREE.Vector3( 10, 0, 0 ) );
<add> ok( a.isIntersectionLine( l1 ), "Passed!" );
<add> ok( a.intersectLine( l1 ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" );
<ide>
<ide> a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), -3 );
<ide>
<del> ok( a.isIntersectionLine( new THREE.Vector3( -10, 0, 0 ), new THREE.Vector3( 10, 0, 0 ) ), "Passed!" );
<del> ok( a.intersectLine( new THREE.Vector3( -10, 0, 0 ), new THREE.Vector3( 10, 0, 0 ) ).equals( new THREE.Vector3( 3, 0, 0 ) ), "Passed!" );
<add> ok( a.isIntersectionLine( l1 ), "Passed!" );
<add> ok( a.intersectLine( l1 ).equals( new THREE.Vector3( 3, 0, 0 ) ), "Passed!" );
<ide>
<ide>
<ide> a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), -11 );
<ide>
<del> ok( ! a.isIntersectionLine( new THREE.Vector3( -10, 0, 0 ), new THREE.Vector3( 10, 0, 0 ) ), "Passed!" );
<del> ok( a.intersectLine( new THREE.Vector3( -10, 0, 0 ), new THREE.Vector3( 10, 0, 0 ) ) === undefined, "Passed!" );
<add> ok( ! a.isIntersectionLine( l1 ), "Passed!" );
<add> ok( a.intersectLine( l1 ) === undefined, "Passed!" );
<ide>
<ide> a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), 11 );
<ide>
<del> ok( ! a.isIntersectionLine( new THREE.Vector3( -10, 0, 0 ), new THREE.Vector3( 10, 0, 0 ) ), "Passed!" );
<del> ok( a.intersectLine( new THREE.Vector3( -10, 0, 0 ), new THREE.Vector3( 10, 0, 0 ) ) === undefined, "Passed!" );
<add> ok( ! a.isIntersectionLine( l1 ), "Passed!" );
<add> ok( a.intersectLine( l1 ) === undefined, "Passed!" );
<ide>
<ide> });
<ide> | 2 |
Javascript | Javascript | fix typo in description | 6518369f25ba72abf3e0fe6ef34a3ae1034e0088 | <ide><path>src/ng/directive/ngClass.js
<ide> function classDirective(name, selector) {
<ide> *
<ide> * The directive won't add duplicate classes if a particular class was already set.
<ide> *
<del> * When the expression changes, the previously added classes are removed and only then the classes
<add> * When the expression changes, the previously added classes are removed and only then the
<ide> * new classes are added.
<ide> *
<ide> * @element ANY | 1 |
Ruby | Ruby | remove some evals from formula dsl | 28fa5b0261b3efef222e8f92f5b3906cccfeb388 | <ide><path>Library/Homebrew/formula.rb
<ide> def mirror val
<ide> stable.mirror(val)
<ide> end
<ide>
<del> Checksum::TYPES.each do |cksum|
<del> class_eval <<-EOS, __FILE__, __LINE__ + 1
<del> def #{cksum}(val)
<del> stable.#{cksum}(val)
<del> end
<del> EOS
<add> Checksum::TYPES.each do |type|
<add> define_method(type) { |val| stable.send(type, val) }
<ide> end
<ide>
<ide> def bottle *, &block
<ide><path>Library/Homebrew/resource.rb
<ide> def verify_download_integrity fn
<ide> puts "For your reference the SHA1 is: #{fn.sha1}"
<ide> end
<ide>
<del> Checksum::TYPES.each do |cksum|
<del> class_eval <<-EOS, __FILE__, __LINE__ + 1
<del> def #{cksum}(val)
<del> @checksum = Checksum.new(:#{cksum}, val)
<del> end
<del> EOS
<add> Checksum::TYPES.each do |type|
<add> define_method(type) { |val| @checksum = Checksum.new(type, val) }
<ide> end
<ide>
<ide> def url val=nil, specs={} | 2 |
Python | Python | add more tests for `from_dict()` variants | 56acb7b22be559255e3e481851a8125726cbb4a9 | <ide><path>t/integration/tasks.py
<ide> from time import sleep
<ide>
<del>from celery import Task, chain, chord, group, shared_task
<add>from celery import Signature, Task, chain, chord, group, shared_task
<ide> from celery.exceptions import SoftTimeLimitExceeded
<ide> from celery.utils.log import get_task_logger
<ide>
<ide> def run(self):
<ide> if self.request.retries:
<ide> return self.request.retries
<ide> raise ValueError()
<add>
<add>
<add># The signatures returned by these tasks wouldn't actually run because the
<add># arguments wouldn't be fulfilled - we never actually delay them so it's fine
<add>@shared_task
<add>def return_nested_signature_chain_chain():
<add> return chain(chain([add.s()]))
<add>
<add>
<add>@shared_task
<add>def return_nested_signature_chain_group():
<add> return chain(group([add.s()]))
<add>
<add>
<add>@shared_task
<add>def return_nested_signature_chain_chord():
<add> return chain(chord([add.s()], add.s()))
<add>
<add>
<add>@shared_task
<add>def return_nested_signature_group_chain():
<add> return group(chain([add.s()]))
<add>
<add>
<add>@shared_task
<add>def return_nested_signature_group_group():
<add> return group(group([add.s()]))
<add>
<add>
<add>@shared_task
<add>def return_nested_signature_group_chord():
<add> return group(chord([add.s()], add.s()))
<add>
<add>
<add>@shared_task
<add>def return_nested_signature_chord_chain():
<add> return chord(chain([add.s()]), add.s())
<add>
<add>
<add>@shared_task
<add>def return_nested_signature_chord_group():
<add> return chord(group([add.s()]), add.s())
<add>
<add>
<add>@shared_task
<add>def return_nested_signature_chord_chord():
<add> return chord(chord([add.s()], add.s()), add.s())
<add>
<add>
<add>@shared_task
<add>def rebuild_signature(sig_dict):
<add> sig_obj = Signature.from_dict(sig_dict)
<add>
<add> def _recurse(sig):
<add> if not isinstance(sig, Signature):
<add> raise TypeError("{!r} is not a signature object".format(sig))
<add> # Most canvas types have a `tasks` attribute
<add> if isinstance(sig, (chain, group, chord)):
<add> for task in sig.tasks:
<add> _recurse(task)
<add> # `chord`s also have a `body` attribute
<add> if isinstance(sig, chord):
<add> _recurse(sig.body)
<add> _recurse(sig_obj)
<ide><path>t/integration/test_canvas.py
<ide> from celery.exceptions import TimeoutError
<ide> from celery.result import AsyncResult, GroupResult, ResultSet
<ide>
<add>from . import tasks
<ide> from .conftest import get_active_redis_channels, get_redis_connection
<ide> from .tasks import (ExpectedException, add, add_chord_to_chord, add_replaced,
<ide> add_to_all, add_to_all_to_chord, build_chain_inside_task,
<ide> def test_nested_chord_group_chain_group_tail(self, manager):
<ide> )
<ide> res = sig.delay()
<ide> assert res.get(timeout=TIMEOUT) == [[42, 42]]
<add>
<add>
<add>class test_signature_serialization:
<add> """
<add> Confirm nested signatures can be rebuilt after passing through a backend.
<add>
<add> These tests are expected to finish and return `None` or raise an exception
<add> in the error case. The exception indicates that some element of a nested
<add> signature object was not properly deserialized from its dictionary
<add> representation, and would explode later on if it were used as a signature.
<add> """
<add> def test_rebuild_nested_chain_chain(self, manager):
<add> sig = chain(
<add> tasks.return_nested_signature_chain_chain.s(),
<add> tasks.rebuild_signature.s()
<add> )
<add> sig.delay().get(timeout=TIMEOUT)
<add>
<add> def test_rebuild_nested_chain_group(self, manager):
<add> sig = chain(
<add> tasks.return_nested_signature_chain_group.s(),
<add> tasks.rebuild_signature.s()
<add> )
<add> sig.delay().get(timeout=TIMEOUT)
<add>
<add> def test_rebuild_nested_chain_chord(self, manager):
<add> try:
<add> manager.app.backend.ensure_chords_allowed()
<add> except NotImplementedError as e:
<add> raise pytest.skip(e.args[0])
<add>
<add> sig = chain(
<add> tasks.return_nested_signature_chain_chord.s(),
<add> tasks.rebuild_signature.s()
<add> )
<add> sig.delay().get(timeout=TIMEOUT)
<add>
<add> @pytest.mark.xfail(reason="#6341")
<add> def test_rebuild_nested_group_chain(self, manager):
<add> sig = chain(
<add> tasks.return_nested_signature_group_chain.s(),
<add> tasks.rebuild_signature.s()
<add> )
<add> sig.delay().get(timeout=TIMEOUT)
<add>
<add> @pytest.mark.xfail(reason="#6341")
<add> def test_rebuild_nested_group_group(self, manager):
<add> sig = chain(
<add> tasks.return_nested_signature_group_group.s(),
<add> tasks.rebuild_signature.s()
<add> )
<add> sig.delay().get(timeout=TIMEOUT)
<add>
<add> @pytest.mark.xfail(reason="#6341")
<add> def test_rebuild_nested_group_chord(self, manager):
<add> try:
<add> manager.app.backend.ensure_chords_allowed()
<add> except NotImplementedError as e:
<add> raise pytest.skip(e.args[0])
<add>
<add> sig = chain(
<add> tasks.return_nested_signature_group_chord.s(),
<add> tasks.rebuild_signature.s()
<add> )
<add> sig.delay().get(timeout=TIMEOUT)
<add>
<add> def test_rebuild_nested_chord_chain(self, manager):
<add> try:
<add> manager.app.backend.ensure_chords_allowed()
<add> except NotImplementedError as e:
<add> raise pytest.skip(e.args[0])
<add>
<add> sig = chain(
<add> tasks.return_nested_signature_chord_chain.s(),
<add> tasks.rebuild_signature.s()
<add> )
<add> sig.delay().get(timeout=TIMEOUT)
<add>
<add> def test_rebuild_nested_chord_group(self, manager):
<add> try:
<add> manager.app.backend.ensure_chords_allowed()
<add> except NotImplementedError as e:
<add> raise pytest.skip(e.args[0])
<add>
<add> sig = chain(
<add> tasks.return_nested_signature_chord_group.s(),
<add> tasks.rebuild_signature.s()
<add> )
<add> sig.delay().get(timeout=TIMEOUT)
<add>
<add> def test_rebuild_nested_chord_chord(self, manager):
<add> try:
<add> manager.app.backend.ensure_chords_allowed()
<add> except NotImplementedError as e:
<add> raise pytest.skip(e.args[0])
<add>
<add> sig = chain(
<add> tasks.return_nested_signature_chord_chord.s(),
<add> tasks.rebuild_signature.s()
<add> )
<add> sig.delay().get(timeout=TIMEOUT)
<ide><path>t/unit/tasks/test_canvas.py
<ide> def test_from_dict(self):
<ide> x['args'] = None
<ide> assert group.from_dict(dict(x))
<ide>
<add> @pytest.mark.xfail(reason="#6341")
<add> def test_from_dict_deep_deserialize(self):
<add> original_group = group([self.add.s(1, 2)] * 42)
<add> serialized_group = json.loads(json.dumps(original_group))
<add> deserialized_group = group.from_dict(serialized_group)
<add> assert all(
<add> isinstance(child_task, Signature)
<add> for child_task in deserialized_group.tasks
<add> )
<add>
<add> @pytest.mark.xfail(reason="#6341")
<add> def test_from_dict_deeper_deserialize(self):
<add> inner_group = group([self.add.s(1, 2)] * 42)
<add> outer_group = group([inner_group] * 42)
<add> serialized_group = json.loads(json.dumps(outer_group))
<add> deserialized_group = group.from_dict(serialized_group)
<add> assert all(
<add> isinstance(child_task, Signature)
<add> for child_task in deserialized_group.tasks
<add> )
<add> assert all(
<add> isinstance(grandchild_task, Signature)
<add> for child_task in deserialized_group.tasks
<add> for grandchild_task in child_task.tasks
<add> )
<add>
<ide> def test_call_empty_group(self):
<ide> x = group(app=self.app)
<ide> assert not len(x())
<ide> def chord_add():
<ide> _state.task_join_will_block = fixture_task_join_will_block
<ide> result.task_join_will_block = fixture_task_join_will_block
<ide>
<add> def test_from_dict(self):
<add> header = self.add.s(1, 2)
<add> original_chord = chord(header=header)
<add> rebuilt_chord = chord.from_dict(dict(original_chord))
<add> assert isinstance(rebuilt_chord, chord)
<add>
<add> def test_from_dict_with_body(self):
<add> header = body = self.add.s(1, 2)
<add> original_chord = chord(header=header, body=body)
<add> rebuilt_chord = chord.from_dict(dict(original_chord))
<add> assert isinstance(rebuilt_chord, chord)
<add>
<add> def test_from_dict_deep_deserialize(self, subtests):
<add> header = body = self.add.s(1, 2)
<add> original_chord = chord(header=header, body=body)
<add> serialized_chord = json.loads(json.dumps(original_chord))
<add> deserialized_chord = chord.from_dict(serialized_chord)
<add> with subtests.test(msg="Verify chord is deserialized"):
<add> assert isinstance(deserialized_chord, chord)
<add> with subtests.test(msg="Validate chord header tasks is deserialized"):
<add> assert all(
<add> isinstance(child_task, Signature)
<add> for child_task in deserialized_chord.tasks
<add> )
<add> with subtests.test(msg="Verify chord body is deserialized"):
<add> assert isinstance(deserialized_chord.body, Signature)
<add>
<add> @pytest.mark.xfail(reason="#6341")
<add> def test_from_dict_deep_deserialize_group(self, subtests):
<add> header = body = group([self.add.s(1, 2)] * 42)
<add> original_chord = chord(header=header, body=body)
<add> serialized_chord = json.loads(json.dumps(original_chord))
<add> deserialized_chord = chord.from_dict(serialized_chord)
<add> with subtests.test(msg="Verify chord is deserialized"):
<add> assert isinstance(deserialized_chord, chord)
<add> # A header which is a group gets unpacked into the chord's `tasks`
<add> with subtests.test(
<add> msg="Validate chord header tasks are deserialized and unpacked"
<add> ):
<add> assert all(
<add> isinstance(child_task, Signature)
<add> and not isinstance(child_task, group)
<add> for child_task in deserialized_chord.tasks
<add> )
<add> # A body which is a group remains as it we passed in
<add> with subtests.test(
<add> msg="Validate chord body is deserialized and not unpacked"
<add> ):
<add> assert isinstance(deserialized_chord.body, group)
<add> assert all(
<add> isinstance(body_child_task, Signature)
<add> for body_child_task in deserialized_chord.body.tasks
<add> )
<add>
<add> @pytest.mark.xfail(reason="#6341")
<add> def test_from_dict_deeper_deserialize_group(self, subtests):
<add> inner_group = group([self.add.s(1, 2)] * 42)
<add> header = body = group([inner_group] * 42)
<add> original_chord = chord(header=header, body=body)
<add> serialized_chord = json.loads(json.dumps(original_chord))
<add> deserialized_chord = chord.from_dict(serialized_chord)
<add> with subtests.test(msg="Verify chord is deserialized"):
<add> assert isinstance(deserialized_chord, chord)
<add> # A header which is a group gets unpacked into the chord's `tasks`
<add> with subtests.test(
<add> msg="Validate chord header tasks are deserialized and unpacked"
<add> ):
<add> assert all(
<add> isinstance(child_task, group)
<add> for child_task in deserialized_chord.tasks
<add> )
<add> assert all(
<add> isinstance(grandchild_task, Signature)
<add> for child_task in deserialized_chord.tasks
<add> for grandchild_task in child_task.tasks
<add> )
<add> # A body which is a group remains as it we passed in
<add> with subtests.test(
<add> msg="Validate chord body is deserialized and not unpacked"
<add> ):
<add> assert isinstance(deserialized_chord.body, group)
<add> assert all(
<add> isinstance(body_child_task, group)
<add> for body_child_task in deserialized_chord.body.tasks
<add> )
<add> assert all(
<add> isinstance(body_grandchild_task, Signature)
<add> for body_child_task in deserialized_chord.body.tasks
<add> for body_grandchild_task in body_child_task.tasks
<add> )
<add>
<add> def test_from_dict_deep_deserialize_chain(self, subtests):
<add> header = body = chain([self.add.s(1, 2)] * 42)
<add> original_chord = chord(header=header, body=body)
<add> serialized_chord = json.loads(json.dumps(original_chord))
<add> deserialized_chord = chord.from_dict(serialized_chord)
<add> with subtests.test(msg="Verify chord is deserialized"):
<add> assert isinstance(deserialized_chord, chord)
<add> # A header which is a chain gets unpacked into the chord's `tasks`
<add> with subtests.test(
<add> msg="Validate chord header tasks are deserialized and unpacked"
<add> ):
<add> assert all(
<add> isinstance(child_task, Signature)
<add> and not isinstance(child_task, chain)
<add> for child_task in deserialized_chord.tasks
<add> )
<add> # A body which is a chain gets mutatated into the hidden `_chain` class
<add> with subtests.test(
<add> msg="Validate chord body is deserialized and not unpacked"
<add> ):
<add> assert isinstance(deserialized_chord.body, _chain)
<add>
<ide>
<ide> class test_maybe_signature(CanvasCase):
<ide> | 3 |
Ruby | Ruby | add `old_checksums` helper function | ec841e7b6217e3038b2ca74c2c60084f1a0fd11f | <ide><path>Library/Homebrew/dev-cmd/bottle.rb
<ide> def merge(args:)
<ide> bottle.sha256 tag_hash["sha256"] => tag.to_sym
<ide> end
<ide>
<del> output = bottle_output bottle
<del>
<ide> if args.write?
<ide> path = Pathname.new((HOMEBREW_REPOSITORY/bottle_hash["formula"]["path"]).to_s)
<del> update_or_add = T.let(nil, T.nilable(String))
<add> checksums = old_checksums(path, bottle_hash, args: args)
<add> update_or_add = checksums.nil? ? "add" : "update"
<add>
<add> checksums&.each(&bottle.method(:sha256))
<add> output = bottle_output(bottle)
<add> puts output
<ide>
<ide> Utils::Inreplace.inreplace(path) do |s|
<ide> formula_contents = s.inreplace_string
<del> bottle_node = Utils::AST.bottle_block(formula_contents)
<del> if bottle_node.present?
<del> update_or_add = "update"
<del> if args.keep_old?
<del> old_keys = Utils::AST.body_children(bottle_node.body).map(&:method_name)
<del> old_bottle_spec = Formulary.factory(path).bottle_specification
<del> mismatches, checksums = merge_bottle_spec(old_keys, old_bottle_spec, bottle_hash["bottle"])
<del> if mismatches.present?
<del> odie <<~EOS
<del> --keep-old was passed but there are changes in:
<del> #{mismatches.join("\n")}
<del> EOS
<del> end
<del> checksums.each { |cksum| bottle.sha256(cksum) }
<del> output = bottle_output bottle
<del> end
<del> puts output
<add> case update_or_add
<add> when "update"
<ide> Utils::AST.replace_bottle_stanza!(formula_contents, output)
<del> else
<del> odie "--keep-old was passed but there was no existing bottle block!" if args.keep_old?
<del> puts output
<del> update_or_add = "add"
<add> when "add"
<ide> Utils::AST.add_bottle_stanza!(formula_contents, output)
<ide> end
<ide> end
<ide> def merge(args:)
<ide> end
<ide> end
<ide> else
<del> puts output
<add> puts bottle_output(bottle)
<ide> end
<ide> end
<ide> end
<ide> def merge_bottle_spec(old_keys, old_bottle_spec, new_bottle_hash)
<ide> mismatches << "#{key}: old: #{old_value.inspect}, new: #{new_value.inspect}"
<ide> end
<ide>
<del> return [mismatches, checksums] unless old_keys.include? :sha256
<add> return [mismatches, checksums] if old_keys.exclude? :sha256
<ide>
<ide> old_bottle_spec.collector.each_key do |tag|
<ide> old_value = old_bottle_spec.collector[tag].hexdigest
<ide> def merge_bottle_spec(old_keys, old_bottle_spec, new_bottle_hash)
<ide>
<ide> [mismatches, checksums]
<ide> end
<add>
<add> def old_checksums(formula_path, bottle_hash, args:)
<add> bottle_node = Utils::AST.bottle_block(formula_path.read)
<add> if bottle_node.nil?
<add> odie "--keep-old was passed but there was no existing bottle block!" if args.keep_old?
<add> return
<add> end
<add> return [] unless args.keep_old?
<add>
<add> old_keys = Utils::AST.body_children(bottle_node.body).map(&:method_name)
<add> old_bottle_spec = Formulary.factory(formula_path).bottle_specification
<add> mismatches, checksums = merge_bottle_spec(old_keys, old_bottle_spec, bottle_hash["bottle"])
<add> if mismatches.present?
<add> odie <<~EOS
<add> --keep-old was passed but there are changes in:
<add> #{mismatches.join("\n")}
<add> EOS
<add> end
<add> checksums
<add> end
<ide> end | 1 |
Python | Python | fix initialization of batchnormalization | d9ca798c60641a0ed5eea22e45be95054157af0d | <ide><path>keras/layers/normalization.py
<ide> class BatchNormalization(Layer):
<ide> weights: Initialization weights.
<ide> List of 2 numpy arrays, with shapes:
<ide> `[(input_shape,), (input_shape,)]`
<del>
<add> beta_init: name of initialization function for shift parameter
<add> (see [initializations](../initializations.md)), or alternatively,
<add> Theano function to use for weights initialization. This parameter
<add> is only relevant if you don't pass a `weights` argument.
<add> gamma_init: name of initialization function for scale parameter (see
<add> [initializations](../initializations.md)), or alternatively, Theano
<add> function to use for weights initialization. This parameter is only
<add> relevant if you don't pass a `weights` argument.
<ide> # References
<ide> - [Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift](http://arxiv.org/pdf/1502.03167v3.pdf)
<ide> '''
<ide> def __init__(self, epsilon=1e-6, mode=0, axis=-1, momentum=0.9,
<del> weights=None, **kwargs):
<del> self.init = initializations.get("uniform")
<add> weights=None, beta_init="zero", gamma_init="one", **kwargs):
<add> self.beta_init = initializations.get(beta_init)
<add> self.gamma_init = initializations.get(gamma_init)
<ide> self.epsilon = epsilon
<ide> self.mode = mode
<ide> self.axis = axis
<ide> def build(self):
<ide> input_shape = self.input_shape # starts with samples axis
<ide> shape = (input_shape[self.axis],)
<ide>
<del> self.gamma = self.init(shape,
<del> name='{}_gamma'.format(self.name))
<del> self.beta = K.zeros(shape, name='{}_beta'.format(self.name))
<add> self.gamma = self.gamma_init(shape, name='{}_gamma'.format(self.name))
<add> self.beta = self.beta_init(shape, name='{}_beta'.format(self.name))
<ide> self.trainable_weights = [self.gamma, self.beta]
<ide>
<ide> self.running_mean = K.zeros(shape, | 1 |
Go | Go | normalize comment formatting | c9b2a3cff51a6403f4eac319af5a794b0dbdeba4 | <ide><path>api/server/router/container/container_routes.go
<ide> func (s *containerRouter) postCommit(ctx context.Context, w http.ResponseWriter,
<ide> }
<ide>
<ide> config, _, _, err := s.decoder.DecodeConfig(r.Body)
<del> if err != nil && err != io.EOF { //Do not fail if body is empty.
<add> if err != nil && err != io.EOF { // Do not fail if body is empty.
<ide> return err
<ide> }
<ide>
<ide><path>api/server/router/image/image_routes.go
<ide> func (s *imageRouter) postImagesCreate(ctx context.Context, w http.ResponseWrite
<ide> }
<ide> }
<ide>
<del> if image != "" { //pull
<add> if image != "" { // pull
<ide> metaHeaders := map[string][]string{}
<ide> for k, v := range r.Header {
<ide> if strings.HasPrefix(k, "X-Meta-") {
<ide> func (s *imageRouter) postImagesCreate(ctx context.Context, w http.ResponseWrite
<ide> }
<ide> }
<ide> err = s.backend.PullImage(ctx, image, tag, platform, metaHeaders, authConfig, output)
<del> } else { //import
<add> } else { // import
<ide> src := r.Form.Get("fromSrc")
<ide> // 'err' MUST NOT be defined within this block, we need any error
<ide> // generated from the download to be available to the output
<ide><path>api/server/router/plugin/plugin_routes.go
<ide> func (pr *pluginRouter) createPlugin(ctx context.Context, w http.ResponseWriter,
<ide> if err := pr.backend.CreateFromContext(ctx, r.Body, options); err != nil {
<ide> return err
<ide> }
<del> //TODO: send progress bar
<add> // TODO: send progress bar
<ide> w.WriteHeader(http.StatusNoContent)
<ide> return nil
<ide> }
<ide><path>api/types/backend/backend.go
<ide> type ContainerAttachConfig struct {
<ide> // expectation is for the logger endpoints to assemble the chunks using this
<ide> // metadata.
<ide> type PartialLogMetaData struct {
<del> Last bool //true if this message is last of a partial
<add> Last bool // true if this message is last of a partial
<ide> ID string // identifies group of messages comprising a single record
<ide> Ordinal int // ordering of message in partial group
<ide> }
<ide><path>api/types/client.go
<ide> type ImagePullOptions struct {
<ide> // if the privilege request fails.
<ide> type RequestPrivilegeFunc func() (string, error)
<ide>
<del>//ImagePushOptions holds information to push images.
<add>// ImagePushOptions holds information to push images.
<ide> type ImagePushOptions ImagePullOptions
<ide>
<ide> // ImageRemoveOptions holds parameters to remove images.
<ide><path>api/types/container/host_config.go
<ide> func (n NetworkMode) ConnectedContainer() string {
<ide> return ""
<ide> }
<ide>
<del>//UserDefined indicates user-created network
<add>// UserDefined indicates user-created network
<ide> func (n NetworkMode) UserDefined() string {
<ide> if n.IsUserDefined() {
<ide> return string(n)
<ide><path>api/types/filters/parse.go
<ide> func (args Args) Len() int {
<ide> func (args Args) MatchKVList(key string, sources map[string]string) bool {
<ide> fieldValues := args.fields[key]
<ide>
<del> //do not filter if there is no filter set or cannot determine filter
<add> // do not filter if there is no filter set or cannot determine filter
<ide> if len(fieldValues) == 0 {
<ide> return true
<ide> }
<ide> func (args Args) Match(field, source string) bool {
<ide> // ExactMatch returns true if the source matches exactly one of the values.
<ide> func (args Args) ExactMatch(key, source string) bool {
<ide> fieldValues, ok := args.fields[key]
<del> //do not filter if there is no filter set or cannot determine filter
<add> // do not filter if there is no filter set or cannot determine filter
<ide> if !ok || len(fieldValues) == 0 {
<ide> return true
<ide> }
<ide> func (args Args) ExactMatch(key, source string) bool {
<ide> // matches exactly the value.
<ide> func (args Args) UniqueExactMatch(key, source string) bool {
<ide> fieldValues := args.fields[key]
<del> //do not filter if there is no filter set or cannot determine filter
<add> // do not filter if there is no filter set or cannot determine filter
<ide> if len(fieldValues) == 0 {
<ide> return true
<ide> }
<ide><path>api/types/network/network.go
<ide> type Address struct {
<ide> // IPAM represents IP Address Management
<ide> type IPAM struct {
<ide> Driver string
<del> Options map[string]string //Per network IPAM driver options
<add> Options map[string]string // Per network IPAM driver options
<ide> Config []IPAMConfig
<ide> }
<ide> | 8 |
Python | Python | provide none as default value for layer names | 5824f2eb99b6aa955fb568c564a741af711d64f7 | <ide><path>keras/layers/core.py
<ide> def get_output(self, train=False):
<ide> inputs = OrderedDict()
<ide> for i in range(len(self.layers)):
<ide> X = self.layers[i].get_output(train)
<del> name = getattr(self.layers[i], 'name')
<add> name = getattr(self.layers[i], 'name', None)
<ide> if name is None:
<ide> raise ValueError('merge_mode="join" only works with named inputs.')
<ide> else:
<ide> def get_output_join(self, train=False):
<ide> o = OrderedDict()
<ide> for i in range(len(self.inputs)):
<ide> X = self.get_output_at(i, train)
<del> name = getattr(self.inputs[i], 'name')
<add> name = getattr(self.inputs[i], 'name', None)
<ide> if name is None:
<ide> raise ValueError('merge_mode="join" '
<ide> 'only works with named inputs.') | 1 |
Text | Text | fix url_helper examples in testing guide [ci skip] | e7ba10b9a913b6e3d1e0f311d12eafa981824bbf | <ide><path>guides/source/testing.md
<ide> The `get` method kicks off the web request and populates the results into the `@
<ide>
<ide> All of these keyword arguments are optional.
<ide>
<del>Example: Calling the `:show` action, passing an `id` of 12 as the `params` and setting `HTTP_REFERER` header:
<add>Example: Calling the `:show` action for the first `Article`, passing in an `HTTP_REFERER` header:
<ide>
<ide> ```ruby
<del>get article_url, params: { id: 12 }, headers: { "HTTP_REFERER" => "http://example.com/home" }
<add>get article_url(Article.first), headers: { "HTTP_REFERER" => "http://example.com/home" }
<ide> ```
<ide>
<del>Another example: Calling the `:update` action, passing an `id` of 12 as the `params` as an Ajax request.
<add>Another example: Calling the `:update` action for the last `Article`, passing in new text for the `title` in `params`, as an Ajax request:
<ide>
<ide> ```ruby
<del>patch article_url, params: { id: 12 }, xhr: true
<add>patch article_url(Article.last), params: { article: { title: "updated" } }, xhr: true
<ide> ```
<ide>
<ide> NOTE: If you try running `test_should_create_article` test from `articles_controller_test.rb` it will fail on account of the newly added model level validation and rightly so. | 1 |
PHP | PHP | fix return type of error() | 86c0fa0212cb1f9ee80a568009189c399801dc8c | <ide><path>src/View/Form/ArrayContext.php
<ide> public function hasError($field) {
<ide> * Get the errors for a given field
<ide> *
<ide> * @param string $field A dot separated path to check errors on.
<del> * @return mixed Either a string or an array of errors. Null
<del> * will be returned when the field path is undefined.
<add> * @return array An array of errors, an empty array will be returned when the
<add> * context has no errors.
<ide> */
<ide> public function error($field) {
<ide> if (empty($this->_context['errors'])) {
<del> return null;
<add> return [];
<ide> }
<ide> return Hash::get($this->_context['errors'], $field);
<ide> }
<ide><path>src/View/Form/EntityContext.php
<ide> public function hasError($field) {
<ide> return !empty($errors);
<ide> }
<ide>
<del>
<ide> /**
<ide> * Get the errors for a given field
<ide> *
<ide> * @param string $field A dot separated path to check errors on.
<del> * @return array|null Either an array of errors. Null will be returned when the
<del> * field path is undefined or there is no error.
<add> * @return array An array of errors.
<ide> */
<ide> public function error($field) {
<ide> $parts = explode('.', $field);
<ide> list($entity, $prop) = $this->_getEntity($parts);
<ide> if (!$entity) {
<del> return false;
<add> return [];
<ide> }
<ide> return $entity->errors(array_pop($parts));
<ide> }
<ide><path>tests/TestCase/View/Form/ArrayContextTest.php
<ide> public function testAttributes() {
<ide> * @return void
<ide> */
<ide> public function testError() {
<add> $context = new ArrayContext($this->request, []);
<add> $this->assertEquals([], $context->error('Comments.empty'));
<add>
<ide> $context = new ArrayContext($this->request, [
<ide> 'errors' => [
<ide> 'Comments' => [ | 3 |
Ruby | Ruby | remove side effects from `normalize_format` | c10d7d16908c6858428331b3cdb056bd059aba63 | <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> def initialize(set, path, defaults, as, controller, default_action, modyoule, to
<ide> end
<ide>
<ide> requirements, conditions = split_constraints path_params, constraints
<del> @requirements = Hash[requirements]
<del> @conditions = Hash[conditions]
<add> formats = normalize_format(formatted)
<ide>
<del> normalize_format!(formatted)
<add> @requirements = formats[:requirements].merge Hash[requirements]
<add> @conditions = Hash[conditions]
<add> @defaults = formats[:defaults].merge @defaults
<ide>
<ide> @conditions[:required_defaults] = (split_options[:required_defaults] || []).map(&:first)
<ide> @conditions[:path_info] = path
<ide> def split_constraints(path_params, constraints)
<ide> end
<ide> end
<ide>
<del> def normalize_format!(formatted)
<add> def normalize_format(formatted)
<ide> case formatted
<ide> when true
<del> @requirements[:format] ||= /.+/
<add> { requirements: { format: /.+/ },
<add> defaults: {} }
<ide> when Regexp
<del> @requirements[:format] ||= formatted
<del> @defaults[:format] ||= nil
<add> { requirements: { format: formatted },
<add> defaults: { format: nil } }
<ide> when String
<del> @requirements[:format] ||= Regexp.compile(formatted)
<del> @defaults[:format] ||= formatted
<add> { requirements: { format: Regexp.compile(formatted) },
<add> defaults: { format: formatted } }
<add> else
<add> { requirements: { }, defaults: { } }
<ide> end
<ide> end
<ide> | 1 |
Javascript | Javascript | use fipsmode in test-crypto-fips | feebdc5bc5a44779069a2269f4d3f15d4e36a277 | <ide><path>test/parallel/test-crypto-fips.js
<add>// Flags: --expose-internals
<ide> 'use strict';
<ide> const common = require('../common');
<ide> if (!common.hasCrypto)
<ide> const assert = require('assert');
<ide> const spawnSync = require('child_process').spawnSync;
<ide> const path = require('path');
<ide> const fixtures = require('../common/fixtures');
<add>const { internalBinding } = require('internal/test/binding');
<add>const { fipsMode } = internalBinding('config');
<ide>
<ide> const FIPS_ENABLED = 1;
<ide> const FIPS_DISABLED = 0;
<ide> const CNF_FIPS_OFF = fixtures.path('openssl_fips_disabled.cnf');
<ide> let num_children_ok = 0;
<ide>
<ide> function compiledWithFips() {
<del> return process.config.variables.openssl_fips ? true : false;
<add> return fipsMode ? true : false;
<ide> }
<ide>
<ide> function sharedOpenSSL() { | 1 |
Javascript | Javascript | allow combination of -i and -e cli flags | ba16a120518e972bb3ac0190196fdb4caa32f4a6 | <ide><path>src/node.js
<ide> delete process.env.NODE_UNIQUE_ID;
<ide> }
<ide>
<del> if (process._eval != null) {
<del> // User passed '-e' or '--eval' arguments to Node.
<add> if (process._eval != null && !process._forceRepl) {
<add> // User passed '-e' or '--eval' arguments to Node without '-i' or
<add> // '--interactive'
<ide> startup.preloadModules();
<ide> evalScript('[eval]');
<ide> } else if (process.argv[1]) {
<ide> process.exit();
<ide> });
<ide> });
<add>
<add> if (process._eval != null) {
<add> // User passed '-e' or '--eval'
<add> evalScript('[eval]');
<add> }
<ide> } else {
<ide> // Read all of stdin - execute it.
<ide> process.stdin.setEncoding('utf8');
<ide><path>test/sequential/test-force-repl-with-eval.js
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const spawn = require('child_process').spawn;
<add>
<add>// spawn a node child process in "interactive" mode (force the repl) and eval
<add>const cp = spawn(process.execPath, ['-i', '-e', 'console.log("42")']);
<add>var gotToEnd = false;
<add>const timeoutId = setTimeout(function() {
<add> throw new Error('timeout!');
<add>}, common.platformTimeout(1000)); // give node + the repl 1 second to boot up
<add>
<add>cp.stdout.setEncoding('utf8');
<add>
<add>var output = '';
<add>cp.stdout.on('data', function(b) {
<add> output += b;
<add> if (output === '> 42\n') {
<add> clearTimeout(timeoutId);
<add> gotToEnd = true;
<add> cp.kill();
<add> }
<add>});
<add>
<add>process.on('exit', function() {
<add> assert(gotToEnd);
<add>}); | 2 |
Ruby | Ruby | add mavericks bottles | 0296ffa0efb7692470bbb8312e0b0fcdb61263dd | <ide><path>Library/Homebrew/test/test_formula.rb
<ide> def test_formula_spec_integration
<ide> sha1 'faceb00cfaceb00cfaceb00cfaceb00cfaceb00c' => :snow_leopard
<ide> sha1 'baadf00dbaadf00dbaadf00dbaadf00dbaadf00d' => :lion
<ide> sha1 '8badf00d8badf00d8badf00d8badf00d8badf00d' => :mountain_lion
<add> sha1 'deadf00ddeadf00ddeadf00ddeadf00ddeadf00d' => :mavericks
<ide> end
<ide>
<ide> def initialize(name="spec_test_ball", path=nil)
<ide><path>Library/Homebrew/test/test_formula_spec_selection.rb
<ide> def install_bottle?(*); true; end
<ide> :snow_leopard => 'faceb00c'*5,
<ide> :lion => 'baadf00d'*5,
<ide> :mountain_lion => '8badf00d'*5,
<add> :mavericks => 'deadf00d'*5
<ide> }.each_pair do |cat, val|
<ide> sha1(val => cat)
<ide> end | 2 |
Javascript | Javascript | verify validity of tty before using it | 014eef3c74f93e5b0bce82abc14557c46aa38c2a | <ide><path>packager/src/lib/terminal.js
<ide> function chunkString(str: string, size: number): Array<string> {
<ide> return str.match(new RegExp(`.{1,${size}}`, 'g')) || [];
<ide> }
<ide>
<add>/**
<add> * Get the stream as a TTY if it effectively looks like a valid TTY.
<add> */
<add>function getTTYStream(stream: net$Socket): ?tty.WriteStream {
<add> if (
<add> stream instanceof tty.WriteStream &&
<add> stream.isTTY &&
<add> stream.columns >= 1
<add> ) {
<add> return stream;
<add> }
<add> return null;
<add>}
<add>
<ide> /**
<ide> * We don't just print things to the console, sometimes we also want to show
<ide> * and update progress. This utility just ensures the output stays neat: no
<ide> class Terminal {
<ide> */
<ide> _update(): void {
<ide> const {_statusStr, _stream} = this;
<add> const ttyStream = getTTYStream(_stream);
<ide> if (_statusStr === this._nextStatusStr && this._logLines.length === 0) {
<ide> return;
<ide> }
<del> if (_stream instanceof tty.WriteStream) {
<del> clearStringBackwards(_stream, _statusStr);
<add> if (ttyStream != null) {
<add> clearStringBackwards(ttyStream, _statusStr);
<ide> }
<ide> this._logLines.forEach(line => {
<ide> _stream.write(line);
<ide> _stream.write('\n');
<ide> });
<ide> this._logLines = [];
<del> if (_stream instanceof tty.WriteStream) {
<del> this._nextStatusStr = chunkString(this._nextStatusStr, _stream.columns).join('\n');
<add> if (ttyStream != null) {
<add> this._nextStatusStr = chunkString(this._nextStatusStr, ttyStream.columns).join('\n');
<ide> _stream.write(this._nextStatusStr);
<ide> }
<ide> this._statusStr = this._nextStatusStr; | 1 |
Python | Python | specify range for numpy.angle | fc93cb3e5d5dcf50f95cfda088124768531456f4 | <ide><path>numpy/lib/function_base.py
<ide> def angle(z, deg=False):
<ide> Returns
<ide> -------
<ide> angle : ndarray or scalar
<del> The counterclockwise angle from the positive real axis on
<del> the complex plane, with dtype as numpy.float64.
<add> The counterclockwise angle from the positive real axis on the complex
<add> plane in the range ``(-pi, pi]``, with dtype as numpy.float64.
<ide>
<ide> ..versionchanged:: 1.16.0
<ide> This function works on subclasses of ndarray like `ma.array`. | 1 |
Javascript | Javascript | fix glimmer builds | 3ce73bb00126f20edb7f5cb9ceb6f1a69ae758bb | <ide><path>lib/packages.js
<ide> module.exports = function(features) {
<ide> trees: null,
<ide> templateCompilerOnly: true,
<ide> requirements: ['ember-metal', 'ember-environment', 'ember-console', 'ember-templates'],
<del> templateCompilerVendor: ['simple-html-tokenizer']
<add> templateCompilerVendor: ['simple-html-tokenizer', 'backburner']
<ide> },
<ide> 'ember-templates': { trees: null, requirements: ['ember-metal', 'ember-environment'] },
<ide> 'ember-routing': { trees: null, vendorRequirements: ['router', 'route-recognizer'],
<ide> module.exports = function(features) {
<ide> templateCompilerOnly: true,
<ide> requirements: [],
<ide> vendorRequirements: ['htmlbars-runtime'],
<del> templateCompilerVendor: ['htmlbars-runtime', 'htmlbars-util', 'htmlbars-compiler', 'htmlbars-syntax', 'htmlbars-test-helpers', 'morph-range', 'backburner']
<add> templateCompilerVendor: ['htmlbars-runtime', 'htmlbars-util', 'htmlbars-compiler', 'htmlbars-syntax', 'htmlbars-test-helpers', 'morph-range']
<ide> };
<ide>
<ide> packages['ember-htmlbars'] = { | 1 |
Ruby | Ruby | remove code duplication | 7379114c2f2c2ec1f767a16cf2f8662ea6bd8db2 | <ide><path>activemodel/lib/active_model/validations/exclusion.rb
<ide> class ExclusionValidator < EachValidator
<ide> "and must be supplied as the :in option of the configuration hash"
<ide>
<ide> def check_validity!
<del> unless [:include?, :call].any?{ |method| options[:in].respond_to?(method) }
<add> unless [:include?, :call].any? { |method| options[:in].respond_to?(method) }
<ide> raise ArgumentError, ERROR_MESSAGE
<ide> end
<ide> end
<ide>
<ide> def validate_each(record, attribute, value)
<del> exclusions = options[:in].respond_to?(:call) ? options[:in].call(record) : options[:in]
<add> delimiter = options[:in]
<add> exclusions = delimiter.respond_to?(:call) ? delimiter.call(record) : delimiter
<ide> if exclusions.send(inclusion_method(exclusions), value)
<ide> record.errors.add(attribute, :exclusion, options.except(:in).merge!(:value => value))
<ide> end
<ide><path>activemodel/lib/active_model/validations/format.rb
<ide> module Validations
<ide> class FormatValidator < EachValidator
<ide> def validate_each(record, attribute, value)
<ide> if options[:with]
<del> regexp = options[:with].respond_to?(:call) ? options[:with].call(record) : options[:with]
<del> if regexp.is_a?(Regexp)
<del> record.errors.add(attribute, :invalid, options.except(:with).merge!(:value => value)) if value.to_s !~ regexp
<del> else
<del> raise ArgumentError, "A proc or lambda given to :with option must returns a regular expression"
<del> end
<add> regexp = option_call(record, :with)
<add> record_error(record, attribute, :with, value) if value.to_s !~ regexp
<ide> elsif options[:without]
<del> regexp = options[:without].respond_to?(:call) ? options[:without].call(record) : options[:without]
<del> if regexp.is_a?(Regexp)
<del> record.errors.add(attribute, :invalid, options.except(:without).merge!(:value => value)) if value.to_s =~ regexp
<del> else
<del> raise ArgumentError, "A proc or lambda given to :without option must returns a regular expression"
<del> end
<add> regexp = option_call(record, :without)
<add> record_error(record, attribute, :without, value) if value.to_s =~ regexp
<ide> end
<ide> end
<ide>
<ide> def check_validity!
<ide> raise ArgumentError, "Either :with or :without must be supplied (but not both)"
<ide> end
<ide>
<del> if options[:with] && !options[:with].is_a?(Regexp) && !options[:with].respond_to?(:call)
<del> raise ArgumentError, "A regular expression or a proc or lambda must be supplied as the :with option of the configuration hash"
<del> end
<add> check_options_validity(options, :with)
<add> check_options_validity(options, :without)
<add> end
<add>
<add> private
<add>
<add> def option_call(record, name)
<add> option = options[name]
<add> option.respond_to?(:call) ? option.call(record) : option
<add> end
<add>
<add> def record_error(record, attribute, name, value)
<add> record.errors.add(attribute, :invalid, options.except(name).merge!(:value => value))
<add> end
<ide>
<del> if options[:without] && !options[:without].is_a?(Regexp) && !options[:without].respond_to?(:call)
<del> raise ArgumentError, "A regular expression or a proc or lambda must be supplied as the :without option of the configuration hash"
<add> def check_options_validity(options, name)
<add> option = options[name]
<add> if option && !option.is_a?(Regexp) && !option.respond_to?(:call)
<add> raise ArgumentError, "A regular expression or a proc or lambda must be supplied as :#{name}"
<ide> end
<ide> end
<ide> end
<ide><path>activemodel/lib/active_model/validations/inclusion.rb
<ide> def check_validity!
<ide> end
<ide>
<ide> def validate_each(record, attribute, value)
<del> exclusions = options[:in].respond_to?(:call) ? options[:in].call(record) : options[:in]
<add> delimiter = options[:in]
<add> exclusions = delimiter.respond_to?(:call) ? delimiter.call(record) : delimiter
<ide> unless exclusions.send(inclusion_method(exclusions), value)
<ide> record.errors.add(attribute, :inclusion, options.except(:in).merge!(:value => value))
<ide> end | 3 |
Ruby | Ruby | restore argv even if an exception is raised | 951620f146fde045f106093fcd510a345a6fddd1 | <ide><path>Library/Homebrew/extend/ARGV.rb
<ide> def filter_for_dependencies
<ide> flags_to_clear.concat %w[--verbose -v] if quieter?
<ide> flags_to_clear.each {|flag| delete flag}
<ide>
<del> ret = yield
<del>
<del> replace old_args
<del> ret
<add> yield
<add> ensure
<add> replace(old_args)
<ide> end
<ide>
<ide> private | 1 |
Javascript | Javascript | add `reverse` support to time scale | d7e8b733e36f87e85a5bbccd88cfc74b182ac467 | <ide><path>src/scales/scale.time.js
<ide> function generate(min, max, capacity, options) {
<ide> }
<ide>
<ide> /**
<del> * Returns the right and left offsets from edges in the form of {left, right}.
<add> * Returns the end and start offsets from edges in the form of {start, end}.
<ide> * Offsets are added when the `offset` option is true.
<ide> */
<ide> function computeOffsets(table, ticks, min, max, options) {
<del> var left = 0;
<del> var right = 0;
<add> var start = 0;
<add> var end = 0;
<ide> var upper, lower;
<ide>
<ide> if (options.offset && ticks.length) {
<ide> if (!options.time.min) {
<ide> upper = ticks.length > 1 ? ticks[1] : max;
<ide> lower = ticks[0];
<del> left = (
<add> start = (
<ide> interpolate(table, 'time', upper, 'pos') -
<ide> interpolate(table, 'time', lower, 'pos')
<ide> ) / 2;
<ide> }
<ide> if (!options.time.max) {
<ide> upper = ticks[ticks.length - 1];
<ide> lower = ticks.length > 1 ? ticks[ticks.length - 2] : min;
<del> right = (
<add> end = (
<ide> interpolate(table, 'time', upper, 'pos') -
<ide> interpolate(table, 'time', lower, 'pos')
<ide> ) / 2;
<ide> }
<ide> }
<ide>
<del> return {left: left, right: right};
<add> return options.ticks.reverse ? {start: end, end: start} : {start: start, end: end};
<ide> }
<ide>
<ide> function ticksFromTimestamps(values, majorUnit) {
<ide> module.exports = function() {
<ide> me._offsets = computeOffsets(me._table, ticks, min, max, options);
<ide> me._labelFormat = determineLabelFormat(me._timestamps.data, timeOpts);
<ide>
<add> if (options.ticks.reverse) {
<add> ticks.reverse();
<add> }
<add>
<ide> return ticksFromTimestamps(ticks, me._majorUnit);
<ide> },
<ide>
<ide> module.exports = function() {
<ide> */
<ide> getPixelForOffset: function(time) {
<ide> var me = this;
<add> var isReverse = me.options.ticks.reverse;
<ide> var size = me._horizontal ? me.width : me.height;
<del> var start = me._horizontal ? me.left : me.top;
<add> var start = me._horizontal ? isReverse ? me.right : me.left : isReverse ? me.bottom : me.top;
<ide> var pos = interpolate(me._table, 'time', time, 'pos');
<add> var offset = size * (me._offsets.start + pos) / (me._offsets.start + 1 + me._offsets.end);
<ide>
<del> return start + size * (me._offsets.left + pos) / (me._offsets.left + 1 + me._offsets.right);
<add> return isReverse ? start - offset : start + offset;
<ide> },
<ide>
<ide> getPixelForValue: function(value, index, datasetIndex) {
<ide> module.exports = function() {
<ide> var me = this;
<ide> var size = me._horizontal ? me.width : me.height;
<ide> var start = me._horizontal ? me.left : me.top;
<del> var pos = (size ? (pixel - start) / size : 0) * (me._offsets.left + 1 + me._offsets.left) - me._offsets.right;
<add> var pos = (size ? (pixel - start) / size : 0) * (me._offsets.start + 1 + me._offsets.start) - me._offsets.end;
<ide> var time = interpolate(me._table, 'pos', pos, 'time');
<ide>
<ide> return moment(time);
<ide><path>test/specs/scale.time.tests.js
<ide> describe('Time scale tests', function() {
<ide> });
<ide> });
<ide> });
<add>
<add> describe('when ticks.reverse', function() {
<add> describe('is "true"', function() {
<add> it ('should reverse the labels', function() {
<add> this.chart = window.acquireChart({
<add> type: 'line',
<add> data: {
<add> labels: ['2017', '2019', '2020', '2025', '2042'],
<add> datasets: [{data: [0, 1, 2, 3, 4, 5]}]
<add> },
<add> options: {
<add> scales: {
<add> xAxes: [{
<add> id: 'x',
<add> type: 'time',
<add> time: {
<add> parser: 'YYYY',
<add> },
<add> ticks: {
<add> source: 'labels',
<add> reverse: true
<add> }
<add> }],
<add> yAxes: [{
<add> display: false
<add> }]
<add> }
<add> }
<add> });
<add> var scale = this.chart.scales.x;
<add> expect(scale.getPixelForValue('2017')).toBeCloseToPixel(scale.left + scale.width);
<add> expect(scale.getPixelForValue('2042')).toBeCloseToPixel(scale.left);
<add> });
<add> });
<add> });
<add>
<add> describe('when ticks.reverse is "true" and distribution', function() {
<add> describe('is "series"', function() {
<add> beforeEach(function() {
<add> this.chart = window.acquireChart({
<add> type: 'line',
<add> data: {
<add> labels: ['2017', '2019', '2020', '2025', '2042'],
<add> datasets: [{data: [0, 1, 2, 3, 4, 5]}]
<add> },
<add> options: {
<add> scales: {
<add> xAxes: [{
<add> id: 'x',
<add> type: 'time',
<add> time: {
<add> parser: 'YYYY'
<add> },
<add> distribution: 'series',
<add> ticks: {
<add> source: 'labels',
<add> reverse: true
<add> }
<add> }],
<add> yAxes: [{
<add> display: false
<add> }]
<add> }
<add> }
<add> });
<add> });
<add>
<add> it ('should reverse the labels and space data out with the same gap, whatever their time values', function() {
<add> var scale = this.chart.scales.x;
<add> var start = scale.left;
<add> var slice = scale.width / 4;
<add>
<add> expect(scale.getPixelForValue('2017')).toBeCloseToPixel(start + slice * 4);
<add> expect(scale.getPixelForValue('2019')).toBeCloseToPixel(start + slice * 3);
<add> expect(scale.getPixelForValue('2020')).toBeCloseToPixel(start + slice * 2);
<add> expect(scale.getPixelForValue('2025')).toBeCloseToPixel(start + slice);
<add> expect(scale.getPixelForValue('2042')).toBeCloseToPixel(start);
<add> });
<add>
<add> it ('should reverse the labels and should add a step before if scale.min is before the first data', function() {
<add> var chart = this.chart;
<add> var scale = chart.scales.x;
<add> var options = chart.options.scales.xAxes[0];
<add>
<add> options.time.min = '2012';
<add> chart.update();
<add>
<add> var start = scale.left;
<add> var slice = scale.width / 5;
<add>
<add> expect(scale.getPixelForValue('2017')).toBeCloseToPixel(start + slice * 4);
<add> expect(scale.getPixelForValue('2042')).toBeCloseToPixel(start);
<add> });
<add>
<add> it ('should reverse the labels and should add a step after if scale.max is after the last data', function() {
<add> var chart = this.chart;
<add> var scale = chart.scales.x;
<add> var options = chart.options.scales.xAxes[0];
<add>
<add> options.time.max = '2050';
<add> chart.update();
<add>
<add> var start = scale.left;
<add> var slice = scale.width / 5;
<add>
<add> expect(scale.getPixelForValue('2017')).toBeCloseToPixel(start + slice * 5);
<add> expect(scale.getPixelForValue('2042')).toBeCloseToPixel(start + slice);
<add> });
<add>
<add> it ('should reverse the labels and should add steps before and after if scale.min/max are outside the data range', function() {
<add> var chart = this.chart;
<add> var scale = chart.scales.x;
<add> var options = chart.options.scales.xAxes[0];
<add>
<add> options.time.min = '2012';
<add> options.time.max = '2050';
<add> chart.update();
<add>
<add> var start = scale.left;
<add> var slice = scale.width / 6;
<add>
<add> expect(scale.getPixelForValue('2017')).toBeCloseToPixel(start + slice * 5);
<add> expect(scale.getPixelForValue('2042')).toBeCloseToPixel(start + slice);
<add> });
<add> });
<add> describe('is "linear"', function() {
<add> beforeEach(function() {
<add> this.chart = window.acquireChart({
<add> type: 'line',
<add> data: {
<add> labels: ['2017', '2019', '2020', '2025', '2042'],
<add> datasets: [{data: [0, 1, 2, 3, 4, 5]}]
<add> },
<add> options: {
<add> scales: {
<add> xAxes: [{
<add> id: 'x',
<add> type: 'time',
<add> time: {
<add> parser: 'YYYY'
<add> },
<add> distribution: 'linear',
<add> ticks: {
<add> source: 'labels',
<add> reverse: true
<add> }
<add> }],
<add> yAxes: [{
<add> display: false
<add> }]
<add> }
<add> }
<add> });
<add> });
<add>
<add> it ('should reverse the labels and should space data out with a gap relative to their time values', function() {
<add> var scale = this.chart.scales.x;
<add> var start = scale.left;
<add> var slice = scale.width / (2042 - 2017);
<add>
<add> expect(scale.getPixelForValue('2017')).toBeCloseToPixel(start + slice * (2042 - 2017));
<add> expect(scale.getPixelForValue('2019')).toBeCloseToPixel(start + slice * (2042 - 2019));
<add> expect(scale.getPixelForValue('2020')).toBeCloseToPixel(start + slice * (2042 - 2020));
<add> expect(scale.getPixelForValue('2025')).toBeCloseToPixel(start + slice * (2042 - 2025));
<add> expect(scale.getPixelForValue('2042')).toBeCloseToPixel(start);
<add> });
<add>
<add> it ('should reverse the labels and should take in account scale min and max if outside the ticks range', function() {
<add> var chart = this.chart;
<add> var scale = chart.scales.x;
<add> var options = chart.options.scales.xAxes[0];
<add>
<add> options.time.min = '2012';
<add> options.time.max = '2050';
<add> chart.update();
<add>
<add> var start = scale.left;
<add> var slice = scale.width / (2050 - 2012);
<add>
<add> expect(scale.getPixelForValue('2017')).toBeCloseToPixel(start + slice * (2050 - 2017));
<add> expect(scale.getPixelForValue('2019')).toBeCloseToPixel(start + slice * (2050 - 2019));
<add> expect(scale.getPixelForValue('2020')).toBeCloseToPixel(start + slice * (2050 - 2020));
<add> expect(scale.getPixelForValue('2025')).toBeCloseToPixel(start + slice * (2050 - 2025));
<add> expect(scale.getPixelForValue('2042')).toBeCloseToPixel(start + slice * (2050 - 2042));
<add> });
<add> });
<add> });
<ide> }); | 2 |
PHP | PHP | remove duplicate code | 19ac39963adbb9430b465a03e06731fb2d8eff1d | <ide><path>lib/Cake/Routing/Router.php
<ide> public static function url($url = null, $full = false) {
<ide> for ($i = 0, $len = count(self::$routes); $i < $len; $i++) {
<ide> $originalUrl = $url;
<ide>
<del> if (isset(self::$routes[$i]->options['persist'], $params)) {
<del> $url = self::$routes[$i]->persistParams($url, $params);
<del> }
<add> $url = self::$routes[$i]->persistParams($url, $params);
<ide>
<ide> if ($match = self::$routes[$i]->match($url)) {
<ide> $output = trim($match, '/'); | 1 |
Python | Python | fix ukrainian lemmatizer init | 264862c67a669ab908c2c628c5de8fb4c07e7d18 | <ide><path>spacy/lang/ru/lemmatizer.py
<ide> def __init__(
<ide> mode: str = "pymorphy2",
<ide> overwrite: bool = False,
<ide> ) -> None:
<del> super().__init__(vocab, model, name, mode=mode, overwrite=overwrite)
<del>
<ide> try:
<ide> from pymorphy2 import MorphAnalyzer
<ide> except ImportError:
<ide> def __init__(
<ide> ) from None
<ide> if RussianLemmatizer._morph is None:
<ide> RussianLemmatizer._morph = MorphAnalyzer()
<add> super().__init__(vocab, model, name, mode=mode, overwrite=overwrite)
<ide>
<ide> def pymorphy2_lemmatize(self, token: Token) -> List[str]:
<ide> string = token.text
<ide><path>spacy/lang/uk/lemmatizer.py
<ide>
<ide>
<ide> class UkrainianLemmatizer(RussianLemmatizer):
<add> _morph = None
<add>
<ide> def __init__(
<ide> self,
<ide> vocab: Vocab,
<ide> def __init__(
<ide> mode: str = "pymorphy2",
<ide> overwrite: bool = False,
<ide> ) -> None:
<del> super().__init__(vocab, model, name, mode=mode, overwrite=overwrite)
<ide> try:
<ide> from pymorphy2 import MorphAnalyzer
<ide> except ImportError:
<ide> def __init__(
<ide> ) from None
<ide> if UkrainianLemmatizer._morph is None:
<ide> UkrainianLemmatizer._morph = MorphAnalyzer(lang="uk")
<add> super().__init__(vocab, model, name, mode=mode, overwrite=overwrite) | 2 |
Java | Java | add a way to enable / disable lazy native modules | a4916b8c98085e37a2cdfb130d1089daba697702 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java
<ide> public static class Builder {
<ide> protected @Nullable Activity mCurrentActivity;
<ide> protected @Nullable DefaultHardwareBackBtnHandler mDefaultHardwareBackBtnHandler;
<ide> protected @Nullable RedBoxHandler mRedBoxHandler;
<add> protected boolean mLazyNativeModulesEnabled;
<ide>
<ide> protected Builder() {
<ide> }
<ide> public Builder setRedBoxHandler(@Nullable RedBoxHandler redBoxHandler) {
<ide> return this;
<ide> }
<ide>
<add> public Builder setLazyNativeModulesEnabled(boolean lazyNativeModulesEnabled) {
<add> mLazyNativeModulesEnabled = lazyNativeModulesEnabled;
<add> return this;
<add> }
<add>
<ide> /**
<ide> * Instantiates a new {@link ReactInstanceManagerImpl}.
<ide> * Before calling {@code build}, the following must be called:
<ide> public Builder setRedBoxHandler(@Nullable RedBoxHandler redBoxHandler) {
<ide> */
<ide> public ReactInstanceManager build() {
<ide> Assertions.assertNotNull(
<del> mApplication,
<del> "Application property has not been set with this builder");
<add> mApplication,
<add> "Application property has not been set with this builder");
<ide>
<ide> Assertions.assertCondition(
<del> mUseDeveloperSupport || mJSBundleAssetUrl != null || mJSBundleLoader != null,
<del> "JS Bundle File or Asset URL has to be provided when dev support is disabled");
<add> mUseDeveloperSupport || mJSBundleAssetUrl != null || mJSBundleLoader != null,
<add> "JS Bundle File or Asset URL has to be provided when dev support is disabled");
<ide>
<ide> Assertions.assertCondition(
<del> mJSMainModuleName != null || mJSBundleAssetUrl != null || mJSBundleLoader != null,
<del> "Either MainModuleName or JS Bundle File needs to be provided");
<add> mJSMainModuleName != null || mJSBundleAssetUrl != null || mJSBundleLoader != null,
<add> "Either MainModuleName or JS Bundle File needs to be provided");
<ide>
<ide> if (mUIImplementationProvider == null) {
<ide> // create default UIImplementationProvider if the provided one is null.
<ide> mUIImplementationProvider = new UIImplementationProvider();
<ide> }
<ide>
<ide> return new XReactInstanceManagerImpl(
<del> mApplication,
<del> mCurrentActivity,
<del> mDefaultHardwareBackBtnHandler,
<del> (mJSBundleLoader == null && mJSBundleAssetUrl != null) ?
<del> JSBundleLoader.createAssetLoader(mApplication, mJSBundleAssetUrl) : mJSBundleLoader,
<del> mJSMainModuleName,
<del> mPackages,
<del> mUseDeveloperSupport,
<del> mBridgeIdleDebugListener,
<del> Assertions.assertNotNull(mInitialLifecycleState, "Initial lifecycle state was not set"),
<del> mUIImplementationProvider,
<del> mNativeModuleCallExceptionHandler,
<del> mJSCConfig,
<del> mRedBoxHandler);
<add> mApplication,
<add> mCurrentActivity,
<add> mDefaultHardwareBackBtnHandler,
<add> (mJSBundleLoader == null && mJSBundleAssetUrl != null) ?
<add> JSBundleLoader.createAssetLoader(mApplication, mJSBundleAssetUrl) : mJSBundleLoader,
<add> mJSMainModuleName,
<add> mPackages,
<add> mUseDeveloperSupport,
<add> mBridgeIdleDebugListener,
<add> Assertions.assertNotNull(mInitialLifecycleState, "Initial lifecycle state was not set"),
<add> mUIImplementationProvider,
<add> mNativeModuleCallExceptionHandler,
<add> mJSCConfig,
<add> mRedBoxHandler,
<add> mLazyNativeModulesEnabled);
<ide> }
<ide> }
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/XReactInstanceManagerImpl.java
<ide> private final MemoryPressureRouter mMemoryPressureRouter;
<ide> private final @Nullable NativeModuleCallExceptionHandler mNativeModuleCallExceptionHandler;
<ide> private final JSCConfig mJSCConfig;
<add> private final boolean mLazyNativeModulesEnabled;
<ide>
<ide> private final ReactInstanceDevCommandsHandler mDevInterface =
<ide> new ReactInstanceDevCommandsHandler() {
<ide> public T get() throws Exception {
<ide> UIImplementationProvider uiImplementationProvider,
<ide> NativeModuleCallExceptionHandler nativeModuleCallExceptionHandler,
<ide> JSCConfig jscConfig,
<del> @Nullable RedBoxHandler redBoxHandler) {
<add> @Nullable RedBoxHandler redBoxHandler,
<add> boolean lazyNativeModulesEnabled) {
<ide>
<ide> initializeSoLoaderIfNecessary(applicationContext);
<ide>
<ide> public T get() throws Exception {
<ide> mMemoryPressureRouter = new MemoryPressureRouter(applicationContext);
<ide> mNativeModuleCallExceptionHandler = nativeModuleCallExceptionHandler;
<ide> mJSCConfig = jscConfig;
<add> mLazyNativeModulesEnabled = lazyNativeModulesEnabled;
<ide> }
<ide>
<ide> @Override | 2 |
PHP | PHP | remove unused property | 8f50064a893be90be04e8b3214dc1f2347d88758 | <ide><path>src/TestSuite/TestCase.php
<ide> abstract class TestCase extends BaseTestCase
<ide> */
<ide> protected $_configure = [];
<ide>
<del> /**
<del> * Path settings to restore at the end of the test.
<del> *
<del> * @var array
<del> */
<del> protected $_pathRestore = [];
<del>
<ide> /**
<ide> * Overrides SimpleTestCase::skipIf to provide a boolean return value
<ide> *
<ide> public function tearDown()
<ide> Configure::write($this->_configure);
<ide> }
<ide> $this->getTableLocator()->clear();
<del> $this->_configure = $this->_pathRestore = [];
<add> $this->_configure = [];
<ide> $this->_tableLocator = null;
<ide> }
<ide> | 1 |
Text | Text | replace url with empty array in solution | 8ee2e5eaa961e3ab5a6653e14f3946750dfd2ca1 | <ide><path>guide/english/certifications/coding-interview-prep/algorithms/no-repeats-please/index.md
<ide> A way to visualize this is by considering a tree that starts with the first char
<ide> function permAlone(str) {
<ide>
<ide> // Create a regex to match repeated consecutive characters.
<del> var regex = /(.)\1+/g;
<add> var regex = /(.)\1+/;
<ide>
<ide> // Split the string into an array of characters.
<ide> var arr = str.split('');
<del> var permutations = <a href='https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:"' target='_blank' rel='nofollow'>];
<add> var permutations = [];
<ide> var tmp;
<ide>
<ide> // Return 0 if str contains same character. | 1 |
PHP | PHP | ignore asset requests containing %2e in them | d4db64ff26e83cdbb3e6dac848419afd99334680 | <ide><path>lib/Cake/Routing/Filter/AssetDispatcher.php
<ide> class AssetDispatcher extends DispatcherFilter {
<ide> * @return CakeResponse if the client is requesting a recognized asset, null otherwise
<ide> */
<ide> public function beforeDispatch(CakeEvent $event) {
<del> $url = $event->data['request']->url;
<add> $url = urldecode($event->data['request']->url);
<ide> if (strpos($url, '..') !== false || strpos($url, '.') === false) {
<ide> return;
<ide> }
<ide> protected function _getAssetFile($url) {
<ide> if ($parts[0] === 'theme') {
<ide> $themeName = $parts[1];
<ide> unset($parts[0], $parts[1]);
<del> $fileFragment = urldecode(implode(DS, $parts));
<add> $fileFragment = implode(DS, $parts);
<ide> $path = App::themePath($themeName) . 'webroot' . DS;
<ide> return $path . $fileFragment;
<ide> }
<ide>
<ide> $plugin = Inflector::camelize($parts[0]);
<ide> if ($plugin && CakePlugin::loaded($plugin)) {
<ide> unset($parts[0]);
<del> $fileFragment = urldecode(implode(DS, $parts));
<add> $fileFragment = implode(DS, $parts);
<ide> $pluginWebroot = CakePlugin::path($plugin) . 'webroot' . DS;
<ide> return $pluginWebroot . $fileFragment;
<ide> }
<ide><path>lib/Cake/Test/Case/Routing/Filter/AssetDispatcherTest.php
<ide> public function test404OnDoubleSlash() {
<ide> $this->assertFalse($event->isStopped());
<ide> }
<ide>
<add>/**
<add> * Test that attempts to traverse directories are prevented.
<add> *
<add> * @return void
<add> */
<add> public function test404OnDoubleDot() {
<add> App::build(array(
<add> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS),
<add> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
<add> ), APP::RESET);
<add>
<add> $response = $this->getMock('CakeResponse', array('_sendHeader'));
<add> $request = new CakeRequest('theme/test_theme/../../../../../../VERSION.txt');
<add> $event = new CakeEvent('Dispatcher.beforeRequest', $this, compact('request', 'response'));
<add>
<add> $response->expects($this->never())->method('send');
<add>
<add> $filter = new AssetDispatcher();
<add> $this->assertNull($filter->beforeDispatch($event));
<add> $this->assertFalse($event->isStopped());
<add> }
<add>
<add>/**
<add> * Test that attempts to traverse directories with urlencoded paths fail.
<add> *
<add> * @return void
<add> */
<add> public function test404OnDoubleDotEncoded() {
<add> App::build(array(
<add> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS),
<add> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
<add> ), APP::RESET);
<add>
<add> $response = $this->getMock('CakeResponse', array('_sendHeader', 'send'));
<add> $request = new CakeRequest('theme/test_theme/%2e./%2e./%2e./%2e./%2e./%2e./VERSION.txt');
<add> $event = new CakeEvent('Dispatcher.beforeRequest', $this, compact('request', 'response'));
<add>
<add> $response->expects($this->never())->method('send');
<add>
<add> $filter = new AssetDispatcher();
<add> $this->assertNull($filter->beforeDispatch($event));
<add> $this->assertFalse($event->isStopped());
<add> }
<add>
<ide> } | 2 |
Ruby | Ruby | fix cpuid instruction check on mojave | 16e56907b5cf93bd66f87608089944905c506cf5 | <ide><path>Library/Homebrew/formula_cellar_checks.rb
<ide> def relative_glob(dir, pattern)
<ide>
<ide> def cpuid_instruction?(file, objdump = "objdump")
<ide> @instruction_column_index ||= {}
<del> @instruction_column_index[objdump] ||= if Utils.popen_read(objdump, "--version").include? "LLVM"
<del> 1 # `llvm-objdump` or macOS `objdump`
<del> else
<del> 2 # GNU binutils `objdump`
<add> @instruction_column_index[objdump] ||= begin
<add> objdump_version = Utils.popen_read(objdump, "--version")
<add>
<add> if (objdump_version.match?(/^Apple LLVM/) && MacOS.version <= :mojave) ||
<add> objdump_version.exclude?("LLVM")
<add> 2 # Mojave `objdump` or GNU Binutils `objdump`
<add> else
<add> 1 # `llvm-objdump` or Catalina+ `objdump`
<add> end
<ide> end
<ide>
<ide> has_cpuid_instruction = false | 1 |
Javascript | Javascript | fix logic nit in tools/doc/generate.js | 14460d595fd867e92fdd6328ca0bc5636c1899d9 | <ide><path>tools/doc/generate.js
<ide> function next(er, input) {
<ide> switch (format) {
<ide> case 'json':
<ide> require('./json.js')(input, filename, (er, obj) => {
<del> console.log(JSON.stringify(obj, null, 2));
<ide> if (er) throw er;
<add> console.log(JSON.stringify(obj, null, 2));
<ide> });
<ide> break;
<ide> | 1 |
Mixed | Javascript | add client support for tls keylog events | b0cf62b3a05cf1b207441de2ce3d33a3a57acd5f | <ide><path>doc/api/https.md
<ide> changes:
<ide>
<ide> See [`Session Resumption`][] for information about TLS session reuse.
<ide>
<add>#### Event: 'keylog'
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>* `line` {Buffer} Line of ASCII text, in NSS `SSLKEYLOGFILE` format.
<add>* `tlsSocket` {tls.TLSSocket} The `tls.TLSSocket` instance on which it was
<add> generated.
<add>
<add>The `keylog` event is emitted when key material is generated or received by a
<add>connection managed by this agent (typically before handshake has completed, but
<add>not necessarily). This keying material can be stored for debugging, as it
<add>allows captured TLS traffic to be decrypted. It may be emitted multiple times
<add>for each socket.
<add>
<add>A typical use case is to append received lines to a common text file, which is
<add>later used by software (such as Wireshark) to decrypt the traffic:
<add>
<add>```js
<add>// ...
<add>https.globalAgent.on('keylog', (line, tlsSocket) => {
<add> fs.appendFileSync('/tmp/ssl-keys.log', line, { mode: 0o600 });
<add>});
<add>```
<add>
<ide> ## Class: https.Server
<ide> <!-- YAML
<ide> added: v0.3.4
<ide><path>lib/_http_agent.js
<ide> const {
<ide> ERR_INVALID_ARG_TYPE,
<ide> },
<ide> } = require('internal/errors');
<add>const kOnKeylog = Symbol('onkeylog');
<ide> // New Agent code.
<ide>
<ide> // The largest departure from the previous implementation is that
<ide> function Agent(options) {
<ide> }
<ide> }
<ide> });
<add>
<add> // Don't emit keylog events unless there is a listener for them.
<add> this.on('newListener', maybeEnableKeylog);
<ide> }
<ide> Object.setPrototypeOf(Agent.prototype, EventEmitter.prototype);
<ide> Object.setPrototypeOf(Agent, EventEmitter);
<ide>
<add>function maybeEnableKeylog(eventName) {
<add> if (eventName === 'keylog') {
<add> this.removeListener('newListener', maybeEnableKeylog);
<add> // Future sockets will listen on keylog at creation.
<add> const agent = this;
<add> this[kOnKeylog] = function onkeylog(keylog) {
<add> agent.emit('keylog', keylog, this);
<add> };
<add> // Existing sockets will start listening on keylog now.
<add> const sockets = Object.values(this.sockets);
<add> for (let i = 0; i < sockets.length; i++) {
<add> sockets[i].on('keylog', this[kOnKeylog]);
<add> }
<add> }
<add>}
<add>
<ide> Agent.defaultMaxSockets = Infinity;
<ide>
<ide> Agent.prototype.createConnection = net.createConnection;
<ide> function installListeners(agent, s, options) {
<ide> s.removeListener('agentRemove', onRemove);
<ide> }
<ide> s.on('agentRemove', onRemove);
<add>
<add> if (agent[kOnKeylog]) {
<add> s.on('keylog', agent[kOnKeylog]);
<add> }
<ide> }
<ide>
<ide> Agent.prototype.removeSocket = function removeSocket(s, options) {
<ide><path>test/parallel/test-https-agent-keylog.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<add>const assert = require('assert');
<add>const https = require('https');
<add>const fixtures = require('../common/fixtures');
<add>
<add>const server = https.createServer({
<add> key: fixtures.readKey('agent2-key.pem'),
<add> cert: fixtures.readKey('agent2-cert.pem'),
<add> // Amount of keylog events depends on negotiated protocol
<add> // version, so force a specific one:
<add> minVersion: 'TLSv1.3',
<add> maxVersion: 'TLSv1.3',
<add>}, (req, res) => {
<add> res.end('bye');
<add>}).listen(() => {
<add> https.get({
<add> port: server.address().port,
<add> rejectUnauthorized: false,
<add> }, (res) => {
<add> res.resume();
<add> res.on('end', () => {
<add> // Trigger TLS connection reuse
<add> https.get({
<add> port: server.address().port,
<add> rejectUnauthorized: false,
<add> }, (res) => {
<add> server.close();
<add> res.resume();
<add> });
<add> });
<add> });
<add>});
<add>
<add>const verifyKeylog = (line, tlsSocket) => {
<add> assert(Buffer.isBuffer(line));
<add> assert.strictEqual(tlsSocket.encrypted, true);
<add>};
<add>server.on('keylog', common.mustCall(verifyKeylog, 10));
<add>https.globalAgent.on('keylog', common.mustCall(verifyKeylog, 10));
<ide><path>test/parallel/test-tls-keylog-tlsv13.js
<ide> const server = tls.createServer({
<ide> rejectUnauthorized: false,
<ide> });
<ide>
<del> const verifyBuffer = (line) => assert(Buffer.isBuffer(line));
<del> server.on('keylog', common.mustCall(verifyBuffer, 5));
<del> client.on('keylog', common.mustCall(verifyBuffer, 5));
<add> server.on('keylog', common.mustCall((line, tlsSocket) => {
<add> assert(Buffer.isBuffer(line));
<add> assert.strictEqual(tlsSocket.encrypted, true);
<add> }, 5));
<add> client.on('keylog', common.mustCall((line) => {
<add> assert(Buffer.isBuffer(line));
<add> }, 5));
<ide>
<ide> client.once('secureConnect', () => {
<ide> server.close(); | 4 |
Javascript | Javascript | remove console.logs from fiber | e0e4954061a88f65c3b9ad6041a9b0a1d3881454 | <ide><path>src/renderers/noop/ReactNoop.js
<ide> function flattenChildren(children : HostChildren<Instance>) {
<ide> var NoopRenderer = ReactFiberReconciler({
<ide>
<ide> updateContainer(containerInfo : Container, children : HostChildren<Instance>) : void {
<del> console.log('Update container #' + containerInfo.rootID);
<ide> containerInfo.children = flattenChildren(children);
<ide> },
<ide>
<ide> createInstance(type : string, props : Props, children : HostChildren<Instance>) : Instance {
<del> console.log('Create instance #' + instanceCounter);
<ide> const inst = {
<ide> tag: TERMINAL_TAG,
<ide> id: instanceCounter++,
<ide> var NoopRenderer = ReactFiberReconciler({
<ide> },
<ide>
<ide> prepareUpdate(instance : Instance, oldProps : Props, newProps : Props, children : HostChildren<Instance>) : boolean {
<del> console.log('Prepare for update on #' + instance.id);
<ide> return true;
<ide> },
<ide>
<ide> commitUpdate(instance : Instance, oldProps : Props, newProps : Props, children : HostChildren<Instance>) : void {
<del> console.log('Commit update on #' + instance.id);
<ide> instance.children = flattenChildren(children);
<ide> },
<ide>
<ide> deleteInstance(instance : Instance) : void {
<del> console.log('Delete #' + instance.id);
<ide> },
<ide>
<ide> scheduleHighPriCallback(callback) {
<ide><path>src/renderers/shared/fiber/ReactChildFiber.js
<ide> function createSubsequentChild(
<ide> }
<ide> return prev;
<ide> } else {
<del> console.log('Unknown child', newChildren);
<add> // TODO: Throw for unknown children.
<ide> return previousSibling;
<ide> }
<ide> }
<ide> function createFirstChild(returnFiber, existingChild, newChildren, priority) {
<ide> }
<ide> return first;
<ide> } else {
<del> console.log('Unknown child', newChildren);
<add> // TODO: Throw for unknown children.
<ide> return null;
<ide> }
<ide> }
<ide><path>src/renderers/shared/fiber/ReactFiberBeginWork.js
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> function updateFunctionalComponent(current, workInProgress) {
<ide> var fn = workInProgress.type;
<ide> var props = workInProgress.pendingProps;
<del> console.log('update fn:', fn.name);
<ide> var nextChildren = fn(props);
<ide> reconcileChildren(current, workInProgress, nextChildren);
<ide> workInProgress.pendingWorkPriority = NoWork;
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> var props = workInProgress.pendingProps;
<ide> if (!workInProgress.stateNode) {
<ide> var ctor = workInProgress.type;
<del> console.log('mount class:', workInProgress.type.name);
<ide> workInProgress.stateNode = new ctor(props);
<del> } else {
<del> console.log('update class:', workInProgress.type.name);
<ide> }
<ide> var instance = workInProgress.stateNode;
<ide> instance.props = props;
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> }
<ide>
<ide> function updateHostComponent(current, workInProgress) {
<del> console.log(
<del> 'host component', workInProgress.type,
<del> typeof workInProgress.pendingProps.children === 'string' ? workInProgress.pendingProps.children : ''
<del> );
<del>
<ide> var nextChildren = workInProgress.pendingProps.children;
<ide>
<ide> let priority = workInProgress.pendingWorkPriority;
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> var props = workInProgress.pendingProps;
<ide> var value = fn(props);
<ide> if (typeof value === 'object' && value && typeof value.render === 'function') {
<del> console.log('performed work on class:', fn.name);
<ide> // Proceed under the assumption that this is a class instance
<ide> workInProgress.tag = ClassComponent;
<ide> if (workInProgress.alternate) {
<ide> workInProgress.alternate.tag = ClassComponent;
<ide> }
<ide> value = value.render();
<ide> } else {
<del> console.log('performed work on fn:', fn.name);
<ide> // Proceed under the assumption that this is a functional component
<ide> workInProgress.tag = FunctionalComponent;
<ide> if (workInProgress.alternate) {
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> if (!coroutine) {
<ide> throw new Error('Should be resolved by now');
<ide> }
<del> console.log('begin coroutine', workInProgress.type.name);
<ide> reconcileChildren(current, workInProgress, coroutine.children);
<ide> workInProgress.pendingWorkPriority = NoWork;
<ide> }
<ide><path>src/renderers/shared/fiber/ReactFiberCompleteWork.js
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> function completeWork(current : ?Fiber, workInProgress : Fiber) : ?Fiber {
<ide> switch (workInProgress.tag) {
<ide> case FunctionalComponent:
<del> console.log('/functional component', workInProgress.type.name);
<ide> transferOutput(workInProgress.child, workInProgress);
<ide> return null;
<ide> case ClassComponent:
<del> console.log('/class component', workInProgress.type.name);
<ide> transferOutput(workInProgress.child, workInProgress);
<ide> return null;
<ide> case HostContainer:
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> markForPreEffect(workInProgress);
<ide> return null;
<ide> case HostComponent:
<del> console.log('/host component', workInProgress.type);
<ide> const child = workInProgress.child;
<ide> const children = (child && !child.sibling) ? (child.output : ?Fiber | I) : child;
<ide> const newProps = workInProgress.pendingProps;
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> }
<ide> return null;
<ide> case CoroutineComponent:
<del> console.log('/coroutine component', workInProgress.pendingProps.handler.name);
<ide> return moveCoroutineToHandlerPhase(current, workInProgress);
<ide> case CoroutineHandlerPhase:
<ide> transferOutput(workInProgress.stateNode, workInProgress);
<ide><path>src/renderers/shared/fiber/ReactFiberScheduler.js
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> // "next" scheduled work since we've already scanned passed. That
<ide> // also ensures that work scheduled during reconciliation gets deferred.
<ide> // const hasMoreWork = workInProgress.pendingWorkPriority !== NoWork;
<del> console.log('----- COMPLETED with remaining work:', workInProgress.pendingWorkPriority);
<ide> commitAllWork(workInProgress);
<ide> const nextWork = findNextUnitOfWork();
<ide> // if (!nextWork && hasMoreWork) {
<ide><path>src/renderers/shared/fiber/__tests__/ReactCoroutine-test.js
<ide> describe('ReactCoroutine', function() {
<ide> React = require('React');
<ide> ReactNoop = require('ReactNoop');
<ide> ReactCoroutine = require('ReactCoroutine');
<del> spyOn(console, 'log');
<ide> });
<ide>
<ide> it('should render a coroutine', function() {
<ide><path>src/renderers/shared/fiber/__tests__/ReactIncremental-test.js
<ide> describe('ReactIncremental', function() {
<ide> beforeEach(function() {
<ide> React = require('React');
<ide> ReactNoop = require('ReactNoop');
<del> spyOn(console, 'log');
<ide> });
<ide>
<ide> it('should render a simple component', function() {
<ide><path>src/renderers/shared/fiber/__tests__/ReactIncrementalSideEffects-test.js
<ide> describe('ReactIncremental', function() {
<ide> beforeEach(function() {
<ide> React = require('React');
<ide> ReactNoop = require('ReactNoop');
<del> spyOn(console, 'log');
<ide> });
<ide>
<ide> function div(...children) { | 8 |
Text | Text | add v3.20.0-beta.5 to changelog | 251c17f86f5375187dec7a6165cb8017d3fa7592 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.20.0-beta.5 (July 6, 2020)
<add>
<add>- [#19034](https://github.com/emberjs/ember.js/pull/19034) [BUGFIX] Disable named blocks; please continue to use the polyfill.
<add>
<ide> ### v3.20.0-beta.4 (June 29, 2020)
<ide>
<ide> - [#19025](https://github.com/emberjs/ember.js/pull/19025) [BUGFIX] Updates Glimmer VM to 0.54.0 | 1 |
Text | Text | change http links to https in contributing.md | 4cc6ccacb11bbe79840edb10ff9ef91bccabfad5 | <ide><path>CONTRIBUTING.md
<ide> This project and everyone participating in it is governed by the [Atom Code of C
<ide>
<ide> ## I don't want to read this whole thing I just have a question!!!
<ide>
<del>> **Note:** [Please don't file an issue to ask a question.](http://blog.atom.io/2016/04/19/managing-the-deluge-of-atom-issues.html) You'll get faster results by using the resources below.
<add>> **Note:** [Please don't file an issue to ask a question.](https://blog.atom.io/2016/04/19/managing-the-deluge-of-atom-issues.html) You'll get faster results by using the resources below.
<ide>
<ide> We have an official message board with a detailed FAQ and where the community chimes in with helpful advice if you have questions.
<ide>
<ide> We have an official message board with a detailed FAQ and where the community ch
<ide>
<ide> If chat is more your speed, you can join the Atom and Electron Slack team:
<ide>
<del>* [Join the Atom and Electron Slack Team](http://atom-slack.herokuapp.com/)
<add>* [Join the Atom and Electron Slack Team](https://atom-slack.herokuapp.com/)
<ide> * Even though Slack is a chat service, sometimes it takes several hours for community members to respond — please be patient!
<ide> * Use the `#atom` channel for general questions or discussion about Atom
<ide> * Use the `#electron` channel for questions about Electron
<ide> Before creating bug reports, please check [this list](#before-submitting-a-bug-r
<ide>
<ide> #### Before Submitting A Bug Report
<ide>
<del>* **Check the [debugging guide](http://flight-manual.atom.io/hacking-atom/sections/debugging/).** You might be able to find the cause of the problem and fix things yourself. Most importantly, check if you can reproduce the problem [in the latest version of Atom](http://flight-manual.atom.io/hacking-atom/sections/debugging/#update-to-the-latest-version), if the problem happens when you run Atom in [safe mode](http://flight-manual.atom.io/hacking-atom/sections/debugging/#check-if-the-problem-shows-up-in-safe-mode), and if you can get the desired behavior by changing [Atom's or packages' config settings](http://flight-manual.atom.io/hacking-atom/sections/debugging/#check-atom-and-package-settings).
<add>* **Check the [debugging guide](https://flight-manual.atom.io/hacking-atom/sections/debugging/).** You might be able to find the cause of the problem and fix things yourself. Most importantly, check if you can reproduce the problem [in the latest version of Atom](https://flight-manual.atom.io/hacking-atom/sections/debugging/#update-to-the-latest-version), if the problem happens when you run Atom in [safe mode](https://flight-manual.atom.io/hacking-atom/sections/debugging/#check-if-the-problem-shows-up-in-safe-mode), and if you can get the desired behavior by changing [Atom's or packages' config settings](https://flight-manual.atom.io/hacking-atom/sections/debugging/#check-atom-and-package-settings).
<ide> * **Check the [FAQs on the forum](https://discuss.atom.io/c/faq)** for a list of common questions and problems.
<ide> * **Determine [which repository the problem should be reported in](#atom-and-packages)**.
<ide> * **Perform a [cursory search](https://github.com/issues?q=+is%3Aissue+user%3Aatom)** to see if the problem has already been reported. If it has **and the issue is still open**, add a comment to the existing issue instead of opening a new one.
<ide> Explain the problem and include additional details to help maintainers reproduce
<ide> * **Provide specific examples to demonstrate the steps**. Include links to files or GitHub projects, or copy/pasteable snippets, which you use in those examples. If you're providing snippets in the issue, use [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines).
<ide> * **Describe the behavior you observed after following the steps** and point out what exactly is the problem with that behavior.
<ide> * **Explain which behavior you expected to see instead and why.**
<del>* **Include screenshots and animated GIFs** which show you following the described steps and clearly demonstrate the problem. If you use the keyboard while following the steps, **record the GIF with the [Keybinding Resolver](https://github.com/atom/keybinding-resolver) shown**. You can use [this tool](http://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux.
<add>* **Include screenshots and animated GIFs** which show you following the described steps and clearly demonstrate the problem. If you use the keyboard while following the steps, **record the GIF with the [Keybinding Resolver](https://github.com/atom/keybinding-resolver) shown**. You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux.
<ide> * **If you're reporting that Atom crashed**, include a crash report with a stack trace from the operating system. On macOS, the crash report will be available in `Console.app` under "Diagnostic and usage information" > "User diagnostic reports". Include the crash report in the issue in a [code block](https://help.github.com/articles/markdown-basics/#multiple-lines), a [file attachment](https://help.github.com/articles/file-attachments-on-issues-and-pull-requests/), or put it in a [gist](https://gist.github.com/) and provide link to that gist.
<del>* **If the problem is related to performance or memory**, include a [CPU profile capture](http://flight-manual.atom.io/hacking-atom/sections/debugging/#diagnose-runtime-performance) with your report.
<del>* **If Chrome's developer tools pane is shown without you triggering it**, that normally means that you have a syntax error in one of your themes or in your `styles.less`. Try running in [Safe Mode](http://flight-manual.atom.io/hacking-atom/sections/debugging/#using-safe-mode) and using a different theme or comment out the contents of your `styles.less` to see if that fixes the problem.
<add>* **If the problem is related to performance or memory**, include a [CPU profile capture](https://flight-manual.atom.io/hacking-atom/sections/debugging/#diagnose-runtime-performance) with your report.
<add>* **If Chrome's developer tools pane is shown without you triggering it**, that normally means that you have a syntax error in one of your themes or in your `styles.less`. Try running in [Safe Mode](https://flight-manual.atom.io/hacking-atom/sections/debugging/#using-safe-mode) and using a different theme or comment out the contents of your `styles.less` to see if that fixes the problem.
<ide> * **If the problem wasn't triggered by a specific action**, describe what you were doing before the problem happened and share more information using the guidelines below.
<ide>
<ide> Provide more context by answering these questions:
<ide>
<del>* **Can you reproduce the problem in [safe mode](http://flight-manual.atom.io/hacking-atom/sections/debugging/#diagnose-runtime-performance-problems-with-the-dev-tools-cpu-profiler)?**
<add>* **Can you reproduce the problem in [safe mode](https://flight-manual.atom.io/hacking-atom/sections/debugging/#diagnose-runtime-performance-problems-with-the-dev-tools-cpu-profiler)?**
<ide> * **Did the problem start happening recently** (e.g. after updating to a new version of Atom) or was this always a problem?
<ide> * If the problem started happening recently, **can you reproduce the problem in an older version of Atom?** What's the most recent version in which the problem doesn't happen? You can download older versions of Atom from [the releases page](https://github.com/atom/atom/releases).
<ide> * **Can you reliably reproduce the issue?** If not, provide details about how often the problem happens and under which conditions it normally happens.
<ide> Include details about your configuration and environment:
<ide> * **What's the name and version of the OS you're using**?
<ide> * **Are you running Atom in a virtual machine?** If so, which VM software are you using and which operating systems and versions are used for the host and the guest?
<ide> * **Which [packages](#atom-and-packages) do you have installed?** You can get that list by running `apm list --installed`.
<del>* **Are you using [local configuration files](http://flight-manual.atom.io/using-atom/sections/basic-customization/)** `config.cson`, `keymap.cson`, `snippets.cson`, `styles.less` and `init.coffee` to customize Atom? If so, provide the contents of those files, preferably in a [code block](https://help.github.com/articles/markdown-basics/#multiple-lines) or with a link to a [gist](https://gist.github.com/).
<add>* **Are you using [local configuration files](https://flight-manual.atom.io/using-atom/sections/basic-customization/)** `config.cson`, `keymap.cson`, `snippets.cson`, `styles.less` and `init.coffee` to customize Atom? If so, provide the contents of those files, preferably in a [code block](https://help.github.com/articles/markdown-basics/#multiple-lines) or with a link to a [gist](https://gist.github.com/).
<ide> * **Are you using Atom with multiple monitors?** If so, can you reproduce the problem when you use a single monitor?
<ide> * **Which keyboard layout are you using?** Are you using a US layout or some other layout?
<ide>
<ide> Before creating enhancement suggestions, please check [this list](#before-submit
<ide>
<ide> #### Before Submitting An Enhancement Suggestion
<ide>
<del>* **Check the [debugging guide](http://flight-manual.atom.io/hacking-atom/sections/debugging/)** for tips — you might discover that the enhancement is already available. Most importantly, check if you're using [the latest version of Atom](http://flight-manual.atom.io/hacking-atom/sections/debugging/#update-to-the-latest-version) and if you can get the desired behavior by changing [Atom's or packages' config settings](http://flight-manual.atom.io/hacking-atom/sections/debugging/#check-atom-and-package-settings).
<add>* **Check the [debugging guide](https://flight-manual.atom.io/hacking-atom/sections/debugging/)** for tips — you might discover that the enhancement is already available. Most importantly, check if you're using [the latest version of Atom](https://flight-manual.atom.io/hacking-atom/sections/debugging/#update-to-the-latest-version) and if you can get the desired behavior by changing [Atom's or packages' config settings](https://flight-manual.atom.io/hacking-atom/sections/debugging/#check-atom-and-package-settings).
<ide> * **Check if there's already [a package](https://atom.io/packages) which provides that enhancement.**
<ide> * **Determine [which repository the enhancement should be suggested in](#atom-and-packages).**
<ide> * **Perform a [cursory search](https://github.com/issues?q=+is%3Aissue+user%3Aatom)** to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one.
<ide> Enhancement suggestions are tracked as [GitHub issues](https://guides.github.com
<ide> * **Provide a step-by-step description of the suggested enhancement** in as many details as possible.
<ide> * **Provide specific examples to demonstrate the steps**. Include copy/pasteable snippets which you use in those examples, as [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines).
<ide> * **Describe the current behavior** and **explain which behavior you expected to see instead** and why.
<del>* **Include screenshots and animated GIFs** which help you demonstrate the steps or point out the part of Atom which the suggestion is related to. You can use [this tool](http://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux.
<add>* **Include screenshots and animated GIFs** which help you demonstrate the steps or point out the part of Atom which the suggestion is related to. You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux.
<ide> * **Explain why this enhancement would be useful** to most Atom users and isn't something that can or should be implemented as a [community package](#atom-and-packages).
<ide> * **List some other text editors or applications where this enhancement exists.**
<ide> * **Specify which version of Atom you're using.** You can get the exact version by running `atom -v` in your terminal, or by starting Atom and running the `Application: About` command from the [Command Palette](https://github.com/atom/command-palette).
<ide> Unsure where to begin contributing to Atom? You can start by looking through the
<ide>
<ide> Both issue lists are sorted by total number of comments. While not perfect, number of comments is a reasonable proxy for impact a given change will have.
<ide>
<del>If you want to read about using Atom or developing packages in Atom, the [Atom Flight Manual](http://flight-manual.atom.io) is free and available online. You can find the source to the manual in [atom/flight-manual.atom.io](https://github.com/atom/flight-manual.atom.io).
<add>If you want to read about using Atom or developing packages in Atom, the [Atom Flight Manual](https://flight-manual.atom.io) is free and available online. You can find the source to the manual in [atom/flight-manual.atom.io](https://github.com/atom/flight-manual.atom.io).
<ide>
<ide> #### Local development
<ide>
<del>Atom Core and all packages can be developed locally. For instructions on how to do this, see the following sections in the [Atom Flight Manual](http://flight-manual.atom.io):
<add>Atom Core and all packages can be developed locally. For instructions on how to do this, see the following sections in the [Atom Flight Manual](https://flight-manual.atom.io):
<ide>
<ide> * [Hacking on Atom Core][hacking-on-atom-core]
<ide> * [Contributing to Official Atom Packages][contributing-to-official-atom-packages]
<ide> Atom Core and all packages can be developed locally. For instructions on how to
<ide> * Do not include issue numbers in the PR title
<ide> * Include screenshots and animated GIFs in your pull request whenever possible.
<ide> * Follow the [JavaScript](#javascript-styleguide) and [CoffeeScript](#coffeescript-styleguide) styleguides.
<del>* Include thoughtfully-worded, well-structured [Jasmine](http://jasmine.github.io/) specs in the `./spec` folder. Run them using `atom --test spec`. See the [Specs Styleguide](#specs-styleguide) below.
<add>* Include thoughtfully-worded, well-structured [Jasmine](https://jasmine.github.io/) specs in the `./spec` folder. Run them using `atom --test spec`. See the [Specs Styleguide](#specs-styleguide) below.
<ide> * Document new code based on the [Documentation Styleguide](#documentation-styleguide)
<ide> * End all files with a newline
<del>* [Avoid platform-dependent code](http://flight-manual.atom.io/hacking-atom/sections/cross-platform-compatibility/)
<add>* [Avoid platform-dependent code](https://flight-manual.atom.io/hacking-atom/sections/cross-platform-compatibility/)
<ide> * Place requires in the following order:
<ide> * Built in Node Modules (such as `path`)
<ide> * Built in Atom and Electron Modules (such as `atom`, `remote`)
<ide> Atom Core and all packages can be developed locally. For instructions on how to
<ide>
<ide> ### JavaScript Styleguide
<ide>
<del>All JavaScript must adhere to [JavaScript Standard Style](http://standardjs.com/).
<add>All JavaScript must adhere to [JavaScript Standard Style](https://standardjs.com/).
<ide>
<ide> * Prefer the object spread operator (`{...anotherObj}`) to `Object.assign()`
<ide> * Inline `export`s with expressions whenever possible
<ide> All JavaScript must adhere to [JavaScript Standard Style](http://standardjs.com/
<ide>
<ide> ### Specs Styleguide
<ide>
<del>- Include thoughtfully-worded, well-structured [Jasmine](http://jasmine.github.io/) specs in the `./spec` folder.
<add>- Include thoughtfully-worded, well-structured [Jasmine](https://jasmine.github.io/) specs in the `./spec` folder.
<ide> - Treat `describe` as a noun or situation.
<ide> - Treat `it` as a statement about state or how an operation changes state.
<ide>
<ide> Please open an issue on `atom/atom` if you have suggestions for new labels, and
<ide> | `windows` | [search][search-atom-repo-label-windows] | [search][search-atom-org-label-windows] | Related to Atom running on Windows. |
<ide> | `linux` | [search][search-atom-repo-label-linux] | [search][search-atom-org-label-linux] | Related to Atom running on Linux. |
<ide> | `mac` | [search][search-atom-repo-label-mac] | [search][search-atom-org-label-mac] | Related to Atom running on macOS. |
<del>| `documentation` | [search][search-atom-repo-label-documentation] | [search][search-atom-org-label-documentation] | Related to any type of documentation (e.g. [API documentation](https://atom.io/docs/api/latest/) and the [flight manual](http://flight-manual.atom.io/)). |
<add>| `documentation` | [search][search-atom-repo-label-documentation] | [search][search-atom-org-label-documentation] | Related to any type of documentation (e.g. [API documentation](https://atom.io/docs/api/latest/) and the [flight manual](https://flight-manual.atom.io/)). |
<ide> | `performance` | [search][search-atom-repo-label-performance] | [search][search-atom-org-label-performance] | Related to performance. |
<ide> | `security` | [search][search-atom-repo-label-security] | [search][search-atom-org-label-security] | Related to security. |
<ide> | `ui` | [search][search-atom-repo-label-ui] | [search][search-atom-org-label-ui] | Related to visual design. |
<ide> Please open an issue on `atom/atom` if you have suggestions for new labels, and
<ide>
<ide> [beginner]:https://github.com/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue+label%3Abeginner+label%3Ahelp-wanted+user%3Aatom+sort%3Acomments-desc
<ide> [help-wanted]:https://github.com/issues?q=is%3Aopen+is%3Aissue+label%3Ahelp-wanted+user%3Aatom+sort%3Acomments-desc+-label%3Abeginner
<del>[contributing-to-official-atom-packages]:http://flight-manual.atom.io/hacking-atom/sections/contributing-to-official-atom-packages/
<del>[hacking-on-atom-core]: http://flight-manual.atom.io/hacking-atom/sections/hacking-on-atom-core/
<add>[contributing-to-official-atom-packages]:https://flight-manual.atom.io/hacking-atom/sections/contributing-to-official-atom-packages/
<add>[hacking-on-atom-core]: https://flight-manual.atom.io/hacking-atom/sections/hacking-on-atom-core/ | 1 |
PHP | PHP | fix coding standards | fdcb3dc34f179dd20f4dc7f341bb7dee19da8b37 | <ide><path>lib/Cake/Test/Case/BasicsTest.php
<ide> public function testArrayDiffKey() {
<ide> $two = array('minYear' => null, 'maxYear' => null, 'separator' => '-', 'interval' => 1, 'monthNames' => true);
<ide> $result = array_diff_key($one, $two);
<ide> $this->assertEquals($result, array());
<del>
<ide> }
<ide>
<ide> /**
<ide> public function testArrayDiffKey() {
<ide> public function testEnv() {
<ide> $this->skipIf(!function_exists('ini_get') || ini_get('safe_mode') === '1', 'Safe mode is on.');
<ide>
<del> $__SERVER = $_SERVER;
<del> $__ENV = $_ENV;
<add> $server = $_SERVER;
<add> $env = $_ENV;
<ide>
<ide> $_SERVER['HTTP_HOST'] = 'localhost';
<ide> $this->assertEquals(env('HTTP_BASE'), '.localhost');
<ide> public function testEnv() {
<ide> unset($_ENV['TEST_ME']);
<ide> $this->assertEquals(env('TEST_ME'), 'b');
<ide>
<del> $_SERVER = $__SERVER;
<del> $_ENV = $__ENV;
<add> $_SERVER = $server;
<add> $_ENV = $env;
<ide> }
<ide>
<ide> /**
<ide> public function testClearCache() {
<ide> *
<ide> * @return void
<ide> */
<del> public function test__() {
<add> public function testTranslate() {
<ide> Configure::write('Config.language', 'rule_1_po');
<ide>
<ide> $result = __('Plural Rule 1');
<ide> public function test__() {
<ide> *
<ide> * @return void
<ide> */
<del> public function test__n() {
<add> public function testTranslatePlural() {
<ide> Configure::write('Config.language', 'rule_1_po');
<ide>
<ide> $result = __n('%d = 1', '%d = 0 or > 1', 0);
<ide> public function test__n() {
<ide> *
<ide> * @return void
<ide> */
<del> public function test__d() {
<add> public function testTranslateDomain() {
<ide> Configure::write('Config.language', 'rule_1_po');
<ide>
<ide> $result = __d('default', 'Plural Rule 1');
<ide> public function test__d() {
<ide> *
<ide> * @return void
<ide> */
<del> public function test__dn() {
<add> public function testTranslateDomainPlural() {
<ide> Configure::write('Config.language', 'rule_1_po');
<ide>
<ide> $result = __dn('default', '%d = 1', '%d = 0 or > 1', 0);
<ide> public function test__dn() {
<ide> *
<ide> * @return void
<ide> */
<del> public function test__c() {
<add> public function testTranslateCategory() {
<ide> Configure::write('Config.language', 'rule_1_po');
<ide>
<ide> $result = __c('Plural Rule 1', 6);
<ide> public function test__c() {
<ide> *
<ide> * @return void
<ide> */
<del> public function test__dc() {
<add> public function testTranslateDomainCategory() {
<ide> Configure::write('Config.language', 'rule_1_po');
<ide>
<ide> $result = __dc('default', 'Plural Rule 1', 6);
<ide> public function test__dc() {
<ide> *
<ide> * @return void
<ide> */
<del> public function test__dcn() {
<add> public function testTranslateDomainCategoryPlural() {
<ide> Configure::write('Config.language', 'rule_1_po');
<ide>
<ide> $result = __dcn('default', '%d = 1', '%d = 0 or > 1', 0, 6);
<ide> public function testConvertSlash() {
<ide> */
<ide> public function testDebug() {
<ide> ob_start();
<del> debug('this-is-a-test', false);
<add> debug('this-is-a-test', false);
<ide> $result = ob_get_clean();
<ide> $expectedText = <<<EXPECTED
<ide> %s (line %d)
<ide> public function testDebug() {
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> ob_start();
<del> debug('<div>this-is-a-test</div>', true);
<add> debug('<div>this-is-a-test</div>', true);
<ide> $result = ob_get_clean();
<ide> $expectedHtml = <<<EXPECTED
<ide> <div class="cake-debug-output">
<ide> public function testStripslashesDeep() {
<ide> $this->skipIf(ini_get('magic_quotes_sybase') === '1', 'magic_quotes_sybase is on.');
<ide>
<ide> $this->assertEquals(stripslashes_deep("tes\'t"), "tes't");
<del> $this->assertEquals(stripslashes_deep('tes\\' . chr(0) .'t'), 'tes' . chr(0) .'t');
<add> $this->assertEquals(stripslashes_deep('tes\\' . chr(0) . 't'), 'tes' . chr(0) . 't');
<ide> $this->assertEquals(stripslashes_deep('tes\"t'), 'tes"t');
<ide> $this->assertEquals(stripslashes_deep("tes\'t"), "tes't");
<ide> $this->assertEquals(stripslashes_deep('te\\st'), 'test');
<ide>
<ide> $nested = array(
<ide> 'a' => "tes\'t",
<del> 'b' => 'tes\\' . chr(0) .'t',
<add> 'b' => 'tes\\' . chr(0) . 't',
<ide> 'c' => array(
<ide> 'd' => 'tes\"t',
<ide> 'e' => "te\'s\'t",
<ide> array('f' => "tes\'t")
<ide> ),
<ide> 'g' => 'te\\st'
<del> );
<add> );
<ide> $expected = array(
<ide> 'a' => "tes't",
<del> 'b' => 'tes' . chr(0) .'t',
<add> 'b' => 'tes' . chr(0) . 't',
<ide> 'c' => array(
<ide> 'd' => 'tes"t',
<ide> 'e' => "te's't",
<ide> array('f' => "tes't")
<ide> ),
<ide> 'g' => 'test'
<del> );
<add> );
<ide> $this->assertEquals(stripslashes_deep($nested), $expected);
<ide> }
<ide> | 1 |
Go | Go | fix shared size computation for filtered requests | af3e5568fcca17bacb7d27d1bbff0b68bb855b83 | <ide><path>daemon/images/images.go
<ide> func (i *ImageService) Images(imageFilters filters.Args, all bool, withExtraAttr
<ide> return nil, err
<ide> }
<ide>
<del> var allImages map[image.ID]*image.Image
<add> var selectedImages map[image.ID]*image.Image
<ide> if danglingOnly {
<del> allImages = i.imageStore.Heads()
<add> selectedImages = i.imageStore.Heads()
<ide> } else {
<del> allImages = i.imageStore.Map()
<add> selectedImages = i.imageStore.Map()
<ide> }
<ide>
<ide> var (
<del> summaries []*types.ImageSummary
<add> summaries = make([]*types.ImageSummary, 0, len(selectedImages))
<ide> summaryMap map[*image.Image]*types.ImageSummary
<del> layerRefs map[layer.ChainID]int
<del> allLayers map[layer.ChainID]layer.Layer
<ide> allContainers []*container.Container
<ide> )
<del> for id, img := range allImages {
<add> for id, img := range selectedImages {
<ide> if beforeFilter != nil {
<ide> if img.Created.Equal(beforeFilter.Created) || img.Created.After(beforeFilter.Created) {
<ide> continue
<ide> func (i *ImageService) Images(imageFilters filters.Args, all bool, withExtraAttr
<ide> }
<ide>
<ide> if withExtraAttrs {
<del> // lazily init variables
<add> // Lazily init summaryMap and allContainers
<ide> if summaryMap == nil {
<add> summaryMap = make(map[*image.Image]*types.ImageSummary, len(selectedImages))
<ide> allContainers = i.containers.List()
<del> allLayers = i.layerStore.Map()
<del> summaryMap = make(map[*image.Image]*types.ImageSummary)
<del> layerRefs = make(map[layer.ChainID]int)
<ide> }
<ide>
<ide> // Get container count
<ide> func (i *ImageService) Images(imageFilters filters.Args, all bool, withExtraAttr
<ide> // NOTE: By default, Containers is -1, or "not set"
<ide> summary.Containers = containers
<ide>
<del> // count layer references
<add> summaryMap[img] = summary
<add> }
<add> summaries = append(summaries, summary)
<add> }
<add>
<add> if withExtraAttrs {
<add> allLayers := i.layerStore.Map()
<add> layerRefs := make(map[layer.ChainID]int, len(allLayers))
<add>
<add> allImages := selectedImages
<add> if danglingOnly {
<add> // If danglingOnly is true, then selectedImages include only dangling images,
<add> // but we need to consider all existing images to correctly perform reference counting.
<add> // If danglingOnly is false, selectedImages (and, hence, allImages) is already equal to i.imageStore.Map()
<add> // and we can avoid performing an otherwise redundant method call.
<add> allImages = i.imageStore.Map()
<add> }
<add> // Count layer references across all known images
<add> for _, img := range allImages {
<ide> rootFS := *img.RootFS
<ide> rootFS.DiffIDs = nil
<ide> for _, id := range img.RootFS.DiffIDs {
<ide> rootFS.Append(id)
<ide> layerRefs[rootFS.ChainID()]++
<ide> }
<del> summaryMap[img] = summary
<ide> }
<del> summaries = append(summaries, summary)
<del> }
<ide>
<del> if withExtraAttrs {
<ide> // Get Shared sizes
<ide> for img, summary := range summaryMap {
<ide> rootFS := *img.RootFS | 1 |
Javascript | Javascript | fix mapview crashing problem | 3ec3312c7cc74d67a62b87fe32ad0a84db78ce93 | <ide><path>Libraries/Components/MapView/MapView.js
<ide> if (Platform.OS === 'android') {
<ide> var RCTMap = createReactNativeComponentClass({
<ide> validAttributes: merge(
<ide> ReactNativeViewAttributes.UIView, {
<add> active: true,
<ide> showsUserLocation: true,
<ide> zoomEnabled: true,
<ide> rotateEnabled: true, | 1 |
Go | Go | prevent plugin when volume plugin is disabled | 34f4b197b8cec5b177797e343a5c89473ff1d2aa | <ide><path>plugin/store/store.go
<ide> func (ps *Store) getAllByCap(capability string) []plugingetter.CompatPlugin {
<ide>
<ide> result := make([]plugingetter.CompatPlugin, 0, 1)
<ide> for _, p := range ps.plugins {
<del> if _, err := p.FilterByCap(capability); err == nil {
<del> result = append(result, p)
<add> if p.IsEnabled() {
<add> if _, err := p.FilterByCap(capability); err == nil {
<add> result = append(result, p)
<add> }
<ide> }
<ide> }
<ide> return result | 1 |
Javascript | Javascript | replace @provides with @providesmodule | d82f2553fb0da40b02ca5515767211105e2eec07 | <ide><path>Examples/UIExplorer/js/ListViewPagingExample.js
<ide> * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
<ide> * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<ide> *
<del> * @provides ListViewPagingExample
<add> * @providesModule ListViewPagingExample
<ide> * @flow
<ide> */
<ide> 'use strict';
<ide><path>packager/src/Resolver/polyfills/Array.es6.js
<ide> * LICENSE file in the root directory of this source tree. An additional grant
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<del> * @provides Array.es6
<add> * @providesModule Array.es6
<ide> * @polyfill
<ide> */
<ide>
<ide><path>packager/src/Resolver/polyfills/Array.prototype.es6.js
<ide> * LICENSE file in the root directory of this source tree. An additional grant
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<del> * @provides Array.prototype.es6
<add> * @providesModule Array.prototype.es6
<ide> * @polyfill
<ide> */
<ide>
<ide><path>packager/src/Resolver/polyfills/Number.es6.js
<ide> * LICENSE file in the root directory of this source tree. An additional grant
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<del> * @provides Number.es6
<add> * @providesModule Number.es6
<ide> * @polyfill
<ide> */
<ide>
<ide><path>packager/src/Resolver/polyfills/Object.es7.js
<ide> * LICENSE file in the root directory of this source tree. An additional grant
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<del> * @provides Object.es7
<add> * @providesModule Object.es7
<ide> * @polyfill
<ide> */
<ide>
<ide><path>packager/src/Resolver/polyfills/String.prototype.es6.js
<ide> * LICENSE file in the root directory of this source tree. An additional grant
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<del> * @provides String.prototype.es6
<add> * @providesModule String.prototype.es6
<ide> * @polyfill
<ide> */
<ide>
<ide><path>packager/src/Resolver/polyfills/console.js
<ide> * LICENSE file in the root directory of this source tree. An additional grant
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<del> * @provides console
<add> * @providesModule console
<ide> * @polyfill
<ide> * @nolint
<ide> */
<ide><path>packager/src/Resolver/polyfills/polyfills.js
<ide> * LICENSE file in the root directory of this source tree. An additional grant
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<del> * @provides Object.es6
<add> * @providesModule Object.es6
<ide> * @polyfill
<ide> */
<ide>
<ide><path>packager/src/node-haste/Module.js
<ide> class Module {
<ide> // modules, such as react-haste, fbjs-haste, or react-native or with non-dependency,
<ide> // project-specific code that is using @providesModule.
<ide> const moduleDocBlock = docblock.parseAsObject(docBlock);
<del> const provides = moduleDocBlock.providesModule || moduleDocBlock.provides;
<add> const providesModule = moduleDocBlock.providesModule;
<ide>
<del> const id = provides && !this._depGraphHelpers.isNodeModulesDir(this.path)
<del> ? /^\S+/.exec(provides)[0]
<add> const id =
<add> providesModule && !this._depGraphHelpers.isNodeModulesDir(this.path)
<add> ? /^\S+/.exec(providesModule)[0]
<ide> : undefined;
<ide> return {id, moduleDocBlock};
<ide> }
<ide><path>packager/src/node-haste/__tests__/Module-test.js
<ide> describe('Module', () => {
<ide> });
<ide> });
<ide>
<del> describe('@provides annotations', () => {
<del> beforeEach(() => {
<del> mockIndexFile(source.replace(/@providesModule/, '@provides'));
<del> });
<del>
<del> it('extracts the module name from the header if it has a @provides annotation', () =>
<del> module.getName().then(name => expect(name).toEqual(moduleId))
<del> );
<del>
<del> it('identifies the module as haste module', () =>
<del> module.isHaste().then(isHaste => expect(isHaste).toBe(true))
<del> );
<del>
<del> it('does not transform the file in order to access the name', () => {
<del> const transformCode =
<del> jest.genMockFn().mockReturnValue(Promise.resolve());
<del> return createModule({transformCode}).getName()
<del> .then(() => expect(transformCode).not.toBeCalled());
<del> });
<del>
<del> it('does not transform the file in order to access the haste status', () => {
<del> const transformCode =
<del> jest.genMockFn().mockReturnValue(Promise.resolve());
<del> return createModule({transformCode}).isHaste()
<del> .then(() => expect(transformCode).not.toBeCalled());
<del> });
<del> });
<del>
<ide> describe('no annotation', () => {
<ide> beforeEach(() => {
<ide> mockIndexFile('arbitrary(code);');
<ide><path>website/jsdocs/jsdocs.js
<ide> function getFileDocBlock(commentsForFile) {
<ide> inCopyrightBlock = true;
<ide> }
<ide>
<del> var hasProvides = !!line.match(/^\s*\*\s+@provides/);
<add> var hasProvidesModule = !!line.match(/^\s*\*\s+@providesModule/);
<ide> var hasFlow = !!line.match(/^\s*\*\s+@flow/);
<ide>
<del> if (hasFlow || hasProvides) {
<add> if (hasFlow || hasProvidesModule) {
<ide> inCopyrightBlock = false;
<ide> }
<ide>
<del> return !inCopyrightBlock && !hasFlow && !hasProvides;
<add> return !inCopyrightBlock && !hasFlow && !hasProvidesModule;
<ide> });
<ide> docblock = filteredLines.join('\n');
<ide> return true; | 11 |
Ruby | Ruby | avoid misuse of underscore argument | a076b8cde99281511eab5d2118a3287b1833bb20 | <ide><path>actionpack/lib/action_controller/metal/strong_parameters.rb
<ide> def permitted?
<ide> def permit!
<ide> each_pair do |key, value|
<ide> value = convert_hashes_to_parameters(key, value)
<del> Array.wrap(value).each do |_|
<del> _.permit! if _.respond_to? :permit!
<add> Array.wrap(value).each do |v|
<add> v.permit! if v.respond_to? :permit!
<ide> end
<ide> end
<ide> | 1 |
Javascript | Javascript | use uri instead of url in source property of image | 9b882a3b44a9b35210de53cccc8e61c8fbfca566 | <ide><path>Examples/UIExplorer/js/ImageExample.js
<ide> exports.examples = [
<ide> <View style={{flexDirection: 'row'}}>
<ide> <Image
<ide> source={{
<del> url: 'ImageInBundle',
<add> uri: 'ImageInBundle',
<ide> bundle: 'UIExplorerBundle',
<ide> width: 100,
<ide> height: 100,
<ide> exports.examples = [
<ide> />
<ide> <Image
<ide> source={{
<del> url: 'ImageInAssetCatalog',
<add> uri: 'ImageInAssetCatalog',
<ide> bundle: 'UIExplorerBundle',
<ide> width: 100,
<ide> height: 100, | 1 |
Javascript | Javascript | fix some scrollview lint | f40de0e467815062c9bc61e645a835006b58c574 | <ide><path>Libraries/Components/ScrollView/ScrollView.js
<ide> const ScrollView = createReactClass({
<ide> ScrollViewClass = RCTScrollView;
<ide> ScrollContentContainerViewClass = RCTScrollContentView;
<ide> warning(
<del> !this.props.snapToInterval || !this.props.pagingEnabled,
<add> this.props.snapToInterval != null || !this.props.pagingEnabled,
<ide> 'snapToInterval is currently ignored when pagingEnabled is true.',
<ide> );
<ide> }
<ide> const ScrollView = createReactClass({
<ide> };
<ide>
<ide> const {decelerationRate} = this.props;
<del> if (decelerationRate) {
<add> if (decelerationRate != null) {
<ide> props.decelerationRate = processDecelerationRate(decelerationRate);
<ide> }
<ide> | 1 |
Ruby | Ruby | remove usage of memoizable from actionpack | f2c0fb32c0dce7f8da0ce446e2d2f0cba5fd44b3 | <ide><path>actionpack/lib/action_dispatch/http/headers.rb
<ide> module ActionDispatch
<ide> module Http
<ide> class Headers < ::Hash
<del> extend ActiveSupport::Memoizable
<add> @@env_cache = Hash.new { |h,k| h[k] = "HTTP_#{k.upcase.gsub(/-/, '_')}" }
<ide>
<ide> def initialize(*args)
<add>
<ide> if args.size == 1 && args[0].is_a?(Hash)
<ide> super()
<ide> update(args[0])
<ide> def [](header_name)
<ide> private
<ide> # Converts a HTTP header name to an environment variable name.
<ide> def env_name(header_name)
<del> "HTTP_#{header_name.upcase.gsub(/-/, '_')}"
<add> @@env_cache[header_name]
<ide> end
<del> memoize :env_name
<ide> end
<ide> end
<ide> end
<ide><path>actionpack/lib/action_view/helpers/date_helper.rb
<ide> def time_tag(date_or_time, *args)
<ide> end
<ide>
<ide> class DateTimeSelector #:nodoc:
<del> extend ActiveSupport::Memoizable
<ide> include ActionView::Helpers::TagHelper
<ide>
<ide> DEFAULT_PREFIX = 'date'.freeze
<ide> def select_year
<ide> # Returns translated month names, but also ensures that a custom month
<ide> # name array has a leading nil element.
<ide> def month_names
<del> month_names = @options[:use_month_names] || translated_month_names
<del> month_names.unshift(nil) if month_names.size < 13
<del> month_names
<add> @month_names ||= begin
<add> month_names = @options[:use_month_names] || translated_month_names
<add> month_names.unshift(nil) if month_names.size < 13
<add> month_names
<add> end
<ide> end
<del> memoize :month_names
<ide>
<ide> # Returns translated month names.
<ide> # => [nil, "January", "February", "March",
<ide> def month_name(number)
<ide> end
<ide>
<ide> def date_order
<del> @options[:order] || translated_date_order
<add> @date_order ||= @options[:order] || translated_date_order
<ide> end
<del> memoize :date_order
<ide>
<ide> def translated_date_order
<ide> I18n.translate(:'date.order', :locale => @options[:locale]) || [] | 2 |
Ruby | Ruby | freeze a string in comparator | 045cdd3a3d50b06019361cf7bec57f2521facff6 | <ide><path>actionpack/lib/action_dispatch/routing/route_set.rb
<ide> def normalize_controller!
<ide>
<ide> # Move 'index' action from options to recall
<ide> def normalize_action!
<del> if @options[:action] == 'index'
<add> if @options[:action] == 'index'.freeze
<ide> @recall[:action] = @options.delete(:action)
<ide> end
<ide> end | 1 |
Javascript | Javascript | fix lint error in dom fixtures | 028e0ea9371b890fe6accac6b04ff8430abebd34 | <ide><path>fixtures/dom/src/components/fixtures/date-inputs/index.js
<del>const React = window.React;
<del>
<ide> import Fixture from '../../Fixture';
<ide> import FixtureSet from '../../FixtureSet';
<ide> import TestCase from '../../TestCase';
<ide> import SwitchDateTestCase from './switch-date-test-case';
<ide>
<add>const React = window.React;
<add>
<ide> class DateInputFixtures extends React.Component {
<ide> render() {
<ide> return ( | 1 |
Java | Java | move http.server to http.server.reactive | da98becf72fbeef836dba366431be2a652e5e001 | <add><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/FilterChainHttpHandler.java
<del><path>spring-web-reactive/src/main/java/org/springframework/http/server/FilterChainHttpHandler.java
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> */
<del>package org.springframework.http.server;
<add>package org.springframework.http.server.reactive;
<ide>
<ide> import java.util.Arrays;
<ide> import java.util.Collections;
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<del> * An {@link ReactiveHttpHandler} decorator that delegates to a list of
<del> * {@link ReactiveHttpFilter}s and the target {@link ReactiveHttpHandler}.
<add> * An {@link HttpHandler} decorator that delegates to a list of
<add> * {@link HttpFilter}s and the target {@link HttpHandler}.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> */
<del>public class FilterChainHttpHandler implements ReactiveHttpHandler {
<add>public class FilterChainHttpHandler implements HttpHandler {
<ide>
<del> private final List<ReactiveHttpFilter> filters;
<add> private final List<HttpFilter> filters;
<ide>
<del> private final ReactiveHttpHandler targetHandler;
<add> private final HttpHandler targetHandler;
<ide>
<ide>
<del> public FilterChainHttpHandler(ReactiveHttpHandler targetHandler, ReactiveHttpFilter... filters) {
<add> public FilterChainHttpHandler(HttpHandler targetHandler, HttpFilter... filters) {
<ide> Assert.notNull(targetHandler, "'targetHandler' is required.");
<ide> this.filters = (filters != null ? Arrays.asList(filters) : Collections.emptyList());
<ide> this.targetHandler = targetHandler;
<ide> }
<ide>
<ide>
<ide> @Override
<del> public Publisher<Void> handle(ReactiveServerHttpRequest request, ReactiveServerHttpResponse response) {
<add> public Publisher<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
<ide> return new DefaultHttpFilterChain().filter(request, response);
<ide> }
<ide>
<ide>
<del> private class DefaultHttpFilterChain implements ReactiveHttpFilterChain {
<add> private class DefaultHttpFilterChain implements HttpFilterChain {
<ide>
<ide> private int index;
<ide>
<ide> @Override
<del> public Publisher<Void> filter(ReactiveServerHttpRequest request, ReactiveServerHttpResponse response) {
<add> public Publisher<Void> filter(ServerHttpRequest request, ServerHttpResponse response) {
<ide> if (this.index < filters.size()) {
<del> ReactiveHttpFilter filter = filters.get(this.index++);
<add> HttpFilter filter = filters.get(this.index++);
<ide> return filter.filter(request, response, this);
<ide> }
<ide> else {
<add><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/HttpFilter.java
<del><path>spring-web-reactive/src/main/java/org/springframework/http/server/ReactiveHttpFilter.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.http.server;
<add>package org.springframework.http.server.reactive;
<ide>
<ide> import org.reactivestreams.Publisher;
<ide>
<ide> /**
<ide> * @author Rossen Stoyanchev
<ide> */
<del>public interface ReactiveHttpFilter {
<add>public interface HttpFilter {
<ide>
<ide>
<del> Publisher<Void> filter(ReactiveServerHttpRequest request, ReactiveServerHttpResponse response,
<del> ReactiveHttpFilterChain chain);
<add> Publisher<Void> filter(ServerHttpRequest request, ServerHttpResponse response,
<add> HttpFilterChain chain);
<ide>
<ide> }
<add><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/HttpFilterChain.java
<del><path>spring-web-reactive/src/main/java/org/springframework/http/server/ReactiveHttpFilterChain.java
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> */
<del>package org.springframework.http.server;
<add>package org.springframework.http.server.reactive;
<ide>
<ide> import org.reactivestreams.Publisher;
<ide>
<del>import org.springframework.http.server.ReactiveServerHttpRequest;
<del>import org.springframework.http.server.ReactiveServerHttpResponse;
<del>
<ide>
<ide> /**
<ide> * @author Rossen Stoyanchev
<ide> */
<del>public interface ReactiveHttpFilterChain {
<add>public interface HttpFilterChain {
<ide>
<del> Publisher<Void> filter(ReactiveServerHttpRequest request, ReactiveServerHttpResponse response);
<add> Publisher<Void> filter(ServerHttpRequest request, ServerHttpResponse response);
<ide>
<ide> }
<add><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/HttpHandler.java
<del><path>spring-web-reactive/src/main/java/org/springframework/http/server/ReactiveHttpHandler.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.http.server;
<add>package org.springframework.http.server.reactive;
<ide>
<ide> import org.reactivestreams.Publisher;
<ide>
<ide> * @author Arjen Poutsma
<ide> * @author Rossen Stoyanchev
<ide> * @author Sebastien Deleuze
<del> * @see ReactiveServerHttpRequest#getBody()
<del> * @see ReactiveServerHttpResponse#setBody(Publisher)
<add> * @see ServerHttpRequest#getBody()
<add> * @see ServerHttpResponse#setBody(Publisher)
<ide> */
<del>public interface ReactiveHttpHandler {
<add>public interface HttpHandler {
<ide>
<ide> /**
<ide> * Process the given request, generating a response in an asynchronous non blocking way.
<ide> public interface ReactiveHttpHandler {
<ide> * when the handling is complete (success or error) including the flush of the data on the
<ide> * network.
<ide> */
<del> Publisher<Void> handle(ReactiveServerHttpRequest request, ReactiveServerHttpResponse response);
<add> Publisher<Void> handle(ServerHttpRequest request, ServerHttpResponse response);
<ide>
<ide> }
<add><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/ReactorHttpHandlerAdapter.java
<del><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactor/HttpHandlerChannelHandler.java
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> */
<del>package org.springframework.http.server.reactor;
<add>package org.springframework.http.server.reactive;
<ide>
<ide> import org.reactivestreams.Publisher;
<ide> import reactor.io.buffer.Buffer;
<ide> import reactor.io.net.ReactiveChannelHandler;
<ide> import reactor.io.net.http.HttpChannel;
<ide>
<del>import org.springframework.http.server.ReactiveHttpHandler;
<add>import org.springframework.http.server.reactive.HttpHandler;
<add>import org.springframework.http.server.reactive.ReactorServerHttpRequest;
<add>import org.springframework.http.server.reactive.ReactorServerHttpResponse;
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<ide> * @author Stephane Maldini
<ide> */
<del>public class HttpHandlerChannelHandler
<add>public class ReactorHttpHandlerAdapter
<ide> implements ReactiveChannelHandler<Buffer, Buffer, HttpChannel<Buffer, Buffer>> {
<ide>
<del> private final ReactiveHttpHandler httpHandler;
<add> private final HttpHandler httpHandler;
<ide>
<ide>
<del> public HttpHandlerChannelHandler(ReactiveHttpHandler httpHandler) {
<add> public ReactorHttpHandlerAdapter(HttpHandler httpHandler) {
<ide> Assert.notNull(httpHandler, "'httpHandler' is required.");
<ide> this.httpHandler = httpHandler;
<ide> }
<add><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/ReactorServerHttpRequest.java
<del><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactor/ReactorServerHttpRequest.java
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> */
<del>package org.springframework.http.server.reactor;
<add>package org.springframework.http.server.reactive;
<ide>
<ide> import java.net.URI;
<ide> import java.net.URISyntaxException;
<ide>
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<del>import org.springframework.http.server.ReactiveServerHttpRequest;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<ide> * @author Stephane Maldini
<ide> */
<del>public class ReactorServerHttpRequest implements ReactiveServerHttpRequest {
<add>public class ReactorServerHttpRequest implements ServerHttpRequest {
<ide>
<ide> private final HttpChannel<Buffer, ?> channel;
<ide>
<add><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/ReactorServerHttpResponse.java
<del><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactor/ReactorServerHttpResponse.java
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> */
<del>package org.springframework.http.server.reactor;
<add>package org.springframework.http.server.reactive;
<ide>
<ide> import java.nio.ByteBuffer;
<ide>
<ide>
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpStatus;
<del>import org.springframework.http.server.ReactiveServerHttpResponse;
<add>import org.springframework.http.server.reactive.ServerHttpResponse;
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<ide> * @author Stephane Maldini
<ide> */
<del>public class ReactorServerHttpResponse implements ReactiveServerHttpResponse {
<add>public class ReactorServerHttpResponse implements ServerHttpResponse {
<ide>
<ide> private final HttpChannel<?, Buffer> channel;
<ide>
<add><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/RxNettyHttpHandlerAdapter.java
<del><path>spring-web-reactive/src/main/java/org/springframework/http/server/rxnetty/HttpHandlerRequestHandler.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.http.server.rxnetty;
<add>package org.springframework.http.server.reactive;
<ide>
<ide> import io.netty.buffer.ByteBuf;
<ide> import io.reactivex.netty.protocol.http.server.HttpServerRequest;
<ide> import reactor.core.publisher.convert.RxJava1Converter;
<ide> import rx.Observable;
<ide>
<del>import org.springframework.http.server.ReactiveHttpHandler;
<add>import org.springframework.http.server.reactive.HttpHandler;
<add>import org.springframework.http.server.reactive.RxNettyServerHttpRequest;
<add>import org.springframework.http.server.reactive.RxNettyServerHttpResponse;
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<ide> * @author Rossen Stoyanchev
<ide> */
<del>public class HttpHandlerRequestHandler implements RequestHandler<ByteBuf, ByteBuf> {
<add>public class RxNettyHttpHandlerAdapter implements RequestHandler<ByteBuf, ByteBuf> {
<ide>
<del> private final ReactiveHttpHandler httpHandler;
<add> private final HttpHandler httpHandler;
<ide>
<ide>
<del> public HttpHandlerRequestHandler(ReactiveHttpHandler httpHandler) {
<add> public RxNettyHttpHandlerAdapter(HttpHandler httpHandler) {
<ide> Assert.notNull(httpHandler, "'httpHandler' is required.");
<ide> this.httpHandler = httpHandler;
<ide> }
<add><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/RxNettyServerHttpRequest.java
<del><path>spring-web-reactive/src/main/java/org/springframework/http/server/rxnetty/RxNettyServerHttpRequest.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.http.server.rxnetty;
<add>package org.springframework.http.server.reactive;
<ide>
<ide> import java.net.URI;
<ide> import java.net.URISyntaxException;
<ide>
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<del>import org.springframework.http.server.ReactiveServerHttpRequest;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<ide> * @author Rossen Stoyanchev
<ide> * @author Stephane Maldini
<ide> */
<del>public class RxNettyServerHttpRequest implements ReactiveServerHttpRequest {
<add>public class RxNettyServerHttpRequest implements ServerHttpRequest {
<ide>
<ide> private final HttpServerRequest<ByteBuf> request;
<ide>
<add><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/RxNettyServerHttpResponse.java
<del><path>spring-web-reactive/src/main/java/org/springframework/http/server/rxnetty/RxNettyServerHttpResponse.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.http.server.rxnetty;
<add>package org.springframework.http.server.reactive;
<ide>
<ide> import java.nio.ByteBuffer;
<ide>
<ide>
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpStatus;
<del>import org.springframework.http.server.ReactiveServerHttpResponse;
<add>import org.springframework.http.server.reactive.ServerHttpResponse;
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<ide> * @author Rossen Stoyanchev
<ide> * @author Stephane Maldini
<ide> */
<del>public class RxNettyServerHttpResponse implements ReactiveServerHttpResponse {
<add>public class RxNettyServerHttpResponse implements ServerHttpResponse {
<ide>
<ide> private final HttpServerResponse<?> response;
<ide>
<add><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/ServerHttpRequest.java
<del><path>spring-web-reactive/src/main/java/org/springframework/http/server/ReactiveServerHttpRequest.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.http.server;
<add>package org.springframework.http.server.reactive;
<ide>
<ide> import org.springframework.http.HttpRequest;
<ide> import org.springframework.http.ReactiveHttpInputMessage;
<ide> *
<ide> * @author Arjen Poutsma
<ide> */
<del>public interface ReactiveServerHttpRequest extends HttpRequest, ReactiveHttpInputMessage {
<add>public interface ServerHttpRequest extends HttpRequest, ReactiveHttpInputMessage {
<ide>
<ide> }
<add><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/ServerHttpResponse.java
<del><path>spring-web-reactive/src/main/java/org/springframework/http/server/ReactiveServerHttpResponse.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.http.server;
<add>package org.springframework.http.server.reactive;
<ide>
<ide> import org.reactivestreams.Publisher;
<ide>
<ide> *
<ide> * @author Arjen Poutsma
<ide> */
<del>public interface ReactiveServerHttpResponse extends ReactiveHttpOutputMessage {
<add>public interface ServerHttpResponse extends ReactiveHttpOutputMessage {
<ide>
<ide> /**
<ide> * Set the HTTP status code of the response.
<add><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/ServletAsyncContextSynchronizer.java
<del><path>spring-web-reactive/src/main/java/org/springframework/http/server/servlet31/AsyncContextSynchronizer.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.http.server.servlet31;
<add>package org.springframework.http.server.reactive;
<ide>
<ide> import java.io.IOException;
<ide> import java.util.concurrent.atomic.AtomicInteger;
<ide> * @author Arjen Poutsma
<ide> * @see AsyncContext
<ide> */
<del>final class AsyncContextSynchronizer {
<add>final class ServletAsyncContextSynchronizer {
<ide>
<ide> private static final int NONE_COMPLETE = 0;
<ide>
<ide> final class AsyncContextSynchronizer {
<ide> * Creates a new {@code AsyncContextSynchronizer} based on the given context.
<ide> * @param asyncContext the context to base this synchronizer on
<ide> */
<del> public AsyncContextSynchronizer(AsyncContext asyncContext) {
<add> public ServletAsyncContextSynchronizer(AsyncContext asyncContext) {
<ide> this.asyncContext = asyncContext;
<ide> }
<ide>
<add><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/ServletHttpHandlerAdapter.java
<del><path>spring-web-reactive/src/main/java/org/springframework/http/server/servlet31/HttpHandlerServlet.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.http.server.servlet31;
<add>package org.springframework.http.server.reactive;
<ide>
<ide> import java.io.IOException;
<ide> import javax.servlet.AsyncContext;
<ide> import org.reactivestreams.Subscription;
<ide>
<ide> import org.springframework.http.HttpStatus;
<del>import org.springframework.http.server.ReactiveHttpHandler;
<ide>
<ide> /**
<ide> * @author Arjen Poutsma
<ide> * @author Rossen Stoyanchev
<ide> */
<ide> @WebServlet(asyncSupported = true)
<del>public class HttpHandlerServlet extends HttpServlet {
<add>public class ServletHttpHandlerAdapter extends HttpServlet {
<ide>
<del> private static final int BUFFER_SIZE = 8192;
<add> private static Log logger = LogFactory.getLog(ServletHttpHandlerAdapter.class);
<ide>
<del> private static Log logger = LogFactory.getLog(HttpHandlerServlet.class);
<ide>
<add> private HttpHandler handler;
<ide>
<del> private ReactiveHttpHandler handler;
<ide>
<del>
<del> public void setHandler(ReactiveHttpHandler handler) {
<add> public void setHandler(HttpHandler handler) {
<ide> this.handler = handler;
<ide> }
<ide>
<ide> protected void service(HttpServletRequest request, HttpServletResponse response)
<ide> throws ServletException, IOException {
<ide>
<ide> AsyncContext context = request.startAsync();
<del> AsyncContextSynchronizer synchronizer = new AsyncContextSynchronizer(context);
<add> ServletAsyncContextSynchronizer synchronizer = new ServletAsyncContextSynchronizer(context);
<ide>
<del> RequestBodyPublisher requestPublisher = new RequestBodyPublisher(synchronizer, BUFFER_SIZE);
<del> request.getInputStream().setReadListener(requestPublisher);
<del> Servlet31ServerHttpRequest httpRequest = new Servlet31ServerHttpRequest(request, requestPublisher);
<add> ServletServerHttpRequest httpRequest = new ServletServerHttpRequest(request, synchronizer);
<add> request.getInputStream().setReadListener(httpRequest.getReadListener());
<ide>
<del> ResponseBodySubscriber responseSubscriber = new ResponseBodySubscriber(synchronizer);
<del> response.getOutputStream().setWriteListener(responseSubscriber);
<del> Servlet31ServerHttpResponse httpResponse = new Servlet31ServerHttpResponse(response, responseSubscriber);
<add> ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response, synchronizer);
<add> response.getOutputStream().setWriteListener(httpResponse.getWriteListener());
<ide>
<ide> HandlerResultSubscriber resultSubscriber = new HandlerResultSubscriber(synchronizer, httpResponse);
<ide> this.handler.handle(httpRequest, httpResponse).subscribe(resultSubscriber);
<ide> protected void service(HttpServletRequest request, HttpServletResponse response)
<ide>
<ide> private static class HandlerResultSubscriber implements Subscriber<Void> {
<ide>
<del> private final AsyncContextSynchronizer synchronizer;
<add> private final ServletAsyncContextSynchronizer synchronizer;
<ide>
<del> private final Servlet31ServerHttpResponse response;
<add> private final ServletServerHttpResponse response;
<ide>
<ide>
<del> public HandlerResultSubscriber(AsyncContextSynchronizer synchronizer,
<del> Servlet31ServerHttpResponse response) {
<add> public HandlerResultSubscriber(ServletAsyncContextSynchronizer synchronizer,
<add> ServletServerHttpResponse response) {
<ide>
<ide> this.synchronizer = synchronizer;
<ide> this.response = response;
<ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/ServletServerHttpRequest.java
<add>/*
<add> * Copyright 2002-2015 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.http.server.reactive;
<add>
<add>import java.io.IOException;
<add>import java.net.URI;
<add>import java.net.URISyntaxException;
<add>import java.nio.ByteBuffer;
<add>import java.nio.charset.Charset;
<add>import java.util.Arrays;
<add>import java.util.Enumeration;
<add>import java.util.Map;
<add>import java.util.concurrent.atomic.AtomicLong;
<add>import javax.servlet.ReadListener;
<add>import javax.servlet.ServletInputStream;
<add>import javax.servlet.http.HttpServletRequest;
<add>
<add>import org.apache.commons.logging.Log;
<add>import org.apache.commons.logging.LogFactory;
<add>import org.reactivestreams.Publisher;
<add>import org.reactivestreams.Subscriber;
<add>import org.reactivestreams.Subscription;
<add>
<add>import org.springframework.http.HttpHeaders;
<add>import org.springframework.http.HttpMethod;
<add>import org.springframework.http.MediaType;
<add>import org.springframework.util.Assert;
<add>import org.springframework.util.LinkedCaseInsensitiveMap;
<add>import org.springframework.util.StringUtils;
<add>
<add>/**
<add> * @author Rossen Stoyanchev
<add> */
<add>public class ServletServerHttpRequest implements ServerHttpRequest {
<add>
<add> private static final int BUFFER_SIZE = 8192;
<add>
<add> private static final Log logger = LogFactory.getLog(ServletServerHttpRequest.class);
<add>
<add>
<add> private final HttpServletRequest servletRequest;
<add>
<add> private HttpHeaders headers;
<add>
<add> private final RequestBodyPublisher requestBodyPublisher;
<add>
<add>
<add> public ServletServerHttpRequest(HttpServletRequest servletRequest, ServletAsyncContextSynchronizer synchronizer) {
<add> Assert.notNull(servletRequest, "HttpServletRequest must not be null");
<add> this.servletRequest = servletRequest;
<add> this.requestBodyPublisher = new RequestBodyPublisher(synchronizer, BUFFER_SIZE);
<add> }
<add>
<add>
<add> @Override
<add> public HttpMethod getMethod() {
<add> return HttpMethod.valueOf(this.servletRequest.getMethod());
<add> }
<add>
<add> @Override
<add> public URI getURI() {
<add> try {
<add> return new URI(this.servletRequest.getScheme(), null, this.servletRequest.getServerName(),
<add> this.servletRequest.getServerPort(), this.servletRequest.getRequestURI(),
<add> this.servletRequest.getQueryString(), null);
<add> }
<add> catch (URISyntaxException ex) {
<add> throw new IllegalStateException("Could not get HttpServletRequest URI: " + ex.getMessage(), ex);
<add> }
<add> }
<add>
<add> @Override
<add> public HttpHeaders getHeaders() {
<add> if (this.headers == null) {
<add> this.headers = new HttpHeaders();
<add> for (Enumeration<?> names = this.servletRequest.getHeaderNames(); names.hasMoreElements(); ) {
<add> String headerName = (String) names.nextElement();
<add> for (Enumeration<?> headerValues = this.servletRequest.getHeaders(headerName);
<add> headerValues.hasMoreElements(); ) {
<add> String headerValue = (String) headerValues.nextElement();
<add> this.headers.add(headerName, headerValue);
<add> }
<add> }
<add> // HttpServletRequest exposes some headers as properties: we should include those if not already present
<add> MediaType contentType = this.headers.getContentType();
<add> if (contentType == null) {
<add> String requestContentType = this.servletRequest.getContentType();
<add> if (StringUtils.hasLength(requestContentType)) {
<add> contentType = MediaType.parseMediaType(requestContentType);
<add> this.headers.setContentType(contentType);
<add> }
<add> }
<add> if (contentType != null && contentType.getCharSet() == null) {
<add> String requestEncoding = this.servletRequest.getCharacterEncoding();
<add> if (StringUtils.hasLength(requestEncoding)) {
<add> Charset charSet = Charset.forName(requestEncoding);
<add> Map<String, String> params = new LinkedCaseInsensitiveMap<>();
<add> params.putAll(contentType.getParameters());
<add> params.put("charset", charSet.toString());
<add> MediaType newContentType = new MediaType(contentType.getType(), contentType.getSubtype(), params);
<add> this.headers.setContentType(newContentType);
<add> }
<add> }
<add> if (this.headers.getContentLength() == -1) {
<add> int requestContentLength = this.servletRequest.getContentLength();
<add> if (requestContentLength != -1) {
<add> this.headers.setContentLength(requestContentLength);
<add> }
<add> }
<add> }
<add> return this.headers;
<add> }
<add>
<add> @Override
<add> public Publisher<ByteBuffer> getBody() {
<add> return this.requestBodyPublisher;
<add> }
<add>
<add> ReadListener getReadListener() {
<add> return this.requestBodyPublisher;
<add> }
<add>
<add>
<add> private static class RequestBodyPublisher implements ReadListener, Publisher<ByteBuffer> {
<add>
<add> private final ServletAsyncContextSynchronizer synchronizer;
<add>
<add> private final byte[] buffer;
<add>
<add> private final DemandCounter demand = new DemandCounter();
<add>
<add> private Subscriber<? super ByteBuffer> subscriber;
<add>
<add> private boolean stalled;
<add>
<add> private boolean cancelled;
<add>
<add>
<add> public RequestBodyPublisher(ServletAsyncContextSynchronizer synchronizer, int bufferSize) {
<add> this.synchronizer = synchronizer;
<add> this.buffer = new byte[bufferSize];
<add> }
<add>
<add>
<add> @Override
<add> public void subscribe(Subscriber<? super ByteBuffer> subscriber) {
<add> if (subscriber == null) {
<add> throw new NullPointerException();
<add> }
<add> else if (this.subscriber != null) {
<add> subscriber.onError(new IllegalStateException("Only one subscriber allowed"));
<add> }
<add> this.subscriber = subscriber;
<add> this.subscriber.onSubscribe(new RequestBodySubscription());
<add> }
<add>
<add> @Override
<add> public void onDataAvailable() throws IOException {
<add> if (cancelled) {
<add> return;
<add> }
<add> ServletInputStream input = this.synchronizer.getInputStream();
<add> logger.debug("onDataAvailable: " + input);
<add>
<add> while (true) {
<add> logger.debug("Demand: " + this.demand);
<add>
<add> if (!demand.hasDemand()) {
<add> stalled = true;
<add> break;
<add> }
<add>
<add> boolean ready = input.isReady();
<add> logger.debug("Input ready: " + ready + " finished: " + input.isFinished());
<add>
<add> if (!ready) {
<add> break;
<add> }
<add>
<add> int read = input.read(buffer);
<add> logger.debug("Input read:" + read);
<add>
<add> if (read == -1) {
<add> break;
<add> }
<add> else if (read > 0) {
<add> this.demand.decrement();
<add> byte[] copy = Arrays.copyOf(this.buffer, read);
<add>
<add>// logger.debug("Next: " + new String(copy, UTF_8));
<add>
<add> this.subscriber.onNext(ByteBuffer.wrap(copy));
<add>
<add> }
<add> }
<add> }
<add>
<add> @Override
<add> public void onAllDataRead() throws IOException {
<add> if (cancelled) {
<add> return;
<add> }
<add> logger.debug("All data read");
<add> this.synchronizer.readComplete();
<add> if (this.subscriber != null) {
<add> this.subscriber.onComplete();
<add> }
<add> }
<add>
<add> @Override
<add> public void onError(Throwable t) {
<add> if (cancelled) {
<add> return;
<add> }
<add> logger.error("RequestBodyPublisher Error", t);
<add> this.synchronizer.readComplete();
<add> if (this.subscriber != null) {
<add> this.subscriber.onError(t);
<add> }
<add> }
<add>
<add> private class RequestBodySubscription implements Subscription {
<add>
<add> @Override
<add> public void request(long n) {
<add> if (cancelled) {
<add> return;
<add> }
<add> logger.debug("Updating demand " + demand + " by " + n);
<add>
<add> demand.increase(n);
<add>
<add> logger.debug("Stalled: " + stalled);
<add>
<add> if (stalled) {
<add> stalled = false;
<add> try {
<add> onDataAvailable();
<add> }
<add> catch (IOException ex) {
<add> onError(ex);
<add> }
<add> }
<add> }
<add>
<add> @Override
<add> public void cancel() {
<add> if (cancelled) {
<add> return;
<add> }
<add> cancelled = true;
<add> synchronizer.readComplete();
<add> demand.reset();
<add> }
<add> }
<add>
<add>
<add> /**
<add> * Small utility class for keeping track of Reactive Streams demand.
<add> */
<add> private static final class DemandCounter {
<add>
<add> private final AtomicLong demand = new AtomicLong();
<add>
<add> /**
<add> * Increases the demand by the given number
<add> * @param n the positive number to increase demand by
<add> * @return the increased demand
<add> * @see org.reactivestreams.Subscription#request(long)
<add> */
<add> public long increase(long n) {
<add> Assert.isTrue(n > 0, "'n' must be higher than 0");
<add> return demand.updateAndGet(d -> d != Long.MAX_VALUE ? d + n : Long.MAX_VALUE);
<add> }
<add>
<add> /**
<add> * Decreases the demand by one.
<add> * @return the decremented demand
<add> */
<add> public long decrement() {
<add> return demand.updateAndGet(d -> d != Long.MAX_VALUE ? d - 1 : Long.MAX_VALUE);
<add> }
<add>
<add> /**
<add> * Indicates whether this counter has demand, i.e. whether it is higher than 0.
<add> * @return {@code true} if this counter has demand; {@code false} otherwise
<add> */
<add> public boolean hasDemand() {
<add> return this.demand.get() > 0;
<add> }
<add>
<add> /**
<add> * Resets this counter to 0.
<add> * @see org.reactivestreams.Subscription#cancel()
<add> */
<add> public void reset() {
<add> this.demand.set(0);
<add> }
<add>
<add> @Override
<add> public String toString() {
<add> return demand.toString();
<add> }
<add> }
<add> }
<add>
<add>}
<add><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/ServletServerHttpResponse.java
<del><path>spring-web-reactive/src/main/java/org/springframework/http/server/servlet31/Servlet31ServerHttpResponse.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.http.server.servlet31;
<add>package org.springframework.http.server.reactive;
<ide>
<add>import java.io.IOException;
<ide> import java.nio.ByteBuffer;
<ide> import java.nio.charset.Charset;
<ide> import java.util.List;
<ide> import java.util.Map;
<add>import javax.servlet.ServletOutputStream;
<add>import javax.servlet.WriteListener;
<ide> import javax.servlet.http.HttpServletResponse;
<ide>
<add>import org.apache.commons.logging.Log;
<add>import org.apache.commons.logging.LogFactory;
<ide> import org.reactivestreams.Publisher;
<add>import org.reactivestreams.Subscriber;
<add>import org.reactivestreams.Subscription;
<ide> import reactor.Publishers;
<ide>
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.MediaType;
<del>import org.springframework.http.server.ReactiveServerHttpResponse;
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<ide> * @author Rossen Stoyanchev
<ide> */
<del>public class Servlet31ServerHttpResponse implements ReactiveServerHttpResponse {
<add>public class ServletServerHttpResponse implements ServerHttpResponse {
<ide>
<del> private final HttpServletResponse response;
<add> private static final Log logger = LogFactory.getLog(ServletServerHttpResponse.class);
<ide>
<del> private final ResponseBodySubscriber subscriber;
<add>
<add> private final HttpServletResponse response;
<ide>
<ide> private final HttpHeaders headers;
<ide>
<del> private boolean headersWritten = false;
<add> private final ResponseBodySubscriber subscriber;
<ide>
<add> private boolean headersWritten = false;
<ide>
<del> public Servlet31ServerHttpResponse(HttpServletResponse response,
<del> ResponseBodySubscriber subscriber) {
<ide>
<add> public ServletServerHttpResponse(HttpServletResponse response, ServletAsyncContextSynchronizer synchronizer) {
<ide> Assert.notNull(response, "'response' must not be null");
<del> Assert.notNull(subscriber, "'subscriber' must not be null");
<ide> this.response = response;
<del> this.subscriber = subscriber;
<ide> this.headers = new HttpHeaders();
<add> this.subscriber = new ResponseBodySubscriber(synchronizer);
<ide> }
<ide>
<ide>
<ide> public HttpHeaders getHeaders() {
<ide> return (this.headersWritten ? HttpHeaders.readOnlyHttpHeaders(this.headers) : this.headers);
<ide> }
<ide>
<add> WriteListener getWriteListener() {
<add> return this.subscriber;
<add> }
<add>
<ide> @Override
<ide> public Publisher<Void> writeHeaders() {
<ide> applyHeaders();
<ide> private void applyHeaders() {
<ide> }
<ide> }
<ide>
<add>
<add> private static class ResponseBodySubscriber implements WriteListener, Subscriber<ByteBuffer> {
<add>
<add> private final ServletAsyncContextSynchronizer synchronizer;
<add>
<add> private Subscription subscription;
<add>
<add> private ByteBuffer buffer;
<add>
<add> private volatile boolean subscriberComplete = false;
<add>
<add>
<add> public ResponseBodySubscriber(ServletAsyncContextSynchronizer synchronizer) {
<add> this.synchronizer = synchronizer;
<add> }
<add>
<add>
<add> @Override
<add> public void onSubscribe(Subscription subscription) {
<add> this.subscription = subscription;
<add> this.subscription.request(1);
<add> }
<add>
<add> @Override
<add> public void onNext(ByteBuffer bytes) {
<add>
<add> Assert.isNull(buffer);
<add>
<add> this.buffer = bytes;
<add> try {
<add> onWritePossible();
<add> }
<add> catch (IOException e) {
<add> onError(e);
<add> }
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> logger.debug("Complete buffer: " + (buffer == null));
<add>
<add> this.subscriberComplete = true;
<add>
<add> if (buffer == null) {
<add> this.synchronizer.writeComplete();
<add> }
<add> }
<add>
<add> @Override
<add> public void onWritePossible() throws IOException {
<add> ServletOutputStream output = this.synchronizer.getOutputStream();
<add>
<add> boolean ready = output.isReady();
<add> logger.debug("Output: " + ready + " buffer: " + (buffer == null));
<add>
<add> if (ready) {
<add> if (this.buffer != null) {
<add> byte[] bytes = new byte[this.buffer.remaining()];
<add> this.buffer.get(bytes);
<add> this.buffer = null;
<add> output.write(bytes);
<add> if (!subscriberComplete) {
<add> this.subscription.request(1);
<add> }
<add> else {
<add> this.synchronizer.writeComplete();
<add> }
<add> }
<add> else {
<add> this.subscription.request(1);
<add> }
<add> }
<add> }
<add>
<add> @Override
<add> public void onError(Throwable t) {
<add> logger.error("ResponseBodySubscriber error", t);
<add> }
<add> }
<add>
<ide> }
<add><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/UndertowHttpHandlerAdapter.java
<del><path>spring-web-reactive/src/main/java/org/springframework/http/server/undertow/HttpHandlerHttpHandler.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.http.server.undertow;
<add>package org.springframework.http.server.reactive;
<ide>
<del>import org.springframework.http.server.ReactiveServerHttpRequest;
<del>import org.springframework.http.server.ReactiveServerHttpResponse;
<del>import org.springframework.http.server.ReactiveHttpHandler;
<ide> import org.springframework.util.Assert;
<ide>
<ide> import io.undertow.server.HttpServerExchange;
<ide> * @author Marek Hawrylczak
<ide> * @author Rossen Stoyanchev
<ide> */
<del>public class HttpHandlerHttpHandler implements io.undertow.server.HttpHandler {
<add>public class UndertowHttpHandlerAdapter implements io.undertow.server.HttpHandler {
<ide>
<del> private static Log logger = LogFactory.getLog(HttpHandlerHttpHandler.class);
<add> private static Log logger = LogFactory.getLog(UndertowHttpHandlerAdapter.class);
<ide>
<ide>
<del> private final ReactiveHttpHandler delegate;
<add> private final HttpHandler delegate;
<ide>
<ide>
<del> public HttpHandlerHttpHandler(ReactiveHttpHandler delegate) {
<add> public UndertowHttpHandlerAdapter(HttpHandler delegate) {
<ide> Assert.notNull(delegate, "'delegate' is required.");
<ide> this.delegate = delegate;
<ide> }
<ide>
<ide>
<ide> @Override
<ide> public void handleRequest(HttpServerExchange exchange) throws Exception {
<del> RequestBodyPublisher requestPublisher = new RequestBodyPublisher(exchange);
<del> ReactiveServerHttpRequest request = new UndertowServerHttpRequest(exchange, requestPublisher);
<ide>
<del> ResponseBodySubscriber responseSubscriber = new ResponseBodySubscriber(exchange);
<del> ReactiveServerHttpResponse response = new UndertowServerHttpResponse(exchange, responseSubscriber);
<add> ServerHttpRequest request = new UndertowServerHttpRequest(exchange);
<add> ServerHttpResponse response = new UndertowServerHttpResponse(exchange);
<ide>
<ide> exchange.dispatch();
<ide>
<ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/UndertowServerHttpRequest.java
<add>/*
<add> * Copyright 2002-2015 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.http.server.reactive;
<add>
<add>import java.io.IOException;
<add>import java.net.URI;
<add>import java.net.URISyntaxException;
<add>import java.nio.ByteBuffer;
<add>import java.util.concurrent.atomic.AtomicLongFieldUpdater;
<add>
<add>import io.undertow.connector.PooledByteBuffer;
<add>import io.undertow.server.HttpServerExchange;
<add>import io.undertow.util.HeaderValues;
<add>import io.undertow.util.SameThreadExecutor;
<add>import org.reactivestreams.Publisher;
<add>import org.reactivestreams.Subscriber;
<add>import org.reactivestreams.Subscription;
<add>import org.xnio.ChannelListener;
<add>import org.xnio.channels.StreamSourceChannel;
<add>import reactor.core.error.SpecificationExceptions;
<add>import reactor.core.support.BackpressureUtils;
<add>
<add>import org.springframework.http.HttpHeaders;
<add>import org.springframework.http.HttpMethod;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<add>import org.springframework.util.Assert;
<add>
<add>import static org.xnio.IoUtils.safeClose;
<add>
<add>/**
<add> * @author Marek Hawrylczak
<add> * @author Rossen Stoyanchev
<add> */
<add>public class UndertowServerHttpRequest implements ServerHttpRequest {
<add>
<add> private final HttpServerExchange exchange;
<add>
<add> private final Publisher<ByteBuffer> body = new RequestBodyPublisher();
<add>
<add> private HttpHeaders headers;
<add>
<add>
<add> public UndertowServerHttpRequest(HttpServerExchange exchange) {
<add> Assert.notNull(exchange, "'exchange' is required.");
<add> this.exchange = exchange;
<add> }
<add>
<add>
<add> @Override
<add> public HttpMethod getMethod() {
<add> return HttpMethod.valueOf(this.exchange.getRequestMethod().toString());
<add> }
<add>
<add> @Override
<add> public URI getURI() {
<add> try {
<add> return new URI(this.exchange.getRequestScheme(), null, this.exchange.getHostName(),
<add> this.exchange.getHostPort(), this.exchange.getRequestURI(),
<add> this.exchange.getQueryString(), null);
<add> }
<add> catch (URISyntaxException ex) {
<add> throw new IllegalStateException("Could not get URI: " + ex.getMessage(), ex);
<add> }
<add> }
<add>
<add> @Override
<add> public HttpHeaders getHeaders() {
<add> if (this.headers == null) {
<add> this.headers = new HttpHeaders();
<add> for (HeaderValues headerValues : this.exchange.getRequestHeaders()) {
<add> for (String value : headerValues) {
<add> this.headers.add(headerValues.getHeaderName().toString(), value);
<add> }
<add> }
<add> }
<add> return this.headers;
<add> }
<add>
<add> @Override
<add> public Publisher<ByteBuffer> getBody() {
<add> return this.body;
<add> }
<add>
<add>
<add> private static final AtomicLongFieldUpdater<RequestBodyPublisher.RequestBodySubscription> DEMAND =
<add> AtomicLongFieldUpdater.newUpdater(RequestBodyPublisher.RequestBodySubscription.class, "demand");
<add>
<add> private class RequestBodyPublisher implements Publisher<ByteBuffer> {
<add>
<add> private Subscriber<? super ByteBuffer> subscriber;
<add>
<add>
<add> @Override
<add> public void subscribe(Subscriber<? super ByteBuffer> subscriber) {
<add> if (subscriber == null) {
<add> throw SpecificationExceptions.spec_2_13_exception();
<add> }
<add> if (this.subscriber != null) {
<add> subscriber.onError(new IllegalStateException("Only one subscriber allowed"));
<add> }
<add>
<add> this.subscriber = subscriber;
<add> this.subscriber.onSubscribe(new RequestBodySubscription());
<add> }
<add>
<add>
<add> private class RequestBodySubscription implements Subscription, Runnable,
<add> ChannelListener<StreamSourceChannel> {
<add>
<add> volatile long demand;
<add>
<add> private PooledByteBuffer pooledBuffer;
<add>
<add> private StreamSourceChannel channel;
<add>
<add> private boolean subscriptionClosed;
<add>
<add> private boolean draining;
<add>
<add>
<add> @Override
<add> public void request(long n) {
<add> BackpressureUtils.checkRequest(n, subscriber);
<add> if (this.subscriptionClosed) {
<add> return;
<add> }
<add> BackpressureUtils.getAndAdd(DEMAND, this, n);
<add> scheduleNextMessage();
<add> }
<add>
<add> private void scheduleNextMessage() {
<add> exchange.dispatch(exchange.isInIoThread() ? SameThreadExecutor.INSTANCE :
<add> exchange.getIoThread(), this);
<add> }
<add>
<add> @Override
<add> public void cancel() {
<add> this.subscriptionClosed = true;
<add> close();
<add> }
<add>
<add> private void close() {
<add> if (this.pooledBuffer != null) {
<add> safeClose(this.pooledBuffer);
<add> this.pooledBuffer = null;
<add> }
<add> if (this.channel != null) {
<add> safeClose(this.channel);
<add> this.channel = null;
<add> }
<add> }
<add>
<add> @Override
<add> public void run() {
<add> if (this.subscriptionClosed || this.draining) {
<add> return;
<add> }
<add> if (0 == BackpressureUtils.getAndSub(DEMAND, this, 1)) {
<add> return;
<add> }
<add>
<add> this.draining = true;
<add>
<add> if (this.channel == null) {
<add> this.channel = exchange.getRequestChannel();
<add>
<add> if (this.channel == null) {
<add> if (exchange.isRequestComplete()) {
<add> return;
<add> }
<add> else {
<add> throw new IllegalStateException("Failed to acquire channel!");
<add> }
<add> }
<add> }
<add> if (this.pooledBuffer == null) {
<add> this.pooledBuffer = exchange.getConnection().getByteBufferPool().allocate();
<add> }
<add> else {
<add> this.pooledBuffer.getBuffer().clear();
<add> }
<add>
<add> try {
<add> ByteBuffer buffer = this.pooledBuffer.getBuffer();
<add> int count;
<add> do {
<add> count = this.channel.read(buffer);
<add> if (count == 0) {
<add> this.channel.getReadSetter().set(this);
<add> this.channel.resumeReads();
<add> }
<add> else if (count == -1) {
<add> if (buffer.position() > 0) {
<add> doOnNext(buffer);
<add> }
<add> doOnComplete();
<add> }
<add> else {
<add> if (buffer.remaining() == 0) {
<add> if (this.demand == 0) {
<add> this.channel.suspendReads();
<add> }
<add> doOnNext(buffer);
<add> if (this.demand > 0) {
<add> scheduleNextMessage();
<add> }
<add> break;
<add> }
<add> }
<add> } while (count > 0);
<add> }
<add> catch (IOException e) {
<add> doOnError(e);
<add> }
<add> }
<add>
<add> private void doOnNext(ByteBuffer buffer) {
<add> this.draining = false;
<add> buffer.flip();
<add> subscriber.onNext(buffer);
<add> }
<add>
<add> private void doOnComplete() {
<add> this.subscriptionClosed = true;
<add> try {
<add> subscriber.onComplete();
<add> }
<add> finally {
<add> close();
<add> }
<add> }
<add>
<add> private void doOnError(Throwable t) {
<add> this.subscriptionClosed = true;
<add> try {
<add> subscriber.onError(t);
<add> }
<add> finally {
<add> close();
<add> }
<add> }
<add>
<add> @Override
<add> public void handleEvent(StreamSourceChannel channel) {
<add> if (this.subscriptionClosed) {
<add> return;
<add> }
<add>
<add> try {
<add> ByteBuffer buffer = this.pooledBuffer.getBuffer();
<add> int count;
<add> do {
<add> count = channel.read(buffer);
<add> if (count == 0) {
<add> return;
<add> }
<add> else if (count == -1) {
<add> if (buffer.position() > 0) {
<add> doOnNext(buffer);
<add> }
<add> doOnComplete();
<add> }
<add> else {
<add> if (buffer.remaining() == 0) {
<add> if (this.demand == 0) {
<add> channel.suspendReads();
<add> }
<add> doOnNext(buffer);
<add> if (this.demand > 0) {
<add> scheduleNextMessage();
<add> }
<add> break;
<add> }
<add> }
<add> } while (count > 0);
<add> }
<add> catch (IOException e) {
<add> doOnError(e);
<add> }
<add> }
<add> }
<add> }
<add>
<add>}
<ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/UndertowServerHttpResponse.java
<add>/*
<add> * Copyright 2002-2015 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.http.server.reactive;
<add>
<add>import java.io.IOException;
<add>import java.nio.ByteBuffer;
<add>import java.util.List;
<add>import java.util.Map;
<add>import java.util.Queue;
<add>import java.util.concurrent.ConcurrentLinkedQueue;
<add>import java.util.concurrent.atomic.AtomicBoolean;
<add>import java.util.concurrent.atomic.AtomicInteger;
<add>
<add>import org.springframework.http.HttpHeaders;
<add>import org.springframework.http.HttpStatus;
<add>import org.springframework.util.Assert;
<add>
<add>import io.undertow.connector.PooledByteBuffer;
<add>import io.undertow.server.HttpServerExchange;
<add>import io.undertow.util.HttpString;
<add>import org.apache.commons.logging.Log;
<add>import org.apache.commons.logging.LogFactory;
<add>import org.reactivestreams.Publisher;
<add>import org.reactivestreams.Subscription;
<add>import org.xnio.ChannelListener;
<add>import org.xnio.channels.StreamSinkChannel;
<add>import reactor.core.subscriber.BaseSubscriber;
<add>
<add>import static org.xnio.ChannelListeners.closingChannelExceptionHandler;
<add>import static org.xnio.ChannelListeners.flushingChannelListener;
<add>import static org.xnio.IoUtils.safeClose;
<add>
<add>/**
<add> * @author Marek Hawrylczak
<add> * @author Rossen Stoyanchev
<add> */
<add>public class UndertowServerHttpResponse implements ServerHttpResponse {
<add>
<add> private static final Log logger = LogFactory.getLog(UndertowServerHttpResponse.class);
<add>
<add>
<add> private final HttpServerExchange exchange;
<add>
<add> private final ResponseBodySubscriber bodySubscriber = new ResponseBodySubscriber();
<add>
<add> private final HttpHeaders headers = new HttpHeaders();
<add>
<add> private boolean headersWritten = false;
<add>
<add>
<add> public UndertowServerHttpResponse(HttpServerExchange exchange) {
<add> Assert.notNull(exchange, "'exchange' is required.");
<add> this.exchange = exchange;
<add> }
<add>
<add>
<add> @Override
<add> public void setStatusCode(HttpStatus status) {
<add> Assert.notNull(status);
<add> this.exchange.setStatusCode(status.value());
<add> }
<add>
<add>
<add> @Override
<add> public Publisher<Void> setBody(Publisher<ByteBuffer> bodyPublisher) {
<add> applyHeaders();
<add> return (subscriber -> bodyPublisher.subscribe(bodySubscriber));
<add> }
<add>
<add> @Override
<add> public HttpHeaders getHeaders() {
<add> return (this.headersWritten ? HttpHeaders.readOnlyHttpHeaders(this.headers) : this.headers);
<add> }
<add>
<add> @Override
<add> public Publisher<Void> writeHeaders() {
<add> applyHeaders();
<add> return s -> s.onSubscribe(new Subscription() {
<add> @Override
<add> public void request(long n) {
<add> s.onComplete();
<add> }
<add>
<add> @Override
<add> public void cancel() {
<add> }
<add> });
<add> }
<add>
<add> private void applyHeaders() {
<add> if (!this.headersWritten) {
<add> for (Map.Entry<String, List<String>> entry : this.headers.entrySet()) {
<add> HttpString headerName = HttpString.tryFromString(entry.getKey());
<add> this.exchange.getResponseHeaders().addAll(headerName, entry.getValue());
<add>
<add> }
<add> this.headersWritten = true;
<add> }
<add> }
<add>
<add>
<add> private class ResponseBodySubscriber extends BaseSubscriber<ByteBuffer>
<add> implements ChannelListener<StreamSinkChannel> {
<add>
<add> private Subscription subscription;
<add>
<add> private final Queue<PooledByteBuffer> buffers = new ConcurrentLinkedQueue<>();
<add>
<add> private final AtomicInteger writing = new AtomicInteger();
<add>
<add> private final AtomicBoolean closing = new AtomicBoolean();
<add>
<add> private StreamSinkChannel responseChannel;
<add>
<add>
<add> @Override
<add> public void onSubscribe(Subscription subscription) {
<add> super.onSubscribe(subscription);
<add> this.subscription = subscription;
<add> this.subscription.request(1);
<add> }
<add>
<add> @Override
<add> public void onNext(ByteBuffer buffer) {
<add> super.onNext(buffer);
<add>
<add> if (this.responseChannel == null) {
<add> this.responseChannel = exchange.getResponseChannel();
<add> }
<add>
<add> this.writing.incrementAndGet();
<add> try {
<add> int c;
<add> do {
<add> c = this.responseChannel.write(buffer);
<add> } while (buffer.hasRemaining() && c > 0);
<add>
<add> if (buffer.hasRemaining()) {
<add> this.writing.incrementAndGet();
<add> enqueue(buffer);
<add> this.responseChannel.getWriteSetter().set(this);
<add> this.responseChannel.resumeWrites();
<add> }
<add> else {
<add> this.subscription.request(1);
<add> }
<add>
<add> }
<add> catch (IOException ex) {
<add> onError(ex);
<add> }
<add> finally {
<add> this.writing.decrementAndGet();
<add> if (this.closing.get()) {
<add> closeIfDone();
<add> }
<add> }
<add> }
<add>
<add> private void enqueue(ByteBuffer src) {
<add> do {
<add> PooledByteBuffer buffer = exchange.getConnection().getByteBufferPool().allocate();
<add> ByteBuffer dst = buffer.getBuffer();
<add> copy(dst, src);
<add> dst.flip();
<add> this.buffers.add(buffer);
<add> } while (src.remaining() > 0);
<add> }
<add>
<add> private void copy(ByteBuffer dst, ByteBuffer src) {
<add> int n = Math.min(dst.capacity(), src.remaining());
<add> for (int i = 0; i < n; i++) {
<add> dst.put(src.get());
<add> }
<add> }
<add>
<add> @Override
<add> public void handleEvent(StreamSinkChannel channel) {
<add> try {
<add> int c;
<add> do {
<add> ByteBuffer buffer = this.buffers.peek().getBuffer();
<add> do {
<add> c = channel.write(buffer);
<add> } while (buffer.hasRemaining() && c > 0);
<add>
<add> if (!buffer.hasRemaining()) {
<add> safeClose(this.buffers.remove());
<add> }
<add> } while (!this.buffers.isEmpty() && c > 0);
<add>
<add> if (!this.buffers.isEmpty()) {
<add> channel.resumeWrites();
<add> }
<add> else {
<add> this.writing.decrementAndGet();
<add>
<add> if (this.closing.get()) {
<add> closeIfDone();
<add> }
<add> else {
<add> this.subscription.request(1);
<add> }
<add> }
<add> }
<add> catch (IOException ex) {
<add> onError(ex);
<add> }
<add> }
<add>
<add> @Override
<add> public void onError(Throwable ex) {
<add> super.onError(ex);
<add> logger.error("ResponseBodySubscriber error", ex);
<add> if (!exchange.isResponseStarted() && exchange.getStatusCode() < 500) {
<add> exchange.setStatusCode(500);
<add> }
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> super.onComplete();
<add> if (this.responseChannel != null) {
<add> this.closing.set(true);
<add> closeIfDone();
<add> }
<add> }
<add>
<add> private void closeIfDone() {
<add> if (this.writing.get() == 0) {
<add> if (this.closing.compareAndSet(true, false)) {
<add> closeChannel();
<add> }
<add> }
<add> }
<add>
<add> private void closeChannel() {
<add> try {
<add> this.responseChannel.shutdownWrites();
<add>
<add> if (!this.responseChannel.flush()) {
<add> this.responseChannel.getWriteSetter().set(flushingChannelListener(
<add> o -> safeClose(this.responseChannel), closingChannelExceptionHandler()));
<add> this.responseChannel.resumeWrites();
<add> }
<add> this.responseChannel = null;
<add> }
<add> catch (IOException ex) {
<add> onError(ex);
<add> }
<add> }
<add> }
<add>}
<add><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/boot/HttpServer.java
<del><path>spring-web-reactive/src/main/java/org/springframework/http/server/support/HttpServer.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.http.server.support;
<add>package org.springframework.http.server.reactive.boot;
<ide>
<ide>
<ide> import org.springframework.beans.factory.InitializingBean;
<ide> import org.springframework.context.Lifecycle;
<del>import org.springframework.http.server.ReactiveHttpHandler;
<add>import org.springframework.http.server.reactive.HttpHandler;
<ide>
<ide> /**
<ide> * @author Rossen Stoyanchev
<ide> public interface HttpServer extends InitializingBean, Lifecycle {
<ide>
<ide> void setPort(int port);
<ide>
<del> void setHandler(ReactiveHttpHandler handler);
<add> void setHandler(HttpHandler handler);
<ide>
<ide> }
<add><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/boot/HttpServerSupport.java
<del><path>spring-web-reactive/src/main/java/org/springframework/http/server/support/HttpServerSupport.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.http.server.support;
<add>package org.springframework.http.server.reactive.boot;
<ide>
<ide>
<del>import org.springframework.http.server.ReactiveHttpHandler;
<add>import org.springframework.http.server.reactive.HttpHandler;
<ide>
<ide> /**
<ide> * @author Rossen Stoyanchev
<ide> public class HttpServerSupport {
<ide>
<ide> private int port = -1;
<ide>
<del> private ReactiveHttpHandler httpHandler;
<add> private HttpHandler httpHandler;
<ide>
<ide>
<ide> public void setPort(int port) {
<ide> public int getPort() {
<ide> return this.port;
<ide> }
<ide>
<del> public void setHandler(ReactiveHttpHandler handler) {
<add> public void setHandler(HttpHandler handler) {
<ide> this.httpHandler = handler;
<ide> }
<ide>
<del> public ReactiveHttpHandler getHttpHandler() {
<add> public HttpHandler getHttpHandler() {
<ide> return this.httpHandler;
<ide> }
<ide>
<add><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/boot/JettyHttpServer.java
<del><path>spring-web-reactive/src/main/java/org/springframework/http/server/support/JettyHttpServer.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.http.server.support;
<add>package org.springframework.http.server.reactive.boot;
<ide>
<ide> import org.eclipse.jetty.server.Server;
<ide> import org.eclipse.jetty.server.ServerConnector;
<ide> import org.springframework.beans.factory.InitializingBean;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.SocketUtils;
<del>import org.springframework.http.server.servlet31.HttpHandlerServlet;
<add>import org.springframework.http.server.reactive.ServletHttpHandlerAdapter;
<ide>
<ide> /**
<ide> * @author Rossen Stoyanchev
<ide> public void afterPropertiesSet() throws Exception {
<ide> this.jettyServer = new Server();
<ide>
<ide> Assert.notNull(getHttpHandler());
<del> HttpHandlerServlet servlet = new HttpHandlerServlet();
<add> ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter();
<ide> servlet.setHandler(getHttpHandler());
<ide> ServletHolder servletHolder = new ServletHolder(servlet);
<ide>
<add><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/boot/ReactorHttpServer.java
<del><path>spring-web-reactive/src/main/java/org/springframework/http/server/support/ReactorHttpServer.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.http.server.support;
<add>package org.springframework.http.server.reactive.boot;
<ide>
<ide> import reactor.io.buffer.Buffer;
<ide> import reactor.io.net.ReactiveNet;
<ide>
<ide> import org.springframework.beans.factory.InitializingBean;
<ide> import org.springframework.util.Assert;
<del>import org.springframework.http.server.reactor.HttpHandlerChannelHandler;
<add>import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
<ide>
<ide> /**
<ide> * @author Stephane Maldini
<ide> */
<ide> public class ReactorHttpServer extends HttpServerSupport
<ide> implements InitializingBean, HttpServer {
<ide>
<del> private HttpHandlerChannelHandler reactorHandler;
<add> private ReactorHttpHandlerAdapter reactorHandler;
<ide>
<ide> private reactor.io.net.http.HttpServer<Buffer, Buffer> reactorServer;
<ide>
<ide> public boolean isRunning() {
<ide> public void afterPropertiesSet() throws Exception {
<ide>
<ide> Assert.notNull(getHttpHandler());
<del> this.reactorHandler = new HttpHandlerChannelHandler(getHttpHandler());
<add> this.reactorHandler = new ReactorHttpHandlerAdapter(getHttpHandler());
<ide>
<ide> this.reactorServer = (getPort() != -1 ? ReactiveNet.httpServer(getPort()) :
<ide> ReactiveNet.httpServer());
<add><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/boot/RxNettyHttpServer.java
<del><path>spring-web-reactive/src/main/java/org/springframework/http/server/support/RxNettyHttpServer.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.http.server.support;
<add>package org.springframework.http.server.reactive.boot;
<ide>
<ide> import io.netty.buffer.ByteBuf;
<ide>
<ide> import org.springframework.beans.factory.InitializingBean;
<ide> import org.springframework.util.Assert;
<del>import org.springframework.http.server.rxnetty.HttpHandlerRequestHandler;
<add>import org.springframework.http.server.reactive.RxNettyHttpHandlerAdapter;
<ide>
<ide>
<ide> /**
<ide> * @author Rossen Stoyanchev
<ide> */
<ide> public class RxNettyHttpServer extends HttpServerSupport implements InitializingBean, HttpServer {
<ide>
<del> private HttpHandlerRequestHandler rxNettyHandler;
<add> private RxNettyHttpHandlerAdapter rxNettyHandler;
<ide>
<ide> private io.reactivex.netty.protocol.http.server.HttpServer<ByteBuf, ByteBuf> rxNettyServer;
<ide>
<ide> public boolean isRunning() {
<ide> public void afterPropertiesSet() throws Exception {
<ide>
<ide> Assert.notNull(getHttpHandler());
<del> this.rxNettyHandler = new HttpHandlerRequestHandler(getHttpHandler());
<add> this.rxNettyHandler = new RxNettyHttpHandlerAdapter(getHttpHandler());
<ide>
<ide> this.rxNettyServer = (getPort() != -1 ?
<ide> io.reactivex.netty.protocol.http.server.HttpServer.newServer(getPort()) :
<add><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/boot/TomcatHttpServer.java
<del><path>spring-web-reactive/src/main/java/org/springframework/http/server/support/TomcatHttpServer.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.http.server.support;
<add>package org.springframework.http.server.reactive.boot;
<ide>
<ide> import java.io.File;
<ide>
<ide> import org.springframework.beans.factory.InitializingBean;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.SocketUtils;
<del>import org.springframework.http.server.servlet31.HttpHandlerServlet;
<add>import org.springframework.http.server.reactive.ServletHttpHandlerAdapter;
<ide>
<ide>
<ide> /**
<ide> public void afterPropertiesSet() throws Exception {
<ide> this.tomcatServer.setPort(getPort());
<ide>
<ide> Assert.notNull(getHttpHandler());
<del> HttpHandlerServlet servlet = new HttpHandlerServlet();
<add> ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter();
<ide> servlet.setHandler(getHttpHandler());
<ide>
<ide> File base = new File(System.getProperty("java.io.tmpdir"));
<add><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/boot/UndertowHttpServer.java
<del><path>spring-web-reactive/src/main/java/org/springframework/http/server/support/UndertowHttpServer.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.http.server.support;
<add>package org.springframework.http.server.reactive.boot;
<ide>
<ide> import org.springframework.beans.factory.InitializingBean;
<ide> import org.springframework.util.Assert;
<del>import org.springframework.http.server.undertow.HttpHandlerHttpHandler;
<add>import org.springframework.http.server.reactive.UndertowHttpHandlerAdapter;
<ide>
<ide> import io.undertow.Undertow;
<ide> import io.undertow.server.HttpHandler;
<ide> public class UndertowHttpServer extends HttpServerSupport implements Initializin
<ide> @Override
<ide> public void afterPropertiesSet() throws Exception {
<ide> Assert.notNull(getHttpHandler());
<del> HttpHandler handler = new HttpHandlerHttpHandler(getHttpHandler());
<add> HttpHandler handler = new UndertowHttpHandlerAdapter(getHttpHandler());
<ide> int port = (getPort() != -1 ? getPort() : 8080);
<ide> this.server = Undertow.builder().addHttpListener(port, "localhost")
<ide> .setHandler(handler).build();
<add><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/boot/package-info.java
<del><path>spring-web-reactive/src/main/java/org/springframework/http/server/support/package-info.java
<ide> * This package contains temporary interfaces and classes for running embedded servers.
<ide> * They are expected to be replaced by an upcoming Spring Boot support.
<ide> */
<del>package org.springframework.http.server.support;
<add>package org.springframework.http.server.reactive.boot;
<ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/servlet31/RequestBodyPublisher.java
<del>/*
<del> * Copyright 2002-2015 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> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.http.server.servlet31;
<del>
<del>import java.io.IOException;
<del>import java.nio.ByteBuffer;
<del>import java.util.Arrays;
<del>import java.util.concurrent.atomic.AtomicLong;
<del>import javax.servlet.ReadListener;
<del>import javax.servlet.ServletInputStream;
<del>
<del>import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<del>import org.reactivestreams.Publisher;
<del>import org.reactivestreams.Subscriber;
<del>import org.reactivestreams.Subscription;
<del>
<del>import org.springframework.util.Assert;
<del>
<del>/**
<del> * @author Arjen Poutsma
<del> */
<del>public class RequestBodyPublisher implements ReadListener, Publisher<ByteBuffer> {
<del>
<del> private static final Log logger = LogFactory.getLog(RequestBodyPublisher.class);
<del>
<del> private final AsyncContextSynchronizer synchronizer;
<del>
<del> private final byte[] buffer;
<del>
<del> private final DemandCounter demand = new DemandCounter();
<del>
<del> private Subscriber<? super ByteBuffer> subscriber;
<del>
<del> private boolean stalled;
<del>
<del> private boolean cancelled;
<del>
<del> public RequestBodyPublisher(AsyncContextSynchronizer synchronizer, int bufferSize) {
<del> this.synchronizer = synchronizer;
<del> this.buffer = new byte[bufferSize];
<del> }
<del>
<del> @Override
<del> public void subscribe(Subscriber<? super ByteBuffer> subscriber) {
<del> if (subscriber == null) {
<del> throw new NullPointerException();
<del> }
<del> else if (this.subscriber != null) {
<del> subscriber.onError(new IllegalStateException("Only one subscriber allowed"));
<del> }
<del> this.subscriber = subscriber;
<del> this.subscriber.onSubscribe(new RequestBodySubscription());
<del> }
<del>
<del> @Override
<del> public void onDataAvailable() throws IOException {
<del> if (cancelled) {
<del> return;
<del> }
<del> ServletInputStream input = this.synchronizer.getInputStream();
<del> logger.debug("onDataAvailable: " + input);
<del>
<del> while (true) {
<del> logger.debug("Demand: " + this.demand);
<del>
<del> if (!demand.hasDemand()) {
<del> stalled = true;
<del> break;
<del> }
<del>
<del> boolean ready = input.isReady();
<del> logger.debug("Input ready: " + ready + " finished: " + input.isFinished());
<del>
<del> if (!ready) {
<del> break;
<del> }
<del>
<del> int read = input.read(buffer);
<del> logger.debug("Input read:" + read);
<del>
<del> if (read == -1) {
<del> break;
<del> }
<del> else if (read > 0) {
<del> this.demand.decrement();
<del> byte[] copy = Arrays.copyOf(this.buffer, read);
<del>
<del>// logger.debug("Next: " + new String(copy, UTF_8));
<del>
<del> this.subscriber.onNext(ByteBuffer.wrap(copy));
<del>
<del> }
<del> }
<del> }
<del>
<del> @Override
<del> public void onAllDataRead() throws IOException {
<del> if (cancelled) {
<del> return;
<del> }
<del> logger.debug("All data read");
<del> this.synchronizer.readComplete();
<del> if (this.subscriber != null) {
<del> this.subscriber.onComplete();
<del> }
<del> }
<del>
<del> @Override
<del> public void onError(Throwable t) {
<del> if (cancelled) {
<del> return;
<del> }
<del> logger.error("RequestBodyPublisher Error", t);
<del> this.synchronizer.readComplete();
<del> if (this.subscriber != null) {
<del> this.subscriber.onError(t);
<del> }
<del> }
<del>
<del> private class RequestBodySubscription implements Subscription {
<del>
<del> @Override
<del> public void request(long n) {
<del> if (cancelled) {
<del> return;
<del> }
<del> logger.debug("Updating demand " + demand + " by " + n);
<del>
<del> demand.increase(n);
<del>
<del> logger.debug("Stalled: " + stalled);
<del>
<del> if (stalled) {
<del> stalled = false;
<del> try {
<del> onDataAvailable();
<del> }
<del> catch (IOException ex) {
<del> onError(ex);
<del> }
<del> }
<del> }
<del>
<del> @Override
<del> public void cancel() {
<del> if (cancelled) {
<del> return;
<del> }
<del> cancelled = true;
<del> synchronizer.readComplete();
<del> demand.reset();
<del> }
<del> }
<del>
<del>
<del> /**
<del> * Small utility class for keeping track of Reactive Streams demand.
<del> */
<del> private static final class DemandCounter {
<del>
<del> private final AtomicLong demand = new AtomicLong();
<del>
<del> /**
<del> * Increases the demand by the given number
<del> * @param n the positive number to increase demand by
<del> * @return the increased demand
<del> * @see org.reactivestreams.Subscription#request(long)
<del> */
<del> public long increase(long n) {
<del> Assert.isTrue(n > 0, "'n' must be higher than 0");
<del> return demand.updateAndGet(d -> d != Long.MAX_VALUE ? d + n : Long.MAX_VALUE);
<del> }
<del>
<del> /**
<del> * Decreases the demand by one.
<del> * @return the decremented demand
<del> */
<del> public long decrement() {
<del> return demand.updateAndGet(d -> d != Long.MAX_VALUE ? d - 1 : Long.MAX_VALUE);
<del> }
<del>
<del> /**
<del> * Indicates whether this counter has demand, i.e. whether it is higher than 0.
<del> * @return {@code true} if this counter has demand; {@code false} otherwise
<del> */
<del> public boolean hasDemand() {
<del> return this.demand.get() > 0;
<del> }
<del>
<del> /**
<del> * Resets this counter to 0.
<del> * @see org.reactivestreams.Subscription#cancel()
<del> */
<del> public void reset() {
<del> this.demand.set(0);
<del> }
<del>
<del> @Override
<del> public String toString() {
<del> return demand.toString();
<del> }
<del> }
<del>}
<ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/servlet31/ResponseBodySubscriber.java
<del>/*
<del> * Copyright 2002-2015 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> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.http.server.servlet31;
<del>
<del>import java.io.IOException;
<del>import java.nio.ByteBuffer;
<del>import javax.servlet.ServletOutputStream;
<del>import javax.servlet.WriteListener;
<del>
<del>import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<del>import org.reactivestreams.Subscriber;
<del>import org.reactivestreams.Subscription;
<del>
<del>import org.springframework.util.Assert;
<del>
<del>/**
<del> * @author Arjen Poutsma
<del> */
<del>public class ResponseBodySubscriber implements WriteListener, Subscriber<ByteBuffer> {
<del>
<del> private static final Log logger = LogFactory.getLog(ResponseBodySubscriber.class);
<del>
<del> private final AsyncContextSynchronizer synchronizer;
<del>
<del> private Subscription subscription;
<del>
<del> private ByteBuffer buffer;
<del>
<del> private volatile boolean subscriberComplete = false;
<del>
<del> public ResponseBodySubscriber(AsyncContextSynchronizer synchronizer) {
<del> this.synchronizer = synchronizer;
<del> }
<del>
<del> @Override
<del> public void onSubscribe(Subscription subscription) {
<del> this.subscription = subscription;
<del> this.subscription.request(1);
<del> }
<del>
<del> @Override
<del> public void onNext(ByteBuffer bytes) {
<del>
<del> Assert.isNull(buffer);
<del>
<del> this.buffer = bytes;
<del> try {
<del> onWritePossible();
<del> }
<del> catch (IOException e) {
<del> onError(e);
<del> }
<del> }
<del>
<del> @Override
<del> public void onComplete() {
<del> logger.debug("Complete buffer: " + (buffer == null));
<del>
<del> this.subscriberComplete = true;
<del>
<del> if (buffer == null) {
<del> this.synchronizer.writeComplete();
<del> }
<del> }
<del>
<del> @Override
<del> public void onWritePossible() throws IOException {
<del> ServletOutputStream output = this.synchronizer.getOutputStream();
<del>
<del> boolean ready = output.isReady();
<del> logger.debug("Output: " + ready + " buffer: " + (buffer == null));
<del>
<del> if (ready) {
<del> if (this.buffer != null) {
<del> byte[] bytes = new byte[this.buffer.remaining()];
<del> this.buffer.get(bytes);
<del> this.buffer = null;
<del> output.write(bytes);
<del> if (!subscriberComplete) {
<del> this.subscription.request(1);
<del> }
<del> else {
<del> this.synchronizer.writeComplete();
<del> }
<del> }
<del> else {
<del> this.subscription.request(1);
<del> }
<del> }
<del> }
<del>
<del> @Override
<del> public void onError(Throwable t) {
<del> logger.error("ResponseBodySubscriber error", t);
<del> }
<del>
<del>}
<ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/servlet31/Servlet31ServerHttpRequest.java
<del>/*
<del> * Copyright 2002-2015 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> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.http.server.servlet31;
<del>
<del>import java.net.URI;
<del>import java.net.URISyntaxException;
<del>import java.nio.ByteBuffer;
<del>import java.nio.charset.Charset;
<del>import java.util.Enumeration;
<del>import java.util.Map;
<del>import javax.servlet.http.HttpServletRequest;
<del>
<del>import org.reactivestreams.Publisher;
<del>
<del>import org.springframework.http.HttpHeaders;
<del>import org.springframework.http.HttpMethod;
<del>import org.springframework.http.MediaType;
<del>import org.springframework.http.server.ReactiveServerHttpRequest;
<del>import org.springframework.util.Assert;
<del>import org.springframework.util.LinkedCaseInsensitiveMap;
<del>import org.springframework.util.StringUtils;
<del>
<del>/**
<del> * @author Rossen Stoyanchev
<del> */
<del>public class Servlet31ServerHttpRequest implements ReactiveServerHttpRequest {
<del>
<del> private final HttpServletRequest servletRequest;
<del>
<del> private final Publisher<ByteBuffer> requestBodyPublisher;
<del>
<del> private HttpHeaders headers;
<del>
<del>
<del> public Servlet31ServerHttpRequest(HttpServletRequest servletRequest,
<del> Publisher<ByteBuffer> requestBodyPublisher) {
<del>
<del> Assert.notNull(servletRequest, "HttpServletRequest must not be null");
<del> this.servletRequest = servletRequest;
<del> this.requestBodyPublisher = requestBodyPublisher;
<del> }
<del>
<del>
<del> @Override
<del> public HttpMethod getMethod() {
<del> return HttpMethod.valueOf(this.servletRequest.getMethod());
<del> }
<del>
<del> @Override
<del> public URI getURI() {
<del> try {
<del> return new URI(this.servletRequest.getScheme(), null, this.servletRequest.getServerName(),
<del> this.servletRequest.getServerPort(), this.servletRequest.getRequestURI(),
<del> this.servletRequest.getQueryString(), null);
<del> }
<del> catch (URISyntaxException ex) {
<del> throw new IllegalStateException("Could not get HttpServletRequest URI: " + ex.getMessage(), ex);
<del> }
<del> }
<del>
<del> @Override
<del> public HttpHeaders getHeaders() {
<del> if (this.headers == null) {
<del> this.headers = new HttpHeaders();
<del> for (Enumeration<?> names = this.servletRequest.getHeaderNames(); names.hasMoreElements(); ) {
<del> String headerName = (String) names.nextElement();
<del> for (Enumeration<?> headerValues = this.servletRequest.getHeaders(headerName);
<del> headerValues.hasMoreElements(); ) {
<del> String headerValue = (String) headerValues.nextElement();
<del> this.headers.add(headerName, headerValue);
<del> }
<del> }
<del> // HttpServletRequest exposes some headers as properties: we should include those if not already present
<del> MediaType contentType = this.headers.getContentType();
<del> if (contentType == null) {
<del> String requestContentType = this.servletRequest.getContentType();
<del> if (StringUtils.hasLength(requestContentType)) {
<del> contentType = MediaType.parseMediaType(requestContentType);
<del> this.headers.setContentType(contentType);
<del> }
<del> }
<del> if (contentType != null && contentType.getCharSet() == null) {
<del> String requestEncoding = this.servletRequest.getCharacterEncoding();
<del> if (StringUtils.hasLength(requestEncoding)) {
<del> Charset charSet = Charset.forName(requestEncoding);
<del> Map<String, String> params = new LinkedCaseInsensitiveMap<>();
<del> params.putAll(contentType.getParameters());
<del> params.put("charset", charSet.toString());
<del> MediaType newContentType = new MediaType(contentType.getType(), contentType.getSubtype(), params);
<del> this.headers.setContentType(newContentType);
<del> }
<del> }
<del> if (this.headers.getContentLength() == -1) {
<del> int requestContentLength = this.servletRequest.getContentLength();
<del> if (requestContentLength != -1) {
<del> this.headers.setContentLength(requestContentLength);
<del> }
<del> }
<del> }
<del> return this.headers;
<del> }
<del>
<del> @Override
<del> public Publisher<ByteBuffer> getBody() {
<del> return this.requestBodyPublisher;
<del> }
<del>
<del>}
<ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/undertow/RequestBodyPublisher.java
<del>/*
<del> * Copyright 2002-2015 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> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.http.server.undertow;
<del>
<del>import static org.xnio.IoUtils.safeClose;
<del>
<del>import java.io.IOException;
<del>import java.nio.ByteBuffer;
<del>import java.util.concurrent.atomic.AtomicLongFieldUpdater;
<del>
<del>import org.springframework.util.Assert;
<del>
<del>import io.undertow.connector.PooledByteBuffer;
<del>import io.undertow.server.HttpServerExchange;
<del>import io.undertow.util.SameThreadExecutor;
<del>import org.reactivestreams.Publisher;
<del>import org.reactivestreams.Subscriber;
<del>import org.reactivestreams.Subscription;
<del>import org.xnio.ChannelListener;
<del>import org.xnio.channels.StreamSourceChannel;
<del>import reactor.core.error.SpecificationExceptions;
<del>import reactor.core.support.BackpressureUtils;
<del>
<del>/**
<del> * @author Marek Hawrylczak
<del> */
<del>class RequestBodyPublisher implements Publisher<ByteBuffer> {
<del>
<del> private static final AtomicLongFieldUpdater<RequestBodySubscription> DEMAND =
<del> AtomicLongFieldUpdater.newUpdater(RequestBodySubscription.class, "demand");
<del>
<del>
<del> private final HttpServerExchange exchange;
<del>
<del> private Subscriber<? super ByteBuffer> subscriber;
<del>
<del>
<del> public RequestBodyPublisher(HttpServerExchange exchange) {
<del> Assert.notNull(exchange, "'exchange' is required.");
<del> this.exchange = exchange;
<del> }
<del>
<del>
<del> @Override
<del> public void subscribe(Subscriber<? super ByteBuffer> subscriber) {
<del> if (subscriber == null) {
<del> throw SpecificationExceptions.spec_2_13_exception();
<del> }
<del> if (this.subscriber != null) {
<del> subscriber.onError(new IllegalStateException("Only one subscriber allowed"));
<del> }
<del>
<del> this.subscriber = subscriber;
<del> this.subscriber.onSubscribe(new RequestBodySubscription());
<del> }
<del>
<del>
<del> private class RequestBodySubscription implements Subscription, Runnable,
<del> ChannelListener<StreamSourceChannel> {
<del>
<del> volatile long demand;
<del>
<del> private PooledByteBuffer pooledBuffer;
<del>
<del> private StreamSourceChannel channel;
<del>
<del> private boolean subscriptionClosed;
<del>
<del> private boolean draining;
<del>
<del>
<del> @Override
<del> public void request(long n) {
<del> BackpressureUtils.checkRequest(n, subscriber);
<del> if (this.subscriptionClosed) {
<del> return;
<del> }
<del> BackpressureUtils.getAndAdd(DEMAND, this, n);
<del> scheduleNextMessage();
<del> }
<del>
<del> private void scheduleNextMessage() {
<del> exchange.dispatch(exchange.isInIoThread() ? SameThreadExecutor.INSTANCE :
<del> exchange.getIoThread(), this);
<del> }
<del>
<del> @Override
<del> public void cancel() {
<del> this.subscriptionClosed = true;
<del> close();
<del> }
<del>
<del> private void close() {
<del> if (this.pooledBuffer != null) {
<del> safeClose(this.pooledBuffer);
<del> this.pooledBuffer = null;
<del> }
<del> if (this.channel != null) {
<del> safeClose(this.channel);
<del> this.channel = null;
<del> }
<del> }
<del>
<del> @Override
<del> public void run() {
<del> if (this.subscriptionClosed || this.draining) {
<del> return;
<del> }
<del> if (0 == BackpressureUtils.getAndSub(DEMAND, this, 1)) {
<del> return;
<del> }
<del>
<del> this.draining = true;
<del>
<del> if (this.channel == null) {
<del> this.channel = exchange.getRequestChannel();
<del>
<del> if (this.channel == null) {
<del> if (exchange.isRequestComplete()) {
<del> return;
<del> }
<del> else {
<del> throw new IllegalStateException("Failed to acquire channel!");
<del> }
<del> }
<del> }
<del> if (this.pooledBuffer == null) {
<del> this.pooledBuffer = exchange.getConnection().getByteBufferPool().allocate();
<del> }
<del> else {
<del> this.pooledBuffer.getBuffer().clear();
<del> }
<del>
<del> try {
<del> ByteBuffer buffer = this.pooledBuffer.getBuffer();
<del> int count;
<del> do {
<del> count = this.channel.read(buffer);
<del> if (count == 0) {
<del> this.channel.getReadSetter().set(this);
<del> this.channel.resumeReads();
<del> }
<del> else if (count == -1) {
<del> if (buffer.position() > 0) {
<del> doOnNext(buffer);
<del> }
<del> doOnComplete();
<del> }
<del> else {
<del> if (buffer.remaining() == 0) {
<del> if (this.demand == 0) {
<del> this.channel.suspendReads();
<del> }
<del> doOnNext(buffer);
<del> if (this.demand > 0) {
<del> scheduleNextMessage();
<del> }
<del> break;
<del> }
<del> }
<del> } while (count > 0);
<del> }
<del> catch (IOException e) {
<del> doOnError(e);
<del> }
<del> }
<del>
<del> private void doOnNext(ByteBuffer buffer) {
<del> this.draining = false;
<del> buffer.flip();
<del> subscriber.onNext(buffer);
<del> }
<del>
<del> private void doOnComplete() {
<del> this.subscriptionClosed = true;
<del> try {
<del> subscriber.onComplete();
<del> }
<del> finally {
<del> close();
<del> }
<del> }
<del>
<del> private void doOnError(Throwable t) {
<del> this.subscriptionClosed = true;
<del> try {
<del> subscriber.onError(t);
<del> }
<del> finally {
<del> close();
<del> }
<del> }
<del>
<del> @Override
<del> public void handleEvent(StreamSourceChannel channel) {
<del> if (this.subscriptionClosed) {
<del> return;
<del> }
<del>
<del> try {
<del> ByteBuffer buffer = this.pooledBuffer.getBuffer();
<del> int count;
<del> do {
<del> count = channel.read(buffer);
<del> if (count == 0) {
<del> return;
<del> }
<del> else if (count == -1) {
<del> if (buffer.position() > 0) {
<del> doOnNext(buffer);
<del> }
<del> doOnComplete();
<del> }
<del> else {
<del> if (buffer.remaining() == 0) {
<del> if (this.demand == 0) {
<del> channel.suspendReads();
<del> }
<del> doOnNext(buffer);
<del> if (this.demand > 0) {
<del> scheduleNextMessage();
<del> }
<del> break;
<del> }
<del> }
<del> } while (count > 0);
<del> }
<del> catch (IOException e) {
<del> doOnError(e);
<del> }
<del> }
<del> }
<del>
<del>}
<ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/undertow/ResponseBodySubscriber.java
<del>/*
<del> * Copyright 2002-2015 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> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.http.server.undertow;
<del>
<del>import java.io.IOException;
<del>import java.nio.ByteBuffer;
<del>import java.util.Queue;
<del>import java.util.concurrent.ConcurrentLinkedQueue;
<del>import java.util.concurrent.atomic.AtomicBoolean;
<del>import java.util.concurrent.atomic.AtomicInteger;
<del>
<del>import io.undertow.connector.PooledByteBuffer;
<del>import io.undertow.server.HttpServerExchange;
<del>import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<del>import org.reactivestreams.Subscription;
<del>import org.xnio.ChannelListener;
<del>import org.xnio.channels.StreamSinkChannel;
<del>import reactor.core.subscriber.BaseSubscriber;
<del>
<del>import static org.xnio.ChannelListeners.closingChannelExceptionHandler;
<del>import static org.xnio.ChannelListeners.flushingChannelListener;
<del>import static org.xnio.IoUtils.safeClose;
<del>
<del>/**
<del> * @author Marek Hawrylczak
<del> * @author Rossen Stoyanchev
<del> */
<del>class ResponseBodySubscriber extends BaseSubscriber<ByteBuffer>
<del> implements ChannelListener<StreamSinkChannel> {
<del>
<del> private static final Log logger = LogFactory.getLog(ResponseBodySubscriber.class);
<del>
<del>
<del> private final HttpServerExchange exchange;
<del>
<del> private Subscription subscription;
<del>
<del> private final Queue<PooledByteBuffer> buffers;
<del>
<del> private final AtomicInteger writing = new AtomicInteger();
<del>
<del> private final AtomicBoolean closing = new AtomicBoolean();
<del>
<del> private StreamSinkChannel responseChannel;
<del>
<del>
<del> public ResponseBodySubscriber(HttpServerExchange exchange) {
<del> this.exchange = exchange;
<del> this.buffers = new ConcurrentLinkedQueue<>();
<del> }
<del>
<del>
<del> @Override
<del> public void onSubscribe(Subscription subscription) {
<del> super.onSubscribe(subscription);
<del> this.subscription = subscription;
<del> this.subscription.request(1);
<del> }
<del>
<del> @Override
<del> public void onNext(ByteBuffer buffer) {
<del> super.onNext(buffer);
<del>
<del> if (this.responseChannel == null) {
<del> this.responseChannel = this.exchange.getResponseChannel();
<del> }
<del>
<del> this.writing.incrementAndGet();
<del> try {
<del> int c;
<del> do {
<del> c = this.responseChannel.write(buffer);
<del> } while (buffer.hasRemaining() && c > 0);
<del>
<del> if (buffer.hasRemaining()) {
<del> this.writing.incrementAndGet();
<del> enqueue(buffer);
<del> this.responseChannel.getWriteSetter().set(this);
<del> this.responseChannel.resumeWrites();
<del> }
<del> else {
<del> this.subscription.request(1);
<del> }
<del>
<del> }
<del> catch (IOException ex) {
<del> onError(ex);
<del> }
<del> finally {
<del> this.writing.decrementAndGet();
<del> if (this.closing.get()) {
<del> closeIfDone();
<del> }
<del> }
<del> }
<del>
<del> private void enqueue(ByteBuffer src) {
<del> do {
<del> PooledByteBuffer buffer = this.exchange.getConnection().getByteBufferPool().allocate();
<del> ByteBuffer dst = buffer.getBuffer();
<del> copy(dst, src);
<del> dst.flip();
<del> this.buffers.add(buffer);
<del> } while (src.remaining() > 0);
<del> }
<del>
<del> private void copy(ByteBuffer dst, ByteBuffer src) {
<del> int n = Math.min(dst.capacity(), src.remaining());
<del> for (int i = 0; i < n; i++) {
<del> dst.put(src.get());
<del> }
<del> }
<del>
<del> @Override
<del> public void handleEvent(StreamSinkChannel channel) {
<del> try {
<del> int c;
<del> do {
<del> ByteBuffer buffer = this.buffers.peek().getBuffer();
<del> do {
<del> c = channel.write(buffer);
<del> } while (buffer.hasRemaining() && c > 0);
<del>
<del> if (!buffer.hasRemaining()) {
<del> safeClose(this.buffers.remove());
<del> }
<del> } while (!this.buffers.isEmpty() && c > 0);
<del>
<del> if (!this.buffers.isEmpty()) {
<del> channel.resumeWrites();
<del> }
<del> else {
<del> this.writing.decrementAndGet();
<del>
<del> if (this.closing.get()) {
<del> closeIfDone();
<del> }
<del> else {
<del> this.subscription.request(1);
<del> }
<del> }
<del> }
<del> catch (IOException ex) {
<del> onError(ex);
<del> }
<del> }
<del>
<del> @Override
<del> public void onError(Throwable ex) {
<del> super.onError(ex);
<del> logger.error("ResponseBodySubscriber error", ex);
<del> if (!this.exchange.isResponseStarted() && this.exchange.getStatusCode() < 500) {
<del> this.exchange.setStatusCode(500);
<del> }
<del> }
<del>
<del> @Override
<del> public void onComplete() {
<del> super.onComplete();
<del> if (this.responseChannel != null) {
<del> this.closing.set(true);
<del> closeIfDone();
<del> }
<del> }
<del>
<del> private void closeIfDone() {
<del> if (this.writing.get() == 0) {
<del> if (this.closing.compareAndSet(true, false)) {
<del> closeChannel();
<del> }
<del> }
<del> }
<del>
<del> private void closeChannel() {
<del> try {
<del> this.responseChannel.shutdownWrites();
<del>
<del> if (!this.responseChannel.flush()) {
<del> this.responseChannel.getWriteSetter().set(flushingChannelListener(
<del> o -> safeClose(this.responseChannel), closingChannelExceptionHandler()));
<del> this.responseChannel.resumeWrites();
<del> }
<del> this.responseChannel = null;
<del> }
<del> catch (IOException ex) {
<del> onError(ex);
<del> }
<del> }
<del>}
<ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/undertow/UndertowServerHttpRequest.java
<del>/*
<del> * Copyright 2002-2015 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> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.http.server.undertow;
<del>
<del>import java.net.URI;
<del>import java.net.URISyntaxException;
<del>import java.nio.ByteBuffer;
<del>
<del>import io.undertow.server.HttpServerExchange;
<del>import io.undertow.util.HeaderValues;
<del>import org.reactivestreams.Publisher;
<del>
<del>import org.springframework.http.HttpHeaders;
<del>import org.springframework.http.HttpMethod;
<del>import org.springframework.http.server.ReactiveServerHttpRequest;
<del>
<del>/**
<del> * @author Marek Hawrylczak
<del> * @author Rossen Stoyanchev
<del> */
<del>class UndertowServerHttpRequest implements ReactiveServerHttpRequest {
<del>
<del> private final HttpServerExchange exchange;
<del>
<del> private final Publisher<ByteBuffer> body;
<del>
<del> private HttpHeaders headers;
<del>
<del>
<del> public UndertowServerHttpRequest(HttpServerExchange exchange, Publisher<ByteBuffer> body) {
<del> this.exchange = exchange;
<del> this.body = body;
<del> }
<del>
<del>
<del> @Override
<del> public HttpMethod getMethod() {
<del> return HttpMethod.valueOf(this.exchange.getRequestMethod().toString());
<del> }
<del>
<del> @Override
<del> public URI getURI() {
<del> try {
<del> return new URI(this.exchange.getRequestScheme(), null, this.exchange.getHostName(),
<del> this.exchange.getHostPort(), this.exchange.getRequestURI(),
<del> this.exchange.getQueryString(), null);
<del> }
<del> catch (URISyntaxException ex) {
<del> throw new IllegalStateException("Could not get URI: " + ex.getMessage(), ex);
<del> }
<del> }
<del>
<del> @Override
<del> public HttpHeaders getHeaders() {
<del> if (this.headers == null) {
<del> this.headers = new HttpHeaders();
<del> for (HeaderValues headerValues : this.exchange.getRequestHeaders()) {
<del> for (String value : headerValues) {
<del> this.headers.add(headerValues.getHeaderName().toString(), value);
<del> }
<del> }
<del> }
<del> return this.headers;
<del> }
<del>
<del> @Override
<del> public Publisher<ByteBuffer> getBody() {
<del> return this.body;
<del> }
<del>
<del>}
<ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/undertow/UndertowServerHttpResponse.java
<del>/*
<del> * Copyright 2002-2015 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> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.http.server.undertow;
<del>
<del>import java.nio.ByteBuffer;
<del>import java.util.List;
<del>import java.util.Map;
<del>
<del>import org.springframework.http.HttpHeaders;
<del>import org.springframework.http.HttpStatus;
<del>import org.springframework.http.server.ReactiveServerHttpResponse;
<del>import org.springframework.util.Assert;
<del>
<del>import io.undertow.server.HttpServerExchange;
<del>import io.undertow.util.HttpString;
<del>import org.reactivestreams.Publisher;
<del>import org.reactivestreams.Subscription;
<del>
<del>/**
<del> * @author Marek Hawrylczak
<del> * @author Rossen Stoyanchev
<del> */
<del>class UndertowServerHttpResponse implements ReactiveServerHttpResponse {
<del>
<del> private final HttpServerExchange exchange;
<del>
<del> private final ResponseBodySubscriber bodySubscriber;
<del>
<del> private final HttpHeaders headers = new HttpHeaders();
<del>
<del> private boolean headersWritten = false;
<del>
<del>
<del> public UndertowServerHttpResponse(HttpServerExchange exchange, ResponseBodySubscriber body) {
<del> this.exchange = exchange;
<del> this.bodySubscriber = body;
<del> }
<del>
<del>
<del> @Override
<del> public void setStatusCode(HttpStatus status) {
<del> Assert.notNull(status);
<del> this.exchange.setStatusCode(status.value());
<del> }
<del>
<del>
<del> @Override
<del> public Publisher<Void> setBody(Publisher<ByteBuffer> bodyPublisher) {
<del> applyHeaders();
<del> return (subscriber -> bodyPublisher.subscribe(bodySubscriber));
<del> }
<del>
<del> @Override
<del> public HttpHeaders getHeaders() {
<del> return (this.headersWritten ? HttpHeaders.readOnlyHttpHeaders(this.headers) : this.headers);
<del> }
<del>
<del> @Override
<del> public Publisher<Void> writeHeaders() {
<del> applyHeaders();
<del> return s -> s.onSubscribe(new Subscription() {
<del> @Override
<del> public void request(long n) {
<del> s.onComplete();
<del> }
<del>
<del> @Override
<del> public void cancel() {
<del> }
<del> });
<del> }
<del>
<del> private void applyHeaders() {
<del> if (!this.headersWritten) {
<del> for (Map.Entry<String, List<String>> entry : this.headers.entrySet()) {
<del> HttpString headerName = HttpString.tryFromString(entry.getKey());
<del> this.exchange.getResponseHeaders().addAll(headerName, entry.getValue());
<del>
<del> }
<del> this.headersWritten = true;
<del> }
<del> }
<del>
<del>}
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/DispatcherHandler.java
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide> import java.util.Map;
<del>import java.util.stream.Collectors;
<ide>
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<ide> import org.springframework.context.ApplicationContext;
<ide> import org.springframework.context.ApplicationContextAware;
<ide> import org.springframework.core.annotation.AnnotationAwareOrderComparator;
<del>import org.springframework.http.server.ReactiveHttpHandler;
<del>import org.springframework.http.server.ReactiveServerHttpRequest;
<del>import org.springframework.http.server.ReactiveServerHttpResponse;
<add>import org.springframework.http.server.reactive.HttpHandler;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<add>import org.springframework.http.server.reactive.ServerHttpResponse;
<ide>
<ide> /**
<ide> * Central dispatcher for HTTP request handlers/controllers. Dispatches to registered
<ide> * @author Rossen Stoyanchev
<ide> * @author Sebastien Deleuze
<ide> */
<del>public class DispatcherHandler implements ReactiveHttpHandler, ApplicationContextAware {
<add>public class DispatcherHandler implements HttpHandler, ApplicationContextAware {
<ide>
<ide> private static final Log logger = LogFactory.getLog(DispatcherHandler.class);
<ide>
<ide> protected void initStrategies(ApplicationContext context) {
<ide>
<ide>
<ide> @Override
<del> public Publisher<Void> handle(ReactiveServerHttpRequest request, ReactiveServerHttpResponse response) {
<add> public Publisher<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
<ide> if (logger.isDebugEnabled()) {
<ide> logger.debug("Processing " + request.getMethod() + " request for [" + request.getURI() + "]");
<ide> }
<ide> private static <E> Publisher<E> first(Publisher<E> source) {
<ide> private static class NotFoundHandlerMapping implements HandlerMapping {
<ide>
<ide> @Override
<del> public Publisher<Object> getHandler(ReactiveServerHttpRequest request) {
<add> public Publisher<Object> getHandler(ServerHttpRequest request) {
<ide> return Publishers.error(new HandlerNotFoundException(request.getMethod(),
<ide> request.getURI().getPath(), request.getHeaders()));
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/HandlerAdapter.java
<ide>
<ide> import org.reactivestreams.Publisher;
<ide>
<del>import org.springframework.http.server.ReactiveServerHttpRequest;
<del>import org.springframework.http.server.ReactiveServerHttpResponse;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<add>import org.springframework.http.server.reactive.ServerHttpResponse;
<ide>
<ide> /**
<ide> * Interface that must be implemented for each handler type to handle an HTTP request.
<ide> public interface HandlerAdapter {
<ide> * returned {@code true}.
<ide> * @return A {@link Publisher} object that produces a single {@link HandlerResult} element
<ide> */
<del> Publisher<HandlerResult> handle(ReactiveServerHttpRequest request,
<del> ReactiveServerHttpResponse response, Object handler);
<add> Publisher<HandlerResult> handle(ServerHttpRequest request, ServerHttpResponse response,
<add> Object handler);
<ide>
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/HandlerMapping.java
<ide>
<ide> import org.reactivestreams.Publisher;
<ide>
<del>import org.springframework.http.server.ReactiveServerHttpRequest;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<ide>
<ide> /**
<ide> * Interface to be implemented by objects that define a mapping between
<ide> public interface HandlerMapping {
<ide> * @param request current HTTP request
<ide> * @return A {@link Publisher} object that produces a single handler element
<ide> */
<del> Publisher<Object> getHandler(ReactiveServerHttpRequest request);
<add> Publisher<Object> getHandler(ServerHttpRequest request);
<ide>
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/HandlerResultHandler.java
<ide>
<ide> import org.reactivestreams.Publisher;
<ide>
<del>import org.springframework.http.server.ReactiveServerHttpRequest;
<del>import org.springframework.http.server.ReactiveServerHttpResponse;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<add>import org.springframework.http.server.reactive.ServerHttpResponse;
<ide>
<ide> /**
<ide> * Process the {@link HandlerResult}, usually returned by an {@link HandlerAdapter}.
<ide> public interface HandlerResultHandler {
<ide> * when the handling is complete (success or error) including the flush of the data on the
<ide> * network.
<ide> */
<del> Publisher<Void> handleResult(ReactiveServerHttpRequest request, ReactiveServerHttpResponse response,
<add> Publisher<Void> handleResult(ServerHttpRequest request, ServerHttpResponse response,
<ide> HandlerResult result);
<ide>
<ide> }
<ide>\ No newline at end of file
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/handler/HttpHandlerAdapter.java
<ide> import reactor.Publishers;
<ide>
<ide> import org.springframework.core.ResolvableType;
<del>import org.springframework.http.server.ReactiveServerHttpRequest;
<del>import org.springframework.http.server.ReactiveServerHttpResponse;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<add>import org.springframework.http.server.reactive.ServerHttpResponse;
<ide> import org.springframework.web.reactive.HandlerAdapter;
<ide> import org.springframework.web.reactive.HandlerResult;
<del>import org.springframework.http.server.ReactiveHttpHandler;
<add>import org.springframework.http.server.reactive.HttpHandler;
<ide> import org.springframework.web.reactive.DispatcherHandler;
<ide>
<ide> /**
<del> * Support use of {@link ReactiveHttpHandler} with
<add> * Support use of {@link HttpHandler} with
<ide> * {@link DispatcherHandler
<ide> * DispatcherHandler} (which implements the same contract).
<ide> * The use of {@code DispatcherHandler} this way enables routing requests to
<ide> public class HttpHandlerAdapter implements HandlerAdapter {
<ide>
<ide> @Override
<ide> public boolean supports(Object handler) {
<del> return ReactiveHttpHandler.class.isAssignableFrom(handler.getClass());
<add> return HttpHandler.class.isAssignableFrom(handler.getClass());
<ide> }
<ide>
<ide> @Override
<del> public Publisher<HandlerResult> handle(ReactiveServerHttpRequest request,
<del> ReactiveServerHttpResponse response, Object handler) {
<add> public Publisher<HandlerResult> handle(ServerHttpRequest request,
<add> ServerHttpResponse response, Object handler) {
<ide>
<del> ReactiveHttpHandler httpHandler = (ReactiveHttpHandler)handler;
<add> HttpHandler httpHandler = (HttpHandler)handler;
<ide> Publisher<Void> completion = httpHandler.handle(request, response);
<ide> return Publishers.just(new HandlerResult(httpHandler, completion, PUBLISHER_VOID));
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/handler/SimpleHandlerResultHandler.java
<ide> import org.springframework.core.Ordered;
<ide> import org.springframework.core.ResolvableType;
<ide> import org.springframework.core.convert.ConversionService;
<del>import org.springframework.http.server.ReactiveServerHttpRequest;
<del>import org.springframework.http.server.ReactiveServerHttpResponse;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<add>import org.springframework.http.server.reactive.ServerHttpResponse;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.web.reactive.HandlerResult;
<ide> import org.springframework.web.reactive.HandlerResultHandler;
<ide> private boolean isConvertibleToPublisher(ResolvableType type) {
<ide> }
<ide>
<ide> @Override
<del> public Publisher<Void> handleResult(ReactiveServerHttpRequest request,
<del> ReactiveServerHttpResponse response, HandlerResult result) {
<add> public Publisher<Void> handleResult(ServerHttpRequest request,
<add> ServerHttpResponse response, HandlerResult result) {
<ide>
<ide> Object value = result.getValue();
<ide> if (Void.TYPE.equals(result.getValueType().getRawClass())) {
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/handler/SimpleUrlHandlerMapping.java
<ide> import java.util.Map;
<ide>
<ide> import org.reactivestreams.Publisher;
<del>import reactor.Publishers;
<ide> import reactor.core.publisher.PublisherFactory;
<ide>
<del>import org.springframework.http.server.ReactiveServerHttpRequest;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.web.reactive.HandlerMapping;
<ide>
<ide> /**
<ide> public void setHandlers(Map<String, Object> handlers) {
<ide>
<ide>
<ide> @Override
<del> public Publisher<Object> getHandler(ReactiveServerHttpRequest request) {
<add> public Publisher<Object> getHandler(ServerHttpRequest request) {
<ide> return PublisherFactory.create(subscriber -> {
<ide> String path = request.getURI().getPath();
<ide> Object handler = this.handlerMap.get(path);
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/method/HandlerMethodArgumentResolver.java
<ide> import org.reactivestreams.Publisher;
<ide>
<ide> import org.springframework.core.MethodParameter;
<del>import org.springframework.http.server.ReactiveServerHttpRequest;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<ide>
<ide>
<ide> /**
<ide> public interface HandlerMethodArgumentResolver {
<ide> * does not allow publishing null values, if the value may be {@code null}
<ide> * use {@link java.util.Optional#ofNullable(Object)} to wrap it.
<ide> */
<del> Publisher<Object> resolveArgument(MethodParameter parameter, ReactiveServerHttpRequest request);
<add> Publisher<Object> resolveArgument(MethodParameter parameter, ServerHttpRequest request);
<ide>
<ide>
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/method/InvocableHandlerMethod.java
<ide> import org.springframework.core.GenericTypeResolver;
<ide> import org.springframework.core.MethodParameter;
<ide> import org.springframework.core.ParameterNameDiscoverer;
<del>import org.springframework.http.server.ReactiveServerHttpRequest;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.util.ReflectionUtils;
<ide> import org.springframework.web.method.HandlerMethod;
<ide>
<ide> public void setHandlerMethodArgumentResolvers(List<HandlerMethodArgumentResolver
<ide> }
<ide>
<ide>
<del> public Publisher<Object> invokeForRequest(ReactiveServerHttpRequest request,
<add> public Publisher<Object> invokeForRequest(ServerHttpRequest request,
<ide> Object... providedArgs) {
<ide>
<ide> List<Publisher<Object>> argPublishers = getMethodArguments(request, providedArgs);
<ide> public Publisher<Object> invokeForRequest(ReactiveServerHttpRequest request,
<ide> });
<ide> }
<ide>
<del> private List<Publisher<Object>> getMethodArguments(ReactiveServerHttpRequest request,
<add> private List<Publisher<Object>> getMethodArguments(ServerHttpRequest request,
<ide> Object... providedArgs) {
<ide>
<ide> MethodParameter[] parameters = getMethodParameters();
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/method/annotation/RequestBodyArgumentResolver.java
<ide> import org.springframework.core.ResolvableType;
<ide> import org.springframework.core.convert.ConversionService;
<ide> import org.springframework.http.MediaType;
<del>import org.springframework.http.server.ReactiveServerHttpRequest;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.core.codec.Decoder;
<ide> import org.springframework.web.reactive.method.HandlerMethodArgumentResolver;
<ide> import org.springframework.util.Assert;
<ide> public boolean supportsParameter(MethodParameter parameter) {
<ide> }
<ide>
<ide> @Override
<del> public Publisher<Object> resolveArgument(MethodParameter parameter, ReactiveServerHttpRequest request) {
<add> public Publisher<Object> resolveArgument(MethodParameter parameter, ServerHttpRequest request) {
<ide> MediaType mediaType = request.getHeaders().getContentType();
<ide> if (mediaType == null) {
<ide> mediaType = MediaType.APPLICATION_OCTET_STREAM;
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/method/annotation/RequestMappingHandlerAdapter.java
<ide> import org.springframework.beans.factory.InitializingBean;
<ide> import org.springframework.core.ResolvableType;
<ide> import org.springframework.core.convert.ConversionService;
<del>import org.springframework.http.server.ReactiveServerHttpRequest;
<del>import org.springframework.http.server.ReactiveServerHttpResponse;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<add>import org.springframework.http.server.reactive.ServerHttpResponse;
<ide> import org.springframework.core.codec.support.ByteBufferDecoder;
<ide> import org.springframework.core.codec.Decoder;
<ide> import org.springframework.core.codec.support.JacksonJsonDecoder;
<ide> public boolean supports(Object handler) {
<ide> }
<ide>
<ide> @Override
<del> public Publisher<HandlerResult> handle(ReactiveServerHttpRequest request,
<del> ReactiveServerHttpResponse response, Object handler) {
<add> public Publisher<HandlerResult> handle(ServerHttpRequest request,
<add> ServerHttpResponse response, Object handler) {
<ide>
<ide> InvocableHandlerMethod handlerMethod = new InvocableHandlerMethod((HandlerMethod) handler);
<ide> handlerMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers);
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/method/annotation/RequestMappingHandlerMapping.java
<ide> import org.springframework.context.ApplicationContext;
<ide> import org.springframework.context.ApplicationContextAware;
<ide> import org.springframework.core.annotation.AnnotationUtils;
<del>import org.springframework.http.server.ReactiveServerHttpRequest;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.stereotype.Controller;
<ide> import org.springframework.web.bind.annotation.RequestMapping;
<ide> import org.springframework.web.bind.annotation.RequestMethod;
<ide> protected void detectHandlerMethods(final Object bean) {
<ide> }
<ide>
<ide> @Override
<del> public Publisher<Object> getHandler(ReactiveServerHttpRequest request) {
<add> public Publisher<Object> getHandler(ServerHttpRequest request) {
<ide> return PublisherFactory.create(subscriber -> {
<ide> for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : this.methodMap.entrySet()) {
<ide> RequestMappingInfo info = entry.getKey();
<ide> public Set<RequestMethod> getMethods() {
<ide> return this.methods;
<ide> }
<ide>
<del> public boolean matchesRequest(ReactiveServerHttpRequest request) {
<add> public boolean matchesRequest(ServerHttpRequest request) {
<ide> String httpMethod = request.getMethod().name();
<ide> return request.getURI().getPath().equals(getPath()) &&
<ide> (getMethods().isEmpty() || getMethods().contains(RequestMethod.valueOf(httpMethod)));
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/method/annotation/RequestParamArgumentResolver.java
<ide> import reactor.Publishers;
<ide>
<ide> import org.springframework.core.MethodParameter;
<del>import org.springframework.http.server.ReactiveServerHttpRequest;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.web.reactive.method.HandlerMethodArgumentResolver;
<ide> import org.springframework.web.bind.annotation.RequestParam;
<ide> import org.springframework.web.util.UriComponents;
<ide> public boolean supportsParameter(MethodParameter parameter) {
<ide>
<ide>
<ide> @Override
<del> public Publisher<Object> resolveArgument(MethodParameter param, ReactiveServerHttpRequest request) {
<add> public Publisher<Object> resolveArgument(MethodParameter param, ServerHttpRequest request) {
<ide> RequestParam annotation = param.getParameterAnnotation(RequestParam.class);
<ide> String name = (annotation.value().length() != 0 ? annotation.value() : param.getParameterName());
<ide> UriComponents uriComponents = UriComponentsBuilder.fromUri(request.getURI()).build();
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/method/annotation/ResponseBodyResultHandler.java
<ide> import org.springframework.core.annotation.AnnotatedElementUtils;
<ide> import org.springframework.core.convert.ConversionService;
<ide> import org.springframework.http.MediaType;
<del>import org.springframework.http.server.ReactiveServerHttpRequest;
<del>import org.springframework.http.server.ReactiveServerHttpResponse;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<add>import org.springframework.http.server.reactive.ServerHttpResponse;
<ide> import org.springframework.core.codec.Encoder;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.MimeType;
<ide> public boolean supports(HandlerResult result) {
<ide>
<ide> @Override
<ide> @SuppressWarnings("unchecked")
<del> public Publisher<Void> handleResult(ReactiveServerHttpRequest request,
<del> ReactiveServerHttpResponse response, HandlerResult result) {
<add> public Publisher<Void> handleResult(ServerHttpRequest request,
<add> ServerHttpResponse response, HandlerResult result) {
<ide>
<ide> Object value = result.getValue();
<ide> if (value == null) {
<ide> else if (mediaType.equals(MediaType.ALL) || mediaType.equals(MEDIA_TYPE_APPLICAT
<ide> return Publishers.error(new HttpMediaTypeNotAcceptableException(this.allMediaTypes));
<ide> }
<ide>
<del> private List<MediaType> getAcceptableMediaTypes(ReactiveServerHttpRequest request) {
<add> private List<MediaType> getAcceptableMediaTypes(ServerHttpRequest request) {
<ide> List<MediaType> mediaTypes = request.getHeaders().getAccept();
<ide> return (mediaTypes.isEmpty() ? Collections.singletonList(MediaType.ALL) : mediaTypes);
<ide> }
<ide><path>spring-web-reactive/src/test/java/org/springframework/http/server/AbstractHttpHandlerIntegrationTests.java
<ide> import org.junit.runner.RunWith;
<ide> import org.junit.runners.Parameterized;
<ide>
<del>import org.springframework.http.server.support.HttpServer;
<del>import org.springframework.http.server.support.JettyHttpServer;
<del>import org.springframework.http.server.support.ReactorHttpServer;
<del>import org.springframework.http.server.support.RxNettyHttpServer;
<del>import org.springframework.http.server.support.TomcatHttpServer;
<del>import org.springframework.http.server.support.UndertowHttpServer;
<add>import org.springframework.http.server.reactive.HttpHandler;
<add>import org.springframework.http.server.reactive.boot.HttpServer;
<add>import org.springframework.http.server.reactive.boot.JettyHttpServer;
<add>import org.springframework.http.server.reactive.boot.ReactorHttpServer;
<add>import org.springframework.http.server.reactive.boot.RxNettyHttpServer;
<add>import org.springframework.http.server.reactive.boot.TomcatHttpServer;
<add>import org.springframework.http.server.reactive.boot.UndertowHttpServer;
<ide> import org.springframework.util.SocketUtils;
<ide>
<ide>
<ide> public void setup() throws Exception {
<ide> this.server.start();
<ide> }
<ide>
<del> protected abstract ReactiveHttpHandler createHttpHandler();
<add> protected abstract HttpHandler createHttpHandler();
<ide>
<ide> @After
<ide> public void tearDown() throws Exception {
<ide><path>spring-web-reactive/src/test/java/org/springframework/http/server/EchoHandler.java
<ide>
<ide> import org.reactivestreams.Publisher;
<ide>
<add>import org.springframework.http.server.reactive.HttpHandler;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<add>import org.springframework.http.server.reactive.ServerHttpResponse;
<add>
<ide> /**
<ide> * @author Arjen Poutsma
<ide> */
<del>public class EchoHandler implements ReactiveHttpHandler {
<add>public class EchoHandler implements HttpHandler {
<ide>
<ide> @Override
<del> public Publisher<Void> handle(ReactiveServerHttpRequest request, ReactiveServerHttpResponse response) {
<add> public Publisher<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
<ide> return response.setBody(request.getBody());
<ide> }
<ide> }
<ide><path>spring-web-reactive/src/test/java/org/springframework/http/server/FilterChainHttpHandlerTests.java
<ide> import reactor.Publishers;
<ide> import reactor.rx.Streams;
<ide>
<add>import org.springframework.http.server.reactive.FilterChainHttpHandler;
<add>import org.springframework.http.server.reactive.HttpFilter;
<add>import org.springframework.http.server.reactive.HttpFilterChain;
<add>import org.springframework.http.server.reactive.HttpHandler;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<add>import org.springframework.http.server.reactive.ServerHttpResponse;
<add>
<ide> import static org.junit.Assert.assertFalse;
<ide> import static org.junit.Assert.assertTrue;
<ide> import static org.mockito.Mockito.mock;
<ide> */
<ide> public class FilterChainHttpHandlerTests {
<ide>
<del> private ReactiveServerHttpRequest request;
<add> private ServerHttpRequest request;
<ide>
<del> private ReactiveServerHttpResponse response;
<add> private ServerHttpResponse response;
<ide>
<ide>
<ide> @Before
<ide> public void setUp() throws Exception {
<del> this.request = mock(ReactiveServerHttpRequest.class);
<del> this.response = mock(ReactiveServerHttpResponse.class);
<add> this.request = mock(ServerHttpRequest.class);
<add> this.response = mock(ServerHttpResponse.class);
<ide> }
<ide>
<ide> @Test
<ide> public void shortcircuitFilter() throws Exception {
<ide> }
<ide>
<ide>
<del> private static class TestFilter implements ReactiveHttpFilter {
<add> private static class TestFilter implements HttpFilter {
<ide>
<ide> private boolean invoked;
<ide>
<ide> public boolean invoked() {
<ide> }
<ide>
<ide> @Override
<del> public Publisher<Void> filter(ReactiveServerHttpRequest req, ReactiveServerHttpResponse res,
<del> ReactiveHttpFilterChain chain) {
<add> public Publisher<Void> filter(ServerHttpRequest req, ServerHttpResponse res,
<add> HttpFilterChain chain) {
<ide>
<ide> this.invoked = true;
<ide> return doFilter(req, res, chain);
<ide> }
<ide>
<del> public Publisher<Void> doFilter(ReactiveServerHttpRequest req, ReactiveServerHttpResponse res,
<del> ReactiveHttpFilterChain chain) {
<add> public Publisher<Void> doFilter(ServerHttpRequest req, ServerHttpResponse res,
<add> HttpFilterChain chain) {
<ide>
<ide> return chain.filter(req, res);
<ide> }
<ide> public Publisher<Void> doFilter(ReactiveServerHttpRequest req, ReactiveServerHtt
<ide> private static class ShortcircuitingFilter extends TestFilter {
<ide>
<ide> @Override
<del> public Publisher<Void> doFilter(ReactiveServerHttpRequest req, ReactiveServerHttpResponse res,
<del> ReactiveHttpFilterChain chain) {
<add> public Publisher<Void> doFilter(ServerHttpRequest req, ServerHttpResponse res,
<add> HttpFilterChain chain) {
<ide>
<ide> return Publishers.empty();
<ide> }
<ide> }
<ide>
<del> private static class StubHandler implements ReactiveHttpHandler {
<add> private static class StubHandler implements HttpHandler {
<ide>
<ide> private boolean invoked;
<ide>
<ide> public boolean invoked() {
<ide> }
<ide>
<ide> @Override
<del> public Publisher<Void> handle(ReactiveServerHttpRequest req, ReactiveServerHttpResponse res) {
<add> public Publisher<Void> handle(ServerHttpRequest req, ServerHttpResponse res) {
<ide> this.invoked = true;
<ide> return Publishers.empty();
<ide> }
<ide><path>spring-web-reactive/src/test/java/org/springframework/http/server/RandomHandler.java
<ide> import reactor.io.buffer.Buffer;
<ide> import reactor.rx.Streams;
<ide>
<add>import org.springframework.http.server.reactive.HttpHandler;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<add>import org.springframework.http.server.reactive.ServerHttpResponse;
<add>
<ide> import static org.junit.Assert.assertEquals;
<ide>
<ide> /**
<ide> * @author Arjen Poutsma
<ide> */
<del>public class RandomHandler implements ReactiveHttpHandler {
<add>public class RandomHandler implements HttpHandler {
<ide>
<ide> private static final Log logger = LogFactory.getLog(RandomHandler.class);
<ide>
<ide> public class RandomHandler implements ReactiveHttpHandler {
<ide> private final Random rnd = new Random();
<ide>
<ide> @Override
<del> public Publisher<Void> handle(ReactiveServerHttpRequest request, ReactiveServerHttpResponse response) {
<add> public Publisher<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
<ide>
<ide> request.getBody().subscribe(new Subscriber<ByteBuffer>() {
<ide> private Subscription s;
<ide><path>spring-web-reactive/src/test/java/org/springframework/http/server/XmlHandler.java
<ide> import reactor.rx.Streams;
<ide>
<ide> import org.springframework.http.MediaType;
<add>import org.springframework.http.server.reactive.HttpHandler;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<add>import org.springframework.http.server.reactive.ServerHttpResponse;
<ide> import org.springframework.util.BufferOutputStream;
<ide> import org.springframework.util.ByteBufferPublisherInputStream;
<ide>
<ide> /**
<ide> * @author Arjen Poutsma
<ide> */
<del>public class XmlHandler implements ReactiveHttpHandler {
<add>public class XmlHandler implements HttpHandler {
<ide>
<ide> private static final Log logger = LogFactory.getLog(XmlHandler.class);
<ide>
<ide> @Override
<del> public Publisher<Void> handle(ReactiveServerHttpRequest request,
<del> ReactiveServerHttpResponse response) {
<add> public Publisher<Void> handle(ServerHttpRequest request,
<add> ServerHttpResponse response) {
<ide> try {
<ide> JAXBContext jaxbContext = JAXBContext.newInstance(XmlHandlerIntegrationTests.Person.class);
<ide> Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
<ide><path>spring-web-reactive/src/test/java/org/springframework/http/server/XmlHandlerIntegrationTests.java
<ide>
<ide> import org.springframework.http.RequestEntity;
<ide> import org.springframework.http.ResponseEntity;
<add>import org.springframework.http.server.reactive.HttpHandler;
<ide> import org.springframework.web.client.RestTemplate;
<ide>
<ide> /**
<ide> public class XmlHandlerIntegrationTests extends AbstractHttpHandlerIntegrationTests {
<ide>
<ide> @Override
<del> protected ReactiveHttpHandler createHttpHandler() {
<add> protected HttpHandler createHttpHandler() {
<ide> return new XmlHandler();
<ide> }
<ide>
<add><path>spring-web-reactive/src/test/java/org/springframework/http/server/reactive/AsyncContextSynchronizerTests.java
<del><path>spring-web-reactive/src/test/java/org/springframework/http/server/servlet31/AsyncContextSynchronizerTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.http.server.servlet31;
<add>package org.springframework.http.server.reactive;
<ide>
<ide> import javax.servlet.AsyncContext;
<ide>
<ide> public class AsyncContextSynchronizerTests {
<ide>
<ide> private AsyncContext asyncContext;
<ide>
<del> private AsyncContextSynchronizer synchronizer;
<add> private ServletAsyncContextSynchronizer synchronizer;
<ide>
<ide> @Before
<ide> public void setUp() throws Exception {
<ide> asyncContext = mock(AsyncContext.class);
<del> synchronizer = new AsyncContextSynchronizer(asyncContext);
<add> synchronizer = new ServletAsyncContextSynchronizer(asyncContext);
<ide> }
<ide>
<ide> @Test
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/handler/SimpleUrlHandlerMappingIntegrationTests.java
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.RequestEntity;
<ide> import org.springframework.http.ResponseEntity;
<del>import org.springframework.http.server.ReactiveServerHttpRequest;
<del>import org.springframework.http.server.ReactiveServerHttpResponse;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<add>import org.springframework.http.server.reactive.ServerHttpResponse;
<ide> import org.springframework.web.client.HttpClientErrorException;
<del>import org.springframework.web.client.RestClientException;
<ide> import org.springframework.web.reactive.DispatcherHandler;
<ide> import org.springframework.http.server.AbstractHttpHandlerIntegrationTests;
<del>import org.springframework.http.server.ReactiveHttpHandler;
<add>import org.springframework.http.server.reactive.HttpHandler;
<ide> import org.springframework.web.client.RestTemplate;
<ide> import org.springframework.web.context.support.StaticWebApplicationContext;
<del>import org.springframework.web.reactive.method.annotation.RequestMappingHandlerMapping;
<ide>
<ide> import static org.junit.Assert.assertArrayEquals;
<ide> import static org.junit.Assert.assertEquals;
<ide> public class SimpleUrlHandlerMappingIntegrationTests extends AbstractHttpHandler
<ide>
<ide>
<ide> @Override
<del> protected ReactiveHttpHandler createHttpHandler() {
<add> protected HttpHandler createHttpHandler() {
<ide>
<ide> StaticWebApplicationContext wac = new StaticWebApplicationContext();
<ide> wac.registerSingleton("hm", TestHandlerMapping.class);
<ide> public TestHandlerMapping() {
<ide> }
<ide> }
<ide>
<del> private static class FooHandler implements ReactiveHttpHandler {
<add> private static class FooHandler implements HttpHandler {
<ide>
<ide> @Override
<del> public Publisher<Void> handle(ReactiveServerHttpRequest request, ReactiveServerHttpResponse response) {
<add> public Publisher<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
<ide> return response.setBody(Streams.just(Buffer.wrap("foo").byteBuffer()));
<ide> }
<ide> }
<ide>
<del> private static class BarHandler implements ReactiveHttpHandler {
<add> private static class BarHandler implements HttpHandler {
<ide>
<ide> @Override
<del> public Publisher<Void> handle(ReactiveServerHttpRequest request, ReactiveServerHttpResponse response) {
<add> public Publisher<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
<ide> return response.setBody(Streams.just(Buffer.wrap("bar").byteBuffer()));
<ide> }
<ide> }
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/method/annotation/RequestMappingHandlerMappingTests.java
<ide>
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<del>import org.springframework.http.server.ReactiveServerHttpRequest;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.stereotype.Controller;
<ide> import org.springframework.web.bind.annotation.RequestMapping;
<ide> import org.springframework.web.bind.annotation.RequestMethod;
<ide> public void setup() {
<ide>
<ide> @Test
<ide> public void path() throws Exception {
<del> ReactiveServerHttpRequest request = new MockServerHttpRequest(HttpMethod.GET, "boo");
<add> ServerHttpRequest request = new MockServerHttpRequest(HttpMethod.GET, "boo");
<ide> Publisher<?> handlerPublisher = this.mapping.getHandler(request);
<ide> HandlerMethod handlerMethod = toHandlerMethod(handlerPublisher);
<ide> assertEquals(TestController.class.getMethod("boo"), handlerMethod.getMethod());
<ide> }
<ide>
<ide> @Test
<ide> public void method() throws Exception {
<del> ReactiveServerHttpRequest request = new MockServerHttpRequest(HttpMethod.POST, "foo");
<add> ServerHttpRequest request = new MockServerHttpRequest(HttpMethod.POST, "foo");
<ide> Publisher<?> handlerPublisher = this.mapping.getHandler(request);
<ide> HandlerMethod handlerMethod = toHandlerMethod(handlerPublisher);
<ide> assertEquals(TestController.class.getMethod("postFoo"), handlerMethod.getMethod());
<ide> public String boo() {
<ide> /**
<ide> * TODO: this is more widely needed.
<ide> */
<del> private static class MockServerHttpRequest implements ReactiveServerHttpRequest {
<add> private static class MockServerHttpRequest implements ServerHttpRequest {
<ide>
<ide> private HttpMethod method;
<ide>
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/method/annotation/RequestMappingIntegrationTests.java
<ide> import org.springframework.web.reactive.DispatcherHandler;
<ide> import org.springframework.web.reactive.handler.SimpleHandlerResultHandler;
<ide> import org.springframework.http.server.AbstractHttpHandlerIntegrationTests;
<del>import org.springframework.http.server.ReactiveHttpHandler;
<add>import org.springframework.http.server.reactive.HttpHandler;
<ide> import org.springframework.stereotype.Controller;
<ide> import org.springframework.web.bind.annotation.RequestBody;
<ide> import org.springframework.web.bind.annotation.RequestMapping;
<ide> public class RequestMappingIntegrationTests extends AbstractHttpHandlerIntegrati
<ide>
<ide>
<ide> @Override
<del> protected ReactiveHttpHandler createHttpHandler() {
<add> protected HttpHandler createHttpHandler() {
<ide> this.wac = new AnnotationConfigWebApplicationContext();
<ide> this.wac.register(FrameworkConfig.class, ApplicationConfig.class);
<ide> this.wac.refresh(); | 58 |
Javascript | Javascript | simplify swipeablerow styling | 3ccfb58701d61449b74e387d2b9eced25bdefe31 | <ide><path>Libraries/Experimental/SwipeableRow/SwipeableRow.js
<ide> const SwipeableRow = React.createClass({
<ide> * component A to be transparent until component B is loaded.
<ide> */
<ide> isSwipeableViewRendered: false,
<add> rowHeight: (null: ?number),
<ide> };
<ide> },
<ide>
<ide> const SwipeableRow = React.createClass({
<ide> let slideOutView;
<ide> if (this.state.isSwipeableViewRendered) {
<ide> slideOutView = (
<del> <View style={styles.slideOutContainer}>
<add> <View style={[
<add> styles.slideOutContainer,
<add> {height: this.state.rowHeight},
<add> ]}>
<ide> {this.props.slideoutView}
<ide> </View>
<ide> );
<ide> const SwipeableRow = React.createClass({
<ide>
<ide> return (
<ide> <View
<del> {...this._panResponder.panHandlers}
<del> style={styles.container}>
<add> {...this._panResponder.panHandlers}>
<ide> {slideOutView}
<ide> {swipeableView}
<ide> </View>
<ide> const SwipeableRow = React.createClass({
<ide> if (!this.state.isSwipeableViewRendered) {
<ide> this.setState({
<ide> isSwipeableViewRendered: true,
<add> rowHeight: event.nativeEvent.layout.height,
<ide> });
<ide> }
<ide> },
<ide> const SwipeableRow = React.createClass({
<ide> });
<ide>
<ide> const styles = StyleSheet.create({
<del> container: {
<del> flex: 1,
<del> flexDirection: 'row',
<del> },
<ide> slideOutContainer: {
<ide> bottom: 0,
<del> flex: 1,
<ide> left: 0,
<ide> position: 'absolute',
<ide> right: 0, | 1 |
Javascript | Javascript | remove unused param in test-graph.pipe | 5e443d7398e8dadf0c44b3011f97deead75b1148 | <ide><path>test/async-hooks/test-graph.pipe.js
<ide> sleep
<ide> .on('exit', common.mustCall(onsleepExit))
<ide> .on('close', common.mustCall(onsleepClose));
<ide>
<del>function onsleepExit(code) {}
<add>function onsleepExit() {}
<ide>
<ide> function onsleepClose() {}
<ide> | 1 |
Ruby | Ruby | avoid is_a? calls | 6ac882bb58b429d20b76c96975df7dabaf618988 | <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> def nested_scope
<ide> def shallow?
<ide> @shallow
<ide> end
<add>
<add> def singleton?; false; end
<ide> end
<ide>
<ide> class SingletonResource < Resource #:nodoc:
<ide> def singular
<ide>
<ide> alias :member_scope :path
<ide> alias :nested_scope :path
<add>
<add> def singleton?; true; end
<ide> end
<ide>
<ide> def resources_path_names(options)
<ide> def shallow
<ide> end
<ide>
<ide> def shallow?
<del> parent_resource.instance_of?(Resource) && @scope[:shallow]
<add> !parent_resource.singleton? && @scope[:shallow]
<ide> end
<ide>
<ide> # Matches a url pattern to one or more routes. | 1 |
Javascript | Javascript | fix parallel/test-setproctitle.js on alpine | ee0620b2353df2a4857fc962805b6a0b2cbb0f3a | <ide><path>test/parallel/test-setproctitle.js
<ide> const path = require('path');
<ide> // The title shouldn't be too long; libuv's uv_set_process_title() out of
<ide> // security considerations no longer overwrites envp, only argv, so the
<ide> // maximum title length is possibly quite short.
<del>let title = 'testme';
<add>let title = 'test';
<ide>
<ide> assert.notStrictEqual(process.title, title);
<ide> process.title = title;
<ide> if (common.isWindows) {
<ide> return common.skip('Windows does not have "ps" utility');
<ide> }
<ide>
<del>exec(`ps -p ${process.pid} -o args=`, function callback(error, stdout, stderr) {
<add>// To pass this test on alpine, since Busybox `ps` does not
<add>// support `-p` switch, use `ps -o` and `grep` instead.
<add>const cmd = common.isLinux ?
<add> `ps -o pid,args | grep '${process.pid} ${title}' | grep -v grep` :
<add> `ps -p ${process.pid} -o args=`;
<add>
<add>exec(cmd, common.mustCall((error, stdout, stderr) => {
<ide> assert.ifError(error);
<ide> assert.strictEqual(stderr, '');
<ide>
<ide> exec(`ps -p ${process.pid} -o args=`, function callback(error, stdout, stderr) {
<ide> title += ` (${path.basename(process.execPath)})`;
<ide>
<ide> // omitting trailing whitespace and \n
<del> assert.strictEqual(stdout.replace(/\s+$/, ''), title);
<del>});
<add> assert.strictEqual(stdout.replace(/\s+$/, '').endsWith(title), true);
<add>})); | 1 |
Javascript | Javascript | fix path separator for windows | ab5926366265e74d63718d6999c4576c3b8ffe8b | <ide><path>lib/RequestShortener.js
<ide> class RequestShortener {
<ide> result = result.replace(this.currentDirectoryRegExp, "!.");
<ide> }
<ide> if (this.parentDirectoryRegExp) {
<del> result = result.replace(this.parentDirectoryRegExp, "!../");
<add> result = result.replace(this.parentDirectoryRegExp, `!..${path.sep}`);
<ide> }
<ide> if (!this.buildinsAsModule && this.buildinsRegExp) {
<ide> result = result.replace(this.buildinsRegExp, "!(webpack)"); | 1 |
PHP | PHP | update the describe | 37d26f29234978c59efcd11189aa6e1c1462e502 | <ide><path>lib/Cake/Model/Datasource/Database/Mssql.php
<ide> public function listSources() {
<ide> */
<ide> function describe($model) {
<ide> $cache = parent::describe($model);
<del>
<ide> if ($cache != null) {
<ide> return $cache;
<ide> }
<del>
<add> $fields = false;
<ide> $table = $this->fullTableName($model, false);
<del> $cols = $this->fetchAll("SELECT COLUMN_NAME as Field, DATA_TYPE as Type, COL_LENGTH('" . $table . "', COLUMN_NAME) as Length, IS_NULLABLE As [Null], COLUMN_DEFAULT as [Default], COLUMNPROPERTY(OBJECT_ID('" . $table . "'), COLUMN_NAME, 'IsIdentity') as [Key], NUMERIC_SCALE as Size FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" . $table . "'", false);
<add> $cols = $this->_execute("SELECT COLUMN_NAME as Field, DATA_TYPE as Type, COL_LENGTH('" . $table . "', COLUMN_NAME) as Length, IS_NULLABLE As [Null], COLUMN_DEFAULT as [Default], COLUMNPROPERTY(OBJECT_ID('" . $table . "'), COLUMN_NAME, 'IsIdentity') as [Key], NUMERIC_SCALE as Size FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" . $table . "'");
<add> if (!$cols) {
<add> throw new CakeException(__d('cake_dev', 'Could not describe table for %s', $model->name));
<add> }
<ide>
<del> $fields = false;
<ide> foreach ($cols as $column) {
<del> $field = $column[0]['Field'];
<add> $field = $column->Field;
<ide> $fields[$field] = array(
<del> 'type' => $this->column($column[0]['Type']),
<del> 'null' => (strtoupper($column[0]['Null']) == 'YES'),
<del> 'default' => preg_replace("/^[(]{1,2}'?([^')]*)?'?[)]{1,2}$/", "$1", $column[0]['Default']),
<del> 'length' => intval($column[0]['Length']),
<del> 'key' => ($column[0]['Key'] == '1') ? 'primary' : false
<add> 'type' => $this->column($column->Type),
<add> 'null' => ($column->Null === 'YES' ? true : false),
<add> 'default' => preg_replace("/^[(]{1,2}'?([^')]*)?'?[)]{1,2}$/", "$1", $column->Default),
<add> 'length' => intval($column->Type),
<add> 'key' => ($column->Key == '1') ? 'primary' : false
<ide> );
<add>
<ide> if ($fields[$field]['default'] === 'null') {
<ide> $fields[$field]['default'] = null;
<ide> } else {
<ide> $this->value($fields[$field]['default'], $fields[$field]['type']);
<ide> }
<ide>
<del> if ($fields[$field]['key'] && $fields[$field]['type'] == 'integer') {
<add> if ($fields[$field]['key'] !== false && $fields[$field]['type'] == 'integer') {
<ide> $fields[$field]['length'] = 11;
<del> } elseif (!$fields[$field]['key']) {
<add> } elseif ($fields[$field]['key'] === false) {
<ide> unset($fields[$field]['key']);
<ide> }
<ide> if (in_array($fields[$field]['type'], array('date', 'time', 'datetime', 'timestamp'))) {
<ide> $fields[$field]['length'] = null;
<ide> }
<ide> }
<del> $this->__cacheDescription($this->fullTableName($model, false), $fields);
<add> $this->__cacheDescription($table, $fields);
<add> $cols->closeCursor();
<ide> return $fields;
<ide> }
<ide> | 1 |
Ruby | Ruby | add fortran env helpers | aafe2f20d01ef5b03fd005c4b3107086c8d080a3 | <ide><path>Library/Homebrew/extend/ENV.rb
<ide> def remove keys, value
<ide> delete(key) if self[key].to_s.empty?
<ide> end if value
<ide> end
<del> def cc; self['CC'] or "cc"; end
<del> def cxx; self['CXX'] or "c++"; end
<del> def cflags; self['CFLAGS']; end
<del> def cxxflags;self['CXXFLAGS']; end
<del> def cppflags;self['CPPFLAGS']; end
<del> def ldflags; self['LDFLAGS']; end
<add>
<add> def cc; self['CC'] or "cc"; end
<add> def cxx; self['CXX'] or "c++"; end
<add> def cflags; self['CFLAGS']; end
<add> def cxxflags; self['CXXFLAGS']; end
<add> def cppflags; self['CPPFLAGS']; end
<add> def ldflags; self['LDFLAGS']; end
<add> def fc; self['FC']; end
<add> def fflags; self['FFLAGS']; end
<add> def fcflags; self['FCFLAGS']; end
<ide>
<ide> # Snow Leopard defines an NCURSES value the opposite of most distros
<ide> # See: http://bugs.python.org/issue6848 | 1 |
Javascript | Javascript | update action docs | e49113cb2c83880fb3656ebb306a4ec22e0e2d53 | <ide><path>packages/ember-routing-htmlbars/lib/keywords/action.js
<ide> import closureAction from 'ember-routing-htmlbars/keywords/closure-action';
<ide> supply an `on` option to the helper to specify a different DOM event name:
<ide>
<ide> ```handlebars
<del> <div {{action "anActionName" on="doubleClick"}}>
<add> <div {{action "anActionName" on="double-click"}}>
<ide> click me
<ide> </div>
<ide> ``` | 1 |
PHP | PHP | remove unused import | 8374f3ce0b9d094fcd434555a0887f15a7e07e1b | <ide><path>tests/TestCase/Database/ConnectionTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Database;
<ide>
<del>use Cake\Cache\Cache;
<ide> use Cake\Cache\Engine\NullEngine;
<ide> use Cake\Collection\Collection;
<ide> use Cake\Database\Connection; | 1 |
Javascript | Javascript | fix race condition in profiling plugin | 735f99c01bb82a4ea703b63d1a1ac74a8d7235b7 | <ide><path>lib/debug/ProfilingPlugin.js
<ide> function createTrace(outputPath) {
<ide> trace,
<ide> counter,
<ide> profiler,
<del> end: callback => fsStream.end(callback)
<add> end: callback => {
<add> // Wait until the write stream finishes.
<add> fsStream.on("finish", () => {
<add> callback();
<add> });
<add> // Tear down the readable trace stream.
<add> trace.destroy();
<add> }
<ide> };
<ide> }
<ide> | 1 |
Javascript | Javascript | simplify the `inject` implementation | d5c7ef0f7886afdfeb6d78b7e320ba2bfe5c77ba | <ide><path>src/ngMock/angular-mocks.js
<ide> if(window.jasmine || window.mocha) {
<ide> window.inject = angular.mock.inject = function() {
<ide> var blockFns = Array.prototype.slice.call(arguments, 0);
<ide> var errorForStack = new Error('Declaration Location');
<del> return isSpecRunning() ? workFn() : workFn;
<add> return isSpecRunning() ? workFn.call(currentSpec) : workFn;
<ide> /////////////////////
<ide> function workFn() {
<ide> var modules = currentSpec.$modules || [];
<ide> if(window.jasmine || window.mocha) {
<ide> }
<ide> for(var i = 0, ii = blockFns.length; i < ii; i++) {
<ide> try {
<del> // jasmine sets this to be the current spec, so we are mimicing that
<del> injector.invoke(blockFns[i] || angular.noop, currentSpec);
<add> /* jshint -W040 *//* Jasmine explicitly provides a `this` object when calling functions */
<add> injector.invoke(blockFns[i] || angular.noop, this);
<add> /* jshint +W040 */
<ide> } catch (e) {
<ide> if (e.stack && errorForStack) {
<ide> throw new ErrorAddingDeclarationLocationStack(e, errorForStack); | 1 |
Go | Go | write newline after every log message | d593f579528d2555296b535aeae8383f5d2ee9b3 | <ide><path>utils/utils.go
<ide> func (w *WriteBroadcaster) Write(p []byte) (n int, err error) {
<ide> continue
<ide> }
<ide> lp = append(lp, b...)
<add> lp = append(lp, '\n')
<ide> }
<ide> }
<ide> if n, err := sw.wc.Write(lp); err != nil || n != len(lp) { | 1 |
Go | Go | fix panic on network timeout during push | e273445dd407df6803d7b80863b644a6cfa2c1f5 | <ide><path>distribution/push.go
<ide> func Push(ctx context.Context, ref reference.Named, imagePushConfig *ImagePushCo
<ide> // argument so that it can be used with httpBlobWriter's ReadFrom method.
<ide> // Using httpBlobWriter's Write method would send a PATCH request for every
<ide> // Write call.
<del>func compress(in io.Reader) io.ReadCloser {
<add>//
<add>// The second return value is a channel that gets closed when the goroutine
<add>// is finished. This allows the caller to make sure the goroutine finishes
<add>// before it releases any resources connected with the reader that was
<add>// passed in.
<add>func compress(in io.Reader) (io.ReadCloser, chan struct{}) {
<add> compressionDone := make(chan struct{})
<add>
<ide> pipeReader, pipeWriter := io.Pipe()
<ide> // Use a bufio.Writer to avoid excessive chunking in HTTP request.
<ide> bufWriter := bufio.NewWriterSize(pipeWriter, compressionBufSize)
<ide> func compress(in io.Reader) io.ReadCloser {
<ide> } else {
<ide> pipeWriter.Close()
<ide> }
<add> close(compressionDone)
<ide> }()
<ide>
<del> return pipeReader
<add> return pipeReader, compressionDone
<ide> }
<ide><path>distribution/push_v2.go
<ide> func (pd *v2PushDescriptor) Upload(ctx context.Context, progressOutput progress.
<ide> size, _ := pd.layer.DiffSize()
<ide>
<ide> reader := progress.NewProgressReader(ioutils.NewCancelReadCloser(ctx, arch), progressOutput, size, pd.ID(), "Pushing")
<del> defer reader.Close()
<del> compressedReader := compress(reader)
<add> compressedReader, compressionDone := compress(reader)
<add> defer func() {
<add> reader.Close()
<add> <-compressionDone
<add> }()
<ide>
<ide> digester := digest.Canonical.New()
<ide> tee := io.TeeReader(compressedReader, digester.Hash()) | 2 |
Javascript | Javascript | dashify challenge block property on seed | 5d4a92bcc65a01a833f6778fa00acf265f731bcd | <ide><path>seed/index.js
<ide> Observable.combineLatest(
<ide> challenge.helpRoom = helpRoom;
<ide> challenge.order = order;
<ide> challenge.suborder = index + 1;
<del> challenge.block = blockName;
<add> challenge.block = dasherize(blockName);
<ide> challenge.blockId = block.id;
<ide> challenge.isBeta = challenge.isBeta || isBeta;
<ide> challenge.isComingSoon = challenge.isComingSoon || isComingSoon;
<ide><path>server/services/map.js
<ide> import { Observable } from 'rx';
<ide> import { Schema, valuesOf, arrayOf, normalize } from 'normalizr';
<ide> import { nameify, dasherize, unDasherize } from '../utils';
<del>import { dashify } from '../../common/utils';
<ide> import debug from 'debug';
<ide>
<ide> const isDev = process.env.NODE_ENV !== 'production';
<ide> function getChallengeByDashedName(dashedName, challengeMap$) {
<ide> })
<ide> .map(challenge => ({
<ide> redirect:
<del> `/challenges/${dashify(challenge.block)}/${challenge.dashedName}`,
<add> `/challenges/${challenge.block}/${challenge.dashedName}`,
<ide> entities: { challenge: { [challenge.dashedName]: challenge } },
<ide> result: {
<ide> challenge: challenge.dashedName,
<del> block: dashify(challenge.block)
<add> block: challenge.block
<ide> }
<ide> }));
<ide> } | 2 |
Ruby | Ruby | require mini_magick when it's used | ac26aef11f1be08917f3190b3d2b7ba4434444f7 | <ide><path>app/models/active_storage/variant.rb
<ide> require "active_storage/blob"
<del>require "mini_magick"
<ide>
<ide> # Image blobs can have variants that are the result of a set of transformations applied to the original.
<ide> class ActiveStorage::Variant
<ide> def process
<ide> end
<ide>
<ide> def transform(io)
<add> require "mini_magick"
<ide> File.open MiniMagick::Image.read(io).tap { |image| variation.transform(image) }.path
<ide> end
<ide> end | 1 |
Text | Text | improve pipeline model and meta example [ci skip] | aa5230546142810884321f2c15a59dace8454dba | <ide><path>website/docs/usage/processing-pipelines.md
<ide> components. spaCy then does the following:
<ide> >
<ide> > ```json
<ide> > {
<del>> "name": "example_model",
<ide> > "lang": "en",
<add>> "name": "core_web_sm",
<ide> > "description": "Example model for spaCy",
<del>> "pipeline": ["tagger", "parser"]
<add>> "pipeline": ["tagger", "parser", "ner"]
<ide> > }
<ide> > ```
<ide>
<ide> components. spaCy then does the following:
<ide> So when you call this...
<ide>
<ide> ```python
<del>nlp = spacy.load("en")
<add>nlp = spacy.load("en_core_web_sm")
<ide> ```
<ide>
<del>... the model tells spaCy to use the language `"en"` and the pipeline
<del>`["tagger", "parser", "ner"]`. spaCy will then initialize
<add>... the model's `meta.json` tells spaCy to use the language `"en"` and the
<add>pipeline `["tagger", "parser", "ner"]`. spaCy will then initialize
<ide> `spacy.lang.en.English`, and create each pipeline component and add it to the
<ide> processing pipeline. It'll then load in the model's data from its data directory
<ide> and return the modified `Language` class for you to use as the `nlp` object. | 1 |